Skip to content

Commit

Permalink
Fix indentation token lengths (#1708)
Browse files Browse the repository at this point in the history
When the dedent had some whitespace after it (not an empty line),
that whitespace was considered part of the dedent token,
causing the CST node range to be off
  • Loading branch information
aabounegm authored Oct 14, 2024
1 parent dee64f8 commit d0522c1
Showing 1 changed file with 6 additions and 14 deletions.
20 changes: 6 additions & 14 deletions packages/langium/src/parser/indentation-aware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,16 +272,7 @@ export class IndentationAwareTokenBuilder<Terminals extends string = string, Key

this.indentationStack.push(currIndentLevel);

const indentToken = this.createIndentationTokenInstance(
this.indentTokenType,
text,
match?.[0] ?? '',
offset,
);
tokens.push(indentToken);

// Token already added, let the indentation now be consumed as whitespace and ignored
return null;
return match;
}

/**
Expand Down Expand Up @@ -321,19 +312,20 @@ export class IndentationAwareTokenBuilder<Terminals extends string = string, Key
}

const numberOfDedents = this.indentationStack.length - matchIndentIndex - 1;
const newlinesBeforeDedent = text.substring(0, offset).match(/[\r\n]+$/)?.[0].length ?? 1;

for (let i = 0; i < numberOfDedents; i++) {
const token = this.createIndentationTokenInstance(
this.dedentTokenType,
text,
match?.[0] ?? '',
offset,
'', // Dedents are 0-width tokens
offset - (newlinesBeforeDedent - 1), // Place the dedent after the first new line character
);
tokens.push(token);
this.indentationStack.pop();
}

// Token already added, let the dedentation now be consumed as whitespace and ignored
// Token already added, let the dedentation now be consumed as whitespace (if any) and ignored
return null;
}

Expand Down Expand Up @@ -365,7 +357,7 @@ export class IndentationAwareTokenBuilder<Terminals extends string = string, Key
const remainingDedents: IToken[] = [];
while (this.indentationStack.length > 1) {
remainingDedents.push(
this.createIndentationTokenInstance(this.dedentTokenType, text, this.options.dedentTokenName, text.length)
this.createIndentationTokenInstance(this.dedentTokenType, text, '', text.length)
);
this.indentationStack.pop();
}
Expand Down

0 comments on commit d0522c1

Please sign in to comment.