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

More parser error recovery, unlocking completions in more locations #1987

Merged
merged 1 commit into from
Oct 31, 2024
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
2 changes: 1 addition & 1 deletion compiler/qsc_frontend/src/typeck/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4555,7 +4555,7 @@ fn expr_incomplete_field_access_no_semi() {
&expect![[r##"
#14 55-57 "()" : Unit
#18 65-99 "{\n (new B { C = 5 }).\n }" : ?
#20 75-93 "(new B { C = 5 })." : ?
#20 75-98 "(new B { C = 5 }).\n " : ?
#21 75-92 "(new B { C = 5 })" : UDT<"B": Item 1>
#22 76-91 "new B { C = 5 }" : UDT<"B": Item 1>
#27 88-89 "5" : Int
Expand Down
34 changes: 15 additions & 19 deletions compiler/qsc_parse/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ use crate::{
ClosedBinOp, Delim, InterpolatedEnding, InterpolatedStart, Radix, StringToken, Token,
TokenKind,
},
prim::{ident, opt, pat, recovering_path, recovering_token, seq, shorten, token},
prim::{
ident, opt, parse_or_else, pat, recovering_parse_or_else, recovering_path, seq, shorten,
token,
},
scan::ParserContext,
stmt, Error, ErrorKind, Result,
};
Expand Down Expand Up @@ -247,22 +250,23 @@ fn expr_base(s: &mut ParserContext) -> Result<Box<Expr>> {
fn recovering_struct(s: &mut ParserContext) -> Result<Box<ExprKind>> {
let name = recovering_path(s, WordKinds::PathStruct)?;

if let Err(e) = token(s, TokenKind::Open(Delim::Brace)) {
s.push_error(e);
return Ok(Box::new(ExprKind::Struct(name, None, Box::new([]))));
}
let (copy, fields) = recovering_parse_or_else(
s,
|_| (None, Box::new([])),
&[TokenKind::Close(Delim::Brace)],
struct_fields,
);

let (copy, fields) = struct_fields(s)?;
recovering_token(s, TokenKind::Close(Delim::Brace));
Ok(Box::new(ExprKind::Struct(name, copy, fields)))
}

/// A sequence of field assignments and an optional base expression,
/// e.g. `...a, b = c, d = e`
/// e.g. `{ ...a, b = c, d = e }`
#[allow(clippy::type_complexity)]
fn struct_fields(
s: &mut ParserContext<'_>,
) -> Result<(Option<Box<Expr>>, Box<[Box<FieldAssign>]>)> {
token(s, TokenKind::Open(Delim::Brace))?;
let copy: Option<Box<Expr>> = opt(s, |s| {
token(s, TokenKind::DotDotDot)?;
expr(s)
Expand All @@ -271,6 +275,7 @@ fn struct_fields(
if copy.is_none() || copy.is_some() && token(s, TokenKind::Comma).is_ok() {
(fields, _) = seq(s, parse_field_assign)?;
}
token(s, TokenKind::Close(Delim::Brace))?;
Ok((copy, fields.into_boxed_slice()))
}

Expand Down Expand Up @@ -714,17 +719,8 @@ fn lambda_op(s: &mut ParserContext, input: Expr, kind: CallableKind) -> Result<B
#[allow(clippy::unnecessary_wraps)]
fn recovering_field_op(s: &mut ParserContext, lhs: Box<Expr>) -> Result<Box<ExprKind>> {
s.expect(WordKinds::Field);
let expr = ExprKind::Field(
lhs,
match ident(s) {
Ok(i) => FieldAccess::Ok(i),
Err(e) => {
s.push_error(e);
FieldAccess::Err
}
},
);
Ok(Box::new(expr))
let field_access = parse_or_else(s, |_| FieldAccess::Err, |s| Ok(FieldAccess::Ok(ident(s)?)))?;
Ok(Box::new(ExprKind::Field(lhs, field_access)))
}

fn index_op(s: &mut ParserContext, lhs: Box<Expr>) -> Result<Box<ExprKind>> {
Expand Down
83 changes: 67 additions & 16 deletions compiler/qsc_parse/src/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,26 @@ use super::{
prim::{ident, many, opt, pat, seq, token},
scan::ParserContext,
stmt,
ty::{self, ty},
ty::{self, recovering_ty, ty},
Error, Result,
};

use crate::{
completion::WordKinds,
lex::{ClosedBinOp, Delim, TokenKind},
prim::{
barrier, path, recovering, recovering_path, recovering_semi, recovering_token, shorten,
barrier, parse_or_else, path, recovering, recovering_path, recovering_semi,
recovering_token, shorten,
},
stmt::check_semis,
ty::array_or_arrow,
ErrorKind,
};
use qsc_ast::ast::{
Attr, Block, CallableBody, CallableDecl, CallableKind, FieldDef, Ident, Idents,
Attr, Block, CallableBody, CallableDecl, CallableKind, FieldDef, FunctorExpr, Ident, Idents,
ImportOrExportDecl, ImportOrExportItem, Item, ItemKind, Namespace, NodeId, Pat, PatKind, Path,
PathKind, Spec, SpecBody, SpecDecl, SpecGen, StmtKind, StructDecl, TopLevelNode, Ty, TyDef,
TyDefKind, TyKind,
PathKind, Spec, SpecBody, SpecDecl, SpecGen, Stmt, StmtKind, StructDecl, TopLevelNode, Ty,
TyDef, TyDefKind, TyKind,
};
use qsc_data_structures::language_features::LanguageFeatures;
use qsc_data_structures::span::Span;
Expand Down Expand Up @@ -118,7 +119,23 @@ pub(super) fn parse_namespaces(s: &mut ParserContext) -> Result<Vec<Namespace>>
}

pub(super) fn parse_top_level_nodes(s: &mut ParserContext) -> Result<Vec<TopLevelNode>> {
let nodes = many(s, parse_top_level_node)?;
const RECOVERY_TOKENS: &[TokenKind] = &[TokenKind::Semi, TokenKind::Close(Delim::Brace)];
let nodes = {
many(s, |s| {
recovering(
s,
|span| {
TopLevelNode::Stmt(Box::new(Stmt {
id: NodeId::default(),
span,
kind: Box::new(StmtKind::Err),
}))
},
RECOVERY_TOKENS,
parse_top_level_node,
)
})
}?;
recovering_token(s, TokenKind::Eof);
Ok(nodes)
}
Expand Down Expand Up @@ -498,16 +515,35 @@ fn parse_callable_decl(s: &mut ParserContext) -> Result<Box<CallableDecl>> {

let input = pat(s)?;
check_input_parens(&input)?;
token(s, TokenKind::Colon)?;
throw_away_doc(s);
let output = ty(s)?;
let functors = if token(s, TokenKind::Keyword(Keyword::Is)).is_ok() {
Some(Box::new(ty::functor_expr(s)?))
} else {
None
};

let (output, functors) = parse_or_else(
s,
|span| {
(
Box::new(Ty {
id: NodeId::default(),
span,
kind: Box::new(TyKind::Err),
}),
None,
)
},
parse_callable_output_and_functors,
)?;

throw_away_doc(s);
let body = parse_callable_body(s)?;

let body = parse_or_else(
s,
|span| {
CallableBody::Block(Box::new(Block {
id: NodeId::default(),
span,
stmts: Box::default(),
}))
},
parse_callable_body,
)?;

Ok(Box::new(CallableDecl {
id: NodeId::default(),
Expand All @@ -516,12 +552,27 @@ fn parse_callable_decl(s: &mut ParserContext) -> Result<Box<CallableDecl>> {
name,
generics: generics.into_boxed_slice(),
input,
output: Box::new(output),
output,
functors,
body: Box::new(body),
}))
}

/// The output and functors part of the callable signature, e.g. `: Unit is Adj`
fn parse_callable_output_and_functors(
s: &mut ParserContext,
) -> Result<(Box<Ty>, Option<Box<FunctorExpr>>)> {
token(s, TokenKind::Colon)?;
throw_away_doc(s);
let output = recovering_ty(s)?;
let functors = if token(s, TokenKind::Keyword(Keyword::Is)).is_ok() {
Some(Box::new(ty::functor_expr(s)?))
} else {
None
};
Ok((output.into(), functors))
}

fn parse_callable_body(s: &mut ParserContext) -> Result<CallableBody> {
let lo = s.peek().span.lo;
token(s, TokenKind::Open(Delim::Brace))?;
Expand Down
152 changes: 139 additions & 13 deletions compiler/qsc_parse/src/item/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

use super::{
parse, parse_attr, parse_implicit_namespace, parse_import_or_export, parse_open,
parse_spec_decl,
parse_spec_decl, parse_top_level_nodes,
};
use crate::{
scan::ParserContext,
Expand Down Expand Up @@ -927,19 +927,28 @@ fn function_missing_output_ty() {
parse,
"function Foo() { body intrinsic; }",
&expect![[r#"
Error(
Token(
Colon,
Open(
Brace,
Item _id_ [0-34]:
Callable _id_ [0-34] (Function):
name: Ident _id_ [9-12] "Foo"
input: Pat _id_ [12-14]: Unit
output: Type _id_ [15-15]: Err
body: Specializations:
SpecDecl _id_ [17-32] (Body): Gen: Intrinsic

[
Error(
Token(
Colon,
Open(
Brace,
),
Span {
lo: 15,
hi: 16,
},
),
Span {
lo: 15,
hi: 16,
},
),
)
"#]],
]"#]],
);
}

Expand Down Expand Up @@ -1405,7 +1414,12 @@ fn recover_callable_item() {
body: Block: Block _id_ [47-52]:
Stmt _id_ [49-50]: Expr: Expr _id_ [49-50]: Lit: Int(5)
Item _id_ [65-86]:
Err
Callable _id_ [65-86] (Function):
name: Ident _id_ [74-77] "Bar"
input: Pat _id_ [77-79]: Unit
output: Type _id_ [80-80]: Err
body: Block: Block _id_ [80-86]:
Stmt _id_ [82-84]: Expr: Expr _id_ [82-84]: Lit: Int(10)
Item _id_ [99-131]:
Callable _id_ [99-131] (Operation):
name: Ident _id_ [109-112] "Baz"
Expand Down Expand Up @@ -2252,3 +2266,115 @@ fn missing_semi_between_items() {
]"#]],
);
}

#[test]
fn callable_decl_no_return_type_or_body_recovery() {
check(
parse,
"operation Foo<'T>() : ",
&expect![[r#"
Item _id_ [0-22]:
Callable _id_ [0-22] (Operation):
name: Ident _id_ [10-13] "Foo"
generics:
Ident _id_ [14-16] "'T"
input: Pat _id_ [17-19]: Unit
output: Type _id_ [22-22]: Err
body: Block: Block _id_ [22-22]: <empty>

[
Error(
Rule(
"type",
Eof,
Span {
lo: 22,
hi: 22,
},
),
),
]"#]],
);
}

#[test]
fn callable_decl_broken_return_type_no_body_recovery() {
check(
parse,
"operation Foo<'T>() : () => ",
&expect![[r#"
Item _id_ [0-28]:
Callable _id_ [0-28] (Operation):
name: Ident _id_ [10-13] "Foo"
generics:
Ident _id_ [14-16] "'T"
input: Pat _id_ [17-19]: Unit
output: Type _id_ [22-28]: Arrow (Operation):
param: Type _id_ [22-24]: Unit
return: Type _id_ [28-28]: Err
body: Block: Block _id_ [28-28]: <empty>

[
Error(
Rule(
"type",
Eof,
Span {
lo: 28,
hi: 28,
},
),
),
]"#]],
);
}

#[test]
fn top_level_nodes() {
check_vec(
parse_top_level_nodes,
"function Foo() : Unit { body intrinsic; } let x = 5;",
&expect![[r#"
Stmt _id_ [0-41]: Item: Item _id_ [0-41]:
Callable _id_ [0-41] (Function):
name: Ident _id_ [9-12] "Foo"
input: Pat _id_ [12-14]: Unit
output: Type _id_ [17-21]: Path: Path _id_ [17-21] (Ident _id_ [17-21] "Unit")
body: Specializations:
SpecDecl _id_ [24-39] (Body): Gen: Intrinsic,
Stmt _id_ [42-52]: Local (Immutable):
Pat _id_ [46-47]: Bind:
Ident _id_ [46-47] "x"
Expr _id_ [50-51]: Lit: Int(5)"#]],
);
}

#[test]
fn top_level_nodes_error_recovery() {
check_vec(
parse_top_level_nodes,
"function Foo() : Unit { body intrinsic; } 3 + ",
&expect![[r#"
Stmt _id_ [0-41]: Item: Item _id_ [0-41]:
Callable _id_ [0-41] (Function):
name: Ident _id_ [9-12] "Foo"
input: Pat _id_ [12-14]: Unit
output: Type _id_ [17-21]: Path: Path _id_ [17-21] (Ident _id_ [17-21] "Unit")
body: Specializations:
SpecDecl _id_ [24-39] (Body): Gen: Intrinsic,
Stmt _id_ [42-45]: Err

[
Error(
Rule(
"expression",
Eof,
Span {
lo: 46,
hi: 46,
},
),
),
]"#]],
);
}
Loading
Loading