Fix %== parsing in hack pipes (#13536)

* Fix `%==` parsing in hack pipes

* Use custom token type

* Update packages/babel-parser/src/parser/expression.js

Co-authored-by: Huáng Jùnliàng <jlhwung@gmail.com>

* Apply suggestions from code review

Co-authored-by: J. S. Choi <jschoi@jschoi.org>

Co-authored-by: Huáng Jùnliàng <jlhwung@gmail.com>
Co-authored-by: J. S. Choi <jschoi@jschoi.org>
This commit is contained in:
Nicolò Ribaudo 2021-07-20 16:40:31 +02:00
parent 35e4e1f067
commit ff287ac5a5
3 changed files with 24 additions and 1 deletions

View File

@ -1227,6 +1227,26 @@ export default class ExpressionParser extends LValParser {
return node;
}
case tt.moduloAssign:
if (
this.getPluginOption("pipelineOperator", "proposal") === "hack" &&
this.getPluginOption("pipelineOperator", "topicToken") === "%"
) {
// If we find %= in an expression position, and the Hack-pipes proposal is active,
// then the % could be the topic token (e.g., in x |> %==y or x |> %===y), and so we
// reparse it as %.
// The next readToken() call will start parsing from =.
this.state.value = "%";
this.state.type = tt.modulo;
this.state.pos--;
this.state.end--;
this.state.endLoc.column--;
} else {
throw this.unexpected();
}
// falls through
case tt.modulo:
case tt.hash: {
const pipeProposal = this.getPluginOption(

View File

@ -615,7 +615,7 @@ export default class Tokenizer extends ParserErrors {
if (next === charCodes.equalsTo && !this.state.inType) {
width++;
type = tt.assign;
type = code === charCodes.percentSign ? tt.moduloAssign : tt.assign;
}
this.finishOp(type, width);

View File

@ -140,6 +140,9 @@ export const types: { [name: string]: TokenType } = {
eq: new TokenType("=", { beforeExpr, isAssign }),
assign: new TokenType("_=", { beforeExpr, isAssign }),
slashAssign: new TokenType("_=", { beforeExpr, isAssign }),
// This is only needed to support % as a Hack-pipe topic token. If the proposal
// ends up choosing a different token, it can be merged with tt.assign.
moduloAssign: new TokenType("_=", { beforeExpr, isAssign }),
incDec: new TokenType("++/--", { prefix, postfix, startsExpr }),
bang: new TokenType("!", { beforeExpr, prefix, startsExpr }),
tilde: new TokenType("~", { beforeExpr, prefix, startsExpr }),