Skip to content

added statement expansion to parser #7724

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

Open
wants to merge 1 commit into
base: high-level-inline-macros
Choose a base branch
from
Open
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
4 changes: 4 additions & 0 deletions crates/cairo-lang-parser/src/diagnostic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ pub enum ParserDiagnosticKind {
MissingToken(SyntaxKind),
MissingExpression,
MissingPathSegment,
MissingRepetitionOperator,
MissingTypeClause,
MissingTypeExpression,
MissingWrappedArgList,
Expand Down Expand Up @@ -150,6 +151,9 @@ impl DiagnosticEntry for ParserDiagnostic {
ParserDiagnosticKind::MissingTypeExpression => {
"Missing tokens. Expected a type expression.".to_string()
}
ParserDiagnosticKind::MissingRepetitionOperator => {
"Missing tokens. Expected an operator.".to_string()
}
ParserDiagnosticKind::MissingWrappedArgList => "Missing tokens. Expected an argument \
list wrapped in either parentheses, \
brackets, or braces."
Expand Down
121 changes: 93 additions & 28 deletions crates/cairo-lang-parser/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1503,6 +1503,38 @@ impl<'a> Parser<'a> {
}
}

/// Parses a placeholder repetition block inside a macro.
fn parse_placeholder_repetition_block(&mut self) -> TryParseResult<StatementBlockGreen> {
let dollar = self.take::<TerminalDollar>();
if self.peek().kind != SyntaxKind::TerminalLParen {
return Err(TryParseFailure::SkipToken);
}
let lparen = self.take::<TerminalLParen>();
let elements = StatementList::new_green(
self.db,
self.parse_list(
Self::try_parse_statement,
is_of_kind!(rparen, block, rbrace, module_item_kw),
"statement",
),
);
let rparen = self.parse_token::<TerminalRParen>();
let operator = match self.peek().kind {
SyntaxKind::TerminalQuestionMark => self.take::<TerminalQuestionMark>().into(),
SyntaxKind::TerminalPlus => self.take::<TerminalPlus>().into(),
SyntaxKind::TerminalMul => self.take::<TerminalMul>().into(),
_ => self
.create_and_report_missing::<TerminalPlus>(
ParserDiagnosticKind::MissingRepetitionOperator,
)
.into(),
};
let placeholder_repetition_block = PlaceholderRepetitionBlock::new_green(
self.db, dollar, lparen, elements, rparen, operator,
);
Ok(placeholder_repetition_block.into())
}

/// Returns a GreenId of a node with an
/// ExprPath|ExprFunctionCall|ExprStructCtorCall|ExprParenthesized|ExprTuple kind, or
/// TryParseFailure if such an expression can't be parsed.
Expand Down Expand Up @@ -2149,12 +2181,29 @@ impl<'a> Parser<'a> {
return ExprBlock::new_green(
self.db,
self.create_and_report_missing_terminal::<TerminalLBrace>(),
StatementList::new_green(self.db, vec![]),
StatementList::new_green(self.db, vec![]).into(),
TerminalRBrace::missing(self.db),
);
}
// Don't report diagnostic if one has already been reported.
let lbrace = self.parse_token_ex::<TerminalLBrace>(skipped_tokens.is_ok());
match self.peek().kind {
SyntaxKind::TerminalDollar => {
let placeholder_repetition_block = self.parse_placeholder_repetition_block();
match placeholder_repetition_block {
Ok(placeholder_repetition_block) => {
let rbrace = self.parse_token::<TerminalRBrace>();
ExprBlock::new_green(self.db, lbrace, placeholder_repetition_block, rbrace)
}
Err(_) => self.parse_statements_and_block(lbrace),
}
}
_ => self.parse_statements_and_block(lbrace),
}
}

/// Parses a list of statements and constructs an `ExprBlockGreen`.
fn parse_statements_and_block(&mut self, lbrace: TerminalLBraceGreen) -> ExprBlockGreen {
let statements = StatementList::new_green(
self.db,
self.parse_list(
Expand All @@ -2164,7 +2213,7 @@ impl<'a> Parser<'a> {
),
);
let rbrace = self.parse_token::<TerminalRBrace>();
ExprBlock::new_green(self.db, lbrace, statements, rbrace)
ExprBlock::new_green(self.db, lbrace, statements.into(), rbrace)
}

/// Parses an expr block, while allowing placeholder expressions. Restores the previous
Expand Down Expand Up @@ -2593,22 +2642,41 @@ impl<'a> Parser<'a> {
.into(),
)
.into()),
_ => match self.try_parse_expr() {
Ok(expr) => {
let optional_semicolon = if self.peek().kind == SyntaxKind::TerminalSemicolon {
self.take::<TerminalSemicolon>().into()
} else {
OptionTerminalSemicolonEmpty::new_green(self.db).into()
};
Ok(StatementExpr::new_green(self.db, attributes, expr, optional_semicolon)
.into())
}
Err(_) if has_attrs => Ok(self.skip_taken_node_and_return_missing::<Statement>(
SyntaxKind::TerminalLBrace => {
let expr_block = self.parse_block();
Ok(StatementExpr::new_green(
self.db,
attributes,
ParserDiagnosticKind::AttributesWithoutStatement,
)),
Err(err) => Err(err),
},
expr_block.into(),
OptionTerminalSemicolonEmpty::new_green(self.db).into(),
)
.into())
}
_ => self.parse_statement_expr(attributes, has_attrs),
}
}

/// Parses an expression and wraps it in a StatementExpr.
/// Handles optional semicolon and attributes.
fn parse_statement_expr(
&mut self,
attributes: AttributeListGreen,
has_attrs: bool,
) -> TryParseResult<StatementGreen> {
match self.try_parse_expr() {
Ok(expr) => {
let optional_semicolon = if self.peek().kind == SyntaxKind::TerminalSemicolon {
self.take::<TerminalSemicolon>().into()
} else {
OptionTerminalSemicolonEmpty::new_green(self.db).into()
};
Ok(StatementExpr::new_green(self.db, attributes, expr, optional_semicolon).into())
}
Err(_) if has_attrs => Ok(self.skip_taken_node_and_return_missing::<Statement>(
attributes,
ParserDiagnosticKind::AttributesWithoutStatement,
)),
Err(err) => Err(err),
}
}

Expand Down Expand Up @@ -2825,13 +2893,10 @@ impl<'a> Parser<'a> {
SyntaxKind::TerminalDollar => {
let dollar = self.take::<TerminalDollar>();
if !self.is_inside_macro_expansion {
self.add_diagnostic(
ParserDiagnosticKind::InvalidPlaceholderPath,
TextSpan {
start: self.offset,
end: self.offset.add_width(self.current_width),
},
)
self.add_diagnostic(ParserDiagnosticKind::InvalidPlaceholderPath, TextSpan {
start: self.offset,
end: self.offset.add_width(self.current_width),
})
};
dollar.into()
}
Expand Down Expand Up @@ -3259,10 +3324,10 @@ impl<'a> Parser<'a> {
if let (Some(diagnostic_kind), true) =
(forbid_trailing_separator, !children.is_empty())
{
self.add_diagnostic(
diagnostic_kind,
TextSpan { start: self.offset, end: self.offset },
);
self.add_diagnostic(diagnostic_kind, TextSpan {
start: self.offset,
end: self.offset,
});
}
break;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,7 @@ fn f() {
}

//! > expected_diagnostics
error: Skipped tokens. Expected: statement.
--> dummy_file.cairo:4:7
} + match x {
^
Original file line number Diff line number Diff line change
Expand Up @@ -266,3 +266,135 @@ error: Missing tokens. Expected a macro rule parameter kind.
│ │ └── semicolon (kind: TokenSemicolon): ';'
│ └── rbrace (kind: TokenRBrace): '}'
└── eof (kind: TokenEndOfFile).

//! > ==========================================================================

//! > Test macro statement expansion.

//! > test_runner_name
test_partial_parser_tree(expect_diagnostics: false)

//! > cairo_code
macro array_macro {
($($x:expr), *) => {
let mut arr = ArrayTrait::new();
{$(
arr.append($x);
) * }
arr
};
}

//! > top_level_kind

//! > ignored_kinds

//! > expected_tree
└── root (kind: SyntaxFile)
├── items (kind: ModuleItemList)
│ └── child #0 (kind: ItemMacroDeclaration)
│ ├── attributes (kind: AttributeList) []
│ ├── visibility (kind: VisibilityDefault) []
│ ├── macro_kw (kind: TokenMacro): 'macro'
│ ├── name (kind: TokenIdentifier): 'array_macro'
│ ├── lbrace (kind: TokenLBrace): '{'
│ ├── rules (kind: MacroRulesList)
│ │ └── child #0 (kind: MacroRule)
│ │ ├── lhs (kind: ParenthesizedMacroMatcher)
│ │ │ ├── lparen (kind: TokenLParen): '('
│ │ │ ├── elements (kind: MacroRuleElements)
│ │ │ │ └── child #0 (kind: MacroRepetition)
│ │ │ │ ├── dollar (kind: TokenDollar): '$'
│ │ │ │ ├── lparen (kind: TokenLParen): '('
│ │ │ │ ├── elements (kind: MacroRuleElements)
│ │ │ │ │ └── child #0 (kind: MacroRuleParam)
│ │ │ │ │ ├── dollar (kind: TokenDollar): '$'
│ │ │ │ │ ├── name (kind: TokenIdentifier): 'x'
│ │ │ │ │ ├── colon (kind: TokenColon): ':'
│ │ │ │ │ └── kind (kind: ParamExpr)
│ │ │ │ │ └── expr (kind: TokenIdentifier): 'expr'
│ │ │ │ ├── rparen (kind: TokenRParen): ')'
│ │ │ │ ├── separator (kind: TokenComma): ','
│ │ │ │ └── operator (kind: TokenMul): '*'
│ │ │ └── rparen (kind: TokenRParen): ')'
│ │ ├── fat_arrow (kind: TokenMatchArrow): '=>'
│ │ ├── rhs (kind: ExprBlock)
│ │ │ ├── lbrace (kind: TokenLBrace): '{'
│ │ │ ├── statements (kind: StatementList)
│ │ │ │ ├── child #0 (kind: StatementLet)
│ │ │ │ │ ├── attributes (kind: AttributeList) []
│ │ │ │ │ ├── let_kw (kind: TokenLet): 'let'
│ │ │ │ │ ├── pattern (kind: PatternIdentifier)
│ │ │ │ │ │ ├── modifiers (kind: ModifierList)
│ │ │ │ │ │ │ └── child #0 (kind: TokenMut): 'mut'
│ │ │ │ │ │ └── name (kind: TokenIdentifier): 'arr'
│ │ │ │ │ ├── type_clause (kind: OptionTypeClauseEmpty) []
│ │ │ │ │ ├── eq (kind: TokenEq): '='
│ │ │ │ │ ├── rhs (kind: ExprFunctionCall)
│ │ │ │ │ │ ├── path (kind: ExprPath)
│ │ │ │ │ │ │ ├── dollar (kind: OptionTerminalDollarEmpty) []
│ │ │ │ │ │ │ └── segments (kind: ExprPathInner)
│ │ │ │ │ │ │ ├── item #0 (kind: PathSegmentSimple)
│ │ │ │ │ │ │ │ └── ident (kind: TokenIdentifier): 'ArrayTrait'
│ │ │ │ │ │ │ ├── separator #0 (kind: TokenColonColon): '::'
│ │ │ │ │ │ │ └── item #1 (kind: PathSegmentSimple)
│ │ │ │ │ │ │ └── ident (kind: TokenIdentifier): 'new'
│ │ │ │ │ │ └── arguments (kind: ArgListParenthesized)
│ │ │ │ │ │ ├── lparen (kind: TokenLParen): '('
│ │ │ │ │ │ ├── arguments (kind: ArgList) []
│ │ │ │ │ │ └── rparen (kind: TokenRParen): ')'
│ │ │ │ │ └── semicolon (kind: TokenSemicolon): ';'
│ │ │ │ ├── child #1 (kind: StatementExpr)
│ │ │ │ │ ├── attributes (kind: AttributeList) []
│ │ │ │ │ ├── expr (kind: ExprBlock)
│ │ │ │ │ │ ├── lbrace (kind: TokenLBrace): '{'
│ │ │ │ │ │ ├── statements (kind: PlaceholderRepetitionBlock)
│ │ │ │ │ │ │ ├── dollar (kind: TokenDollar): '$'
│ │ │ │ │ │ │ ├── lparen (kind: TokenLParen): '('
│ │ │ │ │ │ │ ├── elements (kind: StatementList)
│ │ │ │ │ │ │ │ └── child #0 (kind: StatementExpr)
│ │ │ │ │ │ │ │ ├── attributes (kind: AttributeList) []
│ │ │ │ │ │ │ │ ├── expr (kind: ExprBinary)
│ │ │ │ │ │ │ │ │ ├── lhs (kind: ExprPath)
│ │ │ │ │ │ │ │ │ │ ├── dollar (kind: OptionTerminalDollarEmpty) []
│ │ │ │ │ │ │ │ │ │ └── segments (kind: ExprPathInner)
│ │ │ │ │ │ │ │ │ │ └── item #0 (kind: PathSegmentSimple)
│ │ │ │ │ │ │ │ │ │ └── ident (kind: TokenIdentifier): 'arr'
│ │ │ │ │ │ │ │ │ ├── op (kind: TokenDot): '.'
│ │ │ │ │ │ │ │ │ └── rhs (kind: ExprFunctionCall)
│ │ │ │ │ │ │ │ │ ├── path (kind: ExprPath)
│ │ │ │ │ │ │ │ │ │ ├── dollar (kind: OptionTerminalDollarEmpty) []
│ │ │ │ │ │ │ │ │ │ └── segments (kind: ExprPathInner)
│ │ │ │ │ │ │ │ │ │ └── item #0 (kind: PathSegmentSimple)
│ │ │ │ │ │ │ │ │ │ └── ident (kind: TokenIdentifier): 'append'
│ │ │ │ │ │ │ │ │ └── arguments (kind: ArgListParenthesized)
│ │ │ │ │ │ │ │ │ ├── lparen (kind: TokenLParen): '('
│ │ │ │ │ │ │ │ │ ├── arguments (kind: ArgList)
│ │ │ │ │ │ │ │ │ │ └── item #0 (kind: Arg)
│ │ │ │ │ │ │ │ │ │ ├── modifiers (kind: ModifierList) []
│ │ │ │ │ │ │ │ │ │ └── arg_clause (kind: ArgClauseUnnamed)
│ │ │ │ │ │ │ │ │ │ └── value (kind: ExprPath)
│ │ │ │ │ │ │ │ │ │ ├── dollar (kind: TokenDollar): '$'
│ │ │ │ │ │ │ │ │ │ └── segments (kind: ExprPathInner)
│ │ │ │ │ │ │ │ │ │ └── item #0 (kind: PathSegmentSimple)
│ │ │ │ │ │ │ │ │ │ └── ident (kind: TokenIdentifier): 'x'
│ │ │ │ │ │ │ │ │ └── rparen (kind: TokenRParen): ')'
│ │ │ │ │ │ │ │ └── semicolon (kind: TokenSemicolon): ';'
│ │ │ │ │ │ │ ├── rparen (kind: TokenRParen): ')'
│ │ │ │ │ │ │ └── operator (kind: TokenMul): '*'
│ │ │ │ │ │ └── rbrace (kind: TokenRBrace): '}'
│ │ │ │ │ └── semicolon (kind: OptionTerminalSemicolonEmpty) []
│ │ │ │ └── child #2 (kind: StatementExpr)
│ │ │ │ ├── attributes (kind: AttributeList) []
│ │ │ │ ├── expr (kind: ExprPath)
│ │ │ │ │ ├── dollar (kind: OptionTerminalDollarEmpty) []
│ │ │ │ │ └── segments (kind: ExprPathInner)
│ │ │ │ │ └── item #0 (kind: PathSegmentSimple)
│ │ │ │ │ └── ident (kind: TokenIdentifier): 'arr'
│ │ │ │ └── semicolon (kind: OptionTerminalSemicolonEmpty) []
│ │ │ └── rbrace (kind: TokenRBrace): '}'
│ │ └── semicolon (kind: TokenSemicolon): ';'
│ └── rbrace (kind: TokenRBrace): '}'
└── eof (kind: TokenEndOfFile).

//! > expected_diagnostics
Loading
Loading