|
| 1 | +package com.semmle.jcorn; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +import com.semmle.js.ast.AngularPipeRef; |
| 7 | +import com.semmle.js.ast.CallExpression; |
| 8 | +import com.semmle.js.ast.Expression; |
| 9 | +import com.semmle.js.ast.Identifier; |
| 10 | +import com.semmle.js.ast.Position; |
| 11 | +import com.semmle.js.ast.SourceLocation; |
| 12 | +import com.semmle.ts.ast.NonNullAssertion; |
| 13 | + |
| 14 | +/** |
| 15 | + * Parser for Angular template expressions, based on the JS parser with |
| 16 | + * modified handling of the pipe operator. |
| 17 | + */ |
| 18 | +public class AngularExpressionParser extends CustomParser { |
| 19 | + public AngularExpressionParser(Options options, String input, int startPos) { |
| 20 | + super(options, input, startPos); |
| 21 | + } |
| 22 | + |
| 23 | + @Override |
| 24 | + protected Expression buildBinary( |
| 25 | + int startPos, |
| 26 | + Position startLoc, |
| 27 | + Expression left, |
| 28 | + Expression right, |
| 29 | + String op, |
| 30 | + boolean logical) { |
| 31 | + // Angular pipe expression: `x|f:a` is desugared to `f(x, a)` |
| 32 | + if (op.equals("|")) { |
| 33 | + DestructuringErrors refDestructuringErrors = new DestructuringErrors(); |
| 34 | + List<Expression> arguments = new ArrayList<>(); |
| 35 | + arguments.add(left); |
| 36 | + while (this.type == TokenType.colon) { |
| 37 | + this.next(); |
| 38 | + int argStartPos = this.pos; |
| 39 | + Position argStartLocation = this.curPosition(); |
| 40 | + Expression arg = parseMaybeUnary(refDestructuringErrors, false); |
| 41 | + arguments.add(parseExprOp(arg, argStartPos, argStartLocation, TokenType.plusMin.binop, true)); |
| 42 | + } |
| 43 | + SourceLocation loc = new SourceLocation(startLoc); |
| 44 | + if (right instanceof Identifier) { |
| 45 | + right = new AngularPipeRef(new SourceLocation(right.getLoc()), (Identifier)right); |
| 46 | + } |
| 47 | + return this.finishNode(new CallExpression(loc, right, new ArrayList<>(), arguments, false, false)); |
| 48 | + } |
| 49 | + return super.buildBinary(startPos, startLoc, left, right, op, logical); |
| 50 | + } |
| 51 | + |
| 52 | + @Override |
| 53 | + protected Expression parseExprAtom(DestructuringErrors refDestructuringErrors) { |
| 54 | + // Parse postfix "!" operator |
| 55 | + Position startLoc = this.startLoc; |
| 56 | + Expression expr = super.parseExprAtom(refDestructuringErrors); |
| 57 | + if (this.type == TokenType.prefix && "!".equals(this.value)) { |
| 58 | + this.next(); // consume "!" token |
| 59 | + return finishNode(new NonNullAssertion(new SourceLocation(startLoc), expr)); |
| 60 | + } |
| 61 | + return expr; |
| 62 | + } |
| 63 | +} |
0 commit comments