diff --git a/CHANGELOG.md b/CHANGELOG.md index a3c1834ddf7..d0fec342e12 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -758,3 +758,8 @@ - Fixed a bug where the compiler would produce wrong JavaScript code for binary pattern matching expressions using literal strings and byte segments. ([Giacomo Cavalieri](https://github.com/giacomocavalieri)) + +- The compiler now provides a clearer error message when a function's return type + is mistakenly declared using `:` instead of `->`. + ([Gurvir Singh](https://github.com/baraich)) +>>>>>>> Stashed changes diff --git a/compiler-core/src/parse.rs b/compiler-core/src/parse.rs index a67c334a6bc..8f4467c84d9 100644 --- a/compiler-core/src/parse.rs +++ b/compiler-core/src/parse.rs @@ -2117,6 +2117,22 @@ where )?; let (_, rpar_e) = self.expect_one_following_series(&Token::RightParen, "a function parameter")?; + + // Check for TypeScript-style return type annotation (:) instead of arrow (->) + if let Some((colon_start, colon_end)) = self.maybe_one(&Token::Colon) { + return Err(ParseError { + error: ParseErrorType::UnexpectedToken { + token: Token::Colon, + expected: vec!["`->`".into()], + hint: Some("Return type annotations are written using `->`, not `:`".into()), + }, + location: SrcSpan { + start: colon_start, + end: colon_end, + }, + }); + }; + let return_annotation = self.parse_type_annotation(&Token::RArrow)?; let (body_start, body, end, end_position) = match self.maybe_one(&Token::LeftBrace) { diff --git a/compiler-core/src/parse/snapshots/gleam_core__parse__tests__wrong_function_return_type_declaration_using_colon_instead_of_right_arrow.snap b/compiler-core/src/parse/snapshots/gleam_core__parse__tests__wrong_function_return_type_declaration_using_colon_instead_of_right_arrow.snap new file mode 100644 index 00000000000..f194b3e6773 --- /dev/null +++ b/compiler-core/src/parse/snapshots/gleam_core__parse__tests__wrong_function_return_type_declaration_using_colon_instead_of_right_arrow.snap @@ -0,0 +1,19 @@ +--- +source: compiler-core/src/parse/tests.rs +expression: "\npub fn main(): Nil {}\n " +--- +----- SOURCE CODE + +pub fn main(): Nil {} + + +----- ERROR +error: Syntax error + ┌─ /src/parse/error.gleam:2:14 + │ +2 │ pub fn main(): Nil {} + │ ^ I was not expecting this + +Found `:`, expected one of: +- `->` +Hint: Return type annotations are written using `->`, not `:` diff --git a/compiler-core/src/parse/tests.rs b/compiler-core/src/parse/tests.rs index 23e41843456..f9072bb9787 100644 --- a/compiler-core/src/parse/tests.rs +++ b/compiler-core/src/parse/tests.rs @@ -1992,3 +1992,12 @@ pub fn main() { "# ); } + +#[test] +fn wrong_function_return_type_declaration_using_colon_instead_of_right_arrow() { + assert_module_error!( + r#" +pub fn main(): Nil {} + "# + ); +}