Skip to content

Commit 8d0e9e5

Browse files
authored
feat: Validate argument count (#1233)
Resolves #1027 and #1201
1 parent 44df0db commit 8d0e9e5

12 files changed

+399
-363
lines changed

compiler/plc_diagnostics/src/diagnostics.rs

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::fmt::Display;
22

33
use serde::{Deserialize, Serialize};
44

5+
use crate::diagnostics::diagnostics_registry::DIAGNOSTICS;
56
use plc_ast::ast::AstNode;
67
use plc_source::{
78
source_location::{SourceLocation, SourceLocationFactory},
@@ -88,8 +89,10 @@ impl Diagnostic {
8889
self
8990
}
9091

91-
pub fn with_error_code(mut self, error_code: &'static str) -> Self {
92-
self.error_code = error_code;
92+
pub fn with_error_code(mut self, code: &'static str) -> Self {
93+
debug_assert!(DIAGNOSTICS.get(code).is_some(), "Error {code} does not exist");
94+
95+
self.error_code = code;
9396
self
9497
}
9598

@@ -199,12 +202,26 @@ impl Diagnostic {
199202
.with_error_code("E006")
200203
}
201204

202-
pub fn invalid_parameter_count(expected: usize, received: usize, location: SourceLocation) -> Diagnostic {
203-
Diagnostic::new(
204-
format!(
205-
"Invalid parameter count. Received {received} parameters while {expected} parameters were expected.",
206-
)).with_error_code("E032")
207-
.with_location(location)
205+
pub fn invalid_argument_count<T>(expected: usize, actual: usize, location: T) -> Diagnostic
206+
where
207+
T: Into<SourceLocation>,
208+
{
209+
// Let's be extra fancy here 🕺
210+
fn message(value: usize) -> String {
211+
match value {
212+
1 => format!("{value} argument"),
213+
_ => format!("{value} arguments"),
214+
}
215+
}
216+
217+
Diagnostic::new(format!(
218+
"this POU takes {expected} but {actual} {was_or_were} supplied",
219+
expected = message(expected),
220+
actual = message(actual),
221+
was_or_were = if actual == 1 { "was" } else { "were" }
222+
))
223+
.with_error_code("E032")
224+
.with_location(location.into())
208225
}
209226

210227
pub fn unknown_type(type_name: &str, location: SourceLocation) -> Diagnostic {

0 commit comments

Comments
 (0)