Skip to content
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
5 changes: 5 additions & 0 deletions compiler/src/parser_base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ export class TokenStream {
this.loopGuard = 0;
}

/** Current position in the token stream (used to detect lack of progress during error recovery) */
position(): number {
return this.pos;
}

peek(offset: number = 0): Token {
return this.tokens[this.pos + offset] ?? this.tokens[this.tokens.length - 1];
}
Expand Down
16 changes: 16 additions & 0 deletions compiler/src/parser_recovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export class RecoveringParser {
const systems: AST.SystemDeclNode[] = [];

while (!this.s.check(TokenKind.EOF)) {
const before = this.s.position();
try {
systems.push(this.parseSystemDecl());
} catch (e) {
Expand All @@ -67,6 +68,11 @@ export class RecoveringParser {
throw e;
}
}
// Guarantee forward progress: if neither parsing nor synchronization
// consumed a token, skip one to avoid an infinite recovery loop.
if (this.s.position() === before && !this.s.check(TokenKind.EOF)) {
this.s.advance();
}
}

if (systems.length === 0 && this.errors.length === 0) {
Expand Down Expand Up @@ -107,6 +113,7 @@ export class RecoveringParser {

const declarations: AST.DeclarationNode[] = [];
while (!this.s.check(TokenKind.RBrace) && !this.s.check(TokenKind.EOF)) {
const before = this.s.position();
try {
declarations.push(this.parseDeclaration());
} catch (e) {
Expand All @@ -117,6 +124,15 @@ export class RecoveringParser {
throw e;
}
}
// Guarantee forward progress to avoid an infinite recovery loop when
// synchronization lands on a token the body loop cannot consume.
if (
this.s.position() === before &&
!this.s.check(TokenKind.RBrace) &&
!this.s.check(TokenKind.EOF)
) {
this.s.advance();
}
}

this.s.expect(TokenKind.RBrace, "system body close");
Expand Down