Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make case expressions fault tolerant #4169

Merged
merged 4 commits into from
Jan 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
shell starting from OTP27.
([Giacomo Cavalieri](https://github.com/giacomocavalieri))

- Parsing of `case` expressions is now fault tolerant. If a `case` expressions
is missing its body, the compiler can still perform type inference. This also
allows the Language Server to provide completion hints for `case` subjects.
([Surya Rose](https://github.com/GearsDatapacks))

### Build tool

- `gleam new` now has refined project name validation - rather than failing on
Expand Down
3 changes: 2 additions & 1 deletion compiler-core/src/ast/untyped.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ pub enum UntypedExpr {
Case {
location: SrcSpan,
subjects: Vec<Self>,
clauses: Vec<Clause<Self, (), ()>>,
// None if the case expression is missing a body.
clauses: Option<Vec<Clause<Self, (), ()>>>,
},

FieldAccess {
Expand Down
38 changes: 20 additions & 18 deletions compiler-core/src/ast_folder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -457,23 +457,25 @@ pub trait UntypedExprFolder: TypeAstFolder + UntypedConstantFolder + PatternFold
clauses,
} => {
let subjects = subjects.into_iter().map(|e| self.fold_expr(e)).collect();
let clauses = clauses
.into_iter()
.map(|mut c| {
c.pattern = c
.pattern
.into_iter()
.map(|p| self.fold_pattern(p))
.collect();
c.alternative_patterns = c
.alternative_patterns
.into_iter()
.map(|p| p.into_iter().map(|p| self.fold_pattern(p)).collect())
.collect();
c.then = self.fold_expr(c.then);
c
})
.collect();
let clauses = clauses.map(|clauses| {
clauses
.into_iter()
.map(|mut c| {
c.pattern = c
.pattern
.into_iter()
.map(|p| self.fold_pattern(p))
.collect();
c.alternative_patterns = c
.alternative_patterns
.into_iter()
.map(|p| p.into_iter().map(|p| self.fold_pattern(p)).collect())
.collect();
c.then = self.fold_expr(c.then);
c
})
.collect()
});
UntypedExpr::Case {
location,
subjects,
Expand Down Expand Up @@ -742,7 +744,7 @@ pub trait UntypedExprFolder: TypeAstFolder + UntypedConstantFolder + PatternFold
&mut self,
location: SrcSpan,
subjects: Vec<UntypedExpr>,
clauses: Vec<UntypedClause>,
clauses: Option<Vec<UntypedClause>>,
) -> UntypedExpr {
UntypedExpr::Case {
location,
Expand Down
2 changes: 1 addition & 1 deletion compiler-core/src/call_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ impl<'a> CallGraphBuilder<'a> {
for subject in subjects {
self.expression(subject);
}
for clause in clauses {
for clause in clauses.as_deref().unwrap_or_default() {
let names = self.names.clone();
for pattern in &clause.pattern {
self.pattern(pattern);
Expand Down
21 changes: 21 additions & 0 deletions compiler-core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3066,6 +3066,27 @@ The missing patterns are:\n"
}
}

TypeError::MissingCaseBody { location } => {
let text = wrap(
"This case expression is missing its body."
);
Diagnostic {
title: "Missing case body".into(),
text,
hint: None,
level: Level::Error,
location: Some(Location {
src: src.clone(),
path: path.to_path_buf(),
label: Label {
text: None,
span: *location,
},
extra_labels: Vec::new(),
}),
}
}

TypeError::UnsupportedExpressionTarget {
location,
target: current_target,
Expand Down
2 changes: 1 addition & 1 deletion compiler-core/src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1030,7 +1030,7 @@ impl<'comments> Formatter<'comments> {
subjects,
clauses,
location,
} => self.case(subjects, clauses, location),
} => self.case(subjects, clauses.as_deref().unwrap_or_default(), location),

UntypedExpr::FieldAccess {
label, container, ..
Expand Down
15 changes: 15 additions & 0 deletions compiler-core/src/language_server/tests/completion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1886,3 +1886,18 @@ pub fn map(_, _) { [] }
Position::new(3, 8)
);
}

#[test]
fn case_subject() {
let code = "
pub fn main(something: Bool) {
case so
}
";

assert_apply_completion!(
TestProject::for_source(code),
"something",
Position::new(2, 9)
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
source: compiler-core/src/language_server/tests/completion.rs
expression: "\npub fn main(something: Bool) {\n case so\n}\n"
---
pub fn main(something: Bool) {
case so|
}


----- After applying completion -----

pub fn main(something: Bool) {
case something
}
35 changes: 24 additions & 11 deletions compiler-core/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -701,20 +701,33 @@ where
self.advance();
let subjects =
Parser::series_of(self, &Parser::parse_expression, Some(&Token::Comma))?;
let _ = self.expect_one_following_series(&Token::LeftBrace, "an expression")?;
let clauses = Parser::series_of(self, &Parser::parse_case_clause, None)?;
let (_, end) =
self.expect_one_following_series(&Token::RightBrace, "a case clause")?;
if subjects.is_empty() {
return parse_error(
ParseErrorType::ExpectedExpr,
SrcSpan { start, end: case_e },
);
if self.maybe_one(&Token::LeftBrace).is_some() {
let clauses = Parser::series_of(self, &Parser::parse_case_clause, None)?;
let (_, end) =
self.expect_one_following_series(&Token::RightBrace, "a case clause")?;
if subjects.is_empty() {
return parse_error(
ParseErrorType::ExpectedExpr,
SrcSpan { start, end: case_e },
);
} else {
UntypedExpr::Case {
location: SrcSpan { start, end },
subjects,
clauses: Some(clauses),
}
}
} else {
UntypedExpr::Case {
location: SrcSpan { start, end },
location: SrcSpan::new(
start,
subjects
.last()
.map(|subject| subject.location().end)
.unwrap_or(case_e),
),
subjects,
clauses,
clauses: None,
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,86 +27,88 @@ expression: "\ncase 2, 3 {\n x, y if x + y == 1 -> True\n}"
int_value: 3,
},
],
clauses: [
Clause {
location: SrcSpan {
start: 17,
end: 43,
},
pattern: [
Variable {
location: SrcSpan {
start: 17,
end: 18,
},
name: "x",
type_: (),
origin: Variable(
"x",
),
clauses: Some(
[
Clause {
location: SrcSpan {
start: 17,
end: 43,
},
Variable {
location: SrcSpan {
start: 20,
end: 21,
pattern: [
Variable {
location: SrcSpan {
start: 17,
end: 18,
},
name: "x",
type_: (),
origin: Variable(
"x",
),
},
name: "y",
type_: (),
origin: Variable(
"y",
),
},
],
alternative_patterns: [],
guard: Some(
Equals {
location: SrcSpan {
start: 25,
end: 35,
Variable {
location: SrcSpan {
start: 20,
end: 21,
},
name: "y",
type_: (),
origin: Variable(
"y",
),
},
left: AddInt {
],
alternative_patterns: [],
guard: Some(
Equals {
location: SrcSpan {
start: 25,
end: 30,
end: 35,
},
left: Var {
left: AddInt {
location: SrcSpan {
start: 25,
end: 26,
},
type_: (),
name: "x",
},
right: Var {
location: SrcSpan {
start: 29,
end: 30,
},
type_: (),
name: "y",
},
},
right: Constant(
Int {
location: SrcSpan {
start: 34,
end: 35,
left: Var {
location: SrcSpan {
start: 25,
end: 26,
},
type_: (),
name: "x",
},
right: Var {
location: SrcSpan {
start: 29,
end: 30,
},
type_: (),
name: "y",
},
value: "1",
int_value: 1,
},
),
},
),
then: Var {
location: SrcSpan {
start: 39,
end: 43,
right: Constant(
Int {
location: SrcSpan {
start: 34,
end: 35,
},
value: "1",
int_value: 1,
},
),
},
),
then: Var {
location: SrcSpan {
start: 39,
end: 43,
},
name: "True",
},
name: "True",
},
},
],
],
),
},
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
source: compiler-core/src/parse/tests.rs
expression: case a
---
[
Expression(
Case {
location: SrcSpan {
start: 0,
end: 6,
},
subjects: [
Var {
location: SrcSpan {
start: 5,
end: 6,
},
name: "a",
},
],
clauses: None,
},
),
]
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,4 @@ error: Syntax error
│ ^^^^ I was not expecting this

Found the keyword `type`, expected one of:
- `{`
- an expression
- `}`
Loading
Loading