repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/ImportDefaultSpecifier.java
package com.semmle.js.ast; /** * A default import specifier, such as <code>f</code> in <code>import f, { x, y } from 'foo';</code> * . * * <p>Default import specifiers do not have an explicit imported name (the imported name is, * implicitly, <code>default</code>). */ public class ImportDefaultSpecifier extends ImportSpecifier { public ImportDefaultSpecifier(SourceLocation loc, Identifier local) { super("ImportDefaultSpecifier", loc, null, local); } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
566
27.35
100
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/Token.java
package com.semmle.js.ast; import static com.semmle.js.ast.Token.Type.EOF; import static com.semmle.js.ast.Token.Type.FALSE; import static com.semmle.js.ast.Token.Type.KEYWORD; import static com.semmle.js.ast.Token.Type.NAME; import static com.semmle.js.ast.Token.Type.NULL; import static com.semmle.js.ast.Token.Type.NUM; import static com.semmle.js.ast.Token.Type.PUNCTUATOR; import static com.semmle.js.ast.Token.Type.REGEXP; import static com.semmle.js.ast.Token.Type.STRING; import static com.semmle.js.ast.Token.Type.TRUE; /** * A source code token. * * <p>This is not part of the SpiderMonkey AST format. */ public class Token extends SourceElement { /** The supported token types. */ public static enum Type { EOF, NULL, TRUE, FALSE, NUM, STRING, REGEXP, NAME, KEYWORD, PUNCTUATOR }; private final Type type; private final String value; public Token(SourceLocation loc, String typename, Object keyword) { this(loc, getType(typename, keyword)); } public Token(SourceLocation loc, Type type) { super(loc); this.value = loc.getSource(); this.type = type; } private static Type getType(String typename, Object keyword) { if ("eof".equals(typename)) { return EOF; } else if ("num".equals(typename)) { return NUM; } else if ("name".equals(typename) || "jsxName".equals(typename)) { return NAME; } else if ("string".equals(typename) || "template".equals(typename) || "jsxText".equals(typename)) { return STRING; } else if ("regexp".equals(typename)) { return REGEXP; } else if ("true".equals(keyword)) { return TRUE; } else if ("false".equals(keyword)) { return FALSE; } else if ("null".equals(keyword)) { return NULL; } else if (keyword instanceof String) { return KEYWORD; } else { return PUNCTUATOR; } } /** The type of this token. */ public Type getType() { return type; } /** The source text of this token. */ public String getValue() { return value; } }
2,091
24.204819
71
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/MemberDefinition.java
package com.semmle.js.ast; import java.util.ArrayList; import java.util.List; /** * A member definition in a {@linkplain ClassBody}. * * <p>A member definition has a name and an optional initial value, whose type is given by the type * parameter {@code V}. */ public abstract class MemberDefinition<V extends Expression> extends Node { /** A bitmask of flags defined in {@linkplain DeclarationFlags}. */ private final int flags; /** * The name of the member. * * <p>If {@link #isComputed()} is false, this must be an {@link Identifier}, otherwise it can be * an arbitrary expression. */ private final Expression key; /** The initial value of the member. */ private final V value; /** The decorators applied to this member, if any. */ private final List<Decorator> decorators; public MemberDefinition(String type, SourceLocation loc, int flags, Expression key, V value) { super(type, loc); this.flags = flags; this.key = key; this.value = value; this.decorators = new ArrayList<Decorator>(); } /** Returns the flags, as defined by {@linkplain DeclarationFlags}. */ public int getFlags() { return flags; } /** Returns true if this has the <tt>static</tt> modifier. */ public boolean isStatic() { return DeclarationFlags.isStatic(flags); } /** Returns true if the member name is computed. */ public boolean isComputed() { return DeclarationFlags.isComputed(flags); } /** Returns true if this is an abstract member. */ public boolean isAbstract() { return DeclarationFlags.isAbstract(flags); } /** Returns true if has the <tt>public</tt> modifier (not true for implicitly public members). */ public boolean hasPublicKeyword() { return DeclarationFlags.isPublic(flags); } /** Returns true if this is a private member. */ public boolean hasPrivateKeyword() { return DeclarationFlags.isPrivate(flags); } /** Returns true if this is a protected member. */ public boolean hasProtectedKeyword() { return DeclarationFlags.isProtected(flags); } /** Returns true if this is a readonly member. */ public boolean hasReadonlyKeyword() { return DeclarationFlags.isReadonly(flags); } /** Returns true if this has the <tt>declare</tt> modifier. */ public boolean hasDeclareKeyword() { return DeclarationFlags.hasDeclareKeyword(flags); } /** * Returns the expression denoting the name of the member, or {@code null} if this is a * call/construct signature. */ public Expression getKey() { return key; } public V getValue() { return value; } /** The name of the method, if it can be determined. */ public String getName() { if (!isComputed() && key instanceof Identifier) return ((Identifier) key).getName(); if (key instanceof Literal) return ((Literal) key).getStringValue(); return null; } /** True if this is a constructor; does not hold for construct signatures. */ public boolean isConstructor() { return false; } /** True if this is a non-abstract field or a method with a body. */ public abstract boolean isConcrete(); public boolean isCallSignature() { return false; } public boolean isIndexSignature() { return false; } public void addDecorators(List<Decorator> decorators) { this.decorators.addAll(decorators); } public List<Decorator> getDecorators() { return this.decorators; } public boolean isParameterField() { return false; } }
3,498
25.915385
99
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/DeclarationFlags.java
package com.semmle.js.ast; import java.util.Arrays; import java.util.List; /** * Defines bitmasks where each bit corresponds to a flag on {@linkplain MemberDefinition} or * {@linkplain VariableDeclarator}. */ public class DeclarationFlags { public static final int computed = 1 << 0; public static final int abstract_ = 1 << 1; public static final int static_ = 1 << 2; public static final int readonly = 1 << 3; public static final int public_ = 1 << 4; public static final int private_ = 1 << 5; public static final int protected_ = 1 << 6; public static final int optional = 1 << 7; public static final int definiteAssignmentAssertion = 1 << 8; public static final int declareKeyword = 1 << 9; public static final int none = 0; public static final int numberOfFlags = 10; public static final List<String> names = Arrays.asList( "computed", "abstract", "static", "readonly", "public", "private", "protected", "optional", "definiteAssignmentAssertion", "declare"); public static final List<String> relationNames = Arrays.asList( "isComputed", "isAbstractMember", "isStatic", "hasReadonlyKeyword", "hasPublicKeyword", "hasPrivateKeyword", "hasProtectedKeyword", "isOptionalMember", "hasDefiniteAssignmentAssertion", "hasDeclareKeyword"); public static boolean isComputed(int flags) { return (flags & computed) != 0; } public static boolean isAbstract(int flags) { return (flags & abstract_) != 0; } public static boolean isStatic(int flags) { return (flags & static_) != 0; } public static boolean isReadonly(int flags) { return (flags & readonly) != 0; } public static boolean isPublic(int flags) { return (flags & public_) != 0; } public static boolean isPrivate(int flags) { return (flags & private_) != 0; } public static boolean isProtected(int flags) { return (flags & protected_) != 0; } public static boolean isOptional(int flags) { return (flags & optional) != 0; } public static boolean hasDefiniteAssignmentAssertion(int flags) { return (flags & definiteAssignmentAssertion) != 0; } public static boolean hasDeclareKeyword(int flags) { return (flags & declareKeyword) != 0; } /** Returns a mask with the computed bit set to the value of <tt>enable</tt>. */ public static int getComputed(boolean enable) { return enable ? computed : 0; } /** Returns a mask with the abstract bit set to the value of <tt>enable</tt>. */ public static int getAbstract(boolean enable) { return enable ? abstract_ : 0; } /** Returns a mask with the static bit set to the value of <tt>enable</tt>. */ public static int getStatic(boolean enable) { return enable ? static_ : 0; } /** Returns a mask with the public bit set to the value of <tt>enable</tt>. */ public static int getPublic(boolean enable) { return enable ? public_ : 0; } /** Returns a mask with the readonly bit set to the value of <tt>enable</tt>. */ public static int getReadonly(boolean enable) { return enable ? readonly : 0; } /** Returns a mask with the private bit set to the value of <tt>enable</tt>. */ public static int getPrivate(boolean enable) { return enable ? private_ : 0; } /** Returns a mask with the protected bit set to the value of <tt>enable</tt>. */ public static int getProtected(boolean enable) { return enable ? protected_ : 0; } /** Returns a mask with the optional bit set to the value of <tt>enable</tt>. */ public static int getOptional(boolean enable) { return enable ? optional : 0; } /** * Returns a mask with the definite assignment assertion bit set to the value of <tt>enable</tt>. */ public static int getDefiniteAssignmentAssertion(boolean enable) { return enable ? definiteAssignmentAssertion : 0; } /** Returns a mask with the declare keyword bit set to the value of <tt>enable</tt>. */ public static int getDeclareKeyword(boolean enable) { return enable ? declareKeyword : 0; } /** Returns true if the <tt>n</tt>th bit is set in <tt>flags</tt>. */ public static boolean hasNthFlag(int flags, int n) { return (flags & (1 << n)) != 0; } public static String getFlagNames(int flags) { StringBuilder b = new StringBuilder(); for (int i = 0; i < numberOfFlags; ++i) { if (hasNthFlag(flags, i)) { if (b.length() > 0) { b.append(", "); } b.append(names.get(i)); } } return b.toString(); } }
4,708
28.248447
99
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/SwitchCase.java
package com.semmle.js.ast; import java.util.List; /** A case in a switch statement; may be a default case. */ public class SwitchCase extends Statement { private final Expression test; private final List<Statement> consequent; public SwitchCase(SourceLocation loc, Expression test, List<Statement> consequent) { super("SwitchCase", loc); this.test = test; this.consequent = consequent; } @Override public <Q, A> A accept(Visitor<Q, A> v, Q q) { return v.visit(this, q); } /** Does this case have a test expression? */ public boolean hasTest() { return test != null; } /** The test expression of this case; is null for default cases. */ public Expression getTest() { return test; } /** The statements belonging to this case. */ public List<Statement> getConsequent() { return consequent; } /** Is this a default case? */ public boolean isDefault() { return !hasTest(); } }
950
22.195122
86
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/NewExpression.java
package com.semmle.js.ast; import com.semmle.ts.ast.ITypeExpression; import java.util.List; /** A <code>new</code> expression. */ public class NewExpression extends InvokeExpression { public NewExpression( SourceLocation loc, Expression callee, List<ITypeExpression> typeArguments, List<Expression> arguments) { super("NewExpression", loc, callee, typeArguments, arguments, false, false); } @Override public <Q, A> A accept(Visitor<Q, A> v, Q q) { return v.visit(this, q); } }
522
23.904762
80
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/ForInStatement.java
package com.semmle.js.ast; /** * A for-in statement such as * * <pre> * for (var p in src) * dest[p] = src[p]; * </pre> * * This also includes legacy for-each statements. */ public class ForInStatement extends EnhancedForStatement { private final boolean each; public ForInStatement( SourceLocation loc, Node left, Expression right, Statement body, Boolean each) { super("ForInStatement", loc, left, right, body); this.each = each == Boolean.TRUE; } public boolean isEach() { return each; } @Override public <Q, A> A accept(Visitor<Q, A> v, Q q) { return v.visit(this, q); } }
630
19.354839
86
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/Dot.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** An any-character wildcard. */ public class Dot extends RegExpTerm { public Dot(SourceLocation loc) { super(loc, "Dot"); } @Override public void accept(Visitor v) { v.visit(this); } }
283
16.75
40
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/CharacterClassRange.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A character range in a character class. */ public class CharacterClassRange extends RegExpTerm { private final RegExpTerm left, right; public CharacterClassRange(SourceLocation loc, RegExpTerm left, RegExpTerm right) { super(loc, "CharacterClassRange"); this.left = left; this.right = right; } @Override public void accept(Visitor v) { v.visit(this); } /** The left hand side of the character range. */ public RegExpTerm getLeft() { return left; } /** The right hand side of the character range. */ public RegExpTerm getRight() { return right; } }
681
21.733333
85
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/Visitor.java
package com.semmle.js.ast.regexp; /** Visitor interface for {@link RegExpTerm}. */ public interface Visitor { public void visit(Caret nd); public void visit(Constant nd); public void visit(Dollar nd); public void visit(Group nd); public void visit(NonWordBoundary nd); public void visit(Opt nd); public void visit(Plus nd); public void visit(Range nd); public void visit(Sequence nd); public void visit(Star nd); public void visit(WordBoundary nd); public void visit(Disjunction nd); public void visit(ZeroWidthPositiveLookahead nd); public void visit(ZeroWidthNegativeLookahead nd); public void visit(Dot nd); public void visit(DecimalEscape nd); public void visit(HexEscapeSequence nd); public void visit(OctalEscape nd); public void visit(UnicodeEscapeSequence nd); public void visit(BackReference nd); public void visit(ControlEscape nd); public void visit(IdentityEscape nd); public void visit(ControlLetter nd); public void visit(CharacterClassEscape nd); public void visit(CharacterClass nd); public void visit(CharacterClassRange nd); public void visit(NamedBackReference nd); public void visit(ZeroWidthPositiveLookbehind nd); public void visit(ZeroWidthNegativeLookbehind nd); public void visit(UnicodePropertyEscape nd); }
1,324
19.384615
52
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/package-info.java
/** * This package contains a Java implementation of the esregex AST format. * * <p>The root of the AST class hierarchy is {@link com.semmle.js.ast.regexp.RegExpTerm}, which in * turn extends {@link com.semmle.js.ast.SourceElement}. * * <p>Nodes accept visitors implementing interface {@link com.semmle.js.ast.regexp.Visitor}. */ package com.semmle.js.ast.regexp;
371
36.2
98
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/Dollar.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** An end-of-line assertion. */ public class Dollar extends RegExpTerm { public Dollar(SourceLocation loc) { super(loc, "Dollar"); } @Override public void accept(Visitor v) { v.visit(this); } }
291
17.25
40
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/Plus.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A non-empty repetition quantifier such as <code>a+</code>. */ public class Plus extends Quantifier { public Plus(SourceLocation loc, RegExpTerm operand, Boolean greedy) { super(loc, "Plus", operand, greedy); } @Override public void accept(Visitor v) { v.visit(this); } }
371
22.25
71
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/Range.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A range quantifier. */ public class Range extends Quantifier { private final Long lowerBound, upperBound; public Range(SourceLocation loc, RegExpTerm operand, Boolean greedy, Double lo, Double hi) { super(loc, "Range", operand, greedy); this.lowerBound = lo.longValue(); this.upperBound = hi == null ? null : hi.longValue(); } @Override public void accept(Visitor v) { v.visit(this); } /** Get the lower bound of this quantifier. */ public Long getLowerBound() { return lowerBound; } /** Does this range quantifier have an upper bound? */ public boolean hasUpperBound() { return upperBound != null; } /** The upper bound of this quantifier; may be null. */ public Long getUpperBound() { return upperBound; } }
854
23.428571
94
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/NonWordBoundary.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A non-word boundary assertion <code>\B</code>. */ public class NonWordBoundary extends RegExpTerm { public NonWordBoundary(SourceLocation loc) { super(loc, "NonWordBoundary"); } @Override public void accept(Visitor v) { v.visit(this); } }
339
20.25
53
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/Group.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A parenthesized group in a regular expression. */ public class Group extends RegExpTerm { private final boolean capture; private final int number; private final String name; private final RegExpTerm operand; public Group( SourceLocation loc, boolean capture, Number number, String name, RegExpTerm operand) { super(loc, "Group"); this.capture = capture; this.number = number.intValue(); this.name = name; this.operand = operand; } @Override public void accept(Visitor v) { v.visit(this); } /** Is this a capture group? */ public boolean isCapture() { return capture; } /** Get the index of this group. */ public int getNumber() { return number; } /** Is this a named captured group? */ public boolean isNamed() { return name != null; } /** Get the name of this group, if any. */ public String getName() { return name; } /** Get the term inside the group. */ public RegExpTerm getOperand() { return operand; } }
1,097
20.529412
92
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/IdentityEscape.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** An identity escape sequence. */ public class IdentityEscape extends EscapeSequence { public IdentityEscape(SourceLocation loc, String value, Number codepoint, String raw) { super(loc, "IdentityEscape", value, codepoint, raw); } @Override public void accept(Visitor v) { v.visit(this); } }
389
23.375
89
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/UnicodePropertyEscape.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A Unicode property escape such as <code>\p{Number}</code> or <code>\p{Script=Greek}</code>. */ public class UnicodePropertyEscape extends RegExpTerm { private final String name, value, raw; public UnicodePropertyEscape(SourceLocation loc, String name, String value, String raw) { super(loc, "UnicodePropertyEscape"); this.name = name; this.value = value; this.raw = raw; } @Override public void accept(Visitor v) { v.visit(this); } /** The name of the property. */ public String getName() { return name; } /** Does this property have a value? */ public boolean hasValue() { return value != null; } /** The value of the property if any. */ public String getValue() { return value; } /** The source text of the Unicode property escape. */ public String getRaw() { return raw; } }
937
21.878049
98
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/ControlEscape.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A control character escape. */ public class ControlEscape extends EscapeSequence { public ControlEscape(SourceLocation loc, String value, Number codepoint, String raw) { super(loc, "ControlEscape", value, codepoint, raw); } @Override public void accept(Visitor v) { v.visit(this); } }
385
23.125
88
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/Opt.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** An optional quantifier such as <code>s?</code>. */ public class Opt extends Quantifier { public Opt(SourceLocation loc, RegExpTerm operand, Boolean greedy) { super(loc, "Opt", operand, greedy); } @Override public void accept(Visitor v) { v.visit(this); } }
357
21.375
70
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/Quantifier.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A quantifier, that is, one of {@link Opt}, {@link Plus}, {@link Star} or {@link Range}. */ public abstract class Quantifier extends RegExpTerm { private final RegExpTerm operand; private final boolean greedy; public Quantifier(SourceLocation loc, String type, RegExpTerm operand, Boolean greedy) { super(loc, type); this.operand = operand; this.greedy = greedy == Boolean.TRUE; } /** The quantified term. */ public RegExpTerm getOperand() { return operand; } /** Is this a greedy quantifier? */ public boolean isGreedy() { return greedy; } }
666
24.653846
94
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/CharacterClassEscape.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A shorthand character class escape such as <code>\w</code> or <code>\S</code>. */ public class CharacterClassEscape extends RegExpTerm { private final String classIdentifier, raw; public CharacterClassEscape(SourceLocation loc, String classIdentifier, String raw) { super(loc, "CharacterClassEscape"); this.classIdentifier = classIdentifier; this.raw = raw; } @Override public void accept(Visitor v) { v.visit(this); } /** The character class identifier. */ public String getClassIdentifier() { return classIdentifier; } /** The source text of the character class escape. */ public String getRaw() { return raw; } }
749
24
87
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/Literal.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A regular expression subterm representing a literal string. */ public abstract class Literal extends RegExpTerm { private final String value; public Literal(SourceLocation loc, String type, String value) { super(loc, type); this.value = value; } /** The represented string. */ public String getValue() { return value; } }
429
21.631579
66
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/EscapeSequence.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** An escape sequence representing a single character. */ public abstract class EscapeSequence extends Literal { private final String raw; private final int codepoint; public EscapeSequence( SourceLocation loc, String type, String value, Number codepoint, String raw) { super(loc, type, value); this.codepoint = codepoint.intValue(); this.raw = raw; } /** The code point of the represented character. */ public int getCodepoint() { return codepoint; } /** The source text of the escape sequence. */ public String getRaw() { return raw; } }
667
23.740741
84
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/Caret.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A start-of-line assertion. */ public class Caret extends RegExpTerm { public Caret(SourceLocation loc) { super(loc, "Caret"); } @Override public void accept(Visitor v) { v.visit(this); } }
289
17.125
40
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/Constant.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A constant character. */ public class Constant extends Literal { public Constant(SourceLocation loc, String value) { super(loc, "Constant", value); } @Override public void accept(Visitor v) { v.visit(this); } }
311
18.5
53
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/OctalEscape.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** An octal character escape sequence. */ public class OctalEscape extends EscapeSequence { public OctalEscape(SourceLocation loc, String value, Double codepoint, String raw) { super(loc, "OctalEscape", value, codepoint, raw); } @Override public void accept(Visitor v) { v.visit(this); } }
387
23.25
86
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/ZeroWidthNegativeLookahead.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A zero-width negative lookahead assertion of the form <code>(?!p)</code>. */ public class ZeroWidthNegativeLookahead extends RegExpTerm { private final RegExpTerm operand; public ZeroWidthNegativeLookahead(SourceLocation loc, RegExpTerm operand) { super(loc, "ZeroWidthNegativeLookahead"); this.operand = operand; } @Override public void accept(Visitor v) { v.visit(this); } /** The operand of this negative lookahead assertion. */ public RegExpTerm getOperand() { return operand; } }
603
24.166667
80
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/Sequence.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; import java.util.List; /** A sequence of regular expression terms. */ public class Sequence extends RegExpTerm { private final List<RegExpTerm> elements; public Sequence(SourceLocation loc, List<RegExpTerm> elements) { super(loc, "Sequence"); this.elements = elements; } @Override public void accept(Visitor v) { v.visit(this); } /** The individual elements of this sequence. */ public List<RegExpTerm> getElements() { return elements; } }
554
21.2
66
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/HexEscapeSequence.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A hexadecimal character escape sequence. */ public class HexEscapeSequence extends EscapeSequence { public HexEscapeSequence(SourceLocation loc, String value, Double codepoint, String raw) { super(loc, "HexEscapeSequence", value, codepoint, raw); } @Override public void accept(Visitor v) { v.visit(this); } }
410
24.6875
92
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/CharacterClass.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; import java.util.List; /** A character class. */ public class CharacterClass extends RegExpTerm { private final List<RegExpTerm> elements; private final boolean inverted; public CharacterClass(SourceLocation loc, List<RegExpTerm> elements, Boolean inverted) { super(loc, "CharacterClass"); this.elements = elements; this.inverted = inverted == Boolean.TRUE; } @Override public void accept(Visitor v) { v.visit(this); } /** The elements of this character class. */ public List<RegExpTerm> getElements() { return elements; } /** Is this an inverted character class? */ public boolean isInverted() { return inverted; } }
749
22.4375
90
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/RegExpTerm.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceElement; import com.semmle.js.ast.SourceLocation; /** Common superclass of all regular expression AST nodes. */ public abstract class RegExpTerm extends SourceElement { private final String type; public RegExpTerm(SourceLocation loc, String type) { super(loc); this.type = type; } /** Accept a visitor object. */ public abstract void accept(Visitor v); /** The type of this regular expression AST node. */ public String getType() { return type; } }
547
22.826087
61
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/Error.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceElement; import com.semmle.js.ast.SourceLocation; /** An error encountered while parsing a regular expression. */ public class Error extends SourceElement { public static final int UNEXPECTED_EOS = 0; public static final int UNEXPECTED_CHARACTER = 1; public static final int EXPECTED_DIGIT = 2; public static final int EXPECTED_HEX_DIGIT = 3; public static final int EXPECTED_CONTROL_LETTER = 4; public static final int EXPECTED_CLOSING_PAREN = 5; public static final int EXPECTED_CLOSING_BRACE = 6; public static final int EXPECTED_EOS = 7; public static final int OCTAL_ESCAPE = 8; public static final int INVALID_BACKREF = 9; public static final int EXPECTED_RBRACKET = 10; public static final int EXPECTED_IDENTIFIER = 11; public static final int EXPECTED_CLOSING_ANGLE = 12; private final int code; public Error(SourceLocation loc, Number code) { super(loc); this.code = code.intValue(); } /** The error code. */ public int getCode() { return code; } }
1,078
30.735294
63
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/ControlLetter.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A control letter escape. */ public class ControlLetter extends EscapeSequence { public ControlLetter(SourceLocation loc, String value, Number codepoint, String raw) { super(loc, "ControlLetter", value, codepoint, raw); } @Override public void accept(Visitor v) { v.visit(this); } }
382
22.9375
88
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/ZeroWidthPositiveLookbehind.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A zero-width positive lookbehind assertion of the form <code>(?&lt;=p)</code>. */ public class ZeroWidthPositiveLookbehind extends RegExpTerm { private final RegExpTerm operand; public ZeroWidthPositiveLookbehind(SourceLocation loc, RegExpTerm operand) { super(loc, "ZeroWidthPositiveLookbehind"); this.operand = operand; } @Override public void accept(Visitor v) { v.visit(this); } /** The operand of this negative lookbehind assertion. */ public RegExpTerm getOperand() { return operand; } }
612
24.541667
85
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/Star.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A possibly empty repetition. */ public class Star extends Quantifier { public Star(SourceLocation loc, RegExpTerm operand, Boolean greedy) { super(loc, "Star", operand, greedy); } @Override public void accept(Visitor v) { v.visit(this); } }
341
20.375
71
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/NamedBackReference.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A back reference to a named capture group. */ public class NamedBackReference extends RegExpTerm { private final String name; private final String raw; public NamedBackReference(SourceLocation loc, String name, String raw) { super(loc, "NamedBackReference"); this.name = name; this.raw = raw; } @Override public void accept(Visitor v) { v.visit(this); } /** The name of the capture group referenced. */ public String getName() { return name; } /** The source text of the back reference. */ public String getRaw() { return raw; } }
666
20.516129
74
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/WordBoundary.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A word-boundary assertion <code>\b</code>. */ public class WordBoundary extends RegExpTerm { public WordBoundary(SourceLocation loc) { super(loc, "WordBoundary"); } @Override public void accept(Visitor v) { v.visit(this); } }
326
19.4375
49
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/BackReference.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A back reference to a capture group. */ public class BackReference extends RegExpTerm { private final Long value; private final String raw; public BackReference(SourceLocation loc, Double value, String raw) { super(loc, "BackReference"); this.value = value.longValue(); this.raw = raw; } @Override public void accept(Visitor v) { v.visit(this); } /** The number of the capture group referenced. */ public Long getValue() { return value; } /** The source text of the back reference. */ public String getRaw() { return raw; } }
661
20.354839
70
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/UnicodeEscapeSequence.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A Unicode escape sequence. */ public class UnicodeEscapeSequence extends EscapeSequence { public UnicodeEscapeSequence(SourceLocation loc, String value, Double codepoint, String raw) { super(loc, "UnicodeEscapeSequence", value, codepoint, raw); } @Override public void accept(Visitor v) { v.visit(this); } }
408
24.5625
96
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/Disjunction.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; import java.util.List; /** A disjunctive pattern. */ public class Disjunction extends RegExpTerm { private final List<RegExpTerm> disjuncts; public Disjunction(SourceLocation loc, List<RegExpTerm> disjuncts) { super(loc, "Disjunction"); this.disjuncts = disjuncts; } @Override public void accept(Visitor v) { v.visit(this); } /** The individual elements of the disjunction. */ public List<RegExpTerm> getDisjuncts() { return disjuncts; } }
554
21.2
70
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/ZeroWidthNegativeLookbehind.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A zero-width negative lookbehind assertion of the form <code>(?&lt;!p)</code>. */ public class ZeroWidthNegativeLookbehind extends RegExpTerm { private final RegExpTerm operand; public ZeroWidthNegativeLookbehind(SourceLocation loc, RegExpTerm operand) { super(loc, "ZeroWidthNegativeLookbehind"); this.operand = operand; } @Override public void accept(Visitor v) { v.visit(this); } /** The operand of this negative lookbehind assertion. */ public RegExpTerm getOperand() { return operand; } }
612
24.541667
85
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/DecimalEscape.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A decimal escape sequence. */ public class DecimalEscape extends EscapeSequence { public DecimalEscape(SourceLocation loc, String value, Double codepoint, String raw) { super(loc, "DecimalEscape", value, codepoint, raw); } @Override public void accept(Visitor v) { v.visit(this); } }
384
23.0625
88
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/regexp/ZeroWidthPositiveLookahead.java
package com.semmle.js.ast.regexp; import com.semmle.js.ast.SourceLocation; /** A zero-width positive lookahead assertion of the form <code>(?=p)</code>. */ public class ZeroWidthPositiveLookahead extends RegExpTerm { private final RegExpTerm operand; public ZeroWidthPositiveLookahead(SourceLocation loc, RegExpTerm operand) { super(loc, "ZeroWidthPositiveLookahead"); this.operand = operand; } @Override public void accept(Visitor v) { v.visit(this); } /** The operand of this negative lookahead assertion. */ public RegExpTerm getOperand() { return operand; } }
603
24.166667
80
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/json/JSONLiteral.java
package com.semmle.js.ast.json; import com.semmle.js.ast.SourceLocation; /** A JSON literal: one of null, true, false, a string, or a number. */ public class JSONLiteral extends JSONValue { private final Object value; private final String raw; public JSONLiteral(SourceLocation loc, Object value) { super("Literal", loc); this.value = value; this.raw = loc.getSource(); } /** The value of the literal. */ public Object getValue() { return value; } /** The value of the literal as a string. */ public String getStringValue() { return String.valueOf(value); } /** The source text of the literal. */ public String getRaw() { return raw; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } @Override public String toString() { return raw; } }
851
19.780488
71
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/json/Visitor.java
package com.semmle.js.ast.json; /** * Visitor interface for {@link JSONValue}. * * <p>Visit methods take a context argument of type {@link C} and return a result of type {@link R}. */ public interface Visitor<C, R> { public R visit(JSONObject nd, C c); public R visit(JSONArray nd, C c); public R visit(JSONLiteral nd, C c); }
340
21.733333
100
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/json/package-info.java
/** * This package contains AST classes for representing parsed JSON values. * * <p>The root of the AST class hierarchy is {@link com.semmle.js.ast.json.JSONValue}, which in turn * extends {@link com.semmle.js.ast.SourceElement}. * * <p>Nodes accept visitors implementing interface {@link com.semmle.js.ast.json.Visitor}. */ package com.semmle.js.ast.json;
364
35.5
100
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/json/JSONArray.java
package com.semmle.js.ast.json; import com.semmle.js.ast.SourceLocation; import java.util.List; /** A JSON array. */ public class JSONArray extends JSONValue { private final List<JSONValue> elements; public JSONArray(SourceLocation loc, List<JSONValue> elements) { super("Array", loc); this.elements = elements; } /** The elements of the array. */ public List<JSONValue> getElements() { return elements; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } @Override public String toString() { StringBuilder res = new StringBuilder("["); String sep = ""; for (JSONValue element : elements) { res.append(sep); res.append(element.toString()); sep = ", "; } res.append("]"); return res.toString(); } }
820
20.605263
66
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/json/JSONValue.java
package com.semmle.js.ast.json; import com.semmle.js.ast.SourceElement; import com.semmle.js.ast.SourceLocation; /** Common superclass for representing JSON values. */ public abstract class JSONValue extends SourceElement { private final String type; public JSONValue(String type, SourceLocation loc) { super(loc); this.type = type; } /** The type of the value. */ public String getType() { return type; } /** Accept a visitor object. */ public abstract <C, R> R accept(Visitor<C, R> v, C c); }
528
22
56
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/json/JSONObject.java
package com.semmle.js.ast.json; import com.semmle.js.ast.SourceLocation; import com.semmle.util.data.Pair; import java.util.List; /** A JSON object. */ public class JSONObject extends JSONValue { private final List<Pair<String, JSONValue>> properties; public JSONObject(SourceLocation loc, List<Pair<String, JSONValue>> properties) { super("Object", loc); this.properties = properties; } /** The properties of this object. */ public List<Pair<String, JSONValue>> getProperties() { return properties; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } @Override public String toString() { StringBuilder res = new StringBuilder("{"); String sep = ""; for (Pair<String, JSONValue> property : properties) { res.append(sep); res.append(property.fst()); res.append(": "); res.append(property.snd()); sep = ", "; } res.append("}"); return res.toString(); } }
987
23.097561
83
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsx/JSXSpreadAttribute.java
package com.semmle.js.ast.jsx; import com.semmle.js.ast.Expression; import com.semmle.js.ast.Node; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; public class JSXSpreadAttribute extends Node implements IJSXAttribute { private final Expression argument; public JSXSpreadAttribute(SourceLocation loc, Expression argument) { super("JSXSpreadAttribute", loc); this.argument = argument; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } public Expression getArgument() { return argument; } }
588
22.56
71
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsx/JSXBoundaryElement.java
package com.semmle.js.ast.jsx; import com.semmle.js.ast.INode; public interface JSXBoundaryElement extends INode { public IJSXName getName(); }
148
17.625
51
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsx/JSXOpeningElement.java
package com.semmle.js.ast.jsx; import com.semmle.js.ast.Node; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; import java.util.List; public class JSXOpeningElement extends Node implements JSXBoundaryElement { private final IJSXName name; private final List<IJSXAttribute> attributes; private final boolean selfClosing; public JSXOpeningElement( SourceLocation loc, IJSXName name, List<IJSXAttribute> attributes, boolean selfClosing) { super("JSXOpeningElement", loc); this.name = name; this.attributes = attributes; this.selfClosing = selfClosing; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } @Override public IJSXName getName() { return name; } public List<IJSXAttribute> getAttributes() { return attributes; } public boolean isSelfClosing() { return selfClosing; } }
912
22.410256
95
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsx/JSXMemberExpression.java
package com.semmle.js.ast.jsx; import com.semmle.js.ast.Expression; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; public class JSXMemberExpression extends Expression implements IJSXName { private final IJSXName object; private final JSXIdentifier property; public JSXMemberExpression(SourceLocation loc, IJSXName object, JSXIdentifier property) { super("JSXMemberExpression", loc); this.object = object; this.property = property; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } @Override public String getQualifiedName() { return object.getQualifiedName() + "." + property.getName(); } public IJSXName getObject() { return object; } public JSXIdentifier getName() { return property; } }
817
22.371429
91
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsx/JSXNamespacedName.java
package com.semmle.js.ast.jsx; import com.semmle.js.ast.Expression; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; public class JSXNamespacedName extends Expression implements IJSXName { private final JSXIdentifier namespace, name; public JSXNamespacedName(SourceLocation loc, JSXIdentifier namespace, JSXIdentifier name) { super("JSXNamespacedName", loc); this.namespace = namespace; this.name = name; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } @Override public String getQualifiedName() { return namespace.getName() + ":" + name.getName(); } public JSXIdentifier getNamespace() { return namespace; } public JSXIdentifier getName() { return name; } }
784
22.088235
93
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsx/IJSXAttribute.java
package com.semmle.js.ast.jsx; import com.semmle.js.ast.INode; public interface IJSXAttribute extends INode {}
113
18
47
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsx/JSXEmptyExpression.java
package com.semmle.js.ast.jsx; import com.semmle.js.ast.Node; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; public class JSXEmptyExpression extends Node implements IJSXExpression { public JSXEmptyExpression(SourceLocation loc) { super("JSXEmptyExpression", loc); } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
401
22.647059
72
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsx/JSXClosingElement.java
package com.semmle.js.ast.jsx; import com.semmle.js.ast.Node; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; public class JSXClosingElement extends Node implements JSXBoundaryElement { private final IJSXName name; public JSXClosingElement(SourceLocation loc, IJSXName name) { super("JSXClosingElement", loc); this.name = name; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } @Override public IJSXName getName() { return name; } }
535
20.44
75
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsx/JSXAttribute.java
package com.semmle.js.ast.jsx; import com.semmle.js.ast.INode; import com.semmle.js.ast.Node; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; public class JSXAttribute extends Node implements IJSXAttribute { private final IJSXName name; private final INode value; public JSXAttribute(SourceLocation loc, IJSXName name, INode value) { super("JSXAttribute", loc); this.name = name; this.value = value; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } public IJSXName getName() { return name; } public INode getValue() { return value; } }
652
20.064516
71
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsx/IJSXName.java
package com.semmle.js.ast.jsx; import com.semmle.js.ast.INode; public interface IJSXName extends INode { public String getQualifiedName(); }
145
17.25
41
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsx/JSXExpressionContainer.java
package com.semmle.js.ast.jsx; import com.semmle.js.ast.INode; import com.semmle.js.ast.Node; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; public class JSXExpressionContainer extends Node implements IJSXExpression { private final INode expression; public JSXExpressionContainer(SourceLocation loc, INode expression) { super("JSXExpressionContainer", loc); this.expression = expression; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } public INode getExpression() { return expression; } }
593
22.76
76
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsx/JSXElement.java
package com.semmle.js.ast.jsx; import com.semmle.js.ast.Expression; import com.semmle.js.ast.INode; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; import java.util.List; public class JSXElement extends Expression { private final JSXOpeningElement openingElement; private final List<INode> children; private final JSXClosingElement closingElement; public JSXElement( SourceLocation loc, JSXOpeningElement openingElement, List<INode> children, JSXClosingElement closingElement) { super("JSXElement", loc); this.openingElement = openingElement; this.children = children; this.closingElement = closingElement; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } public JSXOpeningElement getOpeningElement() { return openingElement; } public List<INode> getChildren() { return children; } public JSXClosingElement getClosingElement() { return closingElement; } }
1,011
23.095238
49
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsx/IJSXExpression.java
package com.semmle.js.ast.jsx; public interface IJSXExpression {}
67
16
34
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsx/JSXIdentifier.java
package com.semmle.js.ast.jsx; import com.semmle.js.ast.Identifier; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; public class JSXIdentifier extends Identifier implements IJSXName { public JSXIdentifier(SourceLocation loc, String name) { super(loc, name); } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } @Override public String getQualifiedName() { return getName(); } }
470
20.409091
67
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/JSDocTag.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; import java.util.List; /** A JSDoc block tag. */ public class JSDocTag extends JSDocElement { private final String title; private final String description; private final String name; private final JSDocTypeExpression type; private final List<String> errors; public JSDocTag( SourceLocation loc, String title, String description, String name, JSDocTypeExpression type, List<String> errors) { super(loc); this.title = title; this.description = description; this.name = name; this.type = type; this.errors = errors; } @Override public void accept(Visitor v) { v.visit(this); } /** The type of this tag; e.g., <code>"param"</code> for a <code>@param</code> tag. */ public String getTitle() { return title; } /** Does this tag have a description? */ public boolean hasDescription() { return description != null; } /** The description of this tag; may be null. */ public String getDescription() { return description; } /** Does this tag specify a name? */ public boolean hasName() { return name != null; } /** The name this tag refers to; null except for <code>@param</code> tags. */ public String getName() { return name; } /** The type expression this tag specifies; may be null. */ public JSDocTypeExpression getType() { return type; } /** Does this tag specify a type expression? */ public boolean hasType() { return type != null; } /** Errors encountered while parsing this tag. */ public List<String> getErrors() { return errors; } }
1,684
21.77027
88
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/Visitor.java
package com.semmle.js.ast.jsdoc; /** Interface for visitors on {@link JSDocElement}. */ public interface Visitor { public void visit(AllLiteral nd); public void visit(ArrayType nd); public void visit(JSDocComment nd); public void visit(JSDocTag nd); public void visit(NameExpression nd); public void visit(NullableLiteral nd); public void visit(NullLiteral nd); public void visit(UndefinedLiteral nd); public void visit(VoidLiteral nd); public void visit(UnionType nd); public void visit(TypeApplication nd); public void visit(FunctionType nd); public void visit(NonNullableType nd); public void visit(NullableType nd); public void visit(OptionalType nd); public void visit(RestType nd); public void visit(RecordType nd); public void visit(FieldType nd); public void visit(ParameterType nd); }
851
18.813953
54
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/package-info.java
/** * This package contains a Java implementation of the <a * href="https://github.com/Constellation/doctrine">Doctrine AST format</a>. * * <p>The root of the AST class hierarchy is {@link com.semmle.js.ast.jsdoc.JSDocElement}, which in * turn extends {@link com.semmle.js.ast.SourceElement}. * * <p>Nodes accept visitors implementing interface {@link com.semmle.js.ast.jsdoc.Visitor}. */ package com.semmle.js.ast.jsdoc;
430
38.181818
99
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/UnionType.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; import java.util.List; /** A union type expression. */ public class UnionType extends CompoundType { public UnionType(SourceLocation loc, List<JSDocTypeExpression> elements) { super("UnionType", loc, elements); } @Override public String pp() { return "(" + super.pp("|") + ")"; } @Override public void accept(Visitor v) { v.visit(this); } }
447
19.363636
76
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/NullLiteral.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; /** The null type. */ public class NullLiteral extends JSDocTypeExpression { public NullLiteral(SourceLocation loc) { super(loc, "NullLiteral"); } @Override public void accept(Visitor v) { v.visit(this); } @Override public String pp() { return "null"; } }
362
16.285714
54
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/RecordType.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; import java.util.List; /** A record type. */ public class RecordType extends JSDocTypeExpression { private final List<FieldType> fields; public RecordType(SourceLocation loc, List<FieldType> fields) { super(loc, "RecordType"); this.fields = fields; } /** The types of the fields of the record. */ public List<FieldType> getFields() { return fields; } @Override public String pp() { StringBuilder result = new StringBuilder("{"); String sep = ""; for (JSDocTypeExpression field : fields) { result.append(sep); result.append(field.pp()); sep = ", "; } result.append("}"); return result.toString(); } @Override public void accept(Visitor v) { v.visit(this); } }
821
20.631579
65
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/NonNullableType.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; /** A non-nullable type such as <code>!string</code>. */ public class NonNullableType extends UnaryTypeConstructor { public NonNullableType(SourceLocation loc, JSDocTypeExpression expression, Boolean prefix) { super(loc, "NonNullableType", expression, prefix, "!"); } @Override public void accept(Visitor v) { v.visit(this); } }
424
25.5625
94
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/UnaryTypeConstructor.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; /** * Common superclass of {@link NonNullableType}, {@link NullableType}, {@link OptionalType} and * {@link RestType}. */ public abstract class UnaryTypeConstructor extends JSDocTypeExpression { private final JSDocTypeExpression expression; private final boolean prefix; private final String operator; public UnaryTypeConstructor( SourceLocation loc, String type, JSDocTypeExpression expression, Boolean prefix, String operator) { super(loc, type); this.expression = expression; this.prefix = prefix == Boolean.TRUE; this.operator = operator; } @Override public String pp() { if (expression == null) return operator; if (prefix) return operator + expression.pp(); else return expression.pp() + operator; } /** The argument of this type constructor. */ public JSDocTypeExpression getExpression() { return expression; } /** Is this a prefix type constructor? */ public boolean isPrefix() { return prefix; } }
1,085
23.681818
95
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/RestType.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; /** A rest type expression like <code>...string</code>. */ public class RestType extends UnaryTypeConstructor { public RestType(SourceLocation loc, JSDocTypeExpression expression) { super(loc, "RestType", expression, true, "..."); } @Override public void accept(Visitor v) { v.visit(this); } }
389
23.375
71
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/VoidLiteral.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; /** The void type. */ public class VoidLiteral extends JSDocTypeExpression { public VoidLiteral(SourceLocation loc) { super(loc, "VoidLiteral"); } @Override public void accept(Visitor v) { v.visit(this); } @Override public String pp() { return "void"; } }
362
16.285714
54
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/FunctionType.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; import java.util.List; /** A function type expression. */ public class FunctionType extends JSDocTypeExpression { private final JSDocTypeExpression _this; private final boolean _new; private final List<JSDocTypeExpression> params; private final JSDocTypeExpression result; public FunctionType( SourceLocation loc, JSDocTypeExpression _this, Boolean _new, List<JSDocTypeExpression> params, JSDocTypeExpression result) { super(loc, "FunctionType"); this._this = _this; this._new = _new == Boolean.TRUE; this.params = params; this.result = result; } @Override public String pp() { StringBuilder sb = new StringBuilder(); sb.append("function ("); if (_this != null) { if (_new) { sb.append("new: "); } else { sb.append("this: "); } sb.append(_this.pp()); } for (JSDocTypeExpression param : params) { if (sb.length() > 10) sb.append(", "); sb.append(param.pp()); } sb.append(")"); if (result != null) { sb.append(": "); sb.append(result.pp()); } return sb.toString(); } @Override public void accept(Visitor v) { v.visit(this); } /** * Does this function type expression specify a receiver type, that is, a type for <code>this * </code>? */ public boolean hasThis() { return _this != null; } /** Get the receiver type for this function expression; may be null. */ public JSDocTypeExpression getThis() { return _this; } /** Is this a constructor type? */ public boolean isNew() { return _new; } /** The parameter types of the function. */ public List<JSDocTypeExpression> getParams() { return params; } /** Does this function type specify a result type? */ public boolean hasResult() { return result != null; } /** The result type of the function; may be null. */ public JSDocTypeExpression getResult() { return result; } }
2,059
20.914894
95
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/NullableLiteral.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; /** A nullable dont-care type <code>?</code>. */ public class NullableLiteral extends JSDocTypeExpression { public NullableLiteral(SourceLocation loc) { super(loc, "NullableLiteral"); } @Override public void accept(Visitor v) { v.visit(this); } @Override public String pp() { return "?"; } }
398
18
58
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/NullableType.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; /** A nullable like <code>string?</code>. */ public class NullableType extends UnaryTypeConstructor { public NullableType(SourceLocation loc, JSDocTypeExpression expression, Boolean prefix) { super(loc, "NullableType", expression, prefix, "?"); } @Override public void accept(Visitor v) { v.visit(this); } }
403
24.25
91
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/TypeApplication.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; import java.util.List; /** A type application like <code>Map.&lt;String, Object&gt;</code>. */ public class TypeApplication extends JSDocTypeExpression { private final JSDocTypeExpression expression; private final List<JSDocTypeExpression> applications; public TypeApplication( SourceLocation loc, JSDocTypeExpression expression, List<JSDocTypeExpression> applications) { super(loc, "TypeApplication"); this.expression = expression; this.applications = applications; } @Override public String pp() { StringBuilder sb = new StringBuilder(); boolean first = true; sb.append(expression.pp()); sb.append(".<"); for (JSDocTypeExpression application : applications) { if (first) first = false; else sb.append(", "); sb.append(application.pp()); } sb.append(">"); return sb.toString(); } @Override public void accept(Visitor v) { v.visit(this); } /** The type constructor being applied. */ public JSDocTypeExpression getExpression() { return expression; } /** The arguments to the type constructor. */ public List<JSDocTypeExpression> getApplications() { return applications; } }
1,268
24.38
99
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/FieldType.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; /** A field type expression describing the type of a field in a record type. */ public class FieldType extends JSDocTypeExpression { private final String key; private final JSDocTypeExpression value; public FieldType(SourceLocation loc, String key, JSDocTypeExpression value) { super(loc, "FieldType"); this.key = key; this.value = value; } /** The field name. */ public String getKey() { return key; } /** Does this field type expression specify a type for the field? */ public boolean hasValue() { return value != null; } /** Get the type expression for the field; may be null. */ public JSDocTypeExpression getValue() { return value; } @Override public String pp() { if (value != null) return key + ": " + value.pp(); else return key; } @Override public void accept(Visitor v) { v.visit(this); } }
957
21.809524
79
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/ArrayType.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; import java.util.List; /** An array type expression such as <code>[number]</code>. */ public class ArrayType extends CompoundType { public ArrayType(SourceLocation loc, List<JSDocTypeExpression> elements) { super("ArrayType", loc, elements); } @Override public String pp() { return "[" + super.pp(", ") + "]"; } @Override public void accept(Visitor v) { v.visit(this); } }
479
20.818182
76
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/NameExpression.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; /** A named JSDoc type. */ public class NameExpression extends JSDocTypeExpression { private final String name; public NameExpression(SourceLocation loc, String name) { super(loc, "NameExpression"); this.name = name; } @Override public void accept(Visitor v) { v.visit(this); } /** The type name. */ public String getName() { return name; } @Override public String pp() { return name; } }
513
16.724138
58
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/OptionalType.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; /** An optional type like <code>=number</code>. */ public class OptionalType extends UnaryTypeConstructor { public OptionalType(SourceLocation loc, JSDocTypeExpression expression) { super(loc, "OptionalType", expression, false, "="); } @Override public void accept(Visitor v) { v.visit(this); } }
392
23.5625
75
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/JSDocTypeExpression.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; /** Common superclass of all JSDoc type expressions. */ public abstract class JSDocTypeExpression extends JSDocElement { private final String type; public JSDocTypeExpression(SourceLocation loc, String type) { super(loc); this.type = type; } /** The type of the expression. */ public final String getType() { return type; } /** A pretty-printed representation of the type. */ public abstract String pp(); }
514
22.409091
64
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/ParameterType.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; /** A parameter type expression describing the type of a named function parameter. */ public class ParameterType extends JSDocTypeExpression { private final String name; private final JSDocTypeExpression expression; public ParameterType(SourceLocation loc, String name, JSDocTypeExpression expression) { super(loc, "ParameterType"); this.name = name; this.expression = expression; } /** The name of the parameter. */ public String getName() { return name; } /** The type of the parameter. */ public JSDocTypeExpression getExpression() { return expression; } @Override public String pp() { return name + ": " + expression.pp(); } @Override public void accept(Visitor v) { v.visit(this); } }
831
22.111111
89
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/JSDocComment.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.Comment; import java.util.List; /** A JSDoc comment. */ public class JSDocComment extends JSDocElement { private final Comment comment; private final String description; private final List<JSDocTag> tags; public JSDocComment(Comment comment, String description, List<JSDocTag> tags) { super(comment.getLoc()); this.comment = comment; this.description = description; this.tags = tags; } @Override public void accept(Visitor v) { v.visit(this); } /** The underlying comment. */ public Comment getComment() { return comment; } /** The description string of this JSDoc comment. */ public String getDescription() { return description; } /** The block tags in this JSDoc comment. */ public List<JSDocTag> getTags() { return tags; } }
859
21.051282
81
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/CompoundType.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; import java.util.List; /** Common superclass of {@link ArrayType} and {@link UnionType}. */ public abstract class CompoundType extends JSDocTypeExpression { private final List<JSDocTypeExpression> elements; public CompoundType(String type, SourceLocation loc, List<JSDocTypeExpression> elements) { super(loc, type); this.elements = elements; } protected String pp(String sep) { StringBuilder sb = new StringBuilder(); for (JSDocTypeExpression element : elements) { if (sb.length() > 0) sb.append(sep); sb.append(element.pp()); } return sb.toString(); } /** The element type expressions of this compound type. */ public List<JSDocTypeExpression> getElements() { return elements; } }
817
27.206897
92
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/AllLiteral.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; /** A dont-care type expression <code>*</code>. */ public class AllLiteral extends JSDocTypeExpression { public AllLiteral(SourceLocation loc) { super(loc, "AllLiteral"); } @Override public void accept(Visitor v) { v.visit(this); } @Override public String pp() { return "*"; } }
385
17.380952
53
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/UndefinedLiteral.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; /** The undefined type. */ public class UndefinedLiteral extends JSDocTypeExpression { public UndefinedLiteral(SourceLocation loc) { super(loc, "UndefinedLiteral"); } @Override public void accept(Visitor v) { v.visit(this); } @Override public String pp() { return "undefined"; } }
387
17.47619
59
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/jsdoc/JSDocElement.java
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceElement; import com.semmle.js.ast.SourceLocation; /** Common superclass of all JSDoc AST nodes. */ public abstract class JSDocElement extends SourceElement { public JSDocElement(SourceLocation loc) { super(loc); } /** Accept a visitor object. */ public abstract void accept(Visitor v); }
367
23.533333
58
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/parser/RegExpParser.java
package com.semmle.js.parser; import com.semmle.js.ast.Position; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.regexp.BackReference; import com.semmle.js.ast.regexp.Caret; import com.semmle.js.ast.regexp.CharacterClass; import com.semmle.js.ast.regexp.CharacterClassEscape; import com.semmle.js.ast.regexp.CharacterClassRange; import com.semmle.js.ast.regexp.Constant; import com.semmle.js.ast.regexp.ControlEscape; import com.semmle.js.ast.regexp.ControlLetter; import com.semmle.js.ast.regexp.DecimalEscape; import com.semmle.js.ast.regexp.Disjunction; import com.semmle.js.ast.regexp.Dollar; import com.semmle.js.ast.regexp.Dot; import com.semmle.js.ast.regexp.Error; import com.semmle.js.ast.regexp.Group; import com.semmle.js.ast.regexp.HexEscapeSequence; import com.semmle.js.ast.regexp.IdentityEscape; import com.semmle.js.ast.regexp.NamedBackReference; import com.semmle.js.ast.regexp.NonWordBoundary; import com.semmle.js.ast.regexp.OctalEscape; import com.semmle.js.ast.regexp.Opt; import com.semmle.js.ast.regexp.Plus; import com.semmle.js.ast.regexp.Range; import com.semmle.js.ast.regexp.RegExpTerm; import com.semmle.js.ast.regexp.Sequence; import com.semmle.js.ast.regexp.Star; import com.semmle.js.ast.regexp.UnicodeEscapeSequence; import com.semmle.js.ast.regexp.UnicodePropertyEscape; import com.semmle.js.ast.regexp.WordBoundary; import com.semmle.js.ast.regexp.ZeroWidthNegativeLookahead; import com.semmle.js.ast.regexp.ZeroWidthNegativeLookbehind; import com.semmle.js.ast.regexp.ZeroWidthPositiveLookahead; import com.semmle.js.ast.regexp.ZeroWidthPositiveLookbehind; import java.util.ArrayList; import java.util.List; /** A parser for ECMAScript 2018 regular expressions. */ public class RegExpParser { /** The result of a parse. */ public static class Result { /** The root of the parsed AST. */ public final RegExpTerm ast; /** A list of errors encountered during parsing. */ public final List<Error> errors; public Result(RegExpTerm ast, List<Error> errors) { this.ast = ast; this.errors = errors; } public RegExpTerm getAST() { return ast; } public List<Error> getErrors() { return errors; } } private String src; private int pos; private List<Error> errors; private List<BackReference> backrefs; private int maxbackref; /** Parse the given string as a regular expression. */ public Result parse(String src) { this.src = src; this.pos = 0; this.errors = new ArrayList<>(); this.backrefs = new ArrayList<>(); this.maxbackref = 0; RegExpTerm root = parsePattern(); for (BackReference backref : backrefs) if (backref.getValue() > maxbackref) errors.add(new Error(backref.getLoc(), Error.INVALID_BACKREF)); return new Result(root, errors); } private static String fromCodePoint(int codepoint) { if (Character.isValidCodePoint(codepoint)) return new String(Character.toChars(codepoint)); // replacement character return "\ufffd"; } private Position pos() { return new Position(1, pos, pos); } private void error(int code, int start, int end) { Position startPos, endPos; startPos = new Position(1, start, start); endPos = new Position(1, end, end); this.errors.add( new Error(new SourceLocation(inputSubstring(start, end), startPos, endPos), code)); } private void error(int code, int start) { error(code, start, start + 1); } private void error(int code) { error(code, this.pos); } private boolean atEOS() { return pos >= src.length(); } private char peekChar(boolean opt) { if (this.atEOS()) { if (!opt) this.error(Error.UNEXPECTED_EOS); return '\0'; } else { return this.src.charAt(this.pos); } } private char nextChar() { char c = peekChar(false); if (this.pos < src.length()) ++this.pos; return c; } private String readHexDigit() { char c = this.peekChar(false); if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F') { ++this.pos; return String.valueOf(c); } if (c != '\0') this.error(Error.EXPECTED_HEX_DIGIT, this.pos); return ""; } private String readHexDigits(int n) { StringBuilder res = new StringBuilder(); while (n-- > 0) { res.append(readHexDigit()); } if (res.length() == 0) return "0"; return res.toString(); } private String readDigits(boolean opt) { StringBuilder res = new StringBuilder(); for (char c = peekChar(true); c >= '0' && c <= '9'; nextChar(), c = peekChar(true)) res.append(c); if (res.length() == 0 && !opt) this.error(Error.EXPECTED_DIGIT); return res.toString(); } private Double toNumber(String s) { if (s.isEmpty()) return 0.0; return Double.valueOf(s); } private String readIdentifier() { StringBuilder res = new StringBuilder(); for (char c = peekChar(true); c != '\0' && Character.isJavaIdentifierPart(c); nextChar(), c = peekChar(true)) res.append(c); if (res.length() == 0) this.error(Error.EXPECTED_IDENTIFIER); return res.toString(); } private void expectRParen() { if (!this.match(")")) this.error(Error.EXPECTED_CLOSING_PAREN, this.pos - 1); } private void expectRBrace() { if (!this.match("}")) this.error(Error.EXPECTED_CLOSING_BRACE, this.pos - 1); } private void expectRAngle() { if (!this.match(">")) this.error(Error.EXPECTED_CLOSING_ANGLE, this.pos - 1); } private boolean lookahead(String... arguments) { for (String prefix : arguments) { if (prefix == null) { if (atEOS()) return true; } else if (inputSubstring(pos, pos + prefix.length()).equals(prefix)) { return true; } } return false; } private boolean match(String... arguments) { for (String prefix : arguments) { if (this.lookahead(prefix)) { if (prefix == null) prefix = ""; this.pos += prefix.length(); return true; } } return false; } private RegExpTerm parsePattern() { RegExpTerm res = parseDisjunction(); if (!this.atEOS()) this.error(Error.EXPECTED_EOS); return res; } protected String inputSubstring(int start, int end) { if (start >= src.length()) return ""; if (end > src.length()) end = src.length(); return src.substring(start, end); } private <T extends RegExpTerm> T finishTerm(T term) { SourceLocation loc = term.getLoc(); Position end = pos(); loc.setSource(inputSubstring(loc.getStart().getOffset(), end.getOffset())); loc.setEnd(end); return term; } private RegExpTerm parseDisjunction() { SourceLocation loc = new SourceLocation(pos()); List<RegExpTerm> disjuncts = new ArrayList<>(); disjuncts.add(this.parseAlternative()); while (this.match("|")) disjuncts.add(this.parseAlternative()); if (disjuncts.size() == 1) return disjuncts.get(0); return this.finishTerm(new Disjunction(loc, disjuncts)); } private RegExpTerm parseAlternative() { SourceLocation loc = new SourceLocation(pos()); List<RegExpTerm> elements = new ArrayList<>(); while (!this.lookahead(null, "|", ")")) elements.add(this.parseTerm()); if (elements.size() == 1) return elements.get(0); return this.finishTerm(new Sequence(loc, elements)); } private RegExpTerm parseTerm() { SourceLocation loc = new SourceLocation(pos()); if (this.match("^")) return this.finishTerm(new Caret(loc)); if (this.match("$")) return this.finishTerm(new Dollar(loc)); if (this.match("\\b")) return this.finishTerm(new WordBoundary(loc)); if (this.match("\\B")) return this.finishTerm(new NonWordBoundary(loc)); if (this.match("(?=")) { RegExpTerm dis = this.parseDisjunction(); this.expectRParen(); return this.finishTerm(new ZeroWidthPositiveLookahead(loc, dis)); } if (this.match("(?!")) { RegExpTerm dis = this.parseDisjunction(); this.expectRParen(); return this.finishTerm(new ZeroWidthNegativeLookahead(loc, dis)); } if (this.match("(?<=")) { RegExpTerm dis = this.parseDisjunction(); this.expectRParen(); return this.finishTerm(new ZeroWidthPositiveLookbehind(loc, dis)); } if (this.match("(?<!")) { RegExpTerm dis = this.parseDisjunction(); this.expectRParen(); return this.finishTerm(new ZeroWidthNegativeLookbehind(loc, dis)); } return this.finishTerm(this.parseQuantifierOpt(loc, this.parseAtom())); } private RegExpTerm parseQuantifierOpt(SourceLocation loc, RegExpTerm atom) { if (this.match("*")) return this.finishTerm(new Star(loc, atom, !this.match("?"))); if (this.match("+")) return this.finishTerm(new Plus(loc, atom, !this.match("?"))); if (this.match("?")) return this.finishTerm(new Opt(loc, atom, !this.match("?"))); if (this.match("{")) { Double lo = toNumber(this.readDigits(false)), hi; if (this.match(",")) { if (!this.lookahead("}")) { // atom{lo, hi} hi = toNumber(this.readDigits(false)); } else { // atom{lo,} hi = null; } } else { // atom{lo} hi = lo; } this.expectRBrace(); return this.finishTerm(new Range(loc, atom, !this.match("?"), lo, hi)); } return atom; } private RegExpTerm parseAtom() { SourceLocation loc = new SourceLocation(pos()); if (this.match(".")) return this.finishTerm(new Dot(loc)); if (this.match("\\")) return this.parseAtomEscape(loc, false); if (this.lookahead("[")) return this.parseCharacterClass(); if (this.match("(")) { boolean capture = !this.match("?:"); String name = null; if (this.match("?<")) { name = this.readIdentifier(); this.expectRAngle(); } if (capture) ++this.maxbackref; int number = this.maxbackref; RegExpTerm dis = this.parseDisjunction(); this.expectRParen(); return this.finishTerm(new Group(loc, capture, number, name, dis)); } // Parse consecutive constants into a single Constant node. // Due to speculative parsing of string literals, this part of the code is fairly hot. int startPos = this.pos; int endPos = startPos; while (endPos < src.length()) { if ("^$\\.*+?()[]{}|".indexOf(src.charAt(endPos)) != -1) break; ++endPos; } if (startPos == endPos) { this.error(Error.UNEXPECTED_CHARACTER, endPos); endPos = startPos + 1; // To ensure progress, make sure we parse at least one character. } // Check if the end of the constant belongs under an upcoming quantifier. if (endPos != startPos + 1 && endPos < src.length() && "*+?{".indexOf(src.charAt(endPos)) != -1) { if (Character.isLowSurrogate(src.charAt(endPos - 1)) && Character.isHighSurrogate(src.charAt(endPos - 2))) { // Don't split the surrogate pair. if (endPos == startPos + 2) { // The whole constant is a single wide character. } else { endPos -= 2; // Last 2 characters belong to an upcoming quantifier. } } else { endPos--; // Last character belongs to an upcoming quantifier. } } String str = src.substring(startPos, endPos); this.pos = endPos; loc.setEnd(pos()); loc.setSource(str); // Do not call finishTerm as it will create another copy of 'str'. return new Constant(loc, str); } private RegExpTerm parseAtomEscape(SourceLocation loc, boolean inCharClass) { String raw, value; double codepoint; if (this.match("x")) { raw = this.readHexDigits(2); codepoint = Integer.parseInt(raw, 16); value = fromCodePoint((int) codepoint); return this.finishTerm(new HexEscapeSequence(loc, value, (double) codepoint, "\\x" + raw)); } if (this.match("u")) { if (this.match("{")) { int closePos = this.src.indexOf("}", this.pos); int n; if (closePos == -1) { // don't attempt to read any digits, but // report missing `}` n = 0; } else if (closePos == this.pos) { // empty escape sequence, trigger an error n = 1; } else { n = closePos - this.pos; } raw = this.readHexDigits(n); this.expectRBrace(); try { codepoint = Long.parseLong(raw, 16); } catch (NumberFormatException nfe) { codepoint = 0; } raw = "{" + raw + "}"; } else { raw = this.readHexDigits(4); codepoint = Integer.parseInt(raw, 16); } value = fromCodePoint((int) codepoint); return this.finishTerm( new UnicodeEscapeSequence(loc, value, (double) codepoint, "\\u" + raw)); } if (this.match("k<")) { String name = this.readIdentifier(); this.expectRAngle(); return this.finishTerm(new NamedBackReference(loc, name, "\\k<" + name + ">")); } if (this.match("p{", "P{")) { String name = this.readIdentifier(); if (this.match("=")) { value = this.readIdentifier(); raw = "\\p{" + name + "=" + value + "}"; } else { value = null; raw = "\\p{" + name + "}"; } this.expectRBrace(); return this.finishTerm(new UnicodePropertyEscape(loc, name, value, raw)); } int startpos = this.pos - 1; char c = this.nextChar(); if (c >= '0' && c <= '9') { raw = c + this.readDigits(true); if (c == '0' || inCharClass) { int base = c == '0' && raw.length() > 1 ? 8 : 10; try { codepoint = Long.parseLong(raw, base); value = fromCodePoint((int) codepoint); } catch (NumberFormatException nfe) { codepoint = 0; value = "\0"; } if (base == 8) { this.error(Error.OCTAL_ESCAPE, startpos, this.pos); return this.finishTerm(new OctalEscape(loc, value, (double) codepoint, "\\" + raw)); } else { return this.finishTerm(new DecimalEscape(loc, value, (double) codepoint, "\\" + raw)); } } else { try { codepoint = Long.parseLong(raw, 10); } catch (NumberFormatException nfe) { codepoint = 0; } BackReference br = this.finishTerm(new BackReference(loc, (double) codepoint, "\\" + raw)); this.backrefs.add(br); return br; } } String ctrltab = "f\fn\nr\rt\tv\u000b"; int idx; if ((idx = ctrltab.indexOf(c)) % 2 == 0) { codepoint = ctrltab.charAt(idx + 1); value = String.valueOf((char) codepoint); return this.finishTerm(new ControlEscape(loc, value, codepoint, "\\" + c)); } if (c == 'c') { c = this.nextChar(); if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')) this.error(Error.EXPECTED_CONTROL_LETTER, this.pos - 1); codepoint = c % 32; value = String.valueOf((char) codepoint); return this.finishTerm(new ControlLetter(loc, value, codepoint, "\\c" + c)); } if ("dDsSwW".indexOf(c) >= 0) { return this.finishTerm(new CharacterClassEscape(loc, String.valueOf(c), "\\" + c)); } codepoint = c; value = String.valueOf((char) codepoint); return this.finishTerm(new IdentityEscape(loc, value, codepoint, "\\" + c)); } private RegExpTerm parseCharacterClass() { SourceLocation loc = new SourceLocation(pos()); List<RegExpTerm> elements = new ArrayList<>(); this.match("["); boolean inverted = this.match("^"); while (!this.match("]")) { if (this.atEOS()) { this.error(Error.EXPECTED_RBRACKET); break; } elements.add(this.parseCharacterClassElement()); } return this.finishTerm(new CharacterClass(loc, elements, inverted)); } private RegExpTerm parseCharacterClassElement() { SourceLocation loc = new SourceLocation(pos()); RegExpTerm atom = this.parseCharacterClassAtom(); if (!this.lookahead("-]") && this.match("-")) return this.finishTerm(new CharacterClassRange(loc, atom, this.parseCharacterClassAtom())); return atom; } private RegExpTerm parseCharacterClassAtom() { SourceLocation loc = new SourceLocation(pos()); char c = this.nextChar(); if (c == '\\') { if (this.match("b")) return this.finishTerm(new ControlEscape(loc, "\b", 8, "\\b")); return this.finishTerm(this.parseAtomEscape(loc, true)); } String value = String.valueOf(c); // Extract a surrogate pair as a single constant. if (Character.isHighSurrogate(c) && Character.isLowSurrogate(peekChar(true))) { value += this.nextChar(); } return this.finishTerm(new Constant(loc, value)); } }
16,803
31.191571
99
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/parser/JcornWrapper.java
package com.semmle.js.parser; import com.semmle.jcorn.CustomParser; import com.semmle.jcorn.Options; import com.semmle.jcorn.SyntaxError; import com.semmle.jcorn.jsx.JSXOptions; import com.semmle.js.ast.Comment; import com.semmle.js.ast.Program; import com.semmle.js.ast.Token; import com.semmle.js.extractor.ExtractorConfig; import com.semmle.js.extractor.ExtractorConfig.ECMAVersion; import com.semmle.js.extractor.ExtractorConfig.SourceType; import java.util.ArrayList; import java.util.List; public class JcornWrapper { /** Parse source code as a program. */ public static JSParser.Result parse( ExtractorConfig config, SourceType sourceType, String source) { ECMAVersion ecmaVersion = config.getEcmaVersion(); List<Comment> comments = new ArrayList<>(); List<Token> tokens = new ArrayList<>(); Options options = new Options() .ecmaVersion(ecmaVersion.legacyVersion) .sourceType(sourceType.toString()) .onComment(comments) .onToken(tokens) .preserveParens(true) .allowReturnOutsideFunction(true); if (config.isMozExtensions()) options.mozExtensions(true); if (config.isJscript()) options.jscript(true); if (config.isJsx()) options = new JSXOptions(options); if (config.isEsnext()) options.esnext(true); if (config.isV8Extensions()) options.v8Extensions(true); if (config.isE4X()) options.e4x(true); Program program = null; List<ParseError> errors = new ArrayList<>(); try { if (config.isTolerateParseErrors()) options.onRecoverableError((err) -> errors.add(mkParseError(err))); program = new CustomParser(options, source, 0).parse(); } catch (SyntaxError e) { errors.add(mkParseError(e)); } return new JSParser.Result(source, program, tokens, comments, errors); } private static ParseError mkParseError(SyntaxError e) { return new ParseError(e.getMessage(), e.getPosition()); } }
1,979
35
75
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/parser/ParsedProject.java
package com.semmle.js.parser; import java.io.File; import java.util.Set; public class ParsedProject { private final File tsConfigFile; private final Set<File> ownFiles; private final Set<File> allFiles; public ParsedProject(File tsConfigFile, Set<File> ownFiles, Set<File> allFiles) { this.tsConfigFile = tsConfigFile; this.ownFiles = ownFiles; this.allFiles = allFiles; } /** Returns the <tt>tsconfig.json</tt> file that defines this project. */ public File getTsConfigFile() { return tsConfigFile; } /** Absolute paths to the files included in this project. */ public Set<File> getOwnFiles() { return allFiles; } /** Absolute paths to the files included in or referenced by this project. */ public Set<File> getAllFiles() { return allFiles; } }
805
24.1875
83
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/parser/JSDocParser.java
package com.semmle.js.parser; import com.semmle.js.ast.Comment; import com.semmle.js.ast.Position; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.jsdoc.AllLiteral; import com.semmle.js.ast.jsdoc.ArrayType; import com.semmle.js.ast.jsdoc.FieldType; import com.semmle.js.ast.jsdoc.FunctionType; import com.semmle.js.ast.jsdoc.JSDocComment; import com.semmle.js.ast.jsdoc.JSDocTag; import com.semmle.js.ast.jsdoc.JSDocTypeExpression; import com.semmle.js.ast.jsdoc.NameExpression; import com.semmle.js.ast.jsdoc.NonNullableType; import com.semmle.js.ast.jsdoc.NullLiteral; import com.semmle.js.ast.jsdoc.NullableLiteral; import com.semmle.js.ast.jsdoc.NullableType; import com.semmle.js.ast.jsdoc.OptionalType; import com.semmle.js.ast.jsdoc.ParameterType; import com.semmle.js.ast.jsdoc.RecordType; import com.semmle.js.ast.jsdoc.RestType; import com.semmle.js.ast.jsdoc.TypeApplication; import com.semmle.js.ast.jsdoc.UndefinedLiteral; import com.semmle.js.ast.jsdoc.UnionType; import com.semmle.js.ast.jsdoc.VoidLiteral; import com.semmle.util.data.Pair; import com.semmle.util.exception.Exceptions; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; /** A Java port of <a href="https://github.com/Constellation/doctrine">doctrine</a>. */ public class JSDocParser { private String source; private int absoluteOffset; /** Parse the given string as a JSDoc comment. */ public JSDocComment parse(Comment comment) { source = comment.getText(); JSDocTagParser p = new JSDocTagParser(); Position startPos = comment.getLoc().getStart(); // Get the start of the first line relative to the 'source' string. // This occurs before the start of 'source', so the lineStart is negative. int firstLineStart = -(startPos.getColumn() + "/**".length() - 1); this.absoluteOffset = startPos.getOffset(); Pair<String, List<JSDocTagParser.Tag>> r = p.new TagParser(null).parseComment(startPos.getLine() - 1, firstLineStart); List<JSDocTag> tags = new ArrayList<>(); for (JSDocTagParser.Tag tag : r.snd()) { String title = tag.title; String description = tag.description; String name = tag.name; int startLine = tag.startLine; int startColumn = tag.startColumn; JSDocTypeExpression jsdocType = tag.type; int lineNumber = startLine + 1; // convert to 1-based SourceLocation loc = new SourceLocation( source, new Position(lineNumber, startColumn, -1), new Position(lineNumber, startColumn + 1 + title.length(), -1)); tags.add(new JSDocTag(loc, title, description, name, jsdocType, tag.errors)); } return new JSDocComment(comment, r.fst(), tags); } /** Specification of Doctrine AST types for JSDoc type expressions. */ private static final Map<Class<? extends JSDocTypeExpression>, List<String>> spec = new LinkedHashMap<Class<? extends JSDocTypeExpression>, List<String>>(); static { spec.put(AllLiteral.class, Arrays.<String>asList()); spec.put(ArrayType.class, Arrays.asList("elements")); spec.put(FieldType.class, Arrays.asList("key", "value")); spec.put(FunctionType.class, Arrays.asList("this", "new", "params", "result")); spec.put(NameExpression.class, Arrays.asList("name")); spec.put(NonNullableType.class, Arrays.asList("expression", "prefix")); spec.put(NullableLiteral.class, Arrays.<String>asList()); spec.put(NullLiteral.class, Arrays.<String>asList()); spec.put(NullableType.class, Arrays.asList("expression", "prefix")); spec.put(OptionalType.class, Arrays.asList("expression")); spec.put(ParameterType.class, Arrays.asList("name", "expression")); spec.put(RecordType.class, Arrays.asList("fields")); spec.put(RestType.class, Arrays.asList("expression")); spec.put(TypeApplication.class, Arrays.asList("expression", "applications")); spec.put(UndefinedLiteral.class, Arrays.<String>asList()); spec.put(UnionType.class, Arrays.asList("elements")); spec.put(VoidLiteral.class, Arrays.<String>asList()); } private static String sliceSource(String source, int index, int last) { if (index >= source.length()) return ""; if (last > source.length()) last = source.length(); return source.substring(index, last); } private static boolean isLineTerminator(int ch) { return ch == '\n' || ch == '\r' || ch == '\u2028' || ch == '\u2029'; } private static boolean isWhiteSpace(char ch) { return Character.isWhitespace(ch) && !isLineTerminator(ch) || ch == '\u00a0'; } private static boolean isWhiteSpaceOrLineTerminator(char ch) { return Character.isWhitespace(ch) || ch == '\u00a0'; } private static boolean isDecimalDigit(char ch) { return "0123456789".indexOf(ch) >= 0; } private static boolean isHexDigit(char ch) { return "0123456789abcdefABCDEF".indexOf(ch) >= 0; } private static boolean isOctalDigit(char ch) { return "01234567".indexOf(ch) >= 0; } private static boolean isASCIIAlphanumeric(char ch) { return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9'); } private static boolean isIdentifierStart(char ch) { return (ch == '\\') || Character.isJavaIdentifierStart(ch); } private static boolean isIdentifierPart(char ch) { return (ch == '\\') || Character.isJavaIdentifierPart(ch); } private static boolean isTypeName(char ch) { return "><(){}[],:*|?!=".indexOf(ch) == -1 && !isWhiteSpace(ch) && !isLineTerminator(ch); } private static boolean isParamTitle(String title) { return title.equals("param") || title.equals("argument") || title.equals("arg"); } private static boolean isProperty(String title) { return title.equals("property") || title.equals("prop"); } private static boolean isNameParameterRequired(String title) { return isParamTitle(title) || isProperty(title) || title.equals("alias") || title.equals("this") || title.equals("mixes") || title.equals("requires"); } private static boolean isAllowedName(String title) { return isNameParameterRequired(title) || title.equals("const") || title.equals("constant"); } private static boolean isAllowedNested(String title) { return isProperty(title) || isParamTitle(title); } private static boolean isTypeParameterRequired(String title) { return isParamTitle(title) || title.equals("define") || title.equals("enum") || title.equals("implements") || title.equals("return") || title.equals("this") || title.equals("type") || title.equals("typedef") || title.equals("returns") || isProperty(title); } // Consider deprecation instead using 'isTypeParameterRequired' and 'Rules' declaration to pick // when a type is optional/required // This would require changes to 'parseType' private static boolean isAllowedType(String title) { return isTypeParameterRequired(title) || title.equals("throws") || title.equals("const") || title.equals("constant") || title.equals("namespace") || title.equals("member") || title.equals("var") || title.equals("module") || title.equals("constructor") || title.equals("class") || title.equals("extends") || title.equals("augments") || title.equals("public") || title.equals("private") || title.equals("protected"); } private static <T> T throwError(String message) throws ParseError { throw new ParseError(message, null); } private enum Token { ILLEGAL, // ILLEGAL DOT, // . DOT_LT, // .< REST, // ... LT, // < GT, // > LPAREN, // ( RPAREN, // ) LBRACE, // { RBRACE, // } LBRACK, // [ RBRACK, // ] COMMA, // , COLON, // : STAR, // * PIPE, // | QUESTION, // ? BANG, // ! EQUAL, // = NAME, // name token STRING, // string NUMBER, // number EOF }; private class TypeExpressionParser { int startIndex; int endIndex; int startOfCurToken, endOfPrevToken, index; Token token; Object value; int lineStart; int lineNumber; private class Context { int _startOfCurToken, _endOfPrevToken, _index; Token _token; Object _value; Context(int startOfCurToken, int endOfPrevToken, int index, Token token, Object value) { this._startOfCurToken = startOfCurToken; this._endOfPrevToken = endOfPrevToken; this._index = index; this._token = token; this._value = value; } void restore() { startOfCurToken = this._startOfCurToken; endOfPrevToken = this._endOfPrevToken; index = this._index; token = this._token; value = this._value; } } Context save() { return new Context(startOfCurToken, endOfPrevToken, index, token, value); } private SourceLocation loc() { return new SourceLocation(pos()); } /** Returns the absolute position of the start of the current token. */ private Position pos() { return new Position( this.lineNumber + 1, startOfCurToken - lineStart, startOfCurToken + absoluteOffset); } /** * Returns the absolute position of the end of the previous token. * * <p>This can differ from the start of the current token in case the two tokens are separated * by whitespace. */ private Position endPos() { return new Position( this.lineNumber + 1, endOfPrevToken - lineStart, endOfPrevToken + absoluteOffset); } private <T extends JSDocTypeExpression> T finishNode(T node) { SourceLocation loc = node.getLoc(); Position end = endPos(); int relativeStartOffset = loc.getStart().getOffset() - absoluteOffset; int relativeEndOffset = end.getOffset() - absoluteOffset; loc.setSource(inputSubstring(relativeStartOffset, relativeEndOffset)); loc.setEnd(end); return node; } private String inputSubstring(int start, int end) { if (start >= source.length()) return ""; if (end > source.length()) end = source.length(); return source.substring(start, end); } private int advance() { if (index >= source.length()) return -1; int ch = source.charAt(index); ++index; if (isLineTerminator(ch) && !(ch == '\r' && index < endIndex && source.charAt(index) == '\n')) { lineNumber += 1; lineStart = index; index = skipStars(index, endIndex); } return ch; } private String scanHexEscape(char prefix) { int i, len, ch, code = 0; len = (prefix == 'u') ? 4 : 2; for (i = 0; i < len; ++i) { if (index < endIndex && isHexDigit(source.charAt(index))) { ch = advance(); code = code * 16 + "0123456789abcdef".indexOf(Character.toLowerCase(ch)); } else { return ""; } } return new String(Character.toChars(code)); } private Token scanString() throws ParseError { StringBuilder str = new StringBuilder(); int quote, ch, code, restore; // TODO review removal octal = false String unescaped; quote = source.charAt(index); ++index; while (index < endIndex) { ch = advance(); if (ch == quote) { quote = -1; break; } else if (ch == '\\') { ch = advance(); if (!isLineTerminator(ch)) { switch (ch) { case 'n': str.append('\n'); break; case 'r': str.append('\r'); break; case 't': str.append('\t'); break; case 'u': case 'x': restore = index; unescaped = scanHexEscape((char) ch); if (!unescaped.isEmpty()) { str.append(unescaped); } else { index = restore; str.append((char) ch); } break; case 'b': str.append('\b'); break; case 'f': str.append('\f'); break; case 'v': str.append('\u000b'); break; default: if (isOctalDigit((char) ch)) { code = "01234567".indexOf(ch); // \0 is not octal escape sequence // Deprecating unused code. TODO review removal // if (code != 0) { // octal = true; // } if (index < endIndex && isOctalDigit(source.charAt(index))) { // TODO Review Removal octal = true; code = code * 8 + "01234567".indexOf(advance()); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ("0123".indexOf(ch) >= 0 && index < endIndex && isOctalDigit(source.charAt(index))) { code = code * 8 + "01234567".indexOf(advance()); } } str.append(Character.toChars(code)); } else { str.append((char) ch); } break; } } else { if (ch == '\r' && index < endIndex && source.charAt(index) == '\n') { ++index; } } } else if (isLineTerminator(ch)) { break; } else { str.append((char) ch); } } if (quote != -1) { throwError("unexpected quote"); } value = str.toString(); return Token.STRING; } private Token scanNumber() throws ParseError { StringBuilder number = new StringBuilder(); boolean isFloat = false; char ch = '\0'; if (ch != '.') { int next = advance(); number.append((char) next); ch = index < endIndex ? source.charAt(index) : '\0'; if (next == '0') { if (ch == 'x' || ch == 'X') { number.append((char) advance()); while (index < endIndex) { ch = source.charAt(index); if (!isHexDigit(ch)) { break; } number.append((char) advance()); } if (number.length() <= 2) { // only 0x throwError("unexpected token"); } if (index < endIndex) { ch = source.charAt(index); if (isIdentifierStart(ch)) { throwError("unexpected token"); } } try { value = Integer.parseInt(number.toString(), 16); } catch (NumberFormatException nfe) { Exceptions.ignore(nfe, "Precise exception content is unimportant"); throwError("Invalid hexadecimal constant " + number); } return Token.NUMBER; } if (isOctalDigit(ch)) { number.append((char) advance()); while (index < endIndex) { ch = source.charAt(index); if (!isOctalDigit(ch)) { break; } number.append((char) advance()); } if (index < endIndex) { ch = source.charAt(index); if (isIdentifierStart(ch) || isDecimalDigit(ch)) { throwError("unexpected token"); } } try { value = Integer.parseInt(number.toString(), 8); } catch (NumberFormatException nfe) { Exceptions.ignore(nfe, "Precise exception content is unimportant"); throwError("Invalid octal constant " + number); } return Token.NUMBER; } if (isDecimalDigit(ch)) { throwError("unexpected token"); } } while (index < endIndex) { ch = source.charAt(index); if (!isDecimalDigit(ch)) { break; } number.append((char) advance()); } } if (ch == '.') { isFloat = true; number.append((char) advance()); while (index < endIndex) { ch = source.charAt(index); if (!isDecimalDigit(ch)) { break; } number.append((char) advance()); } } if (ch == 'e' || ch == 'E') { isFloat = true; number.append((char) advance()); ch = index < endIndex ? source.charAt(index) : '\0'; if (ch == '+' || ch == '-') { number.append((char) advance()); } ch = index < endIndex ? source.charAt(index) : '\0'; if (isDecimalDigit(ch)) { number.append((char) advance()); while (index < endIndex) { ch = source.charAt(index); if (!isDecimalDigit(ch)) { break; } number.append((char) advance()); } } else { throwError("unexpected token"); } } if (index < endIndex) { ch = source.charAt(index); if (isIdentifierStart(ch)) { throwError("unexpected token"); } } String num = number.toString(); try { if (isFloat) value = Double.parseDouble(num); else value = Integer.parseInt(num); } catch (NumberFormatException nfe) { Exceptions.ignore(nfe, "Precise exception content is unimportant"); throwError("Invalid numeric literal " + num); } return Token.NUMBER; } private Token scanTypeName() { char ch, ch2; value = new String(Character.toChars(advance())); while (index < endIndex && isTypeName(source.charAt(index))) { ch = source.charAt(index); if (ch == '.') { if ((index + 1) < endIndex) { ch2 = source.charAt(index + 1); if (ch2 == '<') { break; } } } value += new String(Character.toChars(advance())); } return Token.NAME; } private Token next() throws ParseError { char ch; endOfPrevToken = index; while (index < endIndex && isWhiteSpaceOrLineTerminator(source.charAt(index))) { advance(); } if (index >= endIndex) { token = Token.EOF; return token; } startOfCurToken = index; ch = source.charAt(index); switch (ch) { case '"': token = scanString(); return token; case ':': advance(); token = Token.COLON; return token; case ',': advance(); token = Token.COMMA; return token; case '(': advance(); token = Token.LPAREN; return token; case ')': advance(); token = Token.RPAREN; return token; case '[': advance(); token = Token.LBRACK; return token; case ']': advance(); token = Token.RBRACK; return token; case '{': advance(); token = Token.LBRACE; return token; case '}': advance(); token = Token.RBRACE; return token; case '.': advance(); if (index < endIndex) { ch = source.charAt(index); if (ch == '<') { advance(); token = Token.DOT_LT; return token; } if (ch == '.' && index + 1 < endIndex && source.charAt(index + 1) == '.') { advance(); advance(); token = Token.REST; return token; } if (isDecimalDigit(ch)) { token = scanNumber(); return token; } } token = Token.DOT; return token; case '<': advance(); token = Token.LT; return token; case '>': advance(); token = Token.GT; return token; case '*': advance(); token = Token.STAR; return token; case '|': advance(); token = Token.PIPE; return token; case '?': advance(); token = Token.QUESTION; return token; case '!': advance(); token = Token.BANG; return token; case '=': advance(); token = Token.EQUAL; return token; default: if (isDecimalDigit(ch)) { token = scanNumber(); return token; } // type string permits following case, // // namespace.module.MyClass // // this reduced 1 token TK_NAME if (isTypeName(ch)) { token = scanTypeName(); return token; } token = Token.ILLEGAL; return token; } } private void consume(Token target, String text) throws ParseError { if (token != target) throwError(text == null ? "consumed token not matched" : text); next(); } private void consume(Token target) throws ParseError { consume(target, null); } private void expect(Token target) throws ParseError { if (token != target) { throwError("unexpected token"); } next(); } // UnionType := '(' TypeUnionList ')' // // TypeUnionList := // <<empty>> // | NonemptyTypeUnionList // // NonemptyTypeUnionList := // TypeExpression // | TypeExpression '|' NonemptyTypeUnionList private JSDocTypeExpression parseUnionType() throws ParseError { SourceLocation loc = loc(); List<JSDocTypeExpression> elements = new ArrayList<>(); consume(Token.LPAREN, "UnionType should start with ("); if (token != Token.RPAREN) { while (true) { elements.add(parseTypeExpression()); if (token == Token.RPAREN) { break; } expect(Token.PIPE); } } consume(Token.RPAREN, "UnionType should end with )"); return finishNode(new UnionType(loc, elements)); } // ArrayType := '[' ElementTypeList ']' // // ElementTypeList := // <<empty>> // | TypeExpression // | '...' TypeExpression // | TypeExpression ',' ElementTypeList private JSDocTypeExpression parseArrayType() throws ParseError { SourceLocation loc = loc(); List<JSDocTypeExpression> elements = new ArrayList<>(); consume(Token.LBRACK, "ArrayType should start with ["); while (token != Token.RBRACK) { if (token == Token.REST) { SourceLocation restLoc = loc(); consume(Token.REST); elements.add(finishNode(new RestType(restLoc, parseTypeExpression()))); break; } else { elements.add(parseTypeExpression()); } if (token != Token.RBRACK) { expect(Token.COMMA); } } expect(Token.RBRACK); return finishNode(new ArrayType(loc, elements)); } private String parseFieldName() throws ParseError { Object v = value; if (token == Token.NAME || token == Token.STRING) { next(); return v.toString(); } if (token == Token.NUMBER) { consume(Token.NUMBER); return v.toString(); } return throwError("unexpected token"); } // FieldType := // FieldName // | FieldName ':' TypeExpression // // FieldName := // NameExpression // | StringLiteral // | NumberLiteral // | ReservedIdentifier private FieldType parseFieldType() throws ParseError { String key; SourceLocation loc = loc(); key = parseFieldName(); if (token == Token.COLON) { consume(Token.COLON); return finishNode(new FieldType(loc, key, parseTypeExpression())); } return finishNode(new FieldType(loc, key, null)); } // RecordType := '{' FieldTypeList '}' // // FieldTypeList := // <<empty>> // | FieldType // | FieldType ',' FieldTypeList private JSDocTypeExpression parseRecordType() throws ParseError { List<FieldType> fields = new ArrayList<>(); SourceLocation loc = loc(); consume(Token.LBRACE, "RecordType should start with {"); if (token == Token.COMMA) { consume(Token.COMMA); } else { while (token != Token.RBRACE) { fields.add(parseFieldType()); if (token != Token.RBRACE) { expect(Token.COMMA); } } } expect(Token.RBRACE); return finishNode(new RecordType(loc, fields)); } private JSDocTypeExpression parseNameExpression() throws ParseError { Object name = value; SourceLocation loc = loc(); expect(Token.NAME); return finishNode(new NameExpression(loc, name.toString())); } // TypeExpressionList := // TopLevelTypeExpression // | TopLevelTypeExpression ',' TypeExpressionList private List<JSDocTypeExpression> parseTypeExpressionList() throws ParseError { List<JSDocTypeExpression> elements = new ArrayList<>(); elements.add(parseTop()); while (token == Token.COMMA) { consume(Token.COMMA); elements.add(parseTop()); } return elements; } // TypeName := // NameExpression // | NameExpression TypeApplication // // TypeApplication := // '.<' TypeExpressionList '>' // | '<' TypeExpressionList '>' // this is extension of doctrine private JSDocTypeExpression parseTypeName() throws ParseError { JSDocTypeExpression expr; List<JSDocTypeExpression> applications; SourceLocation loc = loc(); expr = parseNameExpression(); if (token == Token.DOT_LT || token == Token.LT) { next(); applications = parseTypeExpressionList(); expect(Token.GT); return finishNode(new TypeApplication(loc, expr, applications)); } return expr; } // ResultType := // <<empty>> // | ':' void // | ':' TypeExpression // // BNF is above // but, we remove <<empty>> pattern, so token is always TypeToken::COLON private JSDocTypeExpression parseResultType() throws ParseError { consume(Token.COLON, "ResultType should start with :"); SourceLocation loc = loc(); if (token == Token.NAME && value.equals("void")) { consume(Token.NAME); return finishNode(new VoidLiteral(loc)); } return parseTypeExpression(); } // ParametersType := // RestParameterType // | NonRestParametersType // | NonRestParametersType ',' RestParameterType // // RestParameterType := // '...' // '...' Identifier // // NonRestParametersType := // ParameterType ',' NonRestParametersType // | ParameterType // | OptionalParametersType // // OptionalParametersType := // OptionalParameterType // | OptionalParameterType, OptionalParametersType // // OptionalParameterType := ParameterType= // // ParameterType := TypeExpression | Identifier ':' TypeExpression // // Identifier is "new" or "this" private List<JSDocTypeExpression> parseParametersType() throws ParseError { List<JSDocTypeExpression> params = new ArrayList<>(); boolean normal = true; JSDocTypeExpression expr; boolean rest = false; while (token != Token.RPAREN) { if (token == Token.REST) { // RestParameterType consume(Token.REST); rest = true; } SourceLocation loc = loc(); expr = parseTypeExpression(); if (expr instanceof NameExpression && token == Token.COLON) { // Identifier ':' TypeExpression consume(Token.COLON); expr = finishNode( new ParameterType( new SourceLocation(loc), ((NameExpression) expr).getName(), parseTypeExpression())); } if (token == Token.EQUAL) { consume(Token.EQUAL); expr = finishNode(new OptionalType(new SourceLocation(loc), expr)); normal = false; } else { if (!normal) { throwError("unexpected token"); } } if (rest) { expr = finishNode(new RestType(new SourceLocation(loc), expr)); } params.add(expr); if (token != Token.RPAREN) { expect(Token.COMMA); } } return params; } // FunctionType := 'function' FunctionSignatureType // // FunctionSignatureType := // | TypeParameters '(' ')' ResultType // | TypeParameters '(' ParametersType ')' ResultType // | TypeParameters '(' 'this' ':' TypeName ')' ResultType // | TypeParameters '(' 'this' ':' TypeName ',' ParametersType ')' ResultType private JSDocTypeExpression parseFunctionType() throws ParseError { SourceLocation loc = loc(); boolean isNew; JSDocTypeExpression thisBinding; List<JSDocTypeExpression> params; JSDocTypeExpression result; consume(Token.NAME); // Google Closure Compiler is not implementing TypeParameters. // So we do not. if we don't get '(', we see it as error. expect(Token.LPAREN); isNew = false; params = new ArrayList<JSDocTypeExpression>(); thisBinding = null; if (token != Token.RPAREN) { // ParametersType or 'this' if (token == Token.NAME && (value.equals("this") || value.equals("new"))) { // 'this' or 'new' // 'new' is Closure Compiler extension isNew = value.equals("new"); consume(Token.NAME); expect(Token.COLON); thisBinding = parseTypeName(); if (token == Token.COMMA) { consume(Token.COMMA); params = parseParametersType(); } } else { params = parseParametersType(); } } expect(Token.RPAREN); result = null; if (token == Token.COLON) { result = parseResultType(); } return finishNode(new FunctionType(loc, thisBinding, isNew, params, result)); } // BasicTypeExpression := // '*' // | 'null' // | 'undefined' // | TypeName // | FunctionType // | UnionType // | RecordType // | ArrayType private JSDocTypeExpression parseBasicTypeExpression() throws ParseError { Context context; SourceLocation loc; switch (token) { case STAR: loc = loc(); consume(Token.STAR); return finishNode(new AllLiteral(loc)); case LPAREN: return parseUnionType(); case LBRACK: return parseArrayType(); case LBRACE: return parseRecordType(); case NAME: if (value.equals("null")) { loc = loc(); consume(Token.NAME); return finishNode(new NullLiteral(loc)); } if (value.equals("undefined")) { loc = loc(); consume(Token.NAME); return finishNode(new UndefinedLiteral(loc)); } context = save(); if (value.equals("function")) { try { return parseFunctionType(); } catch (ParseError e) { context.restore(); } } return parseTypeName(); default: return throwError("unexpected token"); } } // TypeExpression := // BasicTypeExpression // | '?' BasicTypeExpression // | '!' BasicTypeExpression // | BasicTypeExpression '?' // | BasicTypeExpression '!' // | '?' // | BasicTypeExpression '[]' private JSDocTypeExpression parseTypeExpression() throws ParseError { JSDocTypeExpression expr; SourceLocation loc = loc(); if (token == Token.QUESTION) { consume(Token.QUESTION); if (token == Token.COMMA || token == Token.EQUAL || token == Token.RBRACE || token == Token.RPAREN || token == Token.PIPE || token == Token.EOF || token == Token.RBRACK) { return finishNode(new NullableLiteral(loc)); } return finishNode(new NullableType(loc, parseBasicTypeExpression(), true)); } if (token == Token.BANG) { consume(Token.BANG); return finishNode(new NonNullableType(loc, parseBasicTypeExpression(), true)); } expr = parseBasicTypeExpression(); if (token == Token.BANG) { consume(Token.BANG); return finishNode(new NonNullableType(loc, expr, false)); } if (token == Token.QUESTION) { consume(Token.QUESTION); return finishNode(new NullableType(loc, expr, false)); } if (token == Token.LBRACK) { consume(Token.LBRACK); consume(Token.RBRACK, "expected an array-style type declaration (' + value + '[])"); List<JSDocTypeExpression> expressions = new ArrayList<>(); expressions.add(expr); NameExpression nameExpr = finishNode(new NameExpression(new SourceLocation(loc), "Array")); return finishNode(new TypeApplication(loc, nameExpr, expressions)); } return expr; } // TopLevelTypeExpression := // TypeExpression // | TypeUnionList // // This rule is Google Closure Compiler extension, not ES4 // like, // { number | string } // If strict to ES4, we should write it as // { (number|string) } private JSDocTypeExpression parseTop() throws ParseError { JSDocTypeExpression expr; List<JSDocTypeExpression> elements = new ArrayList<JSDocTypeExpression>(); SourceLocation loc = loc(); expr = parseTypeExpression(); if (token != Token.PIPE) { return expr; } elements.add(expr); consume(Token.PIPE); while (true) { elements.add(parseTypeExpression()); if (token != Token.PIPE) { break; } consume(Token.PIPE); } return finishNode(new UnionType(loc, elements)); } private JSDocTypeExpression parseTopParamType() throws ParseError { JSDocTypeExpression expr; SourceLocation loc = loc(); if (token == Token.REST) { consume(Token.REST); return finishNode(new RestType(loc, parseTop())); } expr = parseTop(); if (token == Token.EQUAL) { consume(Token.EQUAL); return finishNode(new OptionalType(loc, expr)); } return expr; } private JSDocTypeExpression parseType( int startIndex, int endIndex, int lineStart, int lineNumber) throws ParseError { JSDocTypeExpression expr; this.lineNumber = lineNumber; this.lineStart = lineStart; this.startIndex = startIndex; this.endIndex = endIndex; index = startIndex; next(); expr = parseTop(); if (token != Token.EOF) { throwError("not reach to EOF"); } return expr; } private JSDocTypeExpression parseParamType( int startIndex, int endIndex, int lineStart, int lineNumber) throws ParseError { JSDocTypeExpression expr; this.lineNumber = lineNumber; this.lineStart = lineStart; this.startIndex = startIndex; this.endIndex = endIndex; index = startIndex; next(); expr = parseTopParamType(); if (token != Token.EOF) { throwError("not reach to EOF"); } return expr; } } /** Skips the leading indentation and '*' at the beginning of a line. */ private int skipStars(int index, int end) { while (index < end && isWhiteSpace(source.charAt(index)) && !isLineTerminator(source.charAt(index))) { index += 1; } while (index < end && source.charAt(index) == '*') { index += 1; } while (index < end && isWhiteSpace(source.charAt(index)) && !isLineTerminator(source.charAt(index))) { index += 1; } return index; } private TypeExpressionParser typed = new TypeExpressionParser(); private class JSDocTagParser { int index, lineNumber, lineStart, length; boolean recoverable = true, sloppy = false; private char advance() { char ch = source.charAt(index); index += 1; if (isLineTerminator(ch) && !(ch == '\r' && index < length && source.charAt(index) == '\n')) { lineNumber += 1; lineStart = index; index = skipStars(index, length); } return ch; } private String scanTitle() { StringBuilder title = new StringBuilder(); // waste '@' advance(); while (index < length && isASCIIAlphanumeric(source.charAt(index))) { title.append(advance()); } return title.toString(); } private int seekContent() { char ch; boolean waiting = false; int last = index; while (last < length) { ch = source.charAt(last); if (isLineTerminator(ch) && !(ch == '\r' && last + 1 < length && source.charAt(last + 1) == '\n')) { lineNumber += 1; lineStart = last + 1; last = skipStars(last + 1, length) - 1; waiting = true; } else if (waiting) { if (ch == '@') { break; } if (!isWhiteSpace(ch)) { waiting = false; } } last += 1; } return last; } // type expression may have nest brace, such as, // { { ok: string } } // // therefore, scanning type expression with balancing braces. private JSDocTypeExpression parseType(String title, int last) throws ParseError { char ch; int brace; boolean direct = false; // search '{' while (index < last) { ch = source.charAt(index); if (isWhiteSpace(ch)) { advance(); } else if (ch == '{') { advance(); break; } else { // this is direct pattern direct = true; break; } } if (!direct) { // type expression { is found brace = 1; int firstLineStart = this.lineStart; int firstLineNumber = this.lineNumber; int startIndex = index; while (index < last) { ch = source.charAt(index); if (ch == '}') { brace -= 1; if (brace == 0) { advance(); break; } } else if (ch == '{') { brace += 1; } advance(); } if (brace != 0) { // braces is not balanced return throwError("Braces are not balanced"); } try { if (isParamTitle(title)) { return typed.parseParamType(startIndex, index - 1, firstLineStart, firstLineNumber); } return typed.parseType(startIndex, index - 1, firstLineStart, firstLineNumber); } catch (ParseError e) { // parse failed return null; } } else { return null; } } private String scanIdentifier(int last) { StringBuilder identifier = new StringBuilder(); if (!(index < length && isIdentifierStart(source.charAt(index)))) { return null; } identifier.append(advance()); while (index < last && isIdentifierPart(source.charAt(index))) { identifier.append(advance()); } return identifier.toString(); } private void skipWhiteSpace(int last) { while (index < last && (isWhiteSpace(source.charAt(index)) || isLineTerminator(source.charAt(index)))) { advance(); } } private String parseName(int last, boolean allowBrackets, boolean allowNestedParams) { StringBuilder name = new StringBuilder(); boolean useBrackets = false; skipWhiteSpace(last); if (index >= last) { return null; } if (allowBrackets && source.charAt(index) == '[') { useBrackets = true; name.append(advance()); } if (!isIdentifierStart(source.charAt(index))) { return null; } name.append(scanIdentifier(last)); if (allowNestedParams) { while (index < last && (source.charAt(index) == '.' || source.charAt(index) == '#' || source.charAt(index) == '~')) { name.append(source.charAt(index)); index += 1; name.append(scanIdentifier(last)); } } if (useBrackets) { // do we have a default value for this? if (index < last && source.charAt(index) == '=') { // consume the '='' symbol name.append(advance()); // scan in the default value while (index < last && source.charAt(index) != ']') { name.append(advance()); } } if (index >= last || source.charAt(index) != ']') { // we never found a closing ']' return null; } // collect the last ']' name.append(advance()); } return name.toString(); } boolean skipToTag() { while (index < length && source.charAt(index) != '@') { advance(); } if (index >= length) { return false; } return true; } private class Tag { public String description; public String title; List<String> errors = new ArrayList<>(); JSDocTypeExpression type; String name; public int startLine; public int startColumn; } private class TagParser { String _title; Tag _tag; int _last; String _extra_name; TagParser(String title) { this._title = title; this._tag = new Tag(); this._tag.description = null; this._tag.title = title; this._last = 0; // space to save special information for title parsers. this._extra_name = null; } // addError(err, ...) public boolean addError(String errorText, Object... args) { this._tag.errors.add(String.format(errorText, args)); return recoverable; } public boolean parseType() { // type required titles if (isTypeParameterRequired(this._title)) { try { this._tag.type = JSDocTagParser.this.parseType(this._title, this._last); if (this._tag.type == null) { if (!isParamTitle(this._title)) { if (!this.addError("Missing or invalid tag type")) { return false; } } } } catch (ParseError error) { this._tag.type = null; if (!this.addError(error.getMessage())) { return false; } } } else if (isAllowedType(this._title)) { // optional types try { this._tag.type = JSDocTagParser.this.parseType(this._title, this._last); } catch (ParseError e) { // For optional types, lets drop the thrown error when we hit the end of the file } } return true; } private boolean _parseNamePath(boolean optional) { String name = JSDocTagParser.this.parseName(this._last, sloppy && isParamTitle(this._title), true); if (name == null) { if (!optional) { if (!this.addError("Missing or invalid tag name")) { return false; } } } this._tag.name = name; return true; } public boolean parseNamePath() { return _parseNamePath(false); } public boolean parseNamePathOptional() { return this._parseNamePath(true); } public boolean parseName() { String[] assign; String name; // param, property requires name if (isAllowedName(this._title)) { this._tag.name = JSDocTagParser.this.parseName( this._last, sloppy && isParamTitle(this._title), isAllowedNested(this._title)); if (this._tag.name == null) { if (!isNameParameterRequired(this._title)) { return true; } // it's possible the name has already been parsed but interpreted as a type // it's also possible this is a sloppy declaration, in which case it will be // fixed at the end if (isParamTitle(this._title) && this._tag.type != null && this._tag.type instanceof NameExpression) { this._extra_name = ((NameExpression) this._tag.type).getName(); this._tag.name = ((NameExpression) this._tag.type).getName(); this._tag.type = null; } else { if (!this.addError("Missing or invalid tag name")) { return false; } } } else { name = this._tag.name; if (name.charAt(0) == '[' && name.charAt(name.length() - 1) == ']') { // extract the default value if there is one // example: @param {string} [somebody=John Doe] description assign = name.substring(1, name.length() - 1).split("="); this._tag.name = assign[0]; // convert to an optional type if (this._tag.type != null && !(this._tag.type instanceof OptionalType)) { Position start = new Position(_tag.startLine, _tag.startColumn, _tag.startColumn); Position end = new Position(_tag.startLine, _tag.startColumn, _tag.startColumn); SourceLocation loc = new SourceLocation(_extra_name, start, end); this._tag.type = new OptionalType(loc, this._tag.type); } } } } return true; } private boolean parseDescription() { String description = sliceSource(source, index, this._last).trim(); if (!description.isEmpty()) { if (description.matches("(?s)^-\\s+.*")) { description = description.substring(2); } description = description.replaceAll("(?m)^\\s*\\*+\\s*", ""); this._tag.description = description; } return true; } private final Set<String> kinds = new LinkedHashSet<>(); { kinds.add("class"); kinds.add("constant"); kinds.add("event"); kinds.add("external"); kinds.add("file"); kinds.add("function"); kinds.add("member"); kinds.add("mixin"); kinds.add("module"); kinds.add("namespace"); kinds.add("typedef"); } private boolean parseKind() { String kind = sliceSource(source, index, this._last).trim(); if (!kinds.contains(kind)) { if (!this.addError("Invalid kind name \'%s\'", kind)) { return false; } } return true; } private boolean parseAccess() { String access = sliceSource(source, index, this._last).trim(); if (!access.equals("private") && !access.equals("protected") && !access.equals("public")) { if (!this.addError("Invalid access name \'%s\'", access)) { return false; } } return true; } private boolean parseVariation() { double variation; String text = sliceSource(source, index, this._last).trim(); try { variation = Double.parseDouble(text); } catch (NumberFormatException nfe) { variation = Double.NaN; } if (Double.isNaN(variation)) { if (!this.addError("Invalid variation \'%s\'", text)) { return false; } } return true; } private boolean ensureEnd() { String shouldBeEmpty = sliceSource(source, index, this._last).trim(); if (!shouldBeEmpty.matches("^[\\s*]*$")) { if (!this.addError("Unknown content \'%s\'", shouldBeEmpty)) { return false; } } return true; } private boolean epilogue() { String description; description = this._tag.description; // un-fix potentially sloppy declaration if (isParamTitle(this._title) && this._tag.type == null && description != null && description.startsWith("[")) { if (_extra_name != null) { Position start = new Position(_tag.startLine, _tag.startColumn, _tag.startColumn); Position end = new Position(_tag.startLine, _tag.startColumn, _tag.startColumn); SourceLocation loc = new SourceLocation(_extra_name, start, end); this._tag.type = new NameExpression(loc, _extra_name); } this._tag.name = null; if (!sloppy) { if (!this.addError("Missing or invalid tag name")) { return false; } } } return true; } private Tag parse() { int oldLineNumber, oldLineStart, newLineNumber, newLineStart; // empty title if (this._title == null || this._title.isEmpty()) { if (!this.addError("Missing or invalid title")) { return null; } } // Seek to content last index. oldLineNumber = lineNumber; oldLineStart = lineStart; this._last = seekContent(); newLineNumber = lineNumber; newLineStart = lineStart; lineNumber = oldLineNumber; lineStart = oldLineStart; switch (this._title) { // http://usejsdoc.org/tags-access.html case "access": if (!parseAccess()) return null; break; // http://usejsdoc.org/tags-alias.html case "alias": if (!parseNamePath() || !ensureEnd()) return null; break; // http://usejsdoc.org/tags-augments.html case "augments": if (!parseType() || !parseNamePathOptional() || !ensureEnd()) return null; break; // http://usejsdoc.org/tags-constructor.html case "constructor": if (!parseType() || !parseNamePathOptional() || !ensureEnd()) return null; break; // Synonym: http://usejsdoc.org/tags-constructor.html case "class": if (!parseType() || !parseNamePathOptional() || !ensureEnd()) return null; break; // Synonym: http://usejsdoc.org/tags-extends.html case "extends": if (!parseType() || !parseNamePathOptional() || !ensureEnd()) return null; break; // http://usejsdoc.org/tags-deprecated.html case "deprecated": if (!parseDescription()) return null; break; // http://usejsdoc.org/tags-global.html case "global": if (!ensureEnd()) return null; break; // http://usejsdoc.org/tags-inner.html case "inner": if (!ensureEnd()) return null; break; // http://usejsdoc.org/tags-instance.html case "instance": if (!ensureEnd()) return null; break; // http://usejsdoc.org/tags-kind.html case "kind": if (!parseKind()) return null; break; // http://usejsdoc.org/tags-mixes.html case "mixes": if (!parseNamePath() || !ensureEnd()) return null; break; // http://usejsdoc.org/tags-mixin.html case "mixin": if (!parseNamePathOptional() || !ensureEnd()) return null; break; // http://usejsdoc.org/tags-member.html case "member": if (!parseType() || !parseNamePathOptional() || !ensureEnd()) return null; break; // http://usejsdoc.org/tags-method.html case "method": if (!parseNamePathOptional() || !ensureEnd()) return null; break; // http://usejsdoc.org/tags-module.html case "module": if (!parseType() || !parseNamePathOptional() || !ensureEnd()) return null; break; // Synonym: http://usejsdoc.org/tags-method.html case "func": if (!parseNamePathOptional() || !ensureEnd()) return null; break; // Synonym: http://usejsdoc.org/tags-method.html case "function": if (!parseNamePathOptional() || !ensureEnd()) return null; break; // Synonym: http://usejsdoc.org/tags-member.html case "var": if (!parseType() || !parseNamePathOptional() || !ensureEnd()) return null; break; // http://usejsdoc.org/tags-name.html case "name": if (!parseNamePath() || !ensureEnd()) return null; break; // http://usejsdoc.org/tags-namespace.html case "namespace": if (!parseType() || !parseNamePathOptional() || !ensureEnd()) return null; break; // http://usejsdoc.org/tags-private.html case "private": if (!parseType() || !parseDescription()) return null; break; // http://usejsdoc.org/tags-protected.html case "protected": if (!parseType() || !parseDescription()) return null; break; // http://usejsdoc.org/tags-public.html case "public": if (!parseType() || !parseDescription()) return null; break; // http://usejsdoc.org/tags-readonly.html case "readonly": if (!ensureEnd()) return null; break; // http://usejsdoc.org/tags-requires.html case "requires": if (!parseNamePath() || !ensureEnd()) return null; break; // http://usejsdoc.org/tags-since.html case "since": if (!parseDescription()) return null; break; // http://usejsdoc.org/tags-static.html case "static": if (!ensureEnd()) return null; break; // http://usejsdoc.org/tags-summary.html case "summary": if (!parseDescription()) return null; break; // http://usejsdoc.org/tags-this.html case "this": if (!parseNamePath() || !ensureEnd()) return null; break; // http://usejsdoc.org/tags-todo.html case "todo": if (!parseDescription()) return null; break; // http://usejsdoc.org/tags-variation.html case "variation": if (!parseVariation()) return null; break; // http://usejsdoc.org/tags-version.html case "version": if (!parseDescription()) return null; break; // default sequences default: if (!parseType() || !parseName() || !parseDescription() || !epilogue()) return null; break; } // Seek global index to end of this tag. index = this._last; lineNumber = newLineNumber; lineStart = newLineStart; return this._tag; } private Tag parseTag() { String title; Tag res; TagParser parser; int startColumn; int startLine; // skip to tag if (!skipToTag()) { return null; } startLine = lineNumber; startColumn = index - lineStart; // scan title title = scanTitle(); // construct tag parser parser = new TagParser(title); res = parser.parse(); if (res != null) { res.startLine = startLine; res.startColumn = startColumn; } return res; } // // Parse JSDoc // String scanJSDocDescription() { StringBuilder description = new StringBuilder(); char ch; boolean atAllowed; atAllowed = true; while (index < length) { ch = source.charAt(index); if (atAllowed && ch == '@') { break; } if (isLineTerminator(ch)) { atAllowed = true; } else if (atAllowed && !isWhiteSpace(ch)) { atAllowed = false; } description.append(advance()); } return description.toString().trim(); } public Pair<String, List<Tag>> parseComment(int lineNumber_, int lineStart_) { List<Tag> tags = new ArrayList<>(); Tag tag; String description; length = source.length(); index = 1; // Skip initial "*" lineNumber = lineNumber_; lineStart = lineStart_; recoverable = true; sloppy = true; description = scanJSDocDescription(); while (true) { tag = parseTag(); if (tag == null) { break; } tags.add(tag); } return Pair.make(description, tags); } } } }
58,229
29.108583
100
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/parser/JSONParser.java
/* * Based on org.mozilla.javascript.json.JsonParser from Rhino. * * Original licensing information: * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.semmle.js.parser; import com.semmle.js.ast.Position; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.json.JSONArray; import com.semmle.js.ast.json.JSONLiteral; import com.semmle.js.ast.json.JSONObject; import com.semmle.js.ast.json.JSONValue; import com.semmle.util.data.Pair; import com.semmle.util.exception.Exceptions; import com.semmle.util.io.WholeIO; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class JSONParser { public static final Pattern JSON_LINE_ENDING = Pattern.compile("(\r\n|\n|\r)"); private int line, column; private int offset; private int length; private String src; private List<ParseError> recoverableErrors; public Pair<JSONValue, List<ParseError>> parseValue(String json) throws ParseError { line = 1; column = 0; offset = 0; recoverableErrors = new ArrayList<ParseError>(); if (json == null) raise("Input string may not be null"); length = json.length(); src = json; JSONValue value = readValue(); consumeWhitespace(); if (offset < length) raise("Expected end of input"); return Pair.make(value, recoverableErrors); } private <T> T raise(String msg) throws ParseError { throw new ParseError(msg, line, column - 1, offset); } private char next() throws ParseError { if (offset >= length) raise("Unexpected end of input"); char c = src.charAt(offset++); if (c == '\r') { if (offset < length && src.charAt(offset) == '\n') { ++column; } else { ++line; column = 0; } } else if (c == '\n') { ++line; column = 0; } else { ++column; } return c; } private char peek() { return offset < length ? src.charAt(offset) : (char) -1; } private JSONValue readValue() throws ParseError { consumeWhitespace(); while (offset < length) { int startoff = offset; Position start = getCurPos(); char c = next(); switch (c) { case '{': return readObject(startoff, start); case '[': return readArray(startoff, start); case 't': consume("rue"); return mkLiteral(startoff, start, true); case 'f': consume("alse"); return mkLiteral(startoff, start, false); case '"': return mkLiteral(startoff, start, readString()); case 'n': consume("ull"); return mkLiteral(startoff, start, null); case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '0': case '-': return mkLiteral(startoff, start, readNumber()); default: raise("Unexpected token"); } } return raise("Unexpected token"); } private Position getCurPos() { return new Position(line, column, offset); } private JSONLiteral mkLiteral(int startoff, Position start, Object value) { int endoff = offset; Position end = getCurPos(); return new JSONLiteral(new SourceLocation(src.substring(startoff, endoff), start, end), value); } private JSONObject readObject(int startoff, Position start) throws ParseError { List<Pair<String, JSONValue>> properties = new ArrayList<Pair<String, JSONValue>>(); int endoff; Position end; consumeWhitespace(); // handle empty object literal case early out: if (peek() == '}') { next(); } else { String id; JSONValue value; boolean needsComma = false; while (offset < length) { char c = next(); switch (c) { case '}': if (!needsComma) { raise("Trailing commas are not allowed in JSON."); } break out; case ',': if (!needsComma) { raise("Unexpected comma in object literal"); } needsComma = false; break; case '"': if (needsComma) { raise("Missing comma in object literal"); } id = readString(); consumeWhitespace(); consume(':'); value = readValue(); properties.add(Pair.make(id, value)); needsComma = true; break; default: raise("JSON object property keys must be string literals."); } consumeWhitespace(); } ++column; raise("Unexpected token"); } endoff = offset; end = getCurPos(); return new JSONObject( new SourceLocation(src.substring(startoff, endoff), start, end), properties); } private JSONArray readArray(int startoff, Position start) throws ParseError { List<JSONValue> elements = new ArrayList<JSONValue>(); int endoff; Position end; consumeWhitespace(); // handle empty array literal case early out: if (peek() == ']') { next(); } else { boolean needsComma = false; while (offset < length) { char c = peek(); switch (c) { case ']': if (!needsComma) { raise("Omitted elements are not allowed in JSON."); } next(); break out; case ',': if (!needsComma) { next(); raise("Omitted elements are not allowed in JSON."); } needsComma = false; next(); break; default: if (needsComma) { raise("Missing comma in array literal"); } elements.add(readValue()); needsComma = true; } consumeWhitespace(); } raise("Unterminated array literal"); } endoff = offset; end = getCurPos(); return new JSONArray(new SourceLocation(src.substring(startoff, endoff), start, end), elements); } private static final String ESCAPES = "\"\"\\\\//b\bn\nf\fr\rt\t"; private String readString() throws ParseError { /* * Optimization: if the source contains no escaped characters, create the * string directly from the source text. */ int stringStart = offset; while (offset < length) { char c = next(); if (c <= '\u001F') { raise("String contains control character"); } else if (c == '\\') { break; } else if (c == '"') { return src.substring(stringStart, offset - 1); } } /* * Slow case: string contains escaped characters. Copy a maximal sequence * of unescaped characters into a temporary buffer, then an escaped * character, and repeat until the entire string is consumed. */ StringBuilder b = new StringBuilder(); while (offset < length) { b.append(src, stringStart, offset - 1); char c = next(); int i = ESCAPES.indexOf(c); if (i >= 0) { b.append(ESCAPES.charAt(i + 1)); } else if (c == 'u') { try { String esc = src.substring(offset, offset + 4); int code = Integer.parseInt(esc, 16); if (code < 0) throw new NumberFormatException(); b.append((char) code); offset += 4; column += 4; } catch (NumberFormatException nfe) { raise("Invalid character escape"); } catch (IndexOutOfBoundsException ioobe) { Exceptions.ignore(ioobe, "Raise semantically more meaningful exception instead."); raise("Invalid character escape"); } } else { raise("Unexpected character in string literal"); } stringStart = offset; while (offset < length) { c = next(); if (c <= '\u001F') { raise("String contains control character"); } else if (c == '\\') { break; } else if (c == '"') { b.append(src, stringStart, offset - 1); return b.toString(); } } } return raise("Unterminated string literal"); } private static final Pattern NUMBER = Pattern.compile("-?(0|[1-9][0-9]*)(\\.[0-9]+)?([eE][-+]?[0-9]+)?"); private Number readNumber() throws ParseError { Matcher m = NUMBER.matcher(src); if (m.find(offset - 1)) { try { String matched = m.group(); // -1 because offset is already one past the start of the number int l = matched.length() - 1; Double d = Double.valueOf(matched); offset += l; column += l; if (d.longValue() == d) return d.longValue(); return d; } catch (NumberFormatException nfe) { Exceptions.ignore(nfe, "A corresponding exception is raised below."); } } return raise("Invalid number literal"); } private void consumeWhitespace() throws ParseError { while (offset < length) { char c = peek(); switch (c) { case ' ': case '\t': case '\r': case '\n': next(); break; case '/': if (offset + 1 < length) { switch (src.charAt(offset + 1)) { case '*': skipBlockComment(); continue; case '/': skipLineComment(); continue; } } default: return; } } } /** Skips the line comment starting at the current position and records a recoverable error. */ private void skipLineComment() throws ParseError { Position pos = new Position(line, column, offset); char c; next(); next(); while ((c = peek()) != '\r' && c != '\n' && c != -1) next(); recoverableErrors.add(new ParseError("Comments are not legal in JSON.", pos)); } /** Skips the block comment starting at the current position and records a recoverable error. */ private void skipBlockComment() throws ParseError { Position pos = new Position(line, column, offset); char c; next(); next(); do { c = peek(); if (c < 0) raise("Unterminated comment."); next(); if (c == '*' && peek() == '/') { next(); break; } } while (true); recoverableErrors.add(new ParseError("Comments are not legal in JSON.", pos)); } private void consume(char token) throws ParseError { char c = next(); if (c != token) raise("Expected " + token + " found " + c); } private void consume(String chars) throws ParseError { for (int i = 0; i < chars.length(); ++i) consume(chars.charAt(i)); } public static void main(String[] args) throws ParseError { JSONParser parser = new JSONParser(); System.out.println(parser.parseValue(new WholeIO().strictread(new File(args[0]))).fst()); } }
11,150
27.446429
100
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/parser/JSParser.java
package com.semmle.js.parser; import com.semmle.js.ast.Comment; import com.semmle.js.ast.Node; import com.semmle.js.ast.Token; import com.semmle.js.extractor.ExtractionMetrics; import com.semmle.js.extractor.ExtractionMetrics.ExtractionPhase; import com.semmle.js.extractor.ExtractorConfig; import com.semmle.js.extractor.ExtractorConfig.SourceType; import java.util.List; /** Helper class for invoking the underlying JavaScript parser. */ public class JSParser { /** * The result of a parse. * * <p>If the parse was successful, {@link #ast} will be non-null. Otherwise, {@link #errors} holds * a list of parse errors encountered. */ public static class Result { /** The parsed source code. */ private final String source; /** The root of the parsed AST. */ private final Node ast; /** The list of parsed tokens. */ private final List<Token> tokens; /** The list of parsed comments. */ private final List<Comment> comments; /** The list of parser errors encountered while parsing. */ private final List<ParseError> errors; public Result( String source, Node ast, List<Token> tokens, List<Comment> comments, List<ParseError> errors) { this.source = source; this.ast = ast; this.tokens = tokens; this.comments = comments; this.errors = errors; } public Node getAST() { return ast; } public String getSource() { return source; } public List<Comment> getComments() { return comments; } public List<Token> getTokens() { return tokens; } public List<ParseError> getErrors() { return errors; } } public static Result parse( ExtractorConfig config, SourceType sourceType, String source, ExtractionMetrics metrics) { metrics.startPhase(ExtractionPhase.JSParser_parse); Result result = JcornWrapper.parse(config, sourceType, source); metrics.stopPhase(ExtractionPhase.JSParser_parse); return result; } }
2,042
25.192308
100
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/parser/ParseError.java
package com.semmle.js.parser; import com.semmle.js.ast.Position; import com.semmle.util.exception.UserError; /** A parse error including both a message and location information. */ public class ParseError extends Throwable { private static final long serialVersionUID = 1L; private Position position; public ParseError(String message, int line, int column, int offset) { this(message, new Position(line, column, offset)); } public ParseError(String message, Position pos) { super(massage(message)); this.position = pos; } /* * Helper function to remove location information included in the parser's * parse error messages. */ private static String massage(String message) { if (message.contains("(")) return message.substring(0, message.lastIndexOf('(') - 1); return message; } /** Convert this parse error into a {@link UserError}. */ public UserError asUserError() { return new UserError(getMessage() + ": " + position); } public Position getPosition() { return position; } public void setPosition(Position position) { this.position = position; } @Override public String toString() { return getMessage(); } }
1,204
24.104167
89
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/parser/TypeScriptParser.java
package com.semmle.js.parser; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.lang.ProcessBuilder.Redirect; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; import com.semmle.js.extractor.DependencyInstallationResult; import com.semmle.js.extractor.EnvironmentVariables; import com.semmle.js.extractor.ExtractionMetrics; import com.semmle.js.extractor.VirtualSourceRoot; import com.semmle.js.parser.JSParser.Result; import com.semmle.ts.extractor.TypeTable; import com.semmle.util.data.StringUtil; import com.semmle.util.data.UnitParser; import com.semmle.util.exception.CatastrophicError; import com.semmle.util.exception.Exceptions; import com.semmle.util.exception.InterruptedError; import com.semmle.util.exception.ResourceError; import com.semmle.util.exception.UserError; import com.semmle.util.logging.LogbackUtils; import com.semmle.util.process.AbstractProcessBuilder; import com.semmle.util.process.Builder; import com.semmle.util.process.Env; import ch.qos.logback.classic.Level; /** * The Java half of our wrapper for invoking the TypeScript parser. * * <p>The Node.js half of the wrapper is expected to live at {@code * $SEMMLE_DIST/tools/typescript-parser-wrapper/main.js}; non-standard locations can be configured * using the property {@value #PARSER_WRAPPER_PATH_ENV_VAR}. * * <p>The script launches the Node.js wrapper in the Node.js runtime, looking for {@code node} on * the {@code PATH} by default. Non-standard locations can be configured using the property {@value * #TYPESCRIPT_NODE_RUNTIME_VAR}, and additional arguments can be configured using the property * {@value #TYPESCRIPT_NODE_RUNTIME_EXTRA_ARGS_VAR}. * * <p>The script is started upon parsing the first TypeScript file and then is kept running in the * background, passing it requests for parsing files and getting JSON-encoded ASTs as responses. */ public class TypeScriptParser { /** * An environment variable that can be set to indicate the location of the TypeScript parser * wrapper when running without SEMMLE_DIST. */ public static final String PARSER_WRAPPER_PATH_ENV_VAR = "SEMMLE_TYPESCRIPT_PARSER_WRAPPER"; /** * An environment variable that can be set to indicate the location of the Node.js runtime, as an * alternative to adding Node to the PATH. */ public static final String TYPESCRIPT_NODE_RUNTIME_VAR = "SEMMLE_TYPESCRIPT_NODE_RUNTIME"; /** * An environment variable that can be set to provide additional arguments to the Node.js runtime * each time it is invoked. Arguments should be separated by spaces. */ public static final String TYPESCRIPT_NODE_RUNTIME_EXTRA_ARGS_VAR = "SEMMLE_TYPESCRIPT_NODE_RUNTIME_EXTRA_ARGS"; /** * An environment variable that can be set to specify a timeout to use when verifying the * TypeScript installation, in milliseconds. Default is 10000. */ public static final String TYPESCRIPT_TIMEOUT_VAR = "SEMMLE_TYPESCRIPT_TIMEOUT"; /** * An environment variable that can be set to specify a number of retries when verifying * the TypeScript installation. Default is 3. */ public static final String TYPESCRIPT_RETRIES_VAR = "SEMMLE_TYPESCRIPT_RETRIES"; /** * An environment variable (without the <tt>SEMMLE_</tt> or <tt>LGTM_</tt> prefix), that can be * set to indicate the maximum heap space usable by the Node.js process, in addition to its * "reserve memory". * * <p>Defaults to 1.0 GB (for a total heap space of 1.4 GB by default). */ public static final String TYPESCRIPT_RAM_SUFFIX = "TYPESCRIPT_RAM"; /** * An environment variable (without the <tt>SEMMLE_</tt> or <tt>LGTM_</tt> prefix), that can be * set to indicate the amount of heap space the Node.js process should reserve for extracting * individual files. * * <p>When less than this amount of memory is available, the TypeScript compiler instance is * restarted to free space. * * <p>Defaults to 400 MB (for a total heap space of 1.4 GB by default). */ public static final String TYPESCRIPT_RAM_RESERVE_SUFFIX = "TYPESCRIPT_RAM_RESERVE"; /** * An environment variable with additional VM arguments to pass to the Node process. * * <p>Only <code>--inspect</code> or <code>--inspect-brk</code> may be used at the moment. */ public static final String TYPESCRIPT_NODE_FLAGS = "SEMMLE_TYPESCRIPT_NODE_FLAGS"; /** * Exit code for Node.js in case of a fatal error from V8. This exit code sometimes occurs * when the process runs out of memory. */ private static final int NODEJS_EXIT_CODE_FATAL_ERROR = 5; /** * Exit code for Node.js in case it exits due to <code>SIGABRT</code>. This exit code sometimes occurs * when the process runs out of memory. */ private static final int NODEJS_EXIT_CODE_SIG_ABORT = 128 + 6; /** The Node.js parser wrapper process, if it has been started already. */ private Process parserWrapperProcess; private String parserWrapperCommand; /** Streams for communicating with the Node.js parser wrapper process. */ private BufferedWriter toParserWrapper; private BufferedReader fromParserWrapper; private String nodeJsVersionString; /** Command to launch the Node.js runtime. Initialised by {@link #verifyNodeInstallation}. */ private String nodeJsRuntime; /** * Arguments to pass to the Node.js runtime each time it is invoked. Initialised by {@link * #verifyNodeInstallation}. */ private List<String> nodeJsRuntimeExtraArgs = Collections.emptyList(); /** If non-zero, we use this instead of relying on the corresponding environment variable. */ private int typescriptRam = 0; /** Metadata requested immediately after starting the TypeScript parser. */ private TypeScriptParserMetadata metadata; /** Sets the amount of RAM to allocate to the TypeScript compiler.s */ public void setTypescriptRam(int megabytes) { this.typescriptRam = megabytes; } /** * Verifies that Node.js and TypeScript are installed and throws an exception otherwise. * * @param verbose if true, log the Node.js executable path, version strings, and any additional * arguments. */ public void verifyInstallation(boolean verbose) { verifyNodeInstallation(); if (verbose) { System.out.println("Found Node.js at: " + nodeJsRuntime); System.out.println("Found Node.js version: " + nodeJsVersionString); if (!nodeJsRuntimeExtraArgs.isEmpty()) { System.out.println("Additional arguments for Node.js: " + nodeJsRuntimeExtraArgs); } } } /** Checks that Node.js is installed and can be run and returns its version string. */ public String verifyNodeInstallation() { if (nodeJsVersionString != null) return nodeJsVersionString; // Determine where to find the Node.js runtime. String explicitNodeJsRuntime = Env.systemEnv().get(TYPESCRIPT_NODE_RUNTIME_VAR); if (explicitNodeJsRuntime != null) { // Use the specified Node.js executable. nodeJsRuntime = explicitNodeJsRuntime; } else { // Look for `node` on the PATH. nodeJsRuntime = "node"; } // Determine any additional arguments to be passed to Node.js each time it's called. String extraArgs = Env.systemEnv().get(TYPESCRIPT_NODE_RUNTIME_EXTRA_ARGS_VAR); if (extraArgs != null) { nodeJsRuntimeExtraArgs = Arrays.asList(extraArgs.split("\\s+")); } // Run 'node --version' with a timeout, and retry a few times if it times out. // If the Java process is suspended we may get a spurious timeout, and we want to // support long suspensions in cloud environments. Instead of setting a huge timeout, // retrying guarantees we can survive arbitrary suspensions as long as they don't happen // too many times in rapid succession. int timeout = Env.systemEnv().getInt(TYPESCRIPT_TIMEOUT_VAR, 10000); int numRetries = Env.systemEnv().getInt(TYPESCRIPT_RETRIES_VAR, 3); for (int i = 0; i < numRetries - 1; ++i) { try { return startNodeAndGetVersion(timeout); } catch (InterruptedError e) { Exceptions.ignore(e, "We will retry the call that caused this exception."); System.err.println("Starting Node.js seems to take a long time. Retrying."); } } try { return startNodeAndGetVersion(timeout); } catch (InterruptedError e) { Exceptions.ignore(e, "Exception details are not important."); throw new CatastrophicError( "Could not start Node.js (timed out after " + (timeout / 1000) + "s and " + numRetries + " attempts"); } } /** * Checks that Node.js is installed and can be run and returns its version string. */ private String startNodeAndGetVersion(int timeout) throws InterruptedError { ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); Builder b = new Builder( getNodeJsRuntimeInvocation("--version"), out, err, getParserWrapper().getParentFile()); b.expectFailure(); // We want to do our own logging in case of an error. try { int r = b.execute(timeout); String stdout = new String(out.toByteArray()); String stderr = new String(err.toByteArray()); if (r != 0 || stdout.length() == 0) { throw new CatastrophicError( "Could not start Node.js. It is required for TypeScript extraction.\n" + stderr); } return nodeJsVersionString = stdout; } catch (ResourceError e) { // In case 'node' is not found, the process builder converts the IOException // into a ResourceError. Exceptions.ignore(e, "We rewrite this into a UserError"); throw new UserError( "Could not start Node.js. It is required for TypeScript extraction." + "\nPlease install Node.js and ensure 'node' is on the PATH."); } } /** * Gets a command line to invoke the Node.js runtime. Any arguments in {@link * TypeScriptParser#nodeJsRuntimeExtraArgs} are passed first, followed by those in {@code args}. */ private List<String> getNodeJsRuntimeInvocation(String... args) { List<String> result = new ArrayList<>(); result.add(nodeJsRuntime); result.addAll(nodeJsRuntimeExtraArgs); for (String arg : args) { result.add(arg); } return result; } private static int getMegabyteCountFromPrefixedEnv(String suffix, int defaultValue) { String envVar = "SEMMLE_" + suffix; String value = Env.systemEnv().get(envVar); if (value == null || value.length() == 0) { envVar = "LGTM_" + suffix; value = Env.systemEnv().get(envVar); } if (value == null || value.length() == 0) { return defaultValue; } Integer amount = UnitParser.parseOpt(value, UnitParser.MEGABYTES); if (amount == null) { throw new UserError("Invalid value for " + envVar + ": '" + value + "'"); } return amount; } /** Start the Node.js parser wrapper process. */ private void setupParserWrapper() { verifyNodeInstallation(); int mainMemoryMb = typescriptRam != 0 ? typescriptRam : getMegabyteCountFromPrefixedEnv(TYPESCRIPT_RAM_SUFFIX, 2000); int reserveMemoryMb = getMegabyteCountFromPrefixedEnv(TYPESCRIPT_RAM_RESERVE_SUFFIX, 400); File parserWrapper = getParserWrapper(); String debugFlagString = Env.systemEnv().getNonEmpty(TYPESCRIPT_NODE_FLAGS); List<String> debugFlags = new ArrayList<>(); if (debugFlagString != null) { for (String flag : debugFlagString.split(" ")) { if (!flag.startsWith("--inspect") || flag.contains(":")) { System.err.println("Ignoring unrecognized Node flag: '" + flag + "'"); } else { debugFlags.add(flag); } } } List<String> cmd = getNodeJsRuntimeInvocation(); cmd.add("--max_old_space_size=" + (mainMemoryMb + reserveMemoryMb)); cmd.addAll(debugFlags); cmd.add(parserWrapper.getAbsolutePath()); ProcessBuilder pb = new ProcessBuilder(cmd); parserWrapperCommand = StringUtil.glue(" ", cmd); pb.environment().put("SEMMLE_TYPESCRIPT_MEMORY_THRESHOLD", "" + mainMemoryMb); try { pb.redirectError(Redirect.INHERIT); // Forward stderr to our own stderr. parserWrapperProcess = pb.start(); OutputStream os = parserWrapperProcess.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8"); toParserWrapper = new BufferedWriter(osw); InputStream is = parserWrapperProcess.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "UTF-8"); fromParserWrapper = new BufferedReader(isr); this.loadMetadata(); } catch (IOException e) { throw new CatastrophicError( "Could not start TypeScript parser wrapper " + "(command: ." + parserWrapperCommand + ")", e); } } /** Get the location of the Node.js parser wrapper script. */ private File getParserWrapper() { File parserWrapper; LogbackUtils.getLogger(AbstractProcessBuilder.class).setLevel(Level.INFO); String explicitPath = Env.systemEnv().get(PARSER_WRAPPER_PATH_ENV_VAR); if (explicitPath != null) { parserWrapper = new File(explicitPath); } else { parserWrapper = new File( EnvironmentVariables.getExtractorRoot(), "tools/typescript-parser-wrapper/main.js"); } if (!parserWrapper.isFile()) throw new ResourceError( "Could not find TypeScript parser: " + parserWrapper + " does not exist."); return parserWrapper; } /** * Send a {@code request} to the Node.js parser wrapper process, and return the response it * replies with. */ private JsonObject talkToParserWrapper(JsonObject request) { if (parserWrapperProcess == null) setupParserWrapper(); if (!parserWrapperProcess.isAlive()) { throw getExceptionFromMalformedResponse(null, null); } String response = null; try { toParserWrapper.write(request.toString()); toParserWrapper.newLine(); toParserWrapper.flush(); response = fromParserWrapper.readLine(); if (response == null || response.isEmpty()) { throw getExceptionFromMalformedResponse(response, null); } try { return new JsonParser().parse(response).getAsJsonObject(); } catch (JsonParseException | IllegalStateException e) { throw getExceptionFromMalformedResponse(response, e); } } catch (IOException e) { throw new CatastrophicError( "Could not communicate with TypeScript parser wrapper " + "(command: ." + parserWrapperCommand + ").", e); } } /** * Creates an exception object describing the best known reason for the TypeScript parser wrapper * failing to behave as expected. * * Note that the stderr stream is redirected to our stderr so a more descriptive error is likely * to be found in the log, but we try to make the Java exception descriptive as well. */ private RuntimeException getExceptionFromMalformedResponse(String response, Exception e) { try { Integer exitCode = null; if (parserWrapperProcess.waitFor(1L, TimeUnit.SECONDS)) { exitCode = parserWrapperProcess.waitFor(); } if (exitCode != null && (exitCode == NODEJS_EXIT_CODE_FATAL_ERROR || exitCode == NODEJS_EXIT_CODE_SIG_ABORT)) { return new ResourceError("The TypeScript parser wrapper crashed, possibly from running out of memory.", e); } if (exitCode != null) { return new CatastrophicError("The TypeScript parser wrapper crashed with exit code " + exitCode); } } catch (InterruptedException e1) { Exceptions.ignore(e, "This is for diagnostic purposes only."); } if (response == null) { return new CatastrophicError("No response from TypeScript parser wrapper", e); } return new CatastrophicError("Unexpected response from TypeScript parser wrapper:\n" + response, e); } /** * Requests metadata from the TypeScript process. See {@link TypeScriptParserMetadata}. */ private void loadMetadata() { JsonObject request = new JsonObject(); request.add("command", new JsonPrimitive("get-metadata")); JsonObject response = talkToParserWrapper(request); checkResponseType(response, "metadata"); this.metadata = new TypeScriptParserMetadata(response); } /** * Returns the AST for a given source file. * * <p>Type information will be available if the file is part of a currently open project, although * this is not yet implemented. * * <p>If the file is not part of a project, only syntactic information will be extracted. */ public Result parse(File sourceFile, String source, ExtractionMetrics metrics) { JsonObject request = new JsonObject(); request.add("command", new JsonPrimitive("parse")); request.add("filename", new JsonPrimitive(sourceFile.getAbsolutePath())); metrics.startPhase(ExtractionMetrics.ExtractionPhase.TypeScriptParser_talkToParserWrapper); JsonObject response = talkToParserWrapper(request); metrics.stopPhase(ExtractionMetrics.ExtractionPhase.TypeScriptParser_talkToParserWrapper); try { checkResponseType(response, "ast"); JsonObject ast = response.get("ast").getAsJsonObject(); metrics.startPhase(ExtractionMetrics.ExtractionPhase.TypeScriptASTConverter_convertAST); Result converted = new TypeScriptASTConverter(metadata).convertAST(ast, source); metrics.stopPhase(ExtractionMetrics.ExtractionPhase.TypeScriptASTConverter_convertAST); return converted; } catch (IllegalStateException e) { throw new CatastrophicError( "TypeScript parser wrapper sent unexpected response: " + response, e); } } /** * Informs the parser process that the following files are going to be requested, in that order. * * <p>The parser process uses this list to start work on the next file before it is requested. */ public void prepareFiles(List<File> files) { JsonObject request = new JsonObject(); request.add("command", new JsonPrimitive("prepare-files")); JsonArray filenames = new JsonArray(); for (File file : files) { filenames.add(new JsonPrimitive(file.getAbsolutePath())); } request.add("filenames", filenames); JsonObject response = talkToParserWrapper(request); checkResponseType(response, "ok"); } /** * Converts a map to an array of [key, value] pairs. */ private JsonArray mapToArray(Map<String, Path> map) { JsonArray result = new JsonArray(); map.forEach( (key, path) -> { JsonArray entry = new JsonArray(); entry.add(key); entry.add(path.toString()); result.add(entry); }); return result; } private static Set<File> getFilesFromJsonArray(JsonArray array) { Set<File> files = new LinkedHashSet<>(); for (JsonElement elm : array) { files.add(new File(elm.getAsString())); } return files; } /** * Returns the set of files included by the inclusion pattern in the given tsconfig.json file. */ public Set<File> getOwnFiles(File tsConfigFile, DependencyInstallationResult deps, VirtualSourceRoot vroot) { JsonObject request = makeLoadCommand("get-own-files", tsConfigFile, deps, vroot); JsonObject response = talkToParserWrapper(request); try { checkResponseType(response, "file-list"); return getFilesFromJsonArray(response.get("ownFiles").getAsJsonArray()); } catch (IllegalStateException e) { throw new CatastrophicError( "TypeScript parser wrapper sent unexpected response: " + response, e); } } /** * Opens a new project based on a tsconfig.json file. The compiler will analyze all files in the * project. * * <p>Call {@link #parse} to access individual files in the project. * * <p>Only one project should be opened at once. */ public ParsedProject openProject(File tsConfigFile, DependencyInstallationResult deps, VirtualSourceRoot vroot) { JsonObject request = makeLoadCommand("open-project", tsConfigFile, deps, vroot); JsonObject response = talkToParserWrapper(request); try { checkResponseType(response, "project-opened"); ParsedProject project = new ParsedProject(tsConfigFile, getFilesFromJsonArray(response.get("ownFiles").getAsJsonArray()), getFilesFromJsonArray(response.get("allFiles").getAsJsonArray())); return project; } catch (IllegalStateException e) { throw new CatastrophicError( "TypeScript parser wrapper sent unexpected response: " + response, e); } } private JsonObject makeLoadCommand(String command, File tsConfigFile, DependencyInstallationResult deps, VirtualSourceRoot vroot) { JsonObject request = new JsonObject(); request.add("command", new JsonPrimitive(command)); request.add("tsConfig", new JsonPrimitive(tsConfigFile.getPath())); request.add("packageEntryPoints", mapToArray(deps.getPackageEntryPoints())); request.add("packageJsonFiles", mapToArray(deps.getPackageJsonFiles())); request.add("sourceRoot", vroot.getSourceRoot() == null ? JsonNull.INSTANCE : new JsonPrimitive(vroot.getSourceRoot().toString())); request.add("virtualSourceRoot", vroot.getVirtualSourceRoot() == null ? JsonNull.INSTANCE : new JsonPrimitive(vroot.getVirtualSourceRoot().toString())); return request; } /** * Closes a project previously opened. * * <p>This main purpose is to free heap space in the Node.js process. */ public void closeProject(File tsConfigFile) { JsonObject request = new JsonObject(); request.add("command", new JsonPrimitive("close-project")); request.add("tsConfig", new JsonPrimitive(tsConfigFile.getPath())); JsonObject response = talkToParserWrapper(request); try { checkResponseType(response, "project-closed"); } catch (IllegalStateException e) { throw new CatastrophicError( "TypeScript parser wrapper sent unexpected response: " + response, e); } } public TypeTable getTypeTable() { JsonObject request = new JsonObject(); request.add("command", new JsonPrimitive("get-type-table")); JsonObject response = talkToParserWrapper(request); try { checkResponseType(response, "type-table"); return new TypeTable(response.get("typeTable").getAsJsonObject()); } catch (IllegalStateException e) { throw new CatastrophicError( "TypeScript parser wrapper sent unexpected response: " + response, e); } } /** * Closes any open project, and in general, brings the TypeScript wrapper to a fresh state as if * it had just been restarted. * * <p>This is to ensure tests are isolated but without the cost of restarting the Node.js process. */ public void reset() { try { resetInternal(); } catch (CatastrophicError e) { Exceptions.ignore(e, "Restarting process instead"); killProcess(); } } private void resetInternal() { if (parserWrapperProcess == null) { return; // Ignore reset requests if the process is not running. } JsonObject request = new JsonObject(); request.add("command", new JsonPrimitive("reset")); JsonObject response = talkToParserWrapper(request); try { checkResponseType(response, "reset-done"); } catch (IllegalStateException e) { throw new CatastrophicError( "TypeScript parser wrapper sent unexpected response: " + response, e); } } private void checkResponseType(JsonObject response, String type) { JsonElement typeElm = response.get("type"); // Report unexpected response types as an internal error. if (typeElm == null || !typeElm.getAsString().equals(type)) { throw new CatastrophicError( "TypeScript parser sent unexpected response: " + response + ". Expected " + type); } } private void tryClose(Closeable stream) { if (stream == null) return; try { stream.close(); } catch (IOException e) { Exceptions.ignore(e, "Closing stream"); } } /** * Forcibly closes the Node.js process. * * <p>A new process will be started the next time a request is made. */ public void killProcess() { if (parserWrapperProcess != null) { parserWrapperProcess.destroy(); parserWrapperProcess = null; } tryClose(toParserWrapper); tryClose(fromParserWrapper); toParserWrapper = null; fromParserWrapper = null; } }
25,337
37.981538
133
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/parser/TypeScriptASTConverter.java
package com.semmle.js.parser; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.semmle.jcorn.TokenType; import com.semmle.js.ast.ArrayExpression; import com.semmle.js.ast.ArrayPattern; import com.semmle.js.ast.ArrowFunctionExpression; import com.semmle.js.ast.AssignmentExpression; import com.semmle.js.ast.AssignmentPattern; import com.semmle.js.ast.AwaitExpression; import com.semmle.js.ast.BinaryExpression; import com.semmle.js.ast.BlockStatement; import com.semmle.js.ast.BreakStatement; import com.semmle.js.ast.CallExpression; import com.semmle.js.ast.CatchClause; import com.semmle.js.ast.Chainable; import com.semmle.js.ast.ClassBody; import com.semmle.js.ast.ClassDeclaration; import com.semmle.js.ast.ClassExpression; import com.semmle.js.ast.Comment; import com.semmle.js.ast.ConditionalExpression; import com.semmle.js.ast.ContinueStatement; import com.semmle.js.ast.DebuggerStatement; import com.semmle.js.ast.DeclarationFlags; import com.semmle.js.ast.Decorator; import com.semmle.js.ast.DoWhileStatement; import com.semmle.js.ast.DynamicImport; import com.semmle.js.ast.EmptyStatement; import com.semmle.js.ast.ExportAllDeclaration; import com.semmle.js.ast.ExportDeclaration; import com.semmle.js.ast.ExportDefaultDeclaration; import com.semmle.js.ast.ExportNamedDeclaration; import com.semmle.js.ast.ExportNamespaceSpecifier; import com.semmle.js.ast.ExportSpecifier; import com.semmle.js.ast.Expression; import com.semmle.js.ast.ExpressionStatement; import com.semmle.js.ast.FieldDefinition; import com.semmle.js.ast.ForInStatement; import com.semmle.js.ast.ForOfStatement; import com.semmle.js.ast.ForStatement; import com.semmle.js.ast.FunctionDeclaration; import com.semmle.js.ast.FunctionExpression; import com.semmle.js.ast.IFunction; import com.semmle.js.ast.INode; import com.semmle.js.ast.IPattern; import com.semmle.js.ast.Identifier; import com.semmle.js.ast.IfStatement; import com.semmle.js.ast.ImportDeclaration; import com.semmle.js.ast.ImportDefaultSpecifier; import com.semmle.js.ast.ImportNamespaceSpecifier; import com.semmle.js.ast.ImportSpecifier; import com.semmle.js.ast.InvokeExpression; import com.semmle.js.ast.LabeledStatement; import com.semmle.js.ast.Literal; import com.semmle.js.ast.LogicalExpression; import com.semmle.js.ast.MemberDefinition; import com.semmle.js.ast.MemberExpression; import com.semmle.js.ast.MetaProperty; import com.semmle.js.ast.MethodDefinition; import com.semmle.js.ast.MethodDefinition.Kind; import com.semmle.js.ast.NewExpression; import com.semmle.js.ast.Node; import com.semmle.js.ast.ObjectExpression; import com.semmle.js.ast.ObjectPattern; import com.semmle.js.ast.ParenthesizedExpression; import com.semmle.js.ast.Position; import com.semmle.js.ast.Program; import com.semmle.js.ast.Property; import com.semmle.js.ast.RestElement; import com.semmle.js.ast.ReturnStatement; import com.semmle.js.ast.SequenceExpression; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.SpreadElement; import com.semmle.js.ast.Statement; import com.semmle.js.ast.Super; import com.semmle.js.ast.SwitchCase; import com.semmle.js.ast.SwitchStatement; import com.semmle.js.ast.TaggedTemplateExpression; import com.semmle.js.ast.TemplateElement; import com.semmle.js.ast.TemplateLiteral; import com.semmle.js.ast.ThisExpression; import com.semmle.js.ast.ThrowStatement; import com.semmle.js.ast.Token; import com.semmle.js.ast.TryStatement; import com.semmle.js.ast.UnaryExpression; import com.semmle.js.ast.UpdateExpression; import com.semmle.js.ast.VariableDeclaration; import com.semmle.js.ast.VariableDeclarator; import com.semmle.js.ast.WhileStatement; import com.semmle.js.ast.WithStatement; import com.semmle.js.ast.YieldExpression; import com.semmle.js.ast.jsx.IJSXAttribute; import com.semmle.js.ast.jsx.IJSXName; import com.semmle.js.ast.jsx.JSXAttribute; import com.semmle.js.ast.jsx.JSXClosingElement; import com.semmle.js.ast.jsx.JSXElement; import com.semmle.js.ast.jsx.JSXEmptyExpression; import com.semmle.js.ast.jsx.JSXExpressionContainer; import com.semmle.js.ast.jsx.JSXIdentifier; import com.semmle.js.ast.jsx.JSXMemberExpression; import com.semmle.js.ast.jsx.JSXOpeningElement; import com.semmle.js.ast.jsx.JSXSpreadAttribute; import com.semmle.js.parser.JSParser.Result; import com.semmle.ts.ast.ArrayTypeExpr; import com.semmle.ts.ast.ConditionalTypeExpr; import com.semmle.ts.ast.DecoratorList; import com.semmle.ts.ast.EnumDeclaration; import com.semmle.ts.ast.EnumMember; import com.semmle.ts.ast.ExportAsNamespaceDeclaration; import com.semmle.ts.ast.ExportWholeDeclaration; import com.semmle.ts.ast.ExpressionWithTypeArguments; import com.semmle.ts.ast.ExternalModuleDeclaration; import com.semmle.ts.ast.ExternalModuleReference; import com.semmle.ts.ast.FunctionTypeExpr; import com.semmle.ts.ast.GenericTypeExpr; import com.semmle.ts.ast.GlobalAugmentationDeclaration; import com.semmle.ts.ast.INodeWithSymbol; import com.semmle.ts.ast.ITypeExpression; import com.semmle.ts.ast.ITypedAstNode; import com.semmle.ts.ast.ImportTypeExpr; import com.semmle.ts.ast.ImportWholeDeclaration; import com.semmle.ts.ast.IndexedAccessTypeExpr; import com.semmle.ts.ast.InferTypeExpr; import com.semmle.ts.ast.InterfaceDeclaration; import com.semmle.ts.ast.InterfaceTypeExpr; import com.semmle.ts.ast.IntersectionTypeExpr; import com.semmle.ts.ast.KeywordTypeExpr; import com.semmle.ts.ast.MappedTypeExpr; import com.semmle.ts.ast.NamespaceDeclaration; import com.semmle.ts.ast.NonNullAssertion; import com.semmle.ts.ast.OptionalTypeExpr; import com.semmle.ts.ast.ParenthesizedTypeExpr; import com.semmle.ts.ast.PredicateTypeExpr; import com.semmle.ts.ast.RestTypeExpr; import com.semmle.ts.ast.TupleTypeExpr; import com.semmle.ts.ast.TypeAliasDeclaration; import com.semmle.ts.ast.TypeAssertion; import com.semmle.ts.ast.TypeParameter; import com.semmle.ts.ast.TypeofTypeExpr; import com.semmle.ts.ast.UnaryTypeExpr; import com.semmle.ts.ast.UnionTypeExpr; import com.semmle.util.collections.CollectionUtil; import com.semmle.util.data.IntList; /** * Utility class for converting a <a * href="https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API">TypeScript AST * node</a> into a {@link Result}. * * <p>TypeScript AST nodes that have no JavaScript equivalent are omitted. */ public class TypeScriptASTConverter { private String source; private final TypeScriptParserMetadata metadata; private int[] lineStarts; private int syntaxKindExtends; private static final Pattern LINE_TERMINATOR = Pattern.compile("\\n|\\r\\n|\\r|\\u2028|\\u2029"); private static final String WHITESPACE_CHAR = "(?:\\s|//.*|/\\*(?:[^*]|\\*(?!/))*\\*/)"; private static final Pattern WHITESPACE = Pattern.compile("^" + WHITESPACE_CHAR + "*"); private static final Pattern EXPORT_DECL_START = Pattern.compile("^export" + "(" + WHITESPACE_CHAR + "+default)?" + WHITESPACE_CHAR + "+"); private static final Pattern TYPEOF_START = Pattern.compile("^typeof" + WHITESPACE_CHAR + "+"); private static final Pattern WHITESPACE_END_PAREN = Pattern.compile("^" + WHITESPACE_CHAR + "*\\)"); TypeScriptASTConverter(TypeScriptParserMetadata metadata) { this.metadata = metadata; this.syntaxKindExtends = metadata.getSyntaxKindId("ExtendsKeyword"); } /** * Convert the given TypeScript AST (which was parsed from {@code source}) into a parser {@link * Result}. */ public Result convertAST(JsonObject ast, String source) { this.lineStarts = toIntArray(ast.getAsJsonArray("$lineStarts")); List<ParseError> errors = new ArrayList<ParseError>(); // process parse diagnostics (i.e., syntax errors) reported by the TypeScript compiler JsonArray parseDiagnostics = ast.get("parseDiagnostics").getAsJsonArray(); if (parseDiagnostics.size() > 0) { for (JsonElement elt : parseDiagnostics) { JsonObject parseDiagnostic = elt.getAsJsonObject(); String message = parseDiagnostic.get("messageText").getAsString(); Position pos = getPosition(parseDiagnostic.get("$pos")); errors.add(new ParseError(message, pos.getLine(), pos.getColumn(), pos.getOffset())); } return new Result(source, null, new ArrayList<>(), new ArrayList<>(), errors); } this.source = source; List<Token> tokens = new ArrayList<>(); List<Comment> comments = new ArrayList<>(); extractTokensAndComments(ast, tokens, comments); Node converted; try { converted = convertNode(ast); } catch (ParseError e) { converted = null; errors.add(e); } return new Result(source, converted, tokens, comments, errors); } /** Converts a JSON array to an int array. The array is assumed to only contain integers. */ private static int[] toIntArray(JsonArray array) { int[] result = new int[array.size()]; for (int i = 0; i < array.size(); ++i) { result[i] = array.get(i).getAsInt(); } return result; } private int getLineFromPos(int pos) { int low = 0, high = this.lineStarts.length - 1; while (low < high) { int mid = high - ((high - low) >> 1); // Get middle, rounding up. int startOfLine = lineStarts[mid]; if (startOfLine <= pos) { low = mid; } else { high = mid - 1; } } return low; } private int getColumnFromLinePos(int line, int pos) { return pos - lineStarts[line]; } /** Extract tokens and comments from the given TypeScript AST. */ private void extractTokensAndComments( JsonObject ast, List<Token> tokens, List<Comment> comments) { for (JsonElement elt : ast.get("$tokens").getAsJsonArray()) { JsonObject token = elt.getAsJsonObject(); String text = token.get("text").getAsString(); Position start = getPosition(token.get("tokenPos")); Position end = advance(start, text); SourceLocation loc = new SourceLocation(text, start, end); String kind = getKind(token); switch (kind) { case "EndOfFileToken": tokens.add(new Token(loc, Token.Type.EOF)); break; case "SingleLineCommentTrivia": case "MultiLineCommentTrivia": String cookedText; if (text.startsWith("//")) cookedText = text.substring(2); else cookedText = text.substring(2, text.length() - 2); comments.add(new Comment(loc, cookedText)); break; case "TemplateHead": case "TemplateMiddle": case "TemplateTail": case "NoSubstitutionTemplateLiteral": tokens.add(new Token(loc, Token.Type.STRING)); break; case "Identifier": tokens.add(new Token(loc, Token.Type.NAME)); break; case "NumericLiteral": tokens.add(new Token(loc, Token.Type.NUM)); break; case "StringLiteral": tokens.add(new Token(loc, Token.Type.STRING)); break; case "RegularExpressionLiteral": tokens.add(new Token(loc, Token.Type.REGEXP)); break; default: Token.Type tp; if (kind.endsWith("Token")) { tp = Token.Type.PUNCTUATOR; } else if (kind.endsWith("Keyword")) { if (text.equals("null")) tp = Token.Type.NULL; else if (text.equals("true")) tp = Token.Type.TRUE; else if (text.equals("false")) tp = Token.Type.FALSE; else tp = Token.Type.KEYWORD; } else { continue; } tokens.add(new Token(loc, tp)); } } } /** Convert the given TypeScript node and its children into a JavaScript {@link Node}. */ private Node convertNode(JsonObject node) throws ParseError { return convertNode(node, null); } /** * Convert the given TypeScript node and its children into a JavaScript {@link Node}. If the * TypesScript node has no explicit {@code kind}, it is assumed to be {@code defaultKind}. */ private Node convertNode(JsonObject node, String defaultKind) throws ParseError { Node astNode = convertNodeUntyped(node, defaultKind); attachStaticType(astNode, node); return astNode; } /** Helper method for `convertNode` that does everything except attaching type information. */ private Node convertNodeUntyped(JsonObject node, String defaultKind) throws ParseError { String kind = getKind(node); if (kind == null) kind = defaultKind; if (kind == null) { // Identifiers and PrivateIdentifiers do not have a "kind" property like other nodes. // Since we encode identifiers and private identifiers the same, default to Identifier. kind = "Identifier"; } SourceLocation loc = getSourceLocation(node); switch (kind) { case "AnyKeyword": return convertKeywordTypeExpr(node, loc, "any"); case "ArrayBindingPattern": return convertArrayBindingPattern(node, loc); case "ArrayLiteralExpression": return convertArrayLiteralExpression(node, loc); case "ArrayType": return convertArrayType(node, loc); case "ArrowFunction": return convertArrowFunction(node, loc); case "AsExpression": return convertTypeAssertionExpression(node, loc); case "AwaitExpression": return convertAwaitExpression(node, loc); case "BigIntKeyword": return convertKeywordTypeExpr(node, loc, "bigint"); case "BigIntLiteral": return convertBigIntLiteral(node, loc); case "BinaryExpression": return convertBinaryExpression(node, loc); case "Block": return convertBlock(node, loc); case "BooleanKeyword": return convertKeywordTypeExpr(node, loc, "boolean"); case "BreakStatement": return convertBreakStatement(node, loc); case "CallExpression": return convertCallExpression(node, loc); case "CallSignature": return convertCallSignature(node, loc); case "CaseClause": return convertCaseClause(node, loc); case "CatchClause": return convertCatchClause(node, loc); case "ClassDeclaration": case "ClassExpression": return convertClass(node, kind, loc); case "CommaListExpression": return convertCommaListExpression(node, loc); case "ComputedPropertyName": return convertComputedPropertyName(node); case "ConditionalExpression": return convertConditionalExpression(node, loc); case "ConditionalType": return convertConditionalType(node, loc); case "Constructor": return convertConstructor(node, loc); case "ConstructSignature": return convertConstructSignature(node, loc); case "ConstructorType": return convertConstructorType(node, loc); case "ContinueStatement": return convertContinueStatement(node, loc); case "DebuggerStatement": return convertDebuggerStatement(loc); case "Decorator": return convertDecorator(node, loc); case "DefaultClause": return convertCaseClause(node, loc); case "DeleteExpression": return convertDeleteExpression(node, loc); case "DoStatement": return convertDoStatement(node, loc); case "ElementAccessExpression": return convertElementAccessExpression(node, loc); case "EmptyStatement": return convertEmptyStatement(loc); case "EnumDeclaration": return convertEnumDeclaration(node, loc); case "EnumMember": return convertEnumMember(node, loc); case "ExportAssignment": return convertExportAssignment(node, loc); case "ExportDeclaration": return convertExportDeclaration(node, loc); case "ExportSpecifier": return convertExportSpecifier(node, loc); case "ExpressionStatement": return convertExpressionStatement(node, loc); case "ExpressionWithTypeArguments": return convertExpressionWithTypeArguments(node, loc); case "ExternalModuleReference": return convertExternalModuleReference(node, loc); case "FalseKeyword": return convertFalseKeyword(loc); case "NeverKeyword": return convertKeywordTypeExpr(node, loc, "never"); case "NumberKeyword": return convertKeywordTypeExpr(node, loc, "number"); case "NumericLiteral": return convertNumericLiteral(node, loc); case "ForStatement": return convertForStatement(node, loc); case "ForInStatement": return convertForInStatement(node, loc); case "ForOfStatement": return convertForOfStatement(node, loc); case "FunctionDeclaration": return convertFunctionDeclaration(node, loc); case "FunctionExpression": return convertFunctionExpression(node, loc); case "FunctionType": return convertFunctionType(node, loc); case "Identifier": case "PrivateIdentifier": return convertIdentifier(node, loc); case "IfStatement": return convertIfStatement(node, loc); case "ImportClause": return convertImportClause(node, loc); case "ImportDeclaration": return convertImportDeclaration(node, loc); case "ImportEqualsDeclaration": return convertImportEqualsDeclaration(node, loc); case "ImportKeyword": return convertImportKeyword(loc); case "ImportSpecifier": return convertImportSpecifier(node, loc); case "ImportType": return convertImportType(node, loc); case "IndexSignature": return convertIndexSignature(node, loc); case "IndexedAccessType": return convertIndexedAccessType(node, loc); case "InferType": return convertInferType(node, loc); case "InterfaceDeclaration": return convertInterfaceDeclaration(node, loc); case "IntersectionType": return convertIntersectionType(node, loc); case "JsxAttribute": return convertJsxAttribute(node, loc); case "JsxClosingElement": return convertJsxClosingElement(node, loc); case "JsxElement": return convertJsxElement(node, loc); case "JsxExpression": return convertJsxExpression(node, loc); case "JsxFragment": return convertJsxFragment(node, loc); case "JsxOpeningElement": return convertJsxOpeningElement(node, loc); case "JsxOpeningFragment": return convertJsxOpeningFragment(node, loc); case "JsxSelfClosingElement": return convertJsxSelfClosingElement(node, loc); case "JsxClosingFragment": return convertJsxClosingFragment(node, loc); case "JsxSpreadAttribute": return convertJsxSpreadAttribute(node, loc); case "JsxText": case "JsxTextAllWhiteSpaces": return convertJsxText(node, loc); case "LabeledStatement": return convertLabeledStatement(node, loc); case "LiteralType": return convertLiteralType(node, loc); case "MappedType": return convertMappedType(node, loc); case "MetaProperty": return convertMetaProperty(node, loc); case "GetAccessor": case "SetAccessor": case "MethodDeclaration": case "MethodSignature": return convertMethodDeclaration(node, kind, loc); case "ModuleDeclaration": case "NamespaceDeclaration": return convertNamespaceDeclaration(node, loc); case "ModuleBlock": return convertModuleBlock(node, loc); case "NamespaceExport": return convertNamespaceExport(node, loc); case "NamespaceExportDeclaration": return convertNamespaceExportDeclaration(node, loc); case "NamespaceImport": return convertNamespaceImport(node, loc); case "NewExpression": return convertNewExpression(node, loc); case "NonNullExpression": return convertNonNullExpression(node, loc); case "NoSubstitutionTemplateLiteral": return convertNoSubstitutionTemplateLiteral(node, loc); case "NullKeyword": return convertNullKeyword(loc); case "ObjectBindingPattern": return convertObjectBindingPattern(node, loc); case "ObjectKeyword": return convertKeywordTypeExpr(node, loc, "object"); case "ObjectLiteralExpression": return convertObjectLiteralExpression(node, loc); case "OmittedExpression": return convertOmittedExpression(); case "OptionalType": return convertOptionalType(node, loc); case "Parameter": return convertParameter(node, loc); case "ParenthesizedExpression": return convertParenthesizedExpression(node, loc); case "ParenthesizedType": return convertParenthesizedType(node, loc); case "PostfixUnaryExpression": return convertPostfixUnaryExpression(node, loc); case "PrefixUnaryExpression": return convertPrefixUnaryExpression(node, loc); case "PropertyAccessExpression": return convertPropertyAccessExpression(node, loc); case "PropertyAssignment": return convertPropertyAssignment(node, loc); case "PropertyDeclaration": case "PropertySignature": return convertPropertyDeclaration(node, kind, loc); case "RegularExpressionLiteral": return convertRegularExpressionLiteral(loc); case "RestType": return convertRestType(node, loc); case "QualifiedName": return convertQualifiedName(node, loc); case "ReturnStatement": return convertReturnStatement(node, loc); case "SemicolonClassElement": return convertSemicolonClassElement(); case "SourceFile": return convertSourceFile(node, loc); case "ShorthandPropertyAssignment": return convertShorthandPropertyAssignment(node, loc); case "SpreadAssignment": case "SpreadElement": case "SpreadElementExpression": return convertSpreadElement(node, loc); case "StringKeyword": return convertKeywordTypeExpr(node, loc, "string"); case "StringLiteral": return convertStringLiteral(node, loc); case "SuperKeyword": return convertSuperKeyword(loc); case "SwitchStatement": return convertSwitchStatement(node, loc); case "SymbolKeyword": return convertKeywordTypeExpr(node, loc, "symbol"); case "TaggedTemplateExpression": return convertTaggedTemplateExpression(node, loc); case "TemplateExpression": return convertTemplateExpression(node, loc); case "TemplateHead": case "TemplateMiddle": case "TemplateTail": return convertTemplateElement(node, kind, loc); case "ThisKeyword": return convertThisKeyword(loc); case "ThisType": return convertKeywordTypeExpr(node, loc, "this"); case "ThrowStatement": return convertThrowStatement(node, loc); case "TrueKeyword": return convertTrueKeyword(loc); case "TryStatement": return convertTryStatement(node, loc); case "TupleType": return convertTupleType(node, loc); case "TypeAliasDeclaration": return convertTypeAliasDeclaration(node, loc); case "TypeAssertionExpression": return convertTypeAssertionExpression(node, loc); case "TypeLiteral": return convertTypeLiteral(node, loc); case "TypeOfExpression": return convertTypeOfExpression(node, loc); case "TypeOperator": return convertTypeOperator(node, loc); case "TypeParameter": return convertTypeParameter(node, loc); case "TypePredicate": return convertTypePredicate(node, loc); case "TypeReference": return convertTypeReference(node, loc); case "TypeQuery": return convertTypeQuery(node, loc); case "UndefinedKeyword": return convertKeywordTypeExpr(node, loc, "undefined"); case "UnionType": return convertUnionType(node, loc); case "UnknownKeyword": return convertKeywordTypeExpr(node, loc, "unknown"); case "VariableDeclaration": return convertVariableDeclaration(node, loc); case "VariableDeclarationList": return convertVariableDeclarationList(node, loc); case "VariableStatement": return convertVariableStatement(node, loc); case "VoidExpression": return convertVoidExpression(node, loc); case "VoidKeyword": return convertKeywordTypeExpr(node, loc, "void"); case "WhileStatement": return convertWhileStatement(node, loc); case "WithStatement": return convertWithStatement(node, loc); case "YieldExpression": return convertYieldExpression(node, loc); default: throw new ParseError( "Unsupported TypeScript syntax " + kind, getSourceLocation(node).getStart()); } } /** * Attaches type information from the JSON object to the given AST node, if applicable. This is * called from {@link #convertNode}. */ private void attachStaticType(Node astNode, JsonObject json) { if (astNode instanceof ITypedAstNode && json.has("$type")) { ITypedAstNode typedAstNode = (ITypedAstNode) astNode; int typeId = json.get("$type").getAsInt(); typedAstNode.setStaticTypeId(typeId); } } /** Attaches a TypeScript compiler symbol to the given node, if any was provided. */ private void attachSymbolInformation(INodeWithSymbol node, JsonObject json) { if (json.has("$symbol")) { int symbol = json.get("$symbol").getAsInt(); node.setSymbol(symbol); } } /** Attaches call signatures and related symbol information to a call site. */ private void attachResolvedSignature(InvokeExpression node, JsonObject json) { if (json.has("$resolvedSignature")) { int id = json.get("$resolvedSignature").getAsInt(); node.setResolvedSignatureId(id); } if (json.has("$overloadIndex")) { int id = json.get("$overloadIndex").getAsInt(); node.setOverloadIndex(id); } attachSymbolInformation(node, json); } /** Attached the declared call signature to a function. */ private void attachDeclaredSignature(IFunction node, JsonObject json) { if (json.has("$declaredSignature")) { node.setDeclaredSignatureId(json.get("$declaredSignature").getAsInt()); } } /** * Convert the given array of TypeScript AST nodes into a list of JavaScript AST nodes, skipping * any {@code null} elements. */ private <T extends INode> List<T> convertNodes(Iterable<JsonElement> nodes) throws ParseError { return convertNodes(nodes, true); } /** * Convert the given array of TypeScript AST nodes into a list of JavaScript AST nodes, where * {@code skipNull} indicates whether {@code null} elements should be skipped or not. */ @SuppressWarnings("unchecked") private <T extends INode> List<T> convertNodes(Iterable<JsonElement> nodes, boolean skipNull) throws ParseError { List<T> res = new ArrayList<T>(); for (JsonElement elt : nodes) { T converted = (T) convertNode(elt.getAsJsonObject()); if (!skipNull || converted != null) res.add(converted); } return res; } /** * Converts the given child to an AST node of the given type or <tt>null</tt>. A ParseError is * thrown if a different type of node was found. * * <p>This is used to detect syntax errors that are not reported as syntax errors by the * TypeScript parser. Usually they are reported as errors in a later compiler stage, which the * extractor does not run. * * <p>Returns <tt>null</tt> if the child is absent. */ @SuppressWarnings("unchecked") private <T extends Node> T tryConvertChild(JsonObject node, String prop, Class<T> expectedType) throws ParseError { Node child = convertChild(node, prop); if (child == null || expectedType.isInstance(child)) { return (T) child; } else { throw new ParseError("Unsupported TypeScript syntax", getSourceLocation(node).getStart()); } } /** Convert the child node named {@code prop} of AST node {@code node}. */ private <T extends Node> T convertChild(JsonObject node, String prop) throws ParseError { return convertChild(node, prop, null); } /** * Convert the child node named {@code prop} of AST node {@code node}, with {@code kind} as its * default kind. */ @SuppressWarnings("unchecked") private <T extends INode> T convertChild(JsonObject node, String prop, String kind) throws ParseError { JsonElement child = node.get(prop); if (child == null) return null; return (T) convertNode(child.getAsJsonObject(), kind); } /** Convert the child nodes named {@code prop} of AST node {@code node}. */ private <T extends INode> List<T> convertChildren(JsonObject node, String prop) throws ParseError { return convertChildren(node, prop, true); } /** Like convertChildren but returns an empty list if the property is missing. */ private <T extends INode> List<T> convertChildrenNotNull(JsonObject node, String prop) throws ParseError { List<T> nodes = convertChildren(node, prop, true); if (nodes == null) { return Collections.emptyList(); } return nodes; } /** * Convert the child nodes named {@code prop} of AST node {@code node}, where {@code skipNull} * indicates whether or not to skip null children. */ private <T extends INode> List<T> convertChildren(JsonObject node, String prop, boolean skipNull) throws ParseError { JsonElement child = node.get(prop); if (child == null) return null; return convertNodes(child.getAsJsonArray(), skipNull); } /* Converter methods for the individual TypeScript AST node types. */ private Node convertArrayBindingPattern(JsonObject array, SourceLocation loc) throws ParseError { List<Expression> elements = new ArrayList<>(); for (JsonElement elt : array.get("elements").getAsJsonArray()) { JsonObject element = (JsonObject) elt; SourceLocation eltLoc = getSourceLocation(element); Expression convertedElt = convertChild(element, "name"); if (hasChild(element, "initializer")) convertedElt = new AssignmentPattern(eltLoc, "=", convertedElt, convertChild(element, "initializer")); else if (hasChild(element, "dotDotDotToken")) convertedElt = new RestElement(eltLoc, convertedElt); elements.add(convertedElt); } return new ArrayPattern(loc, elements); } private Node convertArrayLiteralExpression(JsonObject node, SourceLocation loc) throws ParseError { return new ArrayExpression(loc, convertChildren(node, "elements", false)); } private Node convertArrayType(JsonObject node, SourceLocation loc) throws ParseError { return new ArrayTypeExpr(loc, convertChildAsType(node, "elementType")); } private Node convertArrowFunction(JsonObject node, SourceLocation loc) throws ParseError { ArrowFunctionExpression function = new ArrowFunctionExpression( loc, convertParameters(node), convertChild(node, "body"), false, hasModifier(node, "AsyncKeyword"), convertChildrenNotNull(node, "typeParameters"), convertParameterTypes(node), convertChildAsType(node, "type"), getOptionalParameterIndices(node)); attachDeclaredSignature(function, node); return function; } private Node convertAwaitExpression(JsonObject node, SourceLocation loc) throws ParseError { return new AwaitExpression(loc, convertChild(node, "expression")); } private Node convertBigIntLiteral(JsonObject node, SourceLocation loc) throws ParseError { String text = node.get("text").getAsString(); String value = text.substring(0, text.length() - 1); // Remove the 'n' suffix. return new Literal(loc, TokenType.bigint, value); } private Node convertBinaryExpression(JsonObject node, SourceLocation loc) throws ParseError { Expression left = convertChild(node, "left"); Expression right = convertChild(node, "right"); JsonObject operatorToken = node.get("operatorToken").getAsJsonObject(); String operator = getSourceLocation(operatorToken).getSource(); switch (operator) { case ",": List<Expression> expressions = new ArrayList<Expression>(); if (left instanceof SequenceExpression) expressions.addAll(((SequenceExpression) left).getExpressions()); else expressions.add(left); if (right instanceof SequenceExpression) expressions.addAll(((SequenceExpression) right).getExpressions()); else expressions.add(right); return new SequenceExpression(loc, expressions); case "||": case "&&": return new LogicalExpression(loc, operator, left, right); case "=": left = convertLValue(left); // For plain assignments, the lhs can be a destructuring pattern. return new AssignmentExpression(loc, operator, left, right); case "+=": case "-=": case "*=": case "**=": case "/=": case "%=": case "^=": case "&=": case "|=": case ">>=": case "<<=": case ">>>=": return new AssignmentExpression(loc, operator, convertLValue(left), right); default: return new BinaryExpression(loc, operator, left, right); } } private Node convertBlock(JsonObject node, SourceLocation loc) throws ParseError { return new BlockStatement(loc, convertChildren(node, "statements")); } private Node convertBreakStatement(JsonObject node, SourceLocation loc) throws ParseError { return new BreakStatement(loc, convertChild(node, "label")); } private Node convertCallExpression(JsonObject node, SourceLocation loc) throws ParseError { List<Expression> arguments = convertChildren(node, "arguments"); if (arguments.size() == 1 && hasKind(node.get("expression"), "ImportKeyword")) { return new DynamicImport(loc, arguments.get(0)); } Expression callee = convertChild(node, "expression"); List<ITypeExpression> typeArguments = convertChildrenAsTypes(node, "typeArguments"); boolean optional = node.has("questionDotToken"); boolean onOptionalChain = Chainable.isOnOptionalChain(optional, callee); CallExpression call = new CallExpression(loc, callee, typeArguments, arguments, optional, onOptionalChain); attachResolvedSignature(call, node); return call; } private MethodDefinition convertCallSignature(JsonObject node, SourceLocation loc) throws ParseError { FunctionExpression function = convertImplicitFunction(node, loc); int flags = getMemberModifierKeywords(node) | DeclarationFlags.abstract_; return new MethodDefinition(loc, flags, Kind.FUNCTION_CALL_SIGNATURE, null, function); } private Node convertCaseClause(JsonObject node, SourceLocation loc) throws ParseError { return convertDefaultClause(node, loc); } private Node convertCatchClause(JsonObject node, SourceLocation loc) throws ParseError { IPattern pattern = null; JsonElement variableDecl = node.get("variableDeclaration"); if (variableDecl != null) pattern = convertChild(variableDecl.getAsJsonObject(), "name"); return new CatchClause(loc, pattern, null, convertChild(node, "block")); } private List<ITypeExpression> convertSuperInterfaceClause(JsonArray supers) throws ParseError { List<ITypeExpression> result = new ArrayList<>(); for (JsonElement elt : supers) { JsonObject superType = elt.getAsJsonObject(); ITypeExpression objectType = convertChildAsType(superType, "expression"); if (objectType == null) continue; List<ITypeExpression> typeArguments = convertChildrenAsTypes(superType, "typeArguments"); if (typeArguments.isEmpty()) { result.add(objectType); } else { result.add(new GenericTypeExpr(getSourceLocation(superType), objectType, typeArguments)); } } return result; } private Node convertClass(JsonObject node, String kind, SourceLocation loc) throws ParseError { Identifier id = convertChild(node, "name"); List<TypeParameter> typeParameters = convertChildrenNotNull(node, "typeParameters"); Expression superClass = null; List<ITypeExpression> superInterfaces = null; int afterHead = id == null ? loc.getStart().getOffset() + 5 : id.getLoc().getEnd().getOffset(); for (JsonElement elt : getChildIterable(node, "heritageClauses")) { JsonObject heritageClause = elt.getAsJsonObject(); JsonArray supers = heritageClause.get("types").getAsJsonArray(); if (heritageClause.get("token").getAsInt() == syntaxKindExtends) { if (supers.size() > 0) { superClass = (Expression) convertNode(supers.get(0).getAsJsonObject()); } } else { superInterfaces = convertSuperInterfaceClause(supers); } afterHead = heritageClause.get("$end").getAsInt(); } if (superInterfaces == null) { superInterfaces = new ArrayList<>(); } String skip = source.substring(loc.getStart().getOffset(), afterHead) + matchWhitespace(afterHead); SourceLocation bodyLoc = new SourceLocation(loc.getSource(), loc.getStart(), loc.getEnd()); advance(bodyLoc, skip); ClassBody body = new ClassBody(bodyLoc, convertChildren(node, "members")); if ("ClassExpression".equals(kind)) { ClassExpression classExpr = new ClassExpression(loc, id, typeParameters, superClass, superInterfaces, body); attachSymbolInformation(classExpr.getClassDef(), node); return fixExports(loc, classExpr); } boolean hasDeclareKeyword = hasModifier(node, "DeclareKeyword"); boolean hasAbstractKeyword = hasModifier(node, "AbstractKeyword"); ClassDeclaration classDecl = new ClassDeclaration( loc, id, typeParameters, superClass, superInterfaces, body, hasDeclareKeyword, hasAbstractKeyword); attachSymbolInformation(classDecl.getClassDef(), node); if (node.has("decorators")) { classDecl.addDecorators(convertChildren(node, "decorators")); advanceUntilAfter(loc, classDecl.getDecorators()); } Node exportedDecl = fixExports(loc, classDecl); // Convert default-exported anonymous class declarations to class expressions. if (exportedDecl instanceof ExportDefaultDeclaration && !classDecl.getClassDef().hasId()) { return new ExportDefaultDeclaration( exportedDecl.getLoc(), new ClassExpression(classDecl.getLoc(), classDecl.getClassDef())); } return exportedDecl; } private Node convertCommaListExpression(JsonObject node, SourceLocation loc) throws ParseError { return new SequenceExpression(loc, convertChildren(node, "elements")); } private Node convertComputedPropertyName(JsonObject node) throws ParseError { return convertChild(node, "expression"); } private Node convertConditionalExpression(JsonObject node, SourceLocation loc) throws ParseError { return new ConditionalExpression( loc, convertChild(node, "condition"), convertChild(node, "whenTrue"), convertChild(node, "whenFalse")); } private Node convertConditionalType(JsonObject node, SourceLocation loc) throws ParseError { return new ConditionalTypeExpr( loc, convertChild(node, "checkType"), convertChild(node, "extendsType"), convertChild(node, "trueType"), convertChild(node, "falseType")); } private SourceLocation getSourceRange(Position from, Position to) { return new SourceLocation(source.substring(from.getOffset(), to.getOffset()), from, to); } private DecoratorList makeDecoratorList(JsonElement decorators) throws ParseError { if (!(decorators instanceof JsonArray)) return null; JsonArray array = decorators.getAsJsonArray(); SourceLocation firstLoc = null, lastLoc = null; List<Decorator> list = new ArrayList<>(); for (JsonElement decoratorElm : array) { JsonObject decorator = decoratorElm.getAsJsonObject(); if (hasKind(decorator, "Decorator")) { SourceLocation location = getSourceLocation(decorator); list.add(convertDecorator(decorator, location)); if (firstLoc == null) { firstLoc = location; } lastLoc = location; } } if (firstLoc == null) return null; return new DecoratorList(getSourceRange(firstLoc.getStart(), lastLoc.getEnd()), list); } private List<DecoratorList> convertParameterDecorators(JsonObject function) throws ParseError { List<DecoratorList> decoratorLists = new ArrayList<>(); for (JsonElement parameter : getProperParameters(function)) { decoratorLists.add(makeDecoratorList(parameter.getAsJsonObject().get("decorators"))); } return decoratorLists; } private Node convertConstructor(JsonObject node, SourceLocation loc) throws ParseError { int flags = getMemberModifierKeywords(node); boolean isComputed = hasComputedName(node); boolean isStatic = DeclarationFlags.isStatic(flags); if (isComputed) { flags |= DeclarationFlags.computed; } // for some reason, the TypeScript compiler treats static methods named "constructor" // and methods with computed name "constructor" as constructors, even though they aren't MethodDefinition.Kind methodKind = isStatic || isComputed ? Kind.METHOD : Kind.CONSTRUCTOR; Expression key; if (isComputed) key = convertChild((JsonObject) node.get("name"), "expression"); else key = new Identifier(loc, "constructor"); List<Expression> params = convertParameters(node); List<ITypeExpression> paramTypes = convertParameterTypes(node); List<DecoratorList> paramDecorators = convertParameterDecorators(node); FunctionExpression value = new FunctionExpression( loc, null, params, convertChild(node, "body"), false, false, Collections.emptyList(), paramTypes, paramDecorators, null, null, getOptionalParameterIndices(node)); attachSymbolInformation(value, node); attachStaticType(value, node); attachDeclaredSignature(value, node); List<FieldDefinition> parameterFields = convertParameterFields(node); return new MethodDefinition(loc, flags, methodKind, key, value, parameterFields); } private MethodDefinition convertConstructSignature(JsonObject node, SourceLocation loc) throws ParseError { FunctionExpression function = convertImplicitFunction(node, loc); int flags = getMemberModifierKeywords(node) | DeclarationFlags.abstract_; return new MethodDefinition(loc, flags, Kind.CONSTRUCTOR_CALL_SIGNATURE, null, function); } private Node convertConstructorType(JsonObject node, SourceLocation loc) throws ParseError { return new FunctionTypeExpr(loc, convertImplicitFunction(node, loc), true); } private Node convertContinueStatement(JsonObject node, SourceLocation loc) throws ParseError { return new ContinueStatement(loc, convertChild(node, "label")); } private Node convertDebuggerStatement(SourceLocation loc) { return new DebuggerStatement(loc); } private Decorator convertDecorator(JsonObject node, SourceLocation loc) throws ParseError { return new Decorator(loc, convertChild(node, "expression")); } private Node convertDefaultClause(JsonObject node, SourceLocation loc) throws ParseError { return new SwitchCase( loc, convertChild(node, "expression"), convertChildren(node, "statements")); } private Node convertDeleteExpression(JsonObject node, SourceLocation loc) throws ParseError { return new UnaryExpression(loc, "delete", convertChild(node, "expression"), true); } private Node convertDoStatement(JsonObject node, SourceLocation loc) throws ParseError { return new DoWhileStatement( loc, convertChild(node, "expression"), convertChild(node, "statement")); } private Node convertElementAccessExpression(JsonObject node, SourceLocation loc) throws ParseError { Expression object = convertChild(node, "expression"); Expression property = convertChild(node, "argumentExpression"); boolean optional = node.has("questionDotToken"); boolean onOptionalChain = Chainable.isOnOptionalChain(optional, object); return new MemberExpression(loc, object, property, true, optional, onOptionalChain); } private Node convertEmptyStatement(SourceLocation loc) { return new EmptyStatement(loc); } private Node convertEnumDeclaration(JsonObject node, SourceLocation loc) throws ParseError { EnumDeclaration enumDeclaration = new EnumDeclaration( loc, hasModifier(node, "ConstKeyword"), hasModifier(node, "DeclareKeyword"), convertChildrenNotNull(node, "decorators"), convertChild(node, "name"), convertChildren(node, "members")); attachSymbolInformation(enumDeclaration, node); advanceUntilAfter(loc, enumDeclaration.getDecorators()); return fixExports(loc, enumDeclaration); } /** * Converts a TypeScript Identifier or StringLiteral node to an Identifier AST node, or {@code * null} if the given node is not of the expected kind. */ private Identifier convertNodeAsIdentifier(JsonObject node) throws ParseError { SourceLocation loc = getSourceLocation(node); if (isIdentifier(node)) { return convertIdentifier(node, loc); } else if (hasKind(node, "StringLiteral")) { return new Identifier(loc, node.get("text").getAsString()); } else { return null; } } private Node convertEnumMember(JsonObject node, SourceLocation loc) throws ParseError { Identifier name = convertNodeAsIdentifier(node.get("name").getAsJsonObject()); if (name == null) return null; EnumMember member = new EnumMember(loc, name, convertChild(node, "initializer")); attachSymbolInformation(member, node); return member; } private Node convertExportAssignment(JsonObject node, SourceLocation loc) throws ParseError { if (hasChild(node, "isExportEquals") && node.get("isExportEquals").getAsBoolean()) return new ExportWholeDeclaration(loc, convertChild(node, "expression")); return new ExportDefaultDeclaration(loc, convertChild(node, "expression")); } private Node convertExportDeclaration(JsonObject node, SourceLocation loc) throws ParseError { Literal source = tryConvertChild(node, "moduleSpecifier", Literal.class); if (hasChild(node, "exportClause")) { boolean hasTypeKeyword = node.get("isTypeOnly").getAsBoolean(); List<ExportSpecifier> specifiers = hasKind(node.get("exportClause"), "NamespaceExport") ? Collections.singletonList(convertChild(node, "exportClause")) : convertChildren(node.get("exportClause").getAsJsonObject(), "elements"); return new ExportNamedDeclaration(loc, null, specifiers, source, hasTypeKeyword); } else { return new ExportAllDeclaration(loc, source); } } private Node convertExportSpecifier(JsonObject node, SourceLocation loc) throws ParseError { return new ExportSpecifier( loc, convertChild(node, hasChild(node, "propertyName") ? "propertyName" : "name"), convertChild(node, "name")); } private Node convertNamespaceExport(JsonObject node, SourceLocation loc) throws ParseError { // Convert the "* as ns" from an export declaration. return new ExportNamespaceSpecifier(loc, convertChild(node, "name")); } private Node convertExpressionStatement(JsonObject node, SourceLocation loc) throws ParseError { Expression expression = convertChild(node, "expression"); return new ExpressionStatement(loc, expression); } private Node convertExpressionWithTypeArguments(JsonObject node, SourceLocation loc) throws ParseError { Expression expression = convertChild(node, "expression"); List<ITypeExpression> typeArguments = convertChildrenAsTypes(node, "typeArguments"); if (typeArguments.isEmpty()) return expression; return new ExpressionWithTypeArguments(loc, expression, typeArguments); } private Node convertExternalModuleReference(JsonObject node, SourceLocation loc) throws ParseError { ExternalModuleReference moduleRef = new ExternalModuleReference(loc, convertChild(node, "expression")); attachSymbolInformation(moduleRef, node); return moduleRef; } private Node convertFalseKeyword(SourceLocation loc) { return new Literal(loc, TokenType._false, false); } private Node convertNumericLiteral(JsonObject node, SourceLocation loc) throws NumberFormatException { return new Literal(loc, TokenType.num, Double.valueOf(node.get("text").getAsString())); } private Node convertForStatement(JsonObject node, SourceLocation loc) throws ParseError { return new ForStatement( loc, convertChild(node, "initializer"), convertChild(node, "condition"), convertChild(node, "incrementor"), convertChild(node, "statement")); } private Node convertForInStatement(JsonObject node, SourceLocation loc) throws ParseError { Node initializer = convertChild(node, "initializer"); if (initializer instanceof Expression) initializer = convertLValue((Expression) initializer); return new ForInStatement( loc, initializer, convertChild(node, "expression"), convertChild(node, "statement"), false); } private Node convertForOfStatement(JsonObject node, SourceLocation loc) throws ParseError { Node initializer = convertChild(node, "initializer"); if (initializer instanceof Expression) initializer = convertLValue((Expression) initializer); return new ForOfStatement( loc, initializer, convertChild(node, "expression"), convertChild(node, "statement")); } private Node convertFunctionDeclaration(JsonObject node, SourceLocation loc) throws ParseError { List<Expression> params = convertParameters(node); Identifier fnId = convertChild(node, "name", "Identifier"); if (fnId == null) { // Anonymous function declarations may occur as part of default exported functions. // We represent these as function expressions. return fixExports(loc, convertFunctionExpression(node, loc)); } BlockStatement fnbody = convertChild(node, "body"); boolean generator = hasChild(node, "asteriskToken"); boolean async = hasModifier(node, "AsyncKeyword"); boolean hasDeclareKeyword = hasModifier(node, "DeclareKeyword"); List<ITypeExpression> paramTypes = convertParameterTypes(node); List<TypeParameter> typeParameters = convertChildrenNotNull(node, "typeParameters"); ITypeExpression returnType = convertChildAsType(node, "type"); ITypeExpression thisParam = convertThisParameterType(node); FunctionDeclaration function = new FunctionDeclaration( loc, fnId, params, fnbody, generator, async, hasDeclareKeyword, typeParameters, paramTypes, returnType, thisParam, getOptionalParameterIndices(node)); attachSymbolInformation(function, node); attachStaticType(function, node); attachDeclaredSignature(function, node); return fixExports(loc, function); } private Node convertFunctionExpression(JsonObject node, SourceLocation loc) throws ParseError { Identifier fnId = convertChild(node, "name", "Identifier"); List<Expression> params = convertParameters(node); BlockStatement fnbody = convertChild(node, "body"); boolean generator = hasChild(node, "asteriskToken"); boolean async = hasModifier(node, "AsyncKeyword"); List<ITypeExpression> paramTypes = convertParameterTypes(node); List<DecoratorList> paramDecorators = convertParameterDecorators(node); ITypeExpression returnType = convertChildAsType(node, "type"); ITypeExpression thisParam = convertThisParameterType(node); FunctionExpression function = new FunctionExpression( loc, fnId, params, fnbody, generator, async, convertChildrenNotNull(node, "typeParameters"), paramTypes, paramDecorators, returnType, thisParam, getOptionalParameterIndices(node)); attachStaticType(function, node); attachDeclaredSignature(function, node); return function; } private Node convertFunctionType(JsonObject node, SourceLocation loc) throws ParseError { return new FunctionTypeExpr(loc, convertImplicitFunction(node, loc), false); } /** Gets the original text out of an Identifier's "escapedText" field. */ private String unescapeLeadingUnderscores(String text) { // The TypeScript compiler inserts an additional underscore in front of // identifiers that begin with two underscores. if (text.startsWith("___")) { return text.substring(1); } else { return text; } } /** Returns the contents of the given identifier as a string. */ private String getIdentifierText(JsonObject identifierNode) { if (identifierNode.has("text")) return identifierNode.get("text").getAsString(); else return unescapeLeadingUnderscores(identifierNode.get("escapedText").getAsString()); } private Identifier convertIdentifier(JsonObject node, SourceLocation loc) { Identifier id = new Identifier(loc, getIdentifierText(node)); attachSymbolInformation(id, node); return id; } private Node convertKeywordTypeExpr(JsonObject node, SourceLocation loc, String text) { return new KeywordTypeExpr(loc, text); } private Node convertUnionType(JsonObject node, SourceLocation loc) throws ParseError { return new UnionTypeExpr(loc, convertChildrenAsTypes(node, "types")); } private Node convertIfStatement(JsonObject node, SourceLocation loc) throws ParseError { return new IfStatement( loc, convertChild(node, "expression"), convertChild(node, "thenStatement"), convertChild(node, "elseStatement")); } private Node convertImportClause(JsonObject node, SourceLocation loc) throws ParseError { return new ImportDefaultSpecifier(loc, convertChild(node, "name")); } private Node convertImportDeclaration(JsonObject node, SourceLocation loc) throws ParseError { Literal src = tryConvertChild(node, "moduleSpecifier", Literal.class); List<ImportSpecifier> specifiers = new ArrayList<>(); boolean hasTypeKeyword = false; if (hasChild(node, "importClause")) { JsonObject importClause = node.get("importClause").getAsJsonObject(); if (hasChild(importClause, "name")) { specifiers.add(convertChild(node, "importClause")); } if (hasChild(importClause, "namedBindings")) { JsonObject namedBindings = importClause.get("namedBindings").getAsJsonObject(); if (hasKind(namedBindings, "NamespaceImport")) { specifiers.add(convertChild(importClause, "namedBindings")); } else { specifiers.addAll(convertChildren(namedBindings, "elements")); } } hasTypeKeyword = importClause.get("isTypeOnly").getAsBoolean(); } ImportDeclaration importDecl = new ImportDeclaration(loc, specifiers, src, hasTypeKeyword); attachSymbolInformation(importDecl, node); return importDecl; } private Node convertImportEqualsDeclaration(JsonObject node, SourceLocation loc) throws ParseError { return fixExports( loc, new ImportWholeDeclaration( loc, convertChild(node, "name"), convertChild(node, "moduleReference"))); } private Node convertImportKeyword(SourceLocation loc) { return new Identifier(loc, "import"); } private Node convertImportSpecifier(JsonObject node, SourceLocation loc) throws ParseError { boolean hasImported = hasChild(node, "propertyName"); Identifier imported = convertChild(node, hasImported ? "propertyName" : "name"); Identifier local = convertChild(node, "name"); return new ImportSpecifier(loc, imported, local); } private Node convertImportType(JsonObject node, SourceLocation loc) throws ParseError { // This is a type such as `import("./foo").bar.Baz`. // // The TypeScript AST represents import types as the root of a qualified name, // whereas we represent them as the leftmost qualifier. // // So in our AST, ImportTypeExpr just represents `import("./foo")`, and `.bar.Baz` // is represented by nested MemberExpr nodes. // // Additionally, an import type can be prefixed by `typeof`, such as `typeof import("foo")`. // We convert these to TypeofTypeExpr. // Get the source range of the `import(path)` part. Position importStart = loc.getStart(); Position importEnd = loc.getEnd(); boolean isTypeof = false; if (node.has("isTypeOf") && node.get("isTypeOf").getAsBoolean() == true) { isTypeof = true; Matcher m = TYPEOF_START.matcher(loc.getSource()); if (m.find()) { importStart = advance(importStart, m.group(0)); } } // Find the ending parenthesis in `import(path)` by skipping whitespace after `path`. ITypeExpression path = convertChild(node, "argument"); String endSrc = loc.getSource().substring(path.getLoc().getEnd().getOffset() - loc.getStart().getOffset()); Matcher m = WHITESPACE_END_PAREN.matcher(endSrc); if (m.find()) { importEnd = advance(path.getLoc().getEnd(), m.group(0)); } SourceLocation importLoc = getSourceRange(importStart, importEnd); ImportTypeExpr imprt = new ImportTypeExpr(importLoc, path); ITypeExpression typeName = buildQualifiedTypeAccess(imprt, (JsonObject) node.get("qualifier")); if (isTypeof) { return new TypeofTypeExpr(loc, typeName); } List<ITypeExpression> typeArguments = convertChildrenAsTypes(node, "typeArguments"); if (!typeArguments.isEmpty()) { return new GenericTypeExpr(loc, typeName, typeArguments); } return (Node) typeName; } /** * Converts the given JSON to a qualified name with `root` as the base. * * <p>For example, `a.b.c` is converted to the AST corresponding to `root.a.b.c`. */ private ITypeExpression buildQualifiedTypeAccess(ITypeExpression root, JsonObject node) throws ParseError { if (node == null) { return root; } String kind = getKind(node); ITypeExpression base; Expression name; if (kind == null || kind.equals("Identifier")) { base = root; name = convertIdentifier(node, getSourceLocation(node)); } else if (kind.equals("QualifiedName")) { base = buildQualifiedTypeAccess(root, (JsonObject) node.get("left")); name = convertChild(node, "right"); } else { throw new ParseError("Unsupported syntax in import type", getSourceLocation(node).getStart()); } MemberExpression member = new MemberExpression(getSourceLocation(node), (Expression) base, name, false, false, false); attachSymbolInformation(member, node); return member; } private Node convertIndexSignature(JsonObject node, SourceLocation loc) throws ParseError { FunctionExpression function = convertImplicitFunction(node, loc); int flags = getMemberModifierKeywords(node) | DeclarationFlags.abstract_; return new MethodDefinition(loc, flags, Kind.INDEX_SIGNATURE, null, function); } private Node convertIndexedAccessType(JsonObject node, SourceLocation loc) throws ParseError { return new IndexedAccessTypeExpr( loc, convertChildAsType(node, "objectType"), convertChildAsType(node, "indexType")); } private Node convertInferType(JsonObject node, SourceLocation loc) throws ParseError { return new InferTypeExpr(loc, convertChild(node, "typeParameter")); } private Node convertInterfaceDeclaration(JsonObject node, SourceLocation loc) throws ParseError { Identifier name = convertChild(node, "name"); List<TypeParameter> typeParameters = convertChildrenNotNull(node, "typeParameters"); List<MemberDefinition<?>> members = convertChildren(node, "members"); List<ITypeExpression> superInterfaces = null; for (JsonElement elt : getChildIterable(node, "heritageClauses")) { JsonObject heritageClause = elt.getAsJsonObject(); if (heritageClause.get("token").getAsInt() == syntaxKindExtends) { superInterfaces = convertSuperInterfaceClause(heritageClause.get("types").getAsJsonArray()); break; } } if (superInterfaces == null) { superInterfaces = new ArrayList<>(); } InterfaceDeclaration iface = new InterfaceDeclaration(loc, name, typeParameters, superInterfaces, members); attachSymbolInformation(iface, node); return fixExports(loc, iface); } private Node convertIntersectionType(JsonObject node, SourceLocation loc) throws ParseError { return new IntersectionTypeExpr(loc, convertChildrenAsTypes(node, "types")); } private Node convertJsxAttribute(JsonObject node, SourceLocation loc) throws ParseError { return new JSXAttribute( loc, convertJSXName(convertChild(node, "name")), convertChild(node, "initializer")); } private Node convertJsxClosingElement(JsonObject node, SourceLocation loc) throws ParseError { return new JSXClosingElement(loc, convertJSXName(convertChild(node, "tagName"))); } private Node convertJsxElement(JsonObject node, SourceLocation loc) throws ParseError { return new JSXElement( loc, convertChild(node, "openingElement"), convertChildren(node, "children"), convertChild(node, "closingElement")); } private Node convertJsxExpression(JsonObject node, SourceLocation loc) throws ParseError { if (hasChild(node, "expression")) return new JSXExpressionContainer(loc, convertChild(node, "expression")); return new JSXExpressionContainer(loc, new JSXEmptyExpression(loc)); } private Node convertJsxFragment(JsonObject node, SourceLocation loc) throws ParseError { return new JSXElement( loc, convertChild(node, "openingFragment"), convertChildren(node, "children"), convertChild(node, "closingFragment")); } private Node convertJsxOpeningFragment(JsonObject node, SourceLocation loc) { return new JSXOpeningElement(loc, null, Collections.emptyList(), false); } private Node convertJsxClosingFragment(JsonObject node, SourceLocation loc) { return new JSXClosingElement(loc, null); } private List<IJSXAttribute> convertJsxAttributes(JsonObject node) throws ParseError { JsonElement attributes = node.get("attributes"); List<IJSXAttribute> convertedAttributes; if (attributes.isJsonArray()) { convertedAttributes = convertNodes(attributes.getAsJsonArray()); } else { convertedAttributes = convertChildren(attributes.getAsJsonObject(), "properties"); } return convertedAttributes; } private Node convertJsxOpeningElement(JsonObject node, SourceLocation loc) throws ParseError { List<IJSXAttribute> convertedAttributes = convertJsxAttributes(node); return new JSXOpeningElement( loc, convertJSXName(convertChild(node, "tagName")), convertedAttributes, hasChild(node, "selfClosing")); } private Node convertJsxSelfClosingElement(JsonObject node, SourceLocation loc) throws ParseError { List<IJSXAttribute> convertedAttributes = convertJsxAttributes(node); JSXOpeningElement opening = new JSXOpeningElement( loc, convertJSXName(convertChild(node, "tagName")), convertedAttributes, true); return new JSXElement(loc, opening, new ArrayList<>(), null); } private Node convertJsxSpreadAttribute(JsonObject node, SourceLocation loc) throws ParseError { return new JSXSpreadAttribute(loc, convertChild(node, "expression")); } private Node convertJsxText(JsonObject node, SourceLocation loc) { String text; if (hasChild(node, "text")) text = node.get("text").getAsString(); else text = ""; return new Literal(loc, TokenType.string, text); } private Node convertLabeledStatement(JsonObject node, SourceLocation loc) throws ParseError { return new LabeledStatement(loc, convertChild(node, "label"), convertChild(node, "statement")); } private Node convertLiteralType(JsonObject node, SourceLocation loc) throws ParseError { Node literal = convertChild(node, "literal"); // Convert a negated literal to a negative number if (literal instanceof UnaryExpression) { UnaryExpression unary = (UnaryExpression) literal; if (unary.getOperator().equals("-") && unary.getArgument() instanceof Literal) { Literal arg = (Literal) unary.getArgument(); literal = new Literal(loc, arg.getTokenType(), "-" + arg.getValue()); } } return literal; } private Node convertMappedType(JsonObject node, SourceLocation loc) throws ParseError { return new MappedTypeExpr( loc, convertChild(node, "typeParameter"), convertChildAsType(node, "type")); } private Node convertMetaProperty(JsonObject node, SourceLocation loc) throws ParseError { Position metaStart = loc.getStart(); String keywordKind = metadata.getSyntaxKindName(node.getAsJsonPrimitive("keywordToken").getAsInt()); String identifier = keywordKind.equals("ImportKeyword") ? "import" : "new"; Position metaEnd = new Position( metaStart.getLine(), metaStart.getColumn() + identifier.length(), metaStart.getOffset() + identifier.length()); SourceLocation metaLoc = new SourceLocation(identifier, metaStart, metaEnd); Identifier meta = new Identifier(metaLoc, identifier); return new MetaProperty(loc, meta, convertChild(node, "name")); } private Node convertMethodDeclaration(JsonObject node, String kind, SourceLocation loc) throws ParseError { int flags = getMemberModifierKeywords(node); if (hasComputedName(node)) { flags |= DeclarationFlags.computed; } if (kind.equals("MethodSignature")) { flags |= DeclarationFlags.abstract_; } MethodDefinition.Kind methodKind; if ("GetAccessor".equals(kind)) methodKind = Kind.GET; else if ("SetAccessor".equals(kind)) methodKind = Kind.SET; else methodKind = Kind.METHOD; FunctionExpression method = convertImplicitFunction(node, loc); MethodDefinition methodDefinition = new MethodDefinition(loc, flags, methodKind, convertChild(node, "name"), method); if (node.has("decorators")) { methodDefinition.addDecorators(convertChildren(node, "decorators")); advanceUntilAfter(loc, methodDefinition.getDecorators()); } return methodDefinition; } private FunctionExpression convertImplicitFunction(JsonObject node, SourceLocation loc) throws ParseError { ITypeExpression returnType = convertChildAsType(node, "type"); List<ITypeExpression> paramTypes = convertParameterTypes(node); List<DecoratorList> paramDecorators = convertParameterDecorators(node); List<TypeParameter> typeParameters = convertChildrenNotNull(node, "typeParameters"); ITypeExpression thisType = convertThisParameterType(node); FunctionExpression function = new FunctionExpression( loc, null, convertParameters(node), convertChild(node, "body"), hasChild(node, "asteriskToken"), hasModifier(node, "AsyncKeyword"), typeParameters, paramTypes, paramDecorators, returnType, thisType, getOptionalParameterIndices(node)); attachSymbolInformation(function, node); attachStaticType(function, node); attachDeclaredSignature(function, node); return function; } private Node convertNamespaceDeclaration(JsonObject node, SourceLocation loc) throws ParseError { Node nameNode = convertChild(node, "name"); List<Statement> body; Statement b = convertChild(node, "body"); if (b instanceof BlockStatement) { body = ((BlockStatement) b).getBody(); } else { body = new ArrayList<>(); body.add(b); } if (nameNode instanceof Literal) { // Declaration of form: declare module "X" {...} return new ExternalModuleDeclaration(loc, (Literal) nameNode, body); } if (hasFlag(node, "GlobalAugmentation")) { // Declaration of form: declare global {...} return new GlobalAugmentationDeclaration(loc, body); } Identifier name = (Identifier) nameNode; boolean isInstantiated = false; for (Statement stmt : body) { isInstantiated = isInstantiated || isInstantiatingNamespaceMember(stmt); } boolean hasDeclareKeyword = hasModifier(node, "DeclareKeyword"); NamespaceDeclaration decl = new NamespaceDeclaration(loc, name, body, isInstantiated, hasDeclareKeyword); attachSymbolInformation(decl, node); if (hasFlag(node, "NestedNamespace")) { // In a nested namespace declaration `namespace A.B`, the nested namespace `B` // is implicitly exported. return new ExportNamedDeclaration(loc, decl, new ArrayList<>(), null); } else { return fixExports(loc, decl); } } private boolean isInstantiatingNamespaceMember(Statement node) { if (node instanceof ExportNamedDeclaration) { // Ignore 'export' modifiers. return isInstantiatingNamespaceMember(((ExportNamedDeclaration) node).getDeclaration()); } if (node instanceof NamespaceDeclaration) { return ((NamespaceDeclaration) node).isInstantiated(); } if (node instanceof InterfaceDeclaration) { return false; } if (node instanceof TypeAliasDeclaration) { return false; } return true; } private Node convertModuleBlock(JsonObject node, SourceLocation loc) throws ParseError { return convertBlock(node, loc); } private Node convertNamespaceExportDeclaration(JsonObject node, SourceLocation loc) throws ParseError { return new ExportAsNamespaceDeclaration(loc, convertChild(node, "name")); } private Node convertNamespaceImport(JsonObject node, SourceLocation loc) throws ParseError { return new ImportNamespaceSpecifier(loc, convertChild(node, "name")); } private Node convertNewExpression(JsonObject node, SourceLocation loc) throws ParseError { List<Expression> arguments; if (hasChild(node, "arguments")) arguments = convertChildren(node, "arguments"); else arguments = new ArrayList<>(); List<ITypeExpression> typeArguments = convertChildrenAsTypes(node, "typeArguments"); NewExpression result = new NewExpression(loc, convertChild(node, "expression"), typeArguments, arguments); attachResolvedSignature(result, node); return result; } private Node convertNonNullExpression(JsonObject node, SourceLocation loc) throws ParseError { return new NonNullAssertion(loc, convertChild(node, "expression")); } private Node convertNoSubstitutionTemplateLiteral(JsonObject node, SourceLocation loc) { List<TemplateElement> quasis = new ArrayList<>(); TemplateElement elm = new TemplateElement( loc, node.get("text").getAsString(), loc.getSource().substring(1, loc.getSource().length() - 1), true); quasis.add(elm); attachStaticType(elm, node); return new TemplateLiteral(loc, new ArrayList<>(), quasis); } private Node convertNullKeyword(SourceLocation loc) { return new Literal(loc, TokenType._null, null); } private Node convertObjectBindingPattern(JsonObject node, SourceLocation loc) throws ParseError { List<Property> properties = new ArrayList<>(); for (JsonElement elt : node.get("elements").getAsJsonArray()) { JsonObject element = elt.getAsJsonObject(); SourceLocation eltLoc = getSourceLocation(element); Expression propKey = hasChild(element, "propertyName") ? convertChild(element, "propertyName") : convertChild(element, "name"); Expression propVal; if (hasChild(element, "dotDotDotToken")) { propVal = new RestElement(eltLoc, propKey); } else if (hasChild(element, "initializer")) { propVal = new AssignmentPattern( eltLoc, "=", convertChild(element, "name"), convertChild(element, "initializer")); } else { propVal = convertChild(element, "name"); } properties.add( new Property( eltLoc, propKey, propVal, "init", hasComputedName(element, "propertyName"), false)); } return new ObjectPattern(loc, properties); } private Node convertObjectLiteralExpression(JsonObject node, SourceLocation loc) throws ParseError { List<Property> properties; properties = new ArrayList<Property>(); for (INode e : convertChildren(node, "properties")) { if (e instanceof SpreadElement) { properties.add( new Property( e.getLoc(), null, (Expression) e, Property.Kind.INIT.name(), false, false)); } else if (e instanceof MethodDefinition) { MethodDefinition md = (MethodDefinition) e; Property.Kind kind = Property.Kind.INIT; if (md.getKind() == Kind.GET) { kind = Property.Kind.GET; } else if (md.getKind() == Kind.SET) { kind = Property.Kind.SET; } properties.add( new Property( e.getLoc(), md.getKey(), md.getValue(), kind.name(), md.isComputed(), true)); } else { properties.add((Property) e); } } return new ObjectExpression(loc, properties); } private Node convertOmittedExpression() { return null; } private Node convertOptionalType(JsonObject node, SourceLocation loc) throws ParseError { return new OptionalTypeExpr(loc, convertChild(node, "type")); } private ITypeExpression asType(Node node) { return node instanceof ITypeExpression ? (ITypeExpression) node : null; } private List<ITypeExpression> convertChildrenAsTypes(JsonObject node, String child) throws ParseError { List<ITypeExpression> result = new ArrayList<>(); JsonElement children = node.get(child); if (!(children instanceof JsonArray)) return result; for (JsonElement childNode : children.getAsJsonArray()) { ITypeExpression type = asType(convertNode(childNode.getAsJsonObject())); if (type != null) result.add(type); } return result; } private ITypeExpression convertChildAsType(JsonObject node, String child) throws ParseError { return asType(convertChild(node, child)); } /** True if the given node is an Identifier node. */ private boolean isIdentifier(JsonElement node) { if (node == null) return false; JsonObject object = node.getAsJsonObject(); if (object == null) return false; String kind = getKind(object); return kind == null || kind.equals("Identifier"); } /** * Returns true if this is the JSON object for the special "this" parameter. * * <p>It should be given the JSON object of kind "Parameter". */ private boolean isThisParameter(JsonElement parameter) { JsonObject name = parameter.getAsJsonObject().get("name").getAsJsonObject(); return isIdentifier(name) && getIdentifierText(name).equals("this"); } /** * Returns the parameters of the given function, omitting the special "this" parameter, which we * do not consider to be a proper parameter. */ private Iterable<JsonElement> getProperParameters(JsonObject function) { if (!function.has("parameters")) return Collections.emptyList(); JsonArray parameters = function.get("parameters").getAsJsonArray(); if (parameters.size() > 0 && isThisParameter(parameters.get(0))) { return CollectionUtil.skipIterable(parameters, 1); } else { return parameters; } } /** * Returns the special "this" parameter of the given function, or {@code null} if the function * does not declare a "this" parameter. */ private ITypeExpression convertThisParameterType(JsonObject function) throws ParseError { if (!function.has("parameters")) return null; JsonArray parameters = function.get("parameters").getAsJsonArray(); if (parameters.size() > 0 && isThisParameter(parameters.get(0))) { return convertChildAsType(parameters.get(0).getAsJsonObject(), "type"); } else { return null; } } private List<Expression> convertParameters(JsonObject function) throws ParseError { return convertNodes(getProperParameters(function), true); } private List<ITypeExpression> convertParameterTypes(JsonObject function) throws ParseError { List<ITypeExpression> result = new ArrayList<>(); for (JsonElement param : getProperParameters(function)) { result.add(convertChildAsType(param.getAsJsonObject(), "type")); } return result; } private IntList getOptionalParameterIndices(JsonObject function) throws ParseError { IntList list = IntList.create(0); int index = -1; for (JsonElement param : getProperParameters(function)) { ++index; if (param.getAsJsonObject().has("questionToken")) { list.add(index); } } return list; } private List<FieldDefinition> convertParameterFields(JsonObject function) throws ParseError { List<FieldDefinition> result = new ArrayList<>(); int index = -1; for (JsonElement paramElm : getProperParameters(function)) { ++index; JsonObject param = paramElm.getAsJsonObject(); int flags = getMemberModifierKeywords(param); if (flags == DeclarationFlags.none) { // If there are no flags, this is not a field parameter. continue; } // We generate a synthetic field node, but do not copy any of the AST nodes from // the parameter. The QL library overrides accessors to the name and type // annotation to return those from the corresponding parameter. SourceLocation loc = getSourceLocation(param); if (param.has("initializer")) { // Do not include the default parameter value in the source range for the field. SourceLocation endLoc; if (param.has("type")) { endLoc = getSourceLocation(param.get("type").getAsJsonObject()); } else { endLoc = getSourceLocation(param.get("name").getAsJsonObject()); } loc.setEnd(endLoc.getEnd()); loc.setSource(source.substring(loc.getStart().getOffset(), loc.getEnd().getOffset())); } FieldDefinition field = new FieldDefinition(loc, flags, null, null, null, index); result.add(field); } return result; } private Node convertParameter(JsonObject node, SourceLocation loc) throws ParseError { // Note that type annotations are not extracted in this function, but in a // separate pass in convertParameterTypes above. Expression name = convertChild(node, "name", "Identifier"); if (hasChild(node, "dotDotDotToken")) return new RestElement(loc, name); if (hasChild(node, "initializer")) return new AssignmentPattern(loc, "=", name, convertChild(node, "initializer")); return name; } private Node convertParenthesizedExpression(JsonObject node, SourceLocation loc) throws ParseError { return new ParenthesizedExpression(loc, convertChild(node, "expression")); } private Node convertParenthesizedType(JsonObject node, SourceLocation loc) throws ParseError { return new ParenthesizedTypeExpr(loc, convertChildAsType(node, "type")); } private Node convertPostfixUnaryExpression(JsonObject node, SourceLocation loc) throws ParseError { String operator = getOperator(node); return new UpdateExpression(loc, operator, convertChild(node, "operand"), false); } private Node convertPrefixUnaryExpression(JsonObject node, SourceLocation loc) throws ParseError { String operator = getOperator(node); if ("++".equals(operator) || "--".equals(operator)) return new UpdateExpression(loc, operator, convertChild(node, "operand"), true); else return new UnaryExpression(loc, operator, convertChild(node, "operand"), true); } private String getOperator(JsonObject node) throws ParseError { int operatorId = node.get("operator").getAsInt(); switch (metadata.getSyntaxKindName(operatorId)) { case "PlusPlusToken": return "++"; case "MinusMinusToken": return "--"; case "PlusToken": return "+"; case "MinusToken": return "-"; case "TildeToken": return "~"; case "ExclamationToken": return "!"; default: throw new ParseError( "Unsupported TypeScript operator " + operatorId, getSourceLocation(node).getStart()); } } private Node convertPropertyAccessExpression(JsonObject node, SourceLocation loc) throws ParseError { Expression base = convertChild(node, "expression"); boolean optional = node.has("questionDotToken"); boolean onOptionalChain = Chainable.isOnOptionalChain(optional, base); return new MemberExpression( loc, base, convertChild(node, "name"), false, optional, onOptionalChain); } private Node convertPropertyAssignment(JsonObject node, SourceLocation loc) throws ParseError { return new Property( loc, convertChild(node, "name"), convertChild(node, "initializer"), "init", hasComputedName(node), false); } private Node convertPropertyDeclaration(JsonObject node, String kind, SourceLocation loc) throws ParseError { int flags = getMemberModifierKeywords(node); if (hasComputedName(node)) { flags |= DeclarationFlags.computed; } if (kind.equals("PropertySignature")) { flags |= DeclarationFlags.abstract_; } if (node.get("questionToken") != null) { flags |= DeclarationFlags.optional; } if (node.get("exclamationToken") != null) { flags |= DeclarationFlags.definiteAssignmentAssertion; } if (hasModifier(node, "DeclareKeyword")) { flags |= DeclarationFlags.declareKeyword; } FieldDefinition fieldDefinition = new FieldDefinition( loc, flags, convertChild(node, "name"), convertChild(node, "initializer"), convertChildAsType(node, "type")); if (node.has("decorators")) { fieldDefinition.addDecorators(convertChildren(node, "decorators")); advanceUntilAfter(loc, fieldDefinition.getDecorators()); } return fieldDefinition; } private Node convertRegularExpressionLiteral(SourceLocation loc) { return new Literal(loc, TokenType.regexp, null); } private Node convertRestType(JsonObject node, SourceLocation loc) throws ParseError { return new RestTypeExpr(loc, convertChild(node, "type")); } private Node convertQualifiedName(JsonObject node, SourceLocation loc) throws ParseError { MemberExpression expr = new MemberExpression( loc, convertChild(node, "left"), convertChild(node, "right"), false, false, false); attachSymbolInformation(expr, node); return expr; } private Node convertReturnStatement(JsonObject node, SourceLocation loc) throws ParseError { return new ReturnStatement(loc, convertChild(node, "expression")); } private Node convertSemicolonClassElement() { return null; } private Node convertSourceFile(JsonObject node, SourceLocation loc) throws ParseError { List<Statement> statements = convertNodes(node.get("statements").getAsJsonArray()); Program program = new Program(loc, statements, "module"); attachSymbolInformation(program, node); return program; } private Node convertShorthandPropertyAssignment(JsonObject node, SourceLocation loc) throws ParseError { return new Property( loc, convertChild(node, "name"), convertChild(node, "name"), "init", false, false); } private Node convertSpreadElement(JsonObject node, SourceLocation loc) throws ParseError { return new SpreadElement(loc, convertChild(node, "expression")); } private Node convertStringLiteral(JsonObject node, SourceLocation loc) { return new Literal(loc, TokenType.string, node.get("text").getAsString()); } private Node convertSuperKeyword(SourceLocation loc) { return new Super(loc); } private Node convertSwitchStatement(JsonObject node, SourceLocation loc) throws ParseError { JsonObject caseBlock = node.get("caseBlock").getAsJsonObject(); return new SwitchStatement( loc, convertChild(node, "expression"), convertChildren(caseBlock, "clauses")); } private Node convertTaggedTemplateExpression(JsonObject node, SourceLocation loc) throws ParseError { return new TaggedTemplateExpression( loc, convertChild(node, "tag"), convertChild(node, "template"), convertChildrenAsTypes(node, "typeArguments")); } private Node convertTemplateExpression(JsonObject node, SourceLocation loc) throws ParseError { List<TemplateElement> quasis; List<Expression> expressions = new ArrayList<>(); quasis = new ArrayList<>(); quasis.add(convertChild(node, "head")); for (JsonElement elt : node.get("templateSpans").getAsJsonArray()) { JsonObject templateSpan = (JsonObject) elt; expressions.add(convertChild(templateSpan, "expression")); quasis.add(convertChild(templateSpan, "literal")); } return new TemplateLiteral(loc, expressions, quasis); } private Node convertTemplateElement(JsonObject node, String kind, SourceLocation loc) { boolean tail = "TemplateTail".equals(kind); if (loc.getSource().startsWith("`") || loc.getSource().startsWith("}")) { loc.setSource(loc.getSource().substring(1)); Position start = loc.getStart(); loc.setStart(new Position(start.getLine(), start.getColumn() + 1, start.getColumn() + 1)); } if (loc.getSource().endsWith("${")) { loc.setSource(loc.getSource().substring(0, loc.getSource().length() - 2)); Position end = loc.getEnd(); loc.setEnd(new Position(end.getLine(), end.getColumn() - 2, end.getColumn() - 2)); } if (loc.getSource().endsWith("`")) { loc.setSource(loc.getSource().substring(0, loc.getSource().length() - 1)); Position end = loc.getEnd(); loc.setEnd(new Position(end.getLine(), end.getColumn() - 1, end.getColumn() - 1)); } return new TemplateElement(loc, node.get("text").getAsString(), loc.getSource(), tail); } private Node convertThisKeyword(SourceLocation loc) { return new ThisExpression(loc); } private Node convertThrowStatement(JsonObject node, SourceLocation loc) throws ParseError { Expression expr = convertChild(node, "expression"); if (expr == null) return convertEmptyStatement(loc); return new ThrowStatement(loc, expr); } private Node convertTrueKeyword(SourceLocation loc) { return new Literal(loc, TokenType._true, true); } private Node convertTryStatement(JsonObject node, SourceLocation loc) throws ParseError { return new TryStatement( loc, convertChild(node, "tryBlock"), convertChild(node, "catchClause"), null, convertChild(node, "finallyBlock")); } private Node convertTupleType(JsonObject node, SourceLocation loc) throws ParseError { return new TupleTypeExpr(loc, convertChildrenAsTypes(node, "elementTypes")); } private Node convertTypeAliasDeclaration(JsonObject node, SourceLocation loc) throws ParseError { TypeAliasDeclaration typeAlias = new TypeAliasDeclaration( loc, convertChild(node, "name"), convertChildrenNotNull(node, "typeParameters"), convertChildAsType(node, "type")); attachSymbolInformation(typeAlias, node); return fixExports(loc, typeAlias); } private Node convertTypeAssertionExpression(JsonObject node, SourceLocation loc) throws ParseError { ITypeExpression type = convertChildAsType(node, "type"); // `T as const` is extracted as a cast to the keyword type `const`. if (type instanceof Identifier && ((Identifier) type).getName().equals("const")) { type = new KeywordTypeExpr(type.getLoc(), "const"); } return new TypeAssertion(loc, convertChild(node, "expression"), type, false); } private Node convertTypeLiteral(JsonObject obj, SourceLocation loc) throws ParseError { return new InterfaceTypeExpr(loc, convertChildren(obj, "members")); } private Node convertTypeOfExpression(JsonObject node, SourceLocation loc) throws ParseError { return new UnaryExpression(loc, "typeof", convertChild(node, "expression"), true); } private Node convertTypeOperator(JsonObject node, SourceLocation loc) throws ParseError { String operator = metadata.getSyntaxKindName(node.get("operator").getAsInt()); if (operator.equals("KeyOfKeyword")) { return new UnaryTypeExpr(loc, UnaryTypeExpr.Kind.Keyof, convertChildAsType(node, "type")); } if (operator.equals("ReadonlyKeyword")) { return new UnaryTypeExpr(loc, UnaryTypeExpr.Kind.Readonly, convertChildAsType(node, "type")); } if (operator.equals("UniqueKeyword")) { return new KeywordTypeExpr(loc, "unique symbol"); } throw new ParseError("Unsupported TypeScript syntax", loc.getStart()); } private Node convertTypeParameter(JsonObject node, SourceLocation loc) throws ParseError { return new TypeParameter( loc, convertChild(node, "name"), convertChildAsType(node, "constraint"), convertChildAsType(node, "default")); } private Node convertTypePredicate(JsonObject node, SourceLocation loc) throws ParseError { return new PredicateTypeExpr( loc, convertChildAsType(node, "parameterName"), convertChildAsType(node, "type"), node.has("assertsModifier")); } private Node convertTypeReference(JsonObject node, SourceLocation loc) throws ParseError { ITypeExpression typeName = convertChild(node, "typeName"); List<ITypeExpression> typeArguments = convertChildrenAsTypes(node, "typeArguments"); if (typeArguments.isEmpty()) return (Node) typeName; return new GenericTypeExpr(loc, typeName, typeArguments); } private Node convertTypeQuery(JsonObject node, SourceLocation loc) throws ParseError { return new TypeofTypeExpr(loc, convertChildAsType(node, "exprName")); } private Node convertVariableDeclaration(JsonObject node, SourceLocation loc) throws ParseError { return new VariableDeclarator( loc, convertChild(node, "name"), convertChild(node, "initializer"), convertChildAsType(node, "type"), DeclarationFlags.getDefiniteAssignmentAssertion(node.get("exclamationToken") != null)); } private Node convertVariableDeclarationList(JsonObject node, SourceLocation loc) throws ParseError { return new VariableDeclaration( loc, getDeclarationKind(node), convertVariableDeclarations(node), false); } private List<VariableDeclarator> convertVariableDeclarations(JsonObject node) throws ParseError { if (node.get("declarations").getAsJsonArray().size() == 0) throw new ParseError("Unexpected token", getSourceLocation(node).getEnd()); return convertChildren(node, "declarations"); } private Node convertVariableStatement(JsonObject node, SourceLocation loc) throws ParseError { JsonObject declarationList = node.get("declarationList").getAsJsonObject(); String declarationKind = getDeclarationKind(declarationList); List<VariableDeclarator> declarations = convertVariableDeclarations(declarationList); boolean hasDeclareKeyword = hasModifier(node, "DeclareKeyword"); VariableDeclaration vd = new VariableDeclaration(loc, declarationKind, declarations, hasDeclareKeyword); return fixExports(loc, vd); } private Node convertVoidExpression(JsonObject node, SourceLocation loc) throws ParseError { return new UnaryExpression(loc, "void", convertChild(node, "expression"), true); } private Node convertWhileStatement(JsonObject node, SourceLocation loc) throws ParseError { return new WhileStatement( loc, convertChild(node, "expression"), convertChild(node, "statement")); } private Node convertWithStatement(JsonObject node, SourceLocation loc) throws ParseError { return new WithStatement( loc, convertChild(node, "expression"), convertChild(node, "statement")); } private Node convertYieldExpression(JsonObject node, SourceLocation loc) throws ParseError { return new YieldExpression( loc, convertChild(node, "expression"), hasChild(node, "asteriskToken")); } /** * Convert {@code e} to an lvalue expression, replacing {@link ArrayExpression} with {@link * ArrayPattern}, {@link AssignmentExpression} with {@link AssignmentPattern}, {@link * ObjectExpression} with {@link ObjectPattern} and {@link SpreadElement} with {@link * RestElement}. */ private Expression convertLValue(Expression e) throws ParseError { if (e == null) return null; SourceLocation loc = e.getLoc(); if (e instanceof ArrayExpression) { List<Expression> elts = new ArrayList<Expression>(); for (Expression elt : ((ArrayExpression) e).getElements()) elts.add(convertLValue(elt)); return new ArrayPattern(loc, elts); } if (e instanceof AssignmentExpression) { AssignmentExpression a = (AssignmentExpression) e; return new AssignmentPattern(loc, a.getOperator(), convertLValue(a.getLeft()), a.getRight()); } if (e instanceof ObjectExpression) { List<Property> props = new ArrayList<Property>(); for (Property prop : ((ObjectExpression) e).getProperties()) { Expression key = prop.getKey(); Expression rawValue = prop.getRawValue(); String kind = prop.getKind().name(); boolean isComputed = prop.isComputed(); boolean isMethod = prop.isMethod(); props.add( new Property(prop.getLoc(), key, convertLValue(rawValue), kind, isComputed, isMethod)); } return new ObjectPattern(loc, props); } if (e instanceof ParenthesizedExpression) return new ParenthesizedExpression( loc, convertLValue(((ParenthesizedExpression) e).getExpression())); if (e instanceof SpreadElement) { Expression argument = convertLValue(((SpreadElement) e).getArgument()); if (argument instanceof AssignmentPattern) { throw new ParseError( "Rest patterns cannot have a default value", argument.getLoc().getStart()); } return new RestElement(e.getLoc(), argument); } return e; } /** Convert {@code e} to an {@link IJSXName}. */ private IJSXName convertJSXName(Expression e) { if (e instanceof Identifier) return new JSXIdentifier(e.getLoc(), ((Identifier) e).getName()); if (e instanceof MemberExpression) { MemberExpression me = (MemberExpression) e; return new JSXMemberExpression( e.getLoc(), convertJSXName(me.getObject()), (JSXIdentifier) convertJSXName(me.getProperty())); } if (e instanceof ThisExpression) return new JSXIdentifier(e.getLoc(), "this"); return (IJSXName) e; } /** * Check whether {@code decl} has an {@code export} annotation, and if so wrap it inside an {@link * ExportDeclaration}. * * <p>If the declared statement has decorators, the {@code loc} should first be advanced past * these using {@link #advanceUntilAfter}. */ private Node fixExports(SourceLocation loc, Node decl) { Matcher m = EXPORT_DECL_START.matcher(loc.getSource()); if (m.find()) { String skipped = m.group(0); SourceLocation outerLoc = new SourceLocation(loc.getSource(), loc.getStart(), loc.getEnd()); advance(loc, skipped); // capture group 1 is `default`, if present if (m.group(1) == null) return new ExportNamedDeclaration(outerLoc, (Statement) decl, new ArrayList<>(), null); return new ExportDefaultDeclaration(outerLoc, decl); } return decl; } /** Holds if the {@code name} property of the given AST node is a computed property name. */ private boolean hasComputedName(JsonObject node) { return hasComputedName(node, "name"); } /** Holds if the given property of the given AST node is a computed property name. */ private boolean hasComputedName(JsonObject node, String propName) { return hasKind(node.get(propName), "ComputedPropertyName"); } /** * Update the start position and source text of {@code loc} by skipping over the string {@code * skipped}. */ private void advance(SourceLocation loc, String skipped) { loc.setStart(advance(loc.getStart(), skipped)); loc.setSource(loc.getSource().substring(skipped.length())); } /** * Update the start position of @{code loc} by skipping over the given children and any following * whitespace and comments, provided they are contained in the source location. */ private void advanceUntilAfter(SourceLocation loc, List<? extends INode> nodes) { if (nodes.isEmpty()) return; INode last = nodes.get(nodes.size() - 1); int offset = last.getLoc().getEnd().getOffset() - loc.getStart().getOffset(); if (offset <= 0) return; offset += matchWhitespace(last.getLoc().getEnd().getOffset()).length(); if (offset >= loc.getSource().length()) return; loc.setStart(advance(loc.getStart(), loc.getSource().substring(0, offset))); loc.setSource(loc.getSource().substring(offset)); } /** Get the longest sequence of whitespace or comment characters starting at the given offset. */ private String matchWhitespace(int offset) { Matcher m = WHITESPACE.matcher(source.substring(offset)); m.find(); return m.group(0); } /** * Create a position corresponding to {@code pos}, but updated by skipping over the string {@code * skipped}. */ private Position advance(Position pos, String skipped) { int innerStartOffset = pos.getOffset() + skipped.length(); int innerStartLine = pos.getLine(), innerStartColumn = pos.getColumn(); Matcher m = LINE_TERMINATOR.matcher(skipped); int lastEnd = 0; while (m.find()) { ++innerStartLine; innerStartColumn = 1; lastEnd = m.end(); } innerStartColumn += skipped.length() - lastEnd; if (lastEnd > 0) --innerStartColumn; Position innerStart = new Position(innerStartLine, innerStartColumn, innerStartOffset); return innerStart; } /** Get the source location of the given AST node. */ private SourceLocation getSourceLocation(JsonObject node) { Position start = getPosition(node.get("$pos")); Position end = getPosition(node.get("$end")); int startOffset = start.getOffset(); int endOffset = end.getOffset(); if (startOffset > endOffset) startOffset = endOffset; if (endOffset > source.length()) endOffset = source.length(); return new SourceLocation(source.substring(startOffset, endOffset), start, end); } /** * Convert the given position object into a {@link Position}. For start positions, we need to skip * over whitespace, which is included in the positions reported by the TypeScript compiler. */ private Position getPosition(JsonElement elm) { int offset = elm.getAsInt(); int line = getLineFromPos(offset); int column = getColumnFromLinePos(line, offset); return new Position(line + 1, column, offset); } private Iterable<JsonElement> getModifiers(JsonObject node) { JsonElement mods = node.get("modifiers"); if (!(mods instanceof JsonArray)) return Collections.emptyList(); return (JsonArray) mods; } /** * Returns a specific modifier from the given node (or <tt>null</tt> if absent), as defined by its * <tt>modifiers</tt> property and the <tt>kind</tt> property of the modifier AST node. */ private JsonObject getModifier(JsonObject node, String modKind) { for (JsonElement mod : getModifiers(node)) if (mod instanceof JsonObject) if (hasKind((JsonObject) mod, modKind)) return (JsonObject) mod; return null; } /** * Check whether a node has a particular modifier, as defined by its <tt>modifiers</tt> property * and the <tt>kind</tt> property of the modifier AST node. */ private boolean hasModifier(JsonObject node, String modKind) { return getModifier(node, modKind) != null; } private int getDeclarationModifierFromKeyword(String kind) { switch (kind) { case "AbstractKeyword": return DeclarationFlags.abstract_; case "StaticKeyword": return DeclarationFlags.static_; case "ReadonlyKeyword": return DeclarationFlags.readonly; case "PublicKeyword": return DeclarationFlags.public_; case "PrivateKeyword": return DeclarationFlags.private_; case "ProtectedKeyword": return DeclarationFlags.protected_; default: return DeclarationFlags.none; } } /** * Returns the set of member flags corresponding to the modifier keywords present on the given * node. */ private int getMemberModifierKeywords(JsonObject node) { int flags = DeclarationFlags.none; for (JsonElement mod : getModifiers(node)) { if (mod instanceof JsonObject) { JsonObject modObject = (JsonObject) mod; flags |= getDeclarationModifierFromKeyword(getKind(modObject)); } } return flags; } /** * Check whether a node has a particular flag, as defined by its <tt>flags</tt> property and the * <tt>ts.NodeFlags</tt> in enum. */ private boolean hasFlag(JsonObject node, String flagName) { int flagId = metadata.getNodeFlagId(flagName); JsonElement flags = node.get("flags"); if (flags instanceof JsonPrimitive) { return (flags.getAsInt() & flagId) != 0; } return false; } /** Check whether a node has a child with a given name. */ private boolean hasChild(JsonObject node, String prop) { if (!node.has(prop)) return false; return !(node.get(prop) instanceof JsonNull); } /** * Returns an iterator over the elements of the given child array, or an empty iterator if the * given child is not an array. */ private Iterable<JsonElement> getChildIterable(JsonObject node, String child) { JsonElement elt = node.get(child); if (!(elt instanceof JsonArray)) return Collections.emptyList(); return (JsonArray) elt; } /** Gets the kind of the given node. */ private String getKind(JsonElement node) { if (node instanceof JsonObject) { JsonElement kind = ((JsonObject) node).get("kind"); if (kind instanceof JsonPrimitive && ((JsonPrimitive) kind).isNumber()) return metadata.getSyntaxKindName(kind.getAsInt()); } return null; } /** Holds if the given node has the given kind. */ private boolean hasKind(JsonElement node, String kind) { return kind.equals(getKind(node)); } /** * Gets the declaration kind of the given node, which is one of {@code "var"}, {@code "let"} or * {@code "const"}. */ private String getDeclarationKind(JsonObject declarationList) { return declarationList.get("$declarationKind").getAsString(); } }
104,005
39.343677
107
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/parser/TypeScriptParserMetadata.java
package com.semmle.js.parser; import java.util.LinkedHashMap; import java.util.Map; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; /** * Static data from the TypeScript compiler needed for decoding ASTs. * <p> * AST nodes store their kind and flags as integers, but the meaning of this integer changes * between compiler versions. The metadata contains mappings from integers to logical names * which are stable across versions. */ public class TypeScriptParserMetadata { private final JsonObject nodeFlags; private final JsonObject syntaxKinds; private final Map<Integer, String> syntaxKindMap = new LinkedHashMap<>(); public TypeScriptParserMetadata(JsonObject metadata) { this.nodeFlags = metadata.get("nodeFlags").getAsJsonObject(); this.syntaxKinds = metadata.get("syntaxKinds").getAsJsonObject(); makeEnumIdMap(syntaxKinds, syntaxKindMap); } /** Builds a mapping from ID to name given a TypeScript enum object. */ private void makeEnumIdMap(JsonObject enumObject, Map<Integer, String> idToName) { for (Map.Entry<String, JsonElement> entry : enumObject.entrySet()) { JsonPrimitive prim = entry.getValue().getAsJsonPrimitive(); if (prim.isNumber() && !idToName.containsKey(prim.getAsInt())) { idToName.put(prim.getAsInt(), entry.getKey()); } } } /** * Returns the logical name associated with syntax kind ID <code>id</code>, * or throws an exception if it does not exist. */ String getSyntaxKindName(int id) { String name = syntaxKindMap.get(id); if (name == null) { throw new RuntimeException( "Incompatible version of TypeScript installed. Missing syntax kind ID " + id); } return name; } /** * Returns the syntax kind ID corresponding to the logical name <code>name</code>, * or throws an exception if it does not exist. */ int getSyntaxKindId(String name) { JsonElement elm = syntaxKinds.get(name); if (elm == null) { throw new RuntimeException( "Incompatible version of TypeScript installed. Missing syntax kind " + name); } return elm.getAsInt(); } /** * Returns the NodeFlag ID from the logical name <code>name</code> * or throws an exception if it does not exist. */ int getNodeFlagId(String name) { JsonElement elm = nodeFlags.get(name); if (elm == null) { throw new RuntimeException( "Incompatible version of TypeScript installed. Missing node flag " + name); } return elm.getAsInt(); } }
2,582
32.545455
92
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/extractor/YAMLExtractor.java
package com.semmle.js.extractor; import com.semmle.util.data.StringUtil; import com.semmle.util.exception.CatastrophicError; import com.semmle.util.exception.UserError; import com.semmle.util.trap.TrapWriter; import com.semmle.util.trap.TrapWriter.Label; import com.semmle.util.trap.TrapWriter.Table; import org.yaml.snakeyaml.composer.Composer; import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.error.MarkedYAMLException; import org.yaml.snakeyaml.events.AliasEvent; import org.yaml.snakeyaml.events.Event; import org.yaml.snakeyaml.events.MappingStartEvent; import org.yaml.snakeyaml.events.NodeEvent; import org.yaml.snakeyaml.events.ScalarEvent; import org.yaml.snakeyaml.events.SequenceStartEvent; import org.yaml.snakeyaml.nodes.NodeId; import org.yaml.snakeyaml.parser.Parser; import org.yaml.snakeyaml.parser.ParserImpl; import org.yaml.snakeyaml.reader.ReaderException; import org.yaml.snakeyaml.reader.StreamReader; import org.yaml.snakeyaml.resolver.Resolver; /** * Extractor for populating YAML files. * * <p>The extractor uses <a href="http://www.snakeyaml.org/">SnakeYAML</a> to parse YAML. */ public class YAMLExtractor implements IExtractor { /** The tables constituting the YAML dbscheme. */ private static enum YAMLTables implements Table { YAML(6), // yaml (id: @yaml_node, kind: int ref, parent: @yaml_node_parent ref, // idx: int ref, tag: string ref, tostring: string ref) YAML_ANCHORS(2), // yaml_anchors (node: @yaml_node ref, anchor: string ref) YAML_ALIASES(2), // yaml_aliases (alias: @yaml_alias_node ref, target: string ref) YAML_SCALARS( 3), // yaml_scalars (scalar: @yaml_scalar_node ref, style: int ref, value: string ref) YAML_ERRORS(2); // yaml_errors (id: @yaml_error, message: string ref) private final int arity; private YAMLTables(int arity) { this.arity = arity; } @Override public String getName() { return StringUtil.lc(name()); } @Override public int getArity() { return arity; } @Override public boolean validate(Object... values) { return true; } } /* * case @yaml_node.kind of * 0 = @yaml_scalar_node * | 1 = @yaml_mapping_node * | 2 = @yaml_sequence_node * | 3 = @yaml_alias_node */ private static enum NodeKind { SCALAR, MAPPING, SEQUENCE, ALIAS }; private final boolean tolerateParseErrors; private LocationManager locationManager; private TrapWriter trapWriter; /** * The underlying SnakeYAML parser; we use the relatively low-level {@linkplain Parser} instead of * the more high-level {@linkplain Composer}, since our dbscheme represents YAML documents in AST * form, with aliases left unresolved. */ private Parser parser; /** The resolver used for resolving type tags. */ private Resolver resolver; public YAMLExtractor(ExtractorConfig config) { this.tolerateParseErrors = config.isTolerateParseErrors(); } @Override public LoCInfo extract(TextualExtractor textualExtractor) { locationManager = textualExtractor.getLocationManager(); trapWriter = textualExtractor.getTrapwriter(); Label fileLabel = locationManager.getFileLabel(); locationManager.setHasLocationTable("yaml_locations"); try { parser = new ParserImpl(new StreamReader(textualExtractor.getSource())); resolver = new Resolver(); int idx = 0; while (!atStreamEnd()) extractDocument(fileLabel, idx++, textualExtractor.getSource().codePoints().toArray()); } catch (MarkedYAMLException e) { int line = e.getProblemMark().getLine() + 1; int column = e.getProblemMark().getColumn() + 1; if (!this.tolerateParseErrors) throw new UserError(e.getProblem() + ": " + line + ":" + column); Label lbl = trapWriter.freshLabel(); trapWriter.addTuple(YAMLTables.YAML_ERRORS, lbl, e.getProblem()); locationManager.emitSnippetLocation(lbl, line, column, line, column); } catch (ReaderException e) { if (!this.tolerateParseErrors) throw new UserError(e.toString()); int c = e.getCodePoint(); String s = String.valueOf(Character.toChars(c)); trapWriter.addTuple( YAMLTables.YAML_ERRORS, trapWriter.freshLabel(), "Unexpected character " + s + "(" + c + ")"); // unfortunately, SnakeYAML does not provide structured location information for // ReaderExceptions } return new LoCInfo(0, 0); } /** Check whether the parser has encountered the end of the YAML input stream. */ private boolean atStreamEnd() { if (parser.checkEvent(Event.ID.StreamStart)) parser.getEvent(); return parser.checkEvent(Event.ID.StreamEnd); } /** Extract a complete YAML document; cf. {@link Composer#getNode}. */ private void extractDocument(Label parent, int idx, int[] codepoints) { // Drop the DOCUMENT-START event parser.getEvent(); extractNode(parent, idx, codepoints); // Drop the DOCUMENT-END event parser.getEvent(); } /** Extract a single YAML node; cf. {@link Composer#composeNode}. */ private void extractNode(Label parent, int idx, int[] codepoints) { Label label = trapWriter.freshLabel(); NodeKind kind; String tag = ""; Event start = parser.getEvent(), end = start; if (start.is(Event.ID.Alias)) { kind = NodeKind.ALIAS; trapWriter.addTuple(YAMLTables.YAML_ALIASES, label, ((AliasEvent) start).getAnchor()); } else { String anchor = start instanceof NodeEvent ? ((NodeEvent) start).getAnchor() : null; if (anchor != null) trapWriter.addTuple(YAMLTables.YAML_ANCHORS, label, anchor); if (start.is(Event.ID.Scalar)) { kind = NodeKind.SCALAR; ScalarEvent scalar = (ScalarEvent) start; tag = getTag( scalar.getTag(), NodeId.scalar, scalar.getValue(), scalar.getImplicit().canOmitTagInPlainScalar()); Character style = scalar.getStyle(); int styleCode = style == null ? 0 : (int) style; trapWriter.addTuple(YAMLTables.YAML_SCALARS, label, styleCode, scalar.getValue()); } else if (start.is(Event.ID.SequenceStart)) { kind = NodeKind.SEQUENCE; SequenceStartEvent sequenceStart = (SequenceStartEvent) start; tag = getTag(sequenceStart.getTag(), NodeId.sequence, null, sequenceStart.getImplicit()); int childIdx = 0; while (!parser.checkEvent(Event.ID.SequenceEnd)) extractNode(label, childIdx++, codepoints); end = parser.getEvent(); } else if (start.is(Event.ID.MappingStart)) { kind = NodeKind.MAPPING; MappingStartEvent mappingStart = (MappingStartEvent) start; tag = getTag(mappingStart.getTag(), NodeId.mapping, null, mappingStart.getImplicit()); int childIdx = 1; while (!parser.checkEvent(Event.ID.MappingEnd)) { extractNode(label, childIdx, codepoints); extractNode(label, -childIdx, codepoints); ++childIdx; } end = parser.getEvent(); } else { throw new CatastrophicError("Unexpected YAML parser event: " + start); } } trapWriter.addTuple( YAMLTables.YAML, label, kind.ordinal(), parent, idx, tag, mkToString(start.getStartMark(), end.getEndMark(), codepoints)); extractLocation(label, start.getStartMark(), end.getEndMark()); } /** Determine the type tag of a node. */ private String getTag(String explicitTag, NodeId kind, String value, boolean implicit) { if (explicitTag == null || "!".equals(explicitTag)) return resolver.resolve(kind, value, implicit).getValue(); return explicitTag; } private static boolean isNewLine(int codePoint) { switch (codePoint) { case '\n': case '\r': case '\u0085': case '\u2028': case '\u2029': return true; default: return false; } } /** * SnakeYAML doesn't directly expose the source text of nodes, but we also take the file contents * as an array of Unicode code points. The start and end marks each contain an index into the code * point stream (the end is exclusive), so we can reconstruct the snippet. For readability, we * stop at the first encountered newline. */ private static String mkToString(Mark startMark, Mark endMark, int[] codepoints) { StringBuilder b = new StringBuilder(); for (int i = startMark.getIndex(); i < endMark.getIndex() && !isNewLine(codepoints[i]); i++) b.appendCodePoint(codepoints[i]); return TextualExtractor.sanitiseToString(b.toString()); } /** Emit a source location for a YAML node. */ private void extractLocation(Label label, Mark startMark, Mark endMark) { int startLine, startColumn, endLine, endColumn; // SnakeYAML uses 0-based indexing for both lines and columns, so need to +1 startLine = startMark.getLine() + 1; startColumn = startMark.getColumn() + 1; // SnakeYAML's end positions are exclusive, so only need to +1 for the line endLine = endMark.getLine() + 1; endColumn = endMark.getColumn(); locationManager.emitSnippetLocation(label, startLine, startColumn, endLine, endColumn); } }
9,320
34.988417
100
java