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
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTExpression.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.annotation.Experimental; import net.sourceforge.pmd.lang.java.types.ast.ExprContext; /** * Represents an expression, in the most general sense. * This corresponds to the <a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-Expression">Expression</a> * of the JLS. * * <p>From 7.0.0 on, this is an interface which all expression nodes * implement. * * <p>Expressions are required to be constant in some parts of the grammar * (in {@link ASTSwitchLabel SwitchLabel}, {@link ASTAnnotation Annotation}, * {@link ASTDefaultValue DefaultValue}). A <i>constant expression</i> is * represented as a normal expression subtree, which does not feature any * {@link ASTMethodReference MethodReference}, {@link ASTLambdaExpression LambdaExpression} * or {@link ASTAssignmentExpression AssignmentExpression}. * * * <pre class="grammar"> * * (: In increasing precedence order :) * Expression ::= {@link ASTAssignmentExpression AssignmentExpression} * | {@link ASTConditionalExpression ConditionalExpression} * | {@link ASTLambdaExpression LambdaExpression} * | {@link ASTInfixExpression InfixExpression} * | {@link ASTUnaryExpression PrefixExpression} | {@link ASTCastExpression CastExpression} * | {@link ASTUnaryExpression PostfixExpression} * | {@link ASTSwitchExpression SwitchExpression} * | {@link ASTPrimaryExpression PrimaryExpression} * * </pre> */ public interface ASTExpression extends JavaNode, TypeNode, ASTMemberValue, ASTSwitchArrowRHS { /** * Always returns true. This is to allow XPath queries * to query like {@code /*[@Expression=true()]} to match * any expression, but is useless in Java code. */ default boolean isExpression() { return true; } /** * Returns the number of parenthesis levels around this expression. * If this method returns 0, then no parentheses are present. * * <p>E.g. the expression {@code (a + b)} is parsed as an AdditiveExpression * whose parenthesisDepth is 1, and in {@code ((a + b))} it's 2. * * <p>This is to avoid the parentheses interfering with analysis. * Parentheses already influence parsing by breaking the natural * precedence of operators. It would mostly hide false positives * to make a ParenthesizedExpr node, because it would make semantically * equivalent nodes have a very different representation. * * <p>On the other hand, when a rule explicitly cares about parentheses, * then this attribute may be used to find out whether parentheses * were mentioned, so no information is lost. */ int getParenthesisDepth(); /** * Returns true if this expression has at least one level of parentheses. * The specific depth can be fetched with {@link #getParenthesisDepth()}. */ default boolean isParenthesized() { return getParenthesisDepth() > 0; } @Override default @Nullable Object getConstValue() { return null; } /** Returns true if this expression is a compile-time constant, and is inlined. */ default boolean isCompileTimeConstant() { return getConstValue() != null; } /** * Returns the type expected by the context. This type may determine * an implicit conversion of this value to that type (eg a boxing * conversion, widening numeric conversion, or widening reference * conversion). * * <p>There are many different cases. * For example, in {@code arr['c']}, {@link #getTypeMirror()} would * return {@code char} for the char literal, but the context type * is {@code int} since it's used as an array index. Hence, a widening * conversion occurs. Similarly, the context type of an expression * in a return statement is the return type of the method, etc. * * <p>If the context is undefined, then the returned object will answer * true to {@link ExprContext#isMissing()}. This is completely normal * and needs to be accounted for by rules. For instance, it occurs * if this expression is used as a statement. * * <p>Note that conversions are a language-level construct only. * Converting from a type to another may not actually require any * concrete operation at runtime. For instance, converting a * {@code char} to an {@code int} is a noop at runtime, because chars * are anyway treated as ints by the JVM (within stack frames). A * boxing conversion will however in general translate to a call to * e.g. {@link Integer#valueOf(int)}. * * <p>Not all contexts allow all kinds of conversions. See * {@link ExprContext}. */ @Experimental default @NonNull ExprContext getConversionContext() { return getRoot().getLazyTypeResolver().getConversionContextForExternalUse(this); } }
5,262
38.571429
128
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTResourceList.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.java.ast.ASTList.ASTNonEmptyList; /** * A list of resources in a {@linkplain ASTTryStatement try-with-resources}. * * <pre class="grammar"> * * ResourceList ::= "(" {@link ASTResource Resource} ( ";" {@link ASTResource Resource} )* ";"? ")" * * </pre> */ public final class ASTResourceList extends ASTNonEmptyList<ASTResource> { private boolean trailingSemi; ASTResourceList(int id) { super(id, ASTResource.class); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } void setTrailingSemi() { this.trailingSemi = true; } /** * Returns true if this resource list has a trailing semicolon, eg * in {@code try (InputStream is = getInputStream();) { ... }}. */ public boolean hasTrailingSemiColon() { return trailingSemi; } }
1,076
23.477273
99
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/AbstractTypeBodyDeclaration.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * @author Clément Fournier * @since 6.2.0 */ abstract class AbstractTypeBodyDeclaration extends AbstractJavaNode implements JavaNode { AbstractTypeBodyDeclaration(int id) { super(id); } }
346
18.277778
89
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/AstImplUtil.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.Node; /** * KEEP PRIVATE * * @author Clément Fournier */ final class AstImplUtil { private AstImplUtil() { } public static String getLastSegment(String nameWithDots, char sep) { assert nameWithDots != null; int lastIdx = nameWithDots.lastIndexOf(sep); return lastIdx < 0 ? nameWithDots : nameWithDots.substring(lastIdx + 1); } public static String getFirstSegment(String nameWithDots, char sep) { assert nameWithDots != null; int lastIdx = nameWithDots.indexOf(sep); return lastIdx < 0 ? nameWithDots : nameWithDots.substring(0, lastIdx); } @Nullable public static <T extends Node> T getChildAs(JavaNode javaNode, int idx, Class<T> type) { if (javaNode.getNumChildren() <= idx || idx < 0) { return null; } Node child = javaNode.getChild(idx); return type.isInstance(child) ? type.cast(child) : null; } static void bumpParenDepth(ASTExpression expression) { assert expression instanceof AbstractJavaExpr : expression.getClass() + " doesn't have parenDepth attribute!"; ((AbstractJavaExpr) expression).bumpParenDepth(); } static void bumpParenDepth(ASTPattern pattern) { assert pattern instanceof ASTTypePattern || pattern instanceof ASTRecordPattern : pattern.getClass() + " doesn't have parenDepth attribute!"; if (pattern instanceof ASTTypePattern) { ((ASTTypePattern) pattern).bumpParenDepth(); } else if (pattern instanceof ASTRecordPattern) { ((ASTRecordPattern) pattern).bumpParenDepth(); } } }
1,900
29.174603
92
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTModuleExportsDirective.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.ast.NodeStream; /** * An "exports" directive of a {@linkplain ASTModuleDeclaration module declaration}. * * <pre class="grammar"> * * ModuleExportsDirective ::= * "exports" &lt;PACKAGE_NAME&gt; * ( "to" {@linkplain ASTModuleName ModuleName} ( "," {@linkplain ASTModuleName ModuleName})* )? * ";" * * </pre> */ public final class ASTModuleExportsDirective extends AbstractPackageNameModuleDirective { ASTModuleExportsDirective(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns a stream of the module names that are found after the "to" keyword. * May be empty */ public NodeStream<ASTModuleName> getTargetModules() { return children(ASTModuleName.class); } }
1,042
25.075
100
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/FinalizableNode.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * A node that may have the final modifier. */ public interface FinalizableNode extends AccessNode { /** * Returns true if this variable, method or class is final (even implicitly). */ @Override default boolean isFinal() { return hasModifiers(JModifier.FINAL); } }
439
19
81
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTModuleDirective.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * A directive of a {@linkplain ASTModuleDeclaration module declaration}. * Implementations provide more specific attributes. * * <pre class="grammar"> * * ModuleDirective ::= {@linkplain ASTModuleRequiresDirective ModuleRequiresDirective} * | {@linkplain ASTModuleOpensDirective ModuleOpensDirective} * | {@linkplain ASTModuleExportsDirective ModuleExportsDirective} * | {@linkplain ASTModuleProvidesDirective ModuleProvidesDirective} * | {@linkplain ASTModuleUsesDirective ModuleUsesDirective} * * </pre> */ public abstract class ASTModuleDirective extends AbstractJavaNode { ASTModuleDirective(int id) { super(id); } }
863
27.8
86
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTArrayAccess.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; /** * An array access expression. * * <pre class="grammar"> * * ArrayAccess ::= {@link ASTExpression Expression} "[" {@link ASTExpression Expression} "]" * * </pre> */ public final class ASTArrayAccess extends AbstractJavaExpr implements ASTAssignableExpr, QualifiableExpression { ASTArrayAccess(int id) { super(id); } /** * Returns the expression to the left of the "[". * This can never be a {@linkplain ASTTypeExpression type}, * and is never {@linkplain ASTAmbiguousName ambiguous}. */ @NonNull @Override public ASTExpression getQualifier() { return (ASTExpression) getChild(0); } /** Returns the expression within the brackets. */ public ASTExpression getIndexExpression() { return (ASTExpression) getChild(1); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
1,166
24.369565
112
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTSynchronizedStatement.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * A synchronized statement. * * <pre class="grammar"> * * SynchronizedStatement ::= "synchronized" "(" {@link ASTExpression Expression} ")" {@link ASTBlock Block} * * </pre> */ public final class ASTSynchronizedStatement extends AbstractStatement { ASTSynchronizedStatement(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns the expression evaluating to the lock object. */ public ASTExpression getLockExpression() { return (ASTExpression) getChild(0); } /** * Returns the body of this statement. */ public ASTBlock getBody() { return (ASTBlock) getChild(1); } }
930
20.651163
107
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/AbstractInvocationExpr.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.java.types.OverloadSelectionResult; /** * */ abstract class AbstractInvocationExpr extends AbstractJavaExpr implements InvocationNode { private OverloadSelectionResult result; AbstractInvocationExpr(int i) { super(i); } void setOverload(OverloadSelectionResult result) { assert result != null; this.result = result; } @Override public OverloadSelectionResult getOverloadSelectionInfo() { forceTypeResolution(); return assertNonNullAfterTypeRes(result); } }
700
21.612903
90
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/JavaNode.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.annotation.DeprecatedUntil700; import net.sourceforge.pmd.lang.ast.AstVisitor; import net.sourceforge.pmd.lang.ast.impl.javacc.JjtreeNode; import net.sourceforge.pmd.lang.java.symbols.table.JSymbolTable; import net.sourceforge.pmd.lang.java.types.TypeSystem; /** * Root interface for all Nodes of the Java AST. */ public interface JavaNode extends JjtreeNode<JavaNode> { /** * Calls back the visitor's visit method corresponding to the runtime type of this Node. * * @param visitor Visitor to dispatch * @param data Visit data * * @deprecated Use {@link #acceptVisitor(AstVisitor, Object)} */ @Deprecated @DeprecatedUntil700 default Object jjtAccept(JavaParserVisitor visitor, Object data) { return acceptVisitor(visitor, data); } /** * Returns the node representing the type declaration this node is * found in. The type of that node is the type of the {@code this} * expression. * * <p>This returns null for nodes that aren't enclosed in a type declaration. * This includes {@linkplain ASTPackageDeclaration PackageDeclaration}, * This includes {@linkplain ASTImportDeclaration ImportDeclaration}, * {@linkplain ASTModuleDeclaration ModuleDeclaration}, * {@linkplain ASTCompilationUnit CompilationUnit}, and top-level * {@linkplain ASTAnyTypeDeclaration AnyTypeDeclaration}s. */ default ASTAnyTypeDeclaration getEnclosingType() { return getFirstParentOfType(ASTAnyTypeDeclaration.class); } @Override @NonNull ASTCompilationUnit getRoot(); /** * Returns the symbol table for the program point represented by * this node. */ @NonNull JSymbolTable getSymbolTable(); /** * Returns the type system with which this node was created. This is * the object responsible for representing types in the compilation * unit. */ TypeSystem getTypeSystem(); }
2,182
29.319444
92
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/AbstractLiteral.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * @author Clément Fournier */ abstract class AbstractLiteral extends AbstractJavaExpr implements ASTLiteral { AbstractLiteral(int i) { super(i); } @Override public boolean isCompileTimeConstant() { return true; // note: NullLiteral overrides this to false } }
436
19.809524
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/TokenUtils.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.NoSuchElementException; import java.util.Objects; import net.sourceforge.pmd.lang.ast.GenericToken; import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken; /** * PRIVATE FOR NOW, find out what is useful to move to the interface * (probably everything). * * @author Clément Fournier */ final class TokenUtils { // mind: getBeginLine and getEndLine on JavaccToken are now very slow. private TokenUtils() { } public static <T extends GenericToken<T>> T nthFollower(T token, int n) { if (n < 0) { throw new IllegalArgumentException("Negative index?"); } while (n-- > 0 && token != null) { token = token.getNext(); } if (token == null) { throw new NoSuchElementException("No such token"); } return token; } /** * This is why we need to doubly link tokens... otherwise we need a * start hint. * * @param startHint Token from which to start iterating, * needed because tokens are not linked to their * previous token. Must be strictly before the anchor * and as close as possible to the expected position of * the anchor. * @param anchor Anchor from which to apply the shift. The n-th previous * token will be returned * @param n An int > 0 * * @throws NoSuchElementException If there's less than n tokens to the left of the anchor. */ // test only public static <T extends GenericToken<T>> T nthPrevious(T startHint, T anchor, int n) { if (startHint.compareTo(anchor) >= 0) { throw new IllegalStateException("Wrong left hint, possibly not left enough"); } if (n <= 0) { throw new IllegalArgumentException("Offset can't be less than 1"); } int numAway = 0; T target = startHint; T current = startHint; while (current != null && !current.equals(anchor)) { current = current.getNext(); // wait "n" iterations before starting to advance the target // then advance "target" at the same rate as "current", but // "n" tokens to the left if (numAway == n) { target = target.getNext(); } else { numAway++; } } if (!Objects.equals(current, anchor)) { throw new IllegalStateException("Wrong left hint, possibly not left enough"); } else if (numAway != n) { // We're not "n" tokens away from the anchor throw new NoSuchElementException("No such token"); } return target; } public static void expectKind(JavaccToken token, int kind) { assert token.kind == kind : "Expected " + token.getDocument().describeKind(kind) + ", got " + token; } }
3,081
32.139785
108
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTCatchClause.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * A "catch" clause of a {@linkplain ASTTryStatement try statement}. * * <pre class="grammar"> * * CatchClause ::= "catch" "(" {@link ASTCatchParameter CatchParameter} ")" {@link ASTBlock Block} * * </pre> */ public final class ASTCatchClause extends AbstractJavaNode { ASTCatchClause(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** Returns the catch parameter. */ public ASTCatchParameter getParameter() { return (ASTCatchParameter) getFirstChild(); } /** Returns the body of this catch branch. */ public ASTBlock getBody() { return getFirstChildOfType(ASTBlock.class); } }
914
22.461538
98
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/JavaVisitorBase.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.ast.AstVisitorBase; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; /** * Base implementation of {@link JavaVisitor}. This adds delegation logic * which the interface doesn't have. * * <p>Contrary to the old visitor, which used Object as both parameter and * return type, this visitor uses separate type parameters for those. This * means you can't just return the parameter, unless your visitor has equal * parameter and return type. This type signature subsumes many possible * signatures. The old one is {@code <Object, Object>}, still implemented * by {@link JavaParserVisitor} for backwards compatibility. If you don't * want to return a value, or don't want a parameter, use {@link Void}. * * <p>Since 7.0.0 we use default methods on the interface, which removes * code duplication. However it's still recommended to extend a base class, * for forward compatibility. */ public class JavaVisitorBase<P, R> extends AstVisitorBase<P, R> implements JavaVisitor<P, R> { // <editor-fold defaultstate="collapsed" desc="Methods/constructors"> public R visitMethodOrCtor(ASTMethodOrConstructorDeclaration node, P data) { return visitJavaNode(node, data); } @Override public R visit(ASTMethodDeclaration node, P data) { return visitMethodOrCtor(node, data); } @Override public R visit(ASTConstructorDeclaration node, P data) { return visitMethodOrCtor(node, data); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Type declarations"> public R visitTypeDecl(ASTAnyTypeDeclaration node, P data) { return visitJavaNode(node, data); } @Override public R visit(ASTClassOrInterfaceDeclaration node, P data) { return visitTypeDecl(node, data); } @Override public R visit(ASTAnonymousClassDeclaration node, P data) { return visitTypeDecl(node, data); } @Override public R visit(ASTRecordDeclaration node, P data) { return visitTypeDecl(node, data); } @Override public R visit(ASTEnumDeclaration node, P data) { return visitTypeDecl(node, data); } @Override public R visit(ASTAnnotationTypeDeclaration node, P data) { return visitTypeDecl(node, data); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Type & ReferenceType"> /** Note that VoidType does not delegate to here. */ public R visitType(ASTType node, P data) { return visitJavaNode(node, data); } @Override public R visit(ASTPrimitiveType node, P data) { return visitType(node, data); } public R visitReferenceType(ASTReferenceType node, P data) { return visitType(node, data); } @Override public R visit(ASTArrayType node, P data) { return visitReferenceType(node, data); } @Override public R visit(ASTIntersectionType node, P data) { return visitReferenceType(node, data); } @Override public R visit(ASTWildcardType node, P data) { return visitReferenceType(node, data); } @Override public R visit(ASTUnionType node, P data) { return visitReferenceType(node, data); } @Override public R visit(ASTClassOrInterfaceType node, P data) { return visitReferenceType(node, data); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Expressions"> public R visitExpression(ASTExpression node, P data) { return visitJavaNode(node, data); } @Override public R visit(ASTLambdaExpression node, P data) { return visitExpression(node, data); } @Override public R visit(ASTAssignmentExpression node, P data) { return visitExpression(node, data); } @Override public R visit(ASTConditionalExpression node, P data) { return visitExpression(node, data); } @Override public R visit(ASTInfixExpression node, P data) { return visitExpression(node, data); } @Override public R visit(ASTUnaryExpression node, P data) { return visitExpression(node, data); } @Override public R visit(ASTCastExpression node, P data) { return visitExpression(node, data); } @Override public R visit(ASTSwitchExpression node, P data) { return visitExpression(node, data); } /* Primaries */ public R visitPrimaryExpr(ASTPrimaryExpression node, P data) { return visitExpression(node, data); } @Override public R visit(ASTMethodCall node, P data) { return visitPrimaryExpr(node, data); } @Override public R visit(ASTConstructorCall node, P data) { return visitPrimaryExpr(node, data); } @Override public R visit(ASTArrayAllocation node, P data) { return visitPrimaryExpr(node, data); } @Override public R visit(ASTArrayAccess node, P data) { return visitPrimaryExpr(node, data); } public R visitNamedExpr(ASTNamedReferenceExpr node, P data) { return visitPrimaryExpr(node, data); } @Override public R visit(ASTVariableAccess node, P data) { return visitNamedExpr(node, data); } @Override public R visit(ASTFieldAccess node, P data) { return visitNamedExpr(node, data); } @Override public R visit(ASTMethodReference node, P data) { return visitPrimaryExpr(node, data); } @Override public R visit(ASTThisExpression node, P data) { return visitPrimaryExpr(node, data); } @Override public R visit(ASTSuperExpression node, P data) { return visitPrimaryExpr(node, data); } @Override public R visit(ASTClassLiteral node, P data) { return visitPrimaryExpr(node, data); } /* Literals */ public R visitLiteral(ASTLiteral node, P data) { return visitPrimaryExpr(node, data); } @Override public R visit(ASTBooleanLiteral node, P data) { return visitLiteral(node, data); } @Override public R visit(ASTNullLiteral node, P data) { return visitLiteral(node, data); } @Override public R visit(ASTNumericLiteral node, P data) { return visitLiteral(node, data); } @Override public R visit(ASTStringLiteral node, P data) { return visitLiteral(node, data); } @Override public R visit(ASTCharLiteral node, P data) { return visitLiteral(node, data); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Statements"> public R visitStatement(ASTStatement node, P data) { return visitJavaNode(node, data); } @Override public R visit(ASTAssertStatement node, P data) { return visitStatement(node, data); } @Override public R visit(ASTBlock node, P data) { return visitStatement(node, data); } @Override public R visit(ASTBreakStatement node, P data) { return visitStatement(node, data); } @Override public R visit(ASTContinueStatement node, P data) { return visitStatement(node, data); } @Override public R visit(ASTDoStatement node, P data) { return visitStatement(node, data); } @Override public R visit(ASTEmptyStatement node, P data) { return visitStatement(node, data); } @Override public R visit(ASTExplicitConstructorInvocation node, P data) { return visitStatement(node, data); } @Override public R visit(ASTExpressionStatement node, P data) { return visitStatement(node, data); } @Override public R visit(ASTForeachStatement node, P data) { return visitStatement(node, data); } @Override public R visit(ASTForStatement node, P data) { return visitStatement(node, data); } @Override public R visit(ASTIfStatement node, P data) { return visitStatement(node, data); } @Override public R visit(ASTLabeledStatement node, P data) { return visitStatement(node, data); } @Override public R visit(ASTLocalClassStatement node, P data) { return visitStatement(node, data); } @Override public R visit(ASTLocalVariableDeclaration node, P data) { return visitStatement(node, data); } @Override public R visit(ASTReturnStatement node, P data) { return visitStatement(node, data); } @Override public R visit(ASTStatementExpressionList node, P data) { return visitStatement(node, data); } @Override public R visit(ASTSwitchStatement node, P data) { return visitStatement(node, data); } @Override public R visit(ASTSynchronizedStatement node, P data) { return visitStatement(node, data); } @Override public R visit(ASTThrowStatement node, P data) { return visitStatement(node, data); } @Override public R visit(ASTTryStatement node, P data) { return visitStatement(node, data); } @Override public R visit(ASTWhileStatement node, P data) { return visitStatement(node, data); } @Override public R visit(ASTYieldStatement node, P data) { return visitStatement(node, data); } // </editor-fold> }
9,596
22.9925
94
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTForStatement.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; /** * Represents a {@code for} loop (distinct from {@linkplain ASTForeachStatement foreach loops}). * * <pre class="grammar"> * * ForStatement ::= "for" "(" {@linkplain ASTForInit ForInit}? ";" {@linkplain ASTExpression Expression}? ";" {@linkplain ASTForUpdate ForUpdate}? ")" * {@linkplain ASTStatement Statement} * * </pre> */ public final class ASTForStatement extends AbstractStatement implements ASTLoopStatement { ASTForStatement(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } @Override public ASTExpression getCondition() { return getFirstChildOfType(ASTExpression.class); } /** * Returns the statement nested within the {@linkplain ASTForInit init clause}, if it exists. * This is either a {@linkplain ASTLocalVariableDeclaration local variable declaration} or a * {@linkplain ASTStatementExpressionList statement expression list}. */ public @Nullable ASTStatement getInit() { ASTForInit init = AstImplUtil.getChildAs(this, 0, ASTForInit.class); return init == null ? null : init.getStatement(); } /** * Returns the statement nested within the update clause, if it exists. */ public @Nullable ASTStatementExpressionList getUpdate() { ASTForUpdate update = firstChild(ASTForUpdate.class); return update == null ? null : update.getExprList(); } }
1,739
29.526316
150
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTVariableDeclaratorId.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; import net.sourceforge.pmd.lang.rule.xpath.DeprecatedAttribute; // @formatter:off /** * Represents an identifier in the context of variable or parameter declarations (not their use in * expressions). Such a node declares a name in the scope it's defined in, and can occur in the following * contexts: * * <ul> * <li> Field and enum constant declarations; * <li> Local variable declarations; * <li> Method, constructor and lambda parameter declarations; * <li> Exception parameter declarations occurring in catch clauses; * <li> Resource declarations occurring in try-with-resources statements. * </ul> * * <p>Since this node conventionally represents the declared variable in PMD, * it owns a {@link JVariableSymbol} and can provide access to * {@linkplain #getLocalUsages() variable usages}. * * <pre class="grammar"> * * VariableDeclaratorId ::= &lt;IDENTIFIER&gt; {@link ASTArrayDimensions ArrayDimensions}? * * </pre> * */ // @formatter:on public final class ASTVariableDeclaratorId extends AbstractTypedSymbolDeclarator<JVariableSymbol> implements AccessNode, SymbolDeclaratorNode, FinalizableNode { private List<ASTNamedReferenceExpr> usages = Collections.emptyList(); ASTVariableDeclaratorId(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns an unmodifiable list of the usages of this variable that * are made in this file. Note that for a record component, this returns * usages both for the formal parameter symbol and its field counterpart. * * <p>Note that a variable initializer is not part of the usages * (though this should be evident from the return type). */ public List<ASTNamedReferenceExpr> getLocalUsages() { return usages; } void addUsage(ASTNamedReferenceExpr usage) { if (usages.isEmpty()) { usages = new ArrayList<>(4); //make modifiable } usages.add(usage); } /** * Returns the extra array dimensions associated with this variable. * For example in the declaration {@code int a[]}, {@link #getTypeNode()} * returns {@code int}, and this method returns the dimensions that follow * the variable ID. Returns null if there are no such dimensions. */ @Nullable public ASTArrayDimensions getExtraDimensions() { return children(ASTArrayDimensions.class).first(); } @NonNull @Override public ASTModifierList getModifiers() { // delegates modifiers return getModifierOwnerParent().getModifiers(); } @Override public Visibility getVisibility() { return isPatternBinding() ? Visibility.V_LOCAL : getModifierOwnerParent().getVisibility(); } private AccessNode getModifierOwnerParent() { JavaNode parent = getParent(); if (parent instanceof ASTVariableDeclarator) { return (AccessNode) parent.getParent(); } return (AccessNode) parent; } /** * @deprecated Use {@link #getName()} */ @Override @DeprecatedAttribute(replaceWith = "@Name") @Deprecated public String getImage() { return getName(); } /** Returns the name of the variable. */ public String getName() { return super.getImage(); } /** * Returns true if the declared variable has an array type. */ public boolean hasArrayType() { return getExtraDimensions() != null || getTypeNode() instanceof ASTArrayType; } /** * Returns true if this nodes declares an exception parameter in * a {@code catch} statement. */ public boolean isExceptionBlockParameter() { return getParent() instanceof ASTCatchParameter; } /** * Returns true if this node declares a formal parameter for a method * declaration or a lambda expression. */ public boolean isFormalParameter() { return getParent() instanceof ASTFormalParameter || isLambdaParameter(); } /** * Returns true if this node declares a record component. The symbol * born by this node is the symbol of the corresponding field (not the * formal parameter of the record constructor). */ public boolean isRecordComponent() { return getParent() instanceof ASTRecordComponent; } /** * Returns true if this node declares a local variable from within * a regular {@link ASTLocalVariableDeclaration}. */ public boolean isLocalVariable() { return getNthParent(2) instanceof ASTLocalVariableDeclaration && !isResourceDeclaration() && !isForeachVariable(); } /** * Returns true if this node is a variable declared in a * {@linkplain ASTForeachStatement foreach loop}. */ public boolean isForeachVariable() { // Foreach/LocalVarDecl/VarDeclarator/VarDeclId return getNthParent(3) instanceof ASTForeachStatement; } /** * Returns true if this node is a variable declared in the init clause * of a {@linkplain ASTForStatement for loop}. */ public boolean isForLoopVariable() { // For/ForInit/LocalVarDecl/VarDeclarator/VarDeclId return getNthParent(3) instanceof ASTForInit; } /** * Returns true if this node declares a formal parameter for * a lambda expression. In that case, the type of this parameter * is not necessarily inferred, see {@link #isTypeInferred()}. */ public boolean isLambdaParameter() { return getParent() instanceof ASTLambdaParameter; } /** * Returns true if this node declares a field from a regular * {@link ASTFieldDeclaration}. This returns false for enum * constants (use {@link JVariableSymbol#isField() getSymbol().isField()} * if you want that). */ public boolean isField() { return getNthParent(2) instanceof ASTFieldDeclaration; } /** * Returns true if this node declares an enum constant. */ public boolean isEnumConstant() { return getParent() instanceof ASTEnumConstant; } /** * Returns the name of the variable. * * @deprecated Use {@link #getName()} */ @Deprecated @DeprecatedAttribute(replaceWith = "@Name") public String getVariableName() { return getName(); } /** * Returns true if this declarator id declares a resource in a try-with-resources statement. */ public boolean isResourceDeclaration() { return getParent() instanceof ASTResource; } /** * Returns true if the declared variable's type is inferred by * the compiler. In Java 8, this can happen if it's in a formal * parameter of a lambda with an inferred type (e.g. {@code (a, b) -> a + b}). * Since Java 10, the type of local variables can be inferred * too, e.g. {@code var i = 2;}. * * <p>This method returns true for declarator IDs in those contexts, * in which case {@link #getTypeNode()} returns {@code null}, * since the type node is absent. */ public boolean isTypeInferred() { return getTypeNode() == null; } /** * Returns true if this is a binding variable in a * {@linkplain ASTPattern pattern}. */ public boolean isPatternBinding() { return getParent() instanceof ASTPattern; } /** * Returns the initializer of the variable, or null if it doesn't exist. */ @Nullable public ASTExpression getInitializer() { if (getParent() instanceof ASTVariableDeclarator) { return ((ASTVariableDeclarator) getParent()).getInitializer(); } return null; } /** * Returns the first child of the node returned by {@link #getTypeNode()}. * The image of that node can usually be interpreted as the image of the * type. */ // TODO unreliable, not typesafe and not useful, should be deprecated @Nullable public Node getTypeNameNode() { return getTypeNode(); } /** * Determines the type node of this variable id, that is, the type node * belonging to the variable declaration of this node (either a * FormalParameter, LocalVariableDeclaration or FieldDeclaration). * * <p>The type of the returned node is not necessarily the type of this * node. See {@link #getType()} for an explanation. * * @return the type node, or {@code null} if there is no explicit type, * e.g. if {@link #isTypeInferred()} returns true. */ public @Nullable ASTType getTypeNode() { AccessNode parent = getModifierOwnerParent(); return parent.firstChild(ASTType.class); } // @formatter:off /** * Returns the type of the declared variable. The type of a declarator ID is * <ul> * <li>1. not necessarily the same as the type written out at the * start of the declaration, e.g. {@code int a[];} * <li>2. not necessarily the same as the types of other variables * declared in the same statement, e.g. {@code int a[], b;}. * </ul> * * <p>These are consequences of Java's allowing programmers to * declare additional pairs of brackets on declarator ids. The type * of the node returned by {@link #getTypeNode()} doesn't take into * account those additional array dimensions, whereas this node's * type takes into account the total number of dimensions, i.e. * those declared on this node plus those declared on the type node. * * <p>The returned type also takes into account whether this variable * is a varargs formal parameter. * * <p>The type of the declarator ID is thus always the real type of * the variable. */ // @formatter:on @Override @SuppressWarnings("PMD.UselessOverridingMethod") public Class<?> getType() { return super.getType(); } }
10,644
31.454268
160
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/BinaryOp.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.Comparator; import java.util.EnumSet; import java.util.Set; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.util.CollectionUtil; /** * Represents the operator of an {@linkplain ASTInfixExpression infix expression}. * Constants are roughly ordered by precedence, except some of them have the same * precedence. * * <p>All of those operators are left-associative. * * @see UnaryOp * @see AssignmentOp */ public enum BinaryOp implements InternalInterfaces.OperatorLike { // shortcut boolean ops /** Conditional (shortcut) OR {@code "||"} operator. */ CONDITIONAL_OR("||"), /** Conditional (shortcut) AND {@code "&&"} operator. */ CONDITIONAL_AND("&&"), // non-shortcut (also bitwise) /** OR {@code "|"} operator. Either logical or bitwise depending on the type of the operands. */ OR("|"), /** XOR {@code "^"} operator. Either logical or bitwise depending on the type of the operands. */ XOR("^"), /** AND {@code "&"} operator. Either logical or bitwise depending on the type of the operands. */ AND("&"), // equality /** Equals {@code "=="} operator. */ EQ("=="), /** Not-equals {@code "!="} operator. */ NE("!="), // relational /** Lower-or-equal {@code "<="} operator. */ LE("<="), /** Greater-or-equal {@code ">="} operator. */ GE(">="), /** Greater-than {@code ">"} operator. */ GT(">"), /** Lower-than {@code "<"} operator. */ LT("<"), /** Type test {@code "instanceof"} operator. */ INSTANCEOF("instanceof"), // shift /** Left shift {@code "<<"} operator. */ LEFT_SHIFT("<<"), /** Right shift {@code ">>"} operator. */ RIGHT_SHIFT(">>"), /** Unsigned right shift {@code ">>>"} operator. */ UNSIGNED_RIGHT_SHIFT(">>>"), // additive /** Addition {@code "+"} operator, or string concatenation. */ ADD("+"), /** Subtraction {@code "-"} operator. */ SUB("-"), // multiplicative /** Multiplication {@code "*"} operator. */ MUL("*"), /** Division {@code "/"} operator. */ DIV("/"), /** Modulo {@code "%"} operator. */ MOD("%"); /** Set of {@code &&} and {@code ||}. Use with {@link JavaAstUtils#isInfixExprWithOperator(JavaNode, Set)}. */ public static final Set<BinaryOp> CONDITIONAL_OPS = CollectionUtil.immutableEnumSet(CONDITIONAL_AND, CONDITIONAL_OR); /** Set of {@code <}, {@code <=}, {@code >=} and {@code >}. Use with {@link JavaAstUtils#isInfixExprWithOperator(JavaNode, Set)}. */ public static final Set<BinaryOp> COMPARISON_OPS = CollectionUtil.immutableEnumSet(LE, GE, GT, LT); /** Set of {@code ==} and {@code !=}. Use with {@link JavaAstUtils#isInfixExprWithOperator(JavaNode, Set)}. */ public static final Set<BinaryOp> EQUALITY_OPS = CollectionUtil.immutableEnumSet(EQ, NE); /** Set of {@code <<}, {@code >>} and {@code >>>}. Use with {@link JavaAstUtils#isInfixExprWithOperator(JavaNode, Set)}. */ public static final Set<BinaryOp> SHIFT_OPS = CollectionUtil.immutableEnumSet(LEFT_SHIFT, RIGHT_SHIFT, UNSIGNED_RIGHT_SHIFT); private final String code; BinaryOp(String code) { this.code = code; } @Override public String getToken() { return code; } @Override public String toString() { return this.code; } /** * Compare the precedence of this operator with that of the other, * as if with a {@link Comparator}. Returns a positive integer if * this operator has a higher precedence as the argument, zero if * they have the same precedence, etc. * * @throws NullPointerException If the argument is null */ public int comparePrecedence(@NonNull BinaryOp other) { // arguments are flipped because precedence class decreases return Integer.compare(other.precedenceClass(), this.precedenceClass()); } /** * Returns true if this operator has the same relative precedence * as the argument. For example, {@link #ADD} and {@link #SUB} have * the same precedence. * * @throws NullPointerException If the argument is null */ public boolean hasSamePrecedenceAs(@NonNull BinaryOp other) { return comparePrecedence(other) == 0; } /** * Returns the ops with strictly greater precedence than the given op. * This may return an empty set. */ public static Set<BinaryOp> opsWithGreaterPrecedence(BinaryOp op) { Set<BinaryOp> range = EnumSet.range(op, MOD); range.remove(op); return range; } private int precedenceClass() { switch (this) { case CONDITIONAL_OR: return 9; case CONDITIONAL_AND: return 8; case OR: return 7; case XOR: return 6; case AND: return 5; case EQ: case NE: return 4; case LE: case GE: case GT: case LT: case INSTANCEOF: return 3; case LEFT_SHIFT: case RIGHT_SHIFT: case UNSIGNED_RIGHT_SHIFT: return 2; case ADD: case SUB: return 1; case MUL: case DIV: case MOD: return 0; default: return -1; } } /** * Complement, for boolean operators. Eg for {@code ==}, return {@code !=}, * for {@code <=}, returns {@code >}. Returns null if this is another kind * of operator. */ public @Nullable BinaryOp getComplement() { switch (this) { case CONDITIONAL_OR: return CONDITIONAL_AND; case CONDITIONAL_AND: return CONDITIONAL_OR; case OR: return AND; case AND: return OR; case EQ: return NE; case NE: return EQ; case LE: return GT; case GE: return LT; case GT: return LE; case LT: return GE; default: return null; } } }
6,292
28
136
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTImportDeclaration.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; /** * Represents an import declaration in a Java file. * * <pre class="grammar"> * * ImportDeclaration ::= "import" "static"? Name ( "." "*" )? ";" * * </pre> * * @see <a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-7.html#jls-7.5">JLS 7.5</a> */ public final class ASTImportDeclaration extends AbstractJavaNode implements ASTTopLevelDeclaration { private boolean isImportOnDemand; private boolean isStatic; ASTImportDeclaration(int id) { super(id); } void setImportOnDemand() { isImportOnDemand = true; } // @formatter:off /** * Returns true if this is an import-on-demand declaration, * aka "wildcard import". * * <ul> * <li>If this is a static import, then the imported names are those * of the accessible static members of the named type; * <li>Otherwise, the imported names are the names of the accessible types * of the named type or named package. * </ul> */ // @formatter:on public boolean isImportOnDemand() { return isImportOnDemand; } void setStatic() { isStatic = true; } /** * Returns true if this is a static import. If this import is not on-demand, * {@link #getImportedSimpleName()} returns the name of the imported member. */ public boolean isStatic() { return isStatic; } /** * Returns the full name of the import. For on-demand imports, this is the name without * the final dot and asterisk. */ public @NonNull String getImportedName() { return super.getImage(); } @Override public String getImage() { // the image was null before 7.0, best keep it that way return null; } /** * Returns the simple name of the type or method imported by this declaration. * For on-demand imports, returns {@code null}. */ public String getImportedSimpleName() { if (isImportOnDemand) { return null; } String importName = getImportedName(); return importName.substring(importName.lastIndexOf('.') + 1); } /** * Returns the "package" prefix of the imported name. For type imports, including on-demand * imports, this is really the package name of the imported type(s). For static imports, * this is actually the qualified name of the enclosing type, including the type name. */ public String getPackageName() { String importName = getImportedName(); if (isImportOnDemand) { return importName; } if (importName.indexOf('.') == -1) { return ""; } int lastDot = importName.lastIndexOf('.'); return importName.substring(0, lastDot); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
3,156
25.529412
100
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTEmptyDeclaration.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * An empty declaration (useless). This is kept separate from {@link ASTStatement} * because they don't occur in the same syntactic contexts. * * <pre class="grammar"> * * EmptyDeclaration ::= ";" * * </pre> */ public final class ASTEmptyDeclaration extends AbstractJavaNode implements ASTBodyDeclaration, ASTTopLevelDeclaration { ASTEmptyDeclaration(int id) { super(id); } @Override public <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
694
22.166667
88
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/TypesFromAst.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.lang.annotation.ElementType; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.pcollections.PSet; import net.sourceforge.pmd.lang.java.symbols.JClassSymbol; import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol; import net.sourceforge.pmd.lang.java.symbols.JTypeParameterSymbol; import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot; import net.sourceforge.pmd.lang.java.symbols.internal.ast.SymbolResolutionPass; import net.sourceforge.pmd.lang.java.symbols.table.internal.JavaResolvers; import net.sourceforge.pmd.lang.java.types.JClassType; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.Substitution; import net.sourceforge.pmd.lang.java.types.TypeSystem; import net.sourceforge.pmd.util.CollectionUtil; /** * Builds type mirrors from AST nodes. */ final class TypesFromAst { private TypesFromAst() { // utility class } public static List<JTypeMirror> fromAst(TypeSystem ts, Substitution subst, List<ASTType> reflected) { return CollectionUtil.map(reflected, it -> fromAst(ts, subst, it)); } /** * Builds a type from an AST node. * * @param lexicalSubst A substitution to apply to type variables * @param node An ast node */ public static JTypeMirror fromAst(TypeSystem ts, Substitution lexicalSubst, ASTType node) { if (node == null) { return null; } return fromAstImpl(ts, lexicalSubst, node); } private static JTypeMirror fromAstImpl(TypeSystem ts, Substitution lexicalSubst, ASTType node) { if (node instanceof ASTClassOrInterfaceType) { return makeFromClassType(ts, (ASTClassOrInterfaceType) node, lexicalSubst); } else if (node instanceof ASTWildcardType) { ASTWildcardType wild = (ASTWildcardType) node; @Nullable JTypeMirror bound = fromAst(ts, lexicalSubst, wild.getTypeBoundNode()); if (bound == null) { bound = ts.OBJECT; } return ts.wildcard(wild.isUpperBound(), bound).withAnnotations(getTypeAnnotations(node)); } else if (node instanceof ASTIntersectionType) { List<JTypeMirror> components = new ArrayList<>(); for (ASTType t : (ASTIntersectionType) node) { components.add(fromAst(ts, lexicalSubst, t)); } try { return ts.glb(components); } catch (IllegalArgumentException e) { return ts.ERROR; } } else if (node instanceof ASTArrayType) { JTypeMirror t = fromAst(ts, lexicalSubst, ((ASTArrayType) node).getElementType()); ASTArrayDimensions dimensions = ((ASTArrayType) node).getDimensions(); // we have to iterate in reverse for (int i = dimensions.size() - 1; i >= 0; i--) { ASTArrayTypeDim dim = dimensions.get(i); PSet<SymAnnot> annots = getSymbolicAnnotations(dim); t = ts.arrayType(t).withAnnotations(annots); } return t; } else if (node instanceof ASTPrimitiveType) { return ts.getPrimitive(((ASTPrimitiveType) node).getKind()).withAnnotations(getTypeAnnotations(node)); } else if (node instanceof ASTAmbiguousName) { return ts.UNKNOWN; } else if (node instanceof ASTUnionType) { return ts.lub(CollectionUtil.map(((ASTUnionType) node).getComponents(), TypeNode::getTypeMirror)); } else if (node instanceof ASTVoidType) { return ts.NO_TYPE; } throw new IllegalStateException("Illegal type " + node.getClass() + " " + node); } private static PSet<SymAnnot> getSymbolicAnnotations(Annotatable dim) { return SymbolResolutionPass.buildSymbolicAnnotations(dim.getDeclaredAnnotations()); } private static JTypeMirror makeFromClassType(TypeSystem ts, ASTClassOrInterfaceType node, Substitution subst) { if (node == null) { return null; } // TODO error handling, what if we're saying List<String, Int> in source: should be caught before PSet<SymAnnot> typeAnnots = getTypeAnnotations(node); JTypeDeclSymbol reference = getReferenceEnsureResolved(node); if (reference instanceof JTypeParameterSymbol) { return subst.apply(((JTypeParameterSymbol) reference).getTypeMirror()).withAnnotations(typeAnnots); } JClassType enclosing = getEnclosing(ts, node, subst, node.getQualifier(), reference); ASTTypeArguments typeArguments = node.getTypeArguments(); List<JTypeMirror> boundGenerics = Collections.emptyList(); if (typeArguments != null) { if (!typeArguments.isDiamond()) { boundGenerics = new ArrayList<>(typeArguments.getNumChildren()); for (ASTType t : typeArguments) { boundGenerics.add(fromAst(ts, subst, t)); } } // fallthrough, this will be set to the raw type (with the correct enclosing type) // until the constructor call is fully type resolved } if (enclosing != null) { return enclosing.selectInner((JClassSymbol) reference, boundGenerics, typeAnnots); } else { return ts.parameterise((JClassSymbol) reference, boundGenerics).withAnnotations(typeAnnots); } } private static @Nullable JClassType getEnclosing(TypeSystem ts, ASTClassOrInterfaceType node, Substitution subst, @Nullable ASTClassOrInterfaceType lhsType, JTypeDeclSymbol reference) { @Nullable JTypeMirror enclosing = makeFromClassType(ts, lhsType, subst); if (enclosing != null && !shouldEnclose(reference)) { // It's possible to write Map.Entry<A,B> but Entry is a static type, // so we should ignore the "enclosing" Map enclosing = null; } else if (enclosing == null && needsEnclosing(reference)) { // class Foo<T> { // class Inner {} // void bar(Inner k) {} // ^^^^^ // This is shorthand for Foo<T>.Inner (because of regular scoping rules) // } enclosing = node.getImplicitEnclosing(); assert enclosing != null : "Implicit enclosing type should have been set by disambiguation, for " + node; } if (enclosing != null) { // the actual enclosing type may be a supertype of the one that was explicitly written // (Sub <: Sup) => (Sub.Inner = Sup.Inner) // We normalize them to the actual declaring class JClassSymbol enclosingClassAccordingToReference = reference.getEnclosingClass(); if (enclosingClassAccordingToReference == null) { return null; } enclosing = enclosing.getAsSuper(enclosingClassAccordingToReference); assert enclosing != null : "We got this symbol by looking into enclosing"; return (JClassType) enclosing; } return null; } // Whether the reference needs an enclosing type if it is unqualified (non-static inner type) private static boolean needsEnclosing(JTypeDeclSymbol reference) { return reference instanceof JClassSymbol && reference.getEnclosingClass() != null && !Modifier.isStatic(reference.getModifiers()); } private static @NonNull JTypeDeclSymbol getReferenceEnsureResolved(ASTClassOrInterfaceType node) { if (node.getReferencedSym() != null) { return node.getReferencedSym(); } else if (node.getParent() instanceof ASTConstructorCall) { ASTExpression qualifier = ((ASTConstructorCall) node.getParent()).getQualifier(); if (qualifier != null) { assert node.getImplicitEnclosing() == null : "Qualified ctor calls should be handled lazily"; // note: this triggers recursive type resolution of the qualifier JTypeMirror qualifierType = qualifier.getTypeMirror(); JClassSymbol symbol; if (qualifierType instanceof JClassType) { JClassType enclosing = (JClassType) qualifierType; JClassType resolved = JavaResolvers.getMemberClassResolver(enclosing, node.getRoot().getPackageName(), node.getEnclosingType().getSymbol(), node.getSimpleName()) .resolveFirst(node.getSimpleName()); if (resolved == null) { // compile-time error symbol = (JClassSymbol) node.getTypeSystem().UNKNOWN.getSymbol(); } else { symbol = resolved.getSymbol(); JClassType actualEnclosing = enclosing.getAsSuper(symbol.getEnclosingClass()); assert actualEnclosing != null : "We got this symbol by looking into enclosing"; node.setImplicitEnclosing(actualEnclosing); } } else { // qualifier is unresolved, compile-time error symbol = (JClassSymbol) node.getTypeSystem().UNKNOWN.getSymbol(); } node.setSymbol(symbol); return symbol; } // else fallthrough } throw new IllegalStateException("Disambiguation pass should resolve everything except qualified ctor calls"); } // Whether the reference is a non-static inner type of the enclosing type // Note most checks have already been done in the disambiguation pass (including reporting) private static boolean shouldEnclose(JTypeDeclSymbol reference) { return !Modifier.isStatic(reference.getModifiers()); } /** * Returns the variable declaration or field or formal, etc, that * may give additional type annotations to the given type. */ private static @Nullable Annotatable getEnclosingAnnotationGiver(JavaNode node) { JavaNode parent = node.getParent(); if (node.getIndexInParent() == 0 && parent instanceof ASTClassOrInterfaceType) { // this is an enclosing type return getEnclosingAnnotationGiver(parent); } else if (node.getIndexInParent() == 0 && parent instanceof ASTArrayType) { // the element type of an array type return getEnclosingAnnotationGiver(parent); } else if (!(parent instanceof ASTType) && parent instanceof ASTVariableDeclarator) { return getEnclosingAnnotationGiver(parent); } else if (!(parent instanceof ASTType) && parent instanceof Annotatable) { return (Annotatable) parent; } return null; } private static PSet<SymAnnot> getTypeAnnotations(ASTType type) { PSet<SymAnnot> annotsOnType = getSymbolicAnnotations(type); if (type instanceof ASTClassOrInterfaceType && ((ASTClassOrInterfaceType) type).getQualifier() != null) { return annotsOnType; // annots on the declaration only apply to the leftmost qualifier } Annotatable parent = getEnclosingAnnotationGiver(type); if (parent != null) { PSet<SymAnnot> parentAnnots = getSymbolicAnnotations(parent); for (SymAnnot parentAnnot : parentAnnots) { // filter annotations by whether they apply to the type use. if (parentAnnot.getAnnotationSymbol().annotationAppliesTo(ElementType.TYPE_USE)) { annotsOnType = annotsOnType.plus(parentAnnot); } } } return annotsOnType; } }
12,172
42.320285
189
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTLambdaParameterList.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.java.ast.ASTList.ASTMaybeEmptyListOf; /** * The parameter list of a {@linkplain ASTLambdaExpression lambda expression}. * * <pre class="grammar"> * * LambdaParameterList ::= "(" ")" * | "(" {@link ASTLambdaParameter LambdaParameter} ("," {@link ASTLambdaParameter LambdaParameter})*")" * * </pre> */ public final class ASTLambdaParameterList extends ASTMaybeEmptyListOf<ASTLambdaParameter> { ASTLambdaParameterList(int id) { super(id, ASTLambdaParameter.class); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
835
25.967742
126
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/InternalApiBridge.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccTokenDocument; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.internal.JavaAstProcessor; import net.sourceforge.pmd.lang.java.symbols.JClassSymbol; import net.sourceforge.pmd.lang.java.symbols.JConstructorSymbol; import net.sourceforge.pmd.lang.java.symbols.JElementSymbol; import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol; import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol; import net.sourceforge.pmd.lang.java.symbols.JTypeParameterSymbol; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; import net.sourceforge.pmd.lang.java.symbols.table.JSymbolTable; import net.sourceforge.pmd.lang.java.symbols.table.internal.ReferenceCtx; import net.sourceforge.pmd.lang.java.types.JMethodSig; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.JVariableSig; import net.sourceforge.pmd.lang.java.types.JVariableSig.FieldSig; import net.sourceforge.pmd.lang.java.types.OverloadSelectionResult; import net.sourceforge.pmd.lang.java.types.Substitution; import net.sourceforge.pmd.lang.java.types.TypeSystem; import net.sourceforge.pmd.lang.java.types.ast.ExprContext; import net.sourceforge.pmd.lang.java.types.ast.LazyTypeResolver; import net.sourceforge.pmd.lang.java.types.internal.infer.Infer; import net.sourceforge.pmd.lang.java.types.internal.infer.TypeInferenceLogger; import net.sourceforge.pmd.util.AssertionUtil; /** * Acts as a bridge between outer parts of PMD and the restricted access * internal API of this package. * * <p><b>None of this is published API, and compatibility can be broken anytime!</b> * Use this only at your own risk. * * @author Clément Fournier * @since 7.0.0 */ @InternalApi public final class InternalApiBridge { private InternalApiBridge() { } @Deprecated public static ASTVariableDeclaratorId newVarId(String image) { ASTVariableDeclaratorId varid = new ASTVariableDeclaratorId(JavaParserImplTreeConstants.JJTVARIABLEDECLARATORID); varid.setImage(image); return varid; } public static void setSymbol(SymbolDeclaratorNode node, JElementSymbol symbol) { if (node instanceof ASTMethodDeclaration) { ((ASTMethodDeclaration) node).setSymbol((JMethodSymbol) symbol); } else if (node instanceof ASTConstructorDeclaration) { ((ASTConstructorDeclaration) node).setSymbol((JConstructorSymbol) symbol); } else if (node instanceof ASTAnyTypeDeclaration) { ((AbstractAnyTypeDeclaration) node).setSymbol((JClassSymbol) symbol); } else if (node instanceof ASTVariableDeclaratorId) { ((ASTVariableDeclaratorId) node).setSymbol((JVariableSymbol) symbol); } else if (node instanceof ASTTypeParameter) { ((ASTTypeParameter) node).setSymbol((JTypeParameterSymbol) symbol); } else if (node instanceof ASTRecordComponentList) { ((ASTRecordComponentList) node).setSymbol((JConstructorSymbol) symbol); } else { throw new AssertionError("Cannot set symbol " + symbol + " on node " + node); } } public static void disambigWithCtx(NodeStream<? extends JavaNode> nodes, ReferenceCtx ctx) { AstDisambiguationPass.disambigWithCtx(nodes, ctx); } /** * Forcing type resolution allows us to report errors more cleanly * than if it was done completely lazy. All errors are reported, if * the */ public static void forceTypeResolutionPhase(JavaAstProcessor processor, ASTCompilationUnit root) { root.descendants(TypeNode.class) .crossFindBoundaries() .forEach(it -> { try { it.getTypeMirror(); } catch (Exception e) { processor.getLogger().warning(it, "Error during type resolution of node " + it.getXPathNodeName()); } }); } public static void usageResolution(JavaAstProcessor processor, ASTCompilationUnit root) { root.descendants(ASTNamedReferenceExpr.class) .crossFindBoundaries() .forEach(node -> { JVariableSymbol sym = node.getReferencedSym(); if (sym != null) { ASTVariableDeclaratorId reffed = sym.tryGetNode(); if (reffed != null) { // declared in this file reffed.addUsage(node); } } }); } public static void overrideResolution(JavaAstProcessor processor, ASTCompilationUnit root) { root.descendants(ASTAnyTypeDeclaration.class) .crossFindBoundaries() .forEach(OverrideResolutionPass::resolveOverrides); } public static @Nullable JTypeMirror getTypeMirrorInternal(TypeNode node) { return ((AbstractJavaTypeNode) node).getTypeMirrorInternal(); } public static void setTypeMirrorInternal(TypeNode node, JTypeMirror inferred) { ((AbstractJavaTypeNode) node).setTypeMirror(inferred); } public static void setSignature(ASTFieldAccess node, FieldSig sig) { node.setTypedSym(sig); } public static void setSignature(ASTVariableAccess node, JVariableSig sig) { node.setTypedSym(sig); } public static void setFunctionalMethod(FunctionalExpression node, JMethodSig methodType) { if (node instanceof ASTMethodReference) { ((ASTMethodReference) node).setFunctionalMethod(methodType); } else if (node instanceof ASTLambdaExpression) { ((ASTLambdaExpression) node).setFunctionalMethod(methodType); } else { throw AssertionUtil.shouldNotReachHere("" + node); } } public static void setCompileTimeDecl(ASTMethodReference methodReference, JMethodSig methodType) { methodReference.setCompileTimeDecl(methodType); } public static void initTypeResolver(ASTCompilationUnit acu, JavaAstProcessor processor, TypeInferenceLogger typeResolver) { acu.setTypeResolver(new LazyTypeResolver(processor, typeResolver)); } public static void setOverload(InvocationNode expression, OverloadSelectionResult result) { if (expression instanceof AbstractInvocationExpr) { ((AbstractInvocationExpr) expression).setOverload(result); } else if (expression instanceof ASTExplicitConstructorInvocation) { ((ASTExplicitConstructorInvocation) expression).setOverload(result); } else if (expression instanceof ASTEnumConstant) { ((ASTEnumConstant) expression).setOverload(result); } else { throw new IllegalArgumentException("Wrong type: " + expression); } } public static JavaAstProcessor getProcessor(JavaNode n) { return n.getRoot().getLazyTypeResolver().getProcessor(); } public static Infer getInferenceEntryPoint(JavaNode n) { return n.getRoot().getLazyTypeResolver().getInfer(); } public static @NonNull LazyTypeResolver getLazyTypeResolver(JavaNode n) { return n.getRoot().getLazyTypeResolver(); } public static @NonNull ExprContext getTopLevelExprContext(TypeNode n) { return n.getRoot().getLazyTypeResolver().getTopLevelContextIncludingInvocation(n); } public static void setSymbolTable(JavaNode node, JSymbolTable table) { ((AbstractJavaNode) node).setSymbolTable(table); } public static void setQname(ASTAnyTypeDeclaration declaration, String binaryName, @Nullable String canon) { ((AbstractAnyTypeDeclaration) declaration).setBinaryName(binaryName, canon); } public static void assignComments(ASTCompilationUnit root) { CommentAssignmentPass.assignCommentsToDeclarations(root); } public static JavaccTokenDocument.TokenDocumentBehavior javaTokenDoc() { return JavaTokenDocumentBehavior.INSTANCE; } public static void setStandaloneTernary(ASTConditionalExpression node) { node.setStandaloneTernary(); } public static boolean isStandaloneInternal(ASTConditionalExpression node) { return node.isStandalone(); } public static JTypeMirror buildTypeFromAstInternal(TypeSystem ts, Substitution lexicalSubst, ASTType node) { return TypesFromAst.fromAst(ts, lexicalSubst, node); } public static JTypeDeclSymbol getReferencedSym(ASTClassOrInterfaceType type) { return type.getReferencedSym(); } public static void setTypedSym(ASTFieldAccess expr, JVariableSig.FieldSig sym) { expr.setTypedSym(sym); } public static void setTypedSym(ASTVariableAccess expr, JVariableSig sym) { expr.setTypedSym(sym); } }
9,160
40.080717
127
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTVoidType.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Type node to represent the void pseudo-type. This represents the * absence of a type, not a type, but it's easier to process that way. * Can only occur as return type of method declarations, and as the qualifier * of a {@linkplain ASTClassLiteral class literal}. * * <pre class="grammar"> * * VoidType ::= "void" * * </pre> */ public final class ASTVoidType extends AbstractJavaTypeNode implements ASTType { ASTVoidType(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
767
24.6
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTSuperExpression.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; /** * The "super" keyword. Technically not an expression but it's easier to analyse that way. * * <pre class="grammar"> * * SuperExpression ::= "super" * | {@link ASTClassOrInterfaceType TypeName} "." "super" * * </pre> */ public final class ASTSuperExpression extends AbstractJavaExpr implements ASTPrimaryExpression { ASTSuperExpression(int id) { super(id); } @Nullable public ASTClassOrInterfaceType getQualifier() { return getNumChildren() > 0 ? (ASTClassOrInterfaceType) getChild(0) : null; } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
915
24.444444
96
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTMemberValuePair.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Represents a single pair of member name to value in an annotation. * This node also represents the shorthand syntax, see {@link #isShorthand()}. * * <pre class="grammar"> * * MemberValuePair ::= &lt;IDENTIFIER&gt; "=" {@linkplain ASTMemberValue MemberValue} * * ValueShorthand ::= {@linkplain ASTMemberValue MemberValue} * * </pre> */ public final class ASTMemberValuePair extends AbstractJavaNode { /** The name of the 'value' attribute. */ public static final String VALUE_ATTR = "value"; private boolean isShorthand; ASTMemberValuePair(int id) { super(id); } /** * Returns the name of the member set by this pair. * This returns {@code "value"} if this is a shorthand declaration. */ public String getName() { return getImage(); } /** * Returns true if this is a shorthand for the {@code value} attribute. * For example, {@code @A("v")} has exactly the same structure as * {@code @A(value = "v")}, except this attribute returns true for * the first one only. */ public boolean isShorthand() { return isShorthand; } /** * Returns the value of the member set by this pair. */ public ASTMemberValue getValue() { return (ASTMemberValue) getChild(0); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } void setShorthand() { this.isShorthand = true; } }
1,671
24.333333
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTIntersectionType.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.Iterator; import net.sourceforge.pmd.lang.ast.NodeStream; /** * Represents an <a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-4.html#jls-4.9">intersection type</a>. * Can only occur in the following contexts: * <ul> * <li>As the bound of a {@linkplain ASTTypeParameter TypeParameter}</li> * <li>As the target type of a {@linkplain ASTCastExpression CastExpression}, on Java 8 and above</li> * </ul> * * The first type can be a class or interface type, while the additional bounds * are necessarily interface types. * * <pre class="grammar"> * * IntersectionType ::= {@link ASTClassOrInterfaceType ClassOrInterfaceType} ("&amp;" {@link ASTClassOrInterfaceType InterfaceType})+ * * </pre> */ public final class ASTIntersectionType extends AbstractJavaTypeNode implements ASTReferenceType, InternalInterfaces.AtLeastOneChildOfType<ASTType>, Iterable<ASTType> { ASTIntersectionType(int id) { super(id); } /** Returns a stream of component types. */ public NodeStream<ASTClassOrInterfaceType> getComponents() { return children(ASTClassOrInterfaceType.class); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } @Override public Iterator<ASTType> iterator() { return children(ASTType.class).iterator(); } }
1,590
29.018868
133
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/QualifiableExpression.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; /** * Node that may be qualified by an expression, e.g. an instance method call or * inner class constructor invocation. * * <pre class="grammar"> * * QualifiableExpression ::= {@link ASTArrayAccess ArrayAccess} * | {@link ASTConstructorCall ConstructorCall} * | {@link ASTFieldAccess FieldAccess} * | {@link ASTMethodCall MethodCall} * | {@link ASTMethodReference MethodReference} * * </pre> */ public interface QualifiableExpression extends ASTPrimaryExpression { /** * Returns the expression to the left of the "." if it exists. * This may be a {@link ASTTypeExpression type expression}, or * an {@link ASTAmbiguousName ambiguous name}. */ default @Nullable ASTExpression getQualifier() { return AstImplUtil.getChildAs(this, 0, ASTExpression.class); } }
1,100
31.382353
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTType.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil; import net.sourceforge.pmd.lang.rule.xpath.NoAttribute; /** * Represents a type reference. * * <p>Corresponds to the JLS's <a href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-4.html#jls-Type">Type</a> * and <a href="https://docs.oracle.com/javase/specs/jls/se10/html/jls-8.html#jls-UnannType">UnannType</a> * at the same time. In some contexts this can also be an {@linkplain ASTIntersectionType intersection type}, * though the JLS has no production for that. * * <pre class="grammar"> * * Type ::= {@link ASTReferenceType ReferenceType} * | {@link ASTPrimitiveType PrimitiveType} * | {@link ASTVoidType VoidType} * * </pre> * */ public interface ASTType extends TypeNode, Annotatable, LeftRecursiveNode { // these are noAttribute so they don't end up in the tree dump tests /** * For now this returns the name of the type with all the segments, * without annotations, array dimensions, or type parameters. Experimental * because we need to specify it, eg it would be more useful to have * a method return a qualified name with help of the symbol table. * * @deprecated This is not meaningful. Use {@link PrettyPrintingUtil} */ @Deprecated default String getTypeImage() { return PrettyPrintingUtil.prettyPrintType(this); } /** * Returns the number of array dimensions of this type. * This is 0 unless this node {@linkplain #isArrayType()}. */ @Deprecated default int getArrayDepth() { return 0; } /** * Returns true if this is the "void" pseudo-type, ie an {@link ASTVoidType}. */ @NoAttribute default boolean isVoid() { return this instanceof ASTVoidType; } // TODO remove that, there's enough on JTypeMirror @Deprecated default boolean isPrimitiveType() { return this instanceof ASTPrimitiveType; } @Deprecated default boolean isArrayType() { return this instanceof ASTArrayType; } @Deprecated default boolean isClassOrInterfaceType() { return this instanceof ASTClassOrInterfaceType; } }
2,351
27.337349
120
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTAmbiguousName.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.function.BiFunction; import java.util.function.Function; /** * An ambiguous name occurring in any context. Without a disambiguation * pass that taking care of obscuring rules and the current declarations * in scope, this node could be a type, package, or variable name -we * can't know for sure. The node is a placeholder for that unknown entity. * It implements both {@link ASTType} and {@link ASTPrimaryExpression} to * be able to be inserted in their hierarchy (maybe that should be changed * though). * * <p>This node corresponds simultaneously to the <a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-6.html#jls-AmbiguousName">AmbiguousName</a> * and PackageOrTypeName productions of the JLS. * * <pre class="grammar"> * * AmbiguousNameExpr ::= &lt;IDENTIFIER&gt; ( "." &lt;IDENTIFIER&gt;)* * * </pre> * * @implNote <h3>Disambiguation</h3> * * <p>Some ambiguous names are pushed by the expression parser because * we don't want to look too far ahead (in primary prefix). But it can * happen that the next segment (primary suffix) constrains the name to * be e.g. a type name or an expression name. E.g. From the JLS: * * <blockquote> * A name is syntactically classified as an ExpressionName in these contexts: * ... * - As the qualifying expression in a qualified class instance creation * expression (§15.9) * </blockquote> * * We don't know at the moment the name is parsed that it will be * followed by "." "new" and a constructor call. But as soon as the * {@link ASTConstructorCall} is pushed, we know that the LHS must be an * expression. In that case, the name can be reclassified, and e.g. if * it's a simple name be promoted to {@link ASTVariableAccess}. This * type of immediate disambiguation is carried out by the {@link AbstractJavaNode#jjtClose()} * method of those nodes that do force a specific context on their * left-hand side. See also {@link LeftRecursiveNode}. * * <p>Another mechanism is {@link #forceExprContext()} and {@link #forceTypeContext()}, * which are called by the parser to promote an ambiguous name to an * expression or a type when exiting from the {@link JavaParserImpl#PrimaryExpression()} * production or {@link JavaParserImpl#ClassOrInterfaceType()}. * * <p>Those two mechanisms perform the first classification step, the * one that only depends on the syntactic context and not on semantic * information. A second pass on the AST after building the symbol tables * would allow us to remove all the remaining ambiguous names. */ public final class ASTAmbiguousName extends AbstractJavaExpr implements ASTReferenceType, ASTPrimaryExpression { // if true, then this was explitly left in the tree by the disambig // pass, with a warning private boolean wasProcessed = false; ASTAmbiguousName(int id) { super(id); } ASTAmbiguousName(String id) { super(JavaParserImplTreeConstants.JJTAMBIGUOUSNAME); setImage(id); } /** Returns the entire name, including periods if any. */ public String getName() { return super.getImage(); } boolean wasProcessed() { return wasProcessed; } void setProcessed() { this.wasProcessed = true; } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } // Package-private construction methods: /** * Called by the parser if this ambiguous name was a full expression. * Then, since the node was in an expression syntactic context, we * can do some preliminary reclassification: * <ul> * <li>If the name is a single identifier, then this can be * reclassified as an {@link ASTVariableAccess} * <li>If the name is a sequence of identifiers, then the last * segment can be reclassified as an {@link ASTFieldAccess}, * and the rest of the sequence (to the left) is left ambiguous. * </ul> * * @return the node which will replace this node in the tree */ ASTExpression forceExprContext() { // by the time this is called, this node is on top of the stack, // meaning, it has no parent return shrinkOneSegment(ASTVariableAccess::new, ASTFieldAccess::new); } /** * Called by the parser if this ambiguous name was expected to be * a type name. Then we simply promote it to an {@link ASTClassOrInterfaceType} * with the appropriate LHS. * * @return the node which will replace this node in the tree */ ASTClassOrInterfaceType forceTypeContext() { // same, there's no parent here return shrinkOneSegment(ASTClassOrInterfaceType::new, ASTClassOrInterfaceType::new); } /** * Low level method to reclassify this ambiguous name. Basically * the name is split in two: the part before the last dot, and the * part after it. * * @param simpleNameHandler Called with this name as parameter if * this ambiguous name is a simple name. * No resizing of the node is performed. * * @param splitNameConsumer Called with this node as first parameter, * and the last name segment as second * parameter. After the handler is executed, * the text bounds of this node are shrunk * to fit to only the left part. The handler * may e.g. move the node to another parent. * @param <T> Result type * * @return The node that will replace this one. */ private <T extends AbstractJavaNode> T shrinkOneSegment(Function<ASTAmbiguousName, T> simpleNameHandler, BiFunction<ASTAmbiguousName, String, T> splitNameConsumer) { String image = getName(); int lastDotIdx = image.lastIndexOf('.'); if (lastDotIdx < 0) { T res = simpleNameHandler.apply(this); if (res != null) { res.copyTextCoordinates(this); } return res; } String lastSegment = image.substring(lastDotIdx + 1); String remainingAmbiguous = image.substring(0, lastDotIdx); T res = splitNameConsumer.apply(this, lastSegment); // copy coordinates before shrinking if (res != null) { res.copyTextCoordinates(this); } // shift the ident + the dot this.shiftTokens(0, -2); setImage(remainingAmbiguous); return res; } /** * Delete this name from the children of the parent. */ void deleteInParent() { AbstractJavaNode parent = (AbstractJavaNode) getParent(); parent.removeChildAtIndex(this.getIndexInParent()); } /** * A specialized version of {@link #shrinkOneSegment(Function, BiFunction)} * for nodes that carry the unambiguous part as their own image. * Basically the last segment is set as the image of the parent * node, and no node corresponds to it. */ void shrinkOrDeleteInParentSetImage() { // the params of the lambdas here are this object, // but if we use them instead of this, we avoid capturing the // this reference and the lambdas can be optimised to a singleton shrinkOneSegment( simpleName -> { AbstractJavaNode parent = (AbstractJavaNode) simpleName.getParent(); parent.setImage(simpleName.getFirstToken().getImage()); parent.removeChildAtIndex(simpleName.getIndexInParent()); return null; }, (ambig, simpleName) -> { AbstractJavaNode parent = (AbstractJavaNode) ambig.getParent(); parent.setImage(simpleName); return null; } ); } }
8,173
37.375587
156
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTCompactConstructorDeclaration.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.java.symbols.JConstructorSymbol; /** * This defines a compact constructor for a {@linkplain ASTRecordDeclaration RecordDeclaration} (JDK 16 feature). * Compact constructors implicitly declares formal parameters corresponding to the record component list. These can be * fetched from {@link #getSymbol()}. * * <p>Compact record constructors must be declared "public". * * TODO make implicit formal parameter node and implement ASTMethodOrConstructorDeclaration. * * <pre class="grammar"> * * CompactConstructorDeclaration ::= {@link ASTModifierList Modifiers} * &lt;IDENTIFIER&gt; * {@link ASTBlock Block} * * </pre> */ public final class ASTCompactConstructorDeclaration extends AbstractJavaNode implements ASTBodyDeclaration, SymbolDeclaratorNode, AccessNode { ASTCompactConstructorDeclaration(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } public ASTBlock getBody() { return getFirstChildOfType(ASTBlock.class); } public ASTCompactConstructorDeclaration getDeclarationNode() { return this; } @Override public ASTRecordDeclaration getEnclosingType() { return (ASTRecordDeclaration) super.getEnclosingType(); } @Override public JConstructorSymbol getSymbol() { return getEnclosingType().getRecordComponents().getSymbol(); } }
1,701
29.392857
142
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTTopLevelDeclaration.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Marker interface for nodes that can appear on the top-level of a file. * In these contexts, they are children of the {@link ASTCompilationUnit CompilationUnit} * node. Note that both {@link ASTAnyTypeDeclaration AnyTypeDeclaration} * and {@link ASTEmptyDeclaration EmptyDeclaration} can appear also in * a {@linkplain ASTTypeBody type body}. * * <pre class="grammar"> * * BodyDeclaration ::= {@link ASTAnyTypeDeclaration AnyTypeDeclaration} * | {@link ASTImportDeclaration ImportDeclaration} * | {@link ASTPackageDeclaration PackageDeclaration} * | {@link ASTEmptyDeclaration EmptyDeclaration} * * </pre> */ public interface ASTTopLevelDeclaration extends JavaNode { }
878
32.807692
89
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTRecordDeclaration.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.ast.NodeStream; /** * A record declaration is a special data class type (JDK 16 feature). * This is a {@linkplain Node#isFindBoundary() find boundary} for tree traversal methods. * * <pre class="grammar"> * * RecordDeclaration ::= {@link ASTModifierList ModifierList} * "record" * &lt;IDENTIFIER&gt; * {@linkplain ASTTypeParameters TypeParameters}? * {@linkplain ASTRecordComponentList RecordComponents} * {@linkplain ASTImplementsList ImplementsList}? * {@linkplain ASTRecordBody RecordBody} * * </pre> * * @see <a href="https://openjdk.java.net/jeps/395">JEP 395: Records</a> */ public final class ASTRecordDeclaration extends AbstractAnyTypeDeclaration { ASTRecordDeclaration(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } @Override public NodeStream<ASTBodyDeclaration> getDeclarations() { return getFirstChildOfType(ASTRecordBody.class).children(ASTBodyDeclaration.class); } @Override @NonNull public ASTRecordComponentList getRecordComponents() { return getFirstChildOfType(ASTRecordComponentList.class); } }
1,625
30.269231
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTWildcardType.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; /** * Represents a wildcard type. Those can only occur when nested in an * {@link ASTTypeArguments} node. * * <pre class="grammar"> * * WildcardType ::= "?" ( ("extends" | "super") {@link ASTReferenceType ReferenceType} )? * * </pre> */ public final class ASTWildcardType extends AbstractJavaTypeNode implements ASTReferenceType { private boolean isLowerBound; ASTWildcardType(int id) { super(id); } void setLowerBound(boolean lowerBound) { isLowerBound = lowerBound; } /** * Return true if this is an upper type bound, e.g. * {@code <? extends Integer>}, or the unbounded * wildcard {@code <?>}. */ public boolean isUpperBound() { return !isLowerBound; } /** * Returns true if this is a lower type bound, e.g. * in {@code <? super Node>}. */ public boolean isLowerBound() { return isLowerBound; } /** * Returns the type node representing the bound, e.g. * the {@code Node} in {@code <? super Node>}, or null in * the unbounded wildcard {@code <?>}. */ public @Nullable ASTReferenceType getTypeBoundNode() { return firstChild(ASTReferenceType.class); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
1,572
23.578125
93
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/AbstractTypedSymbolDeclarator.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.java.symbols.JElementSymbol; /** * Abstract class for type declarations nodes. */ abstract class AbstractTypedSymbolDeclarator<T extends JElementSymbol> extends AbstractJavaTypeNode implements SymbolDeclaratorNode { private T symbol; AbstractTypedSymbolDeclarator(int i) { super(i); } @NonNull @Override public T getSymbol() { assertSymbolNotNull(symbol, this); return symbol; } static void assertSymbolNotNull(JElementSymbol symbol, SymbolDeclaratorNode node) { assert symbol != null : "Symbol was null, not set by resolver, on " + node; } static void assertSymbolNull(JElementSymbol symbol, SymbolDeclaratorNode node) { assert symbol == null : "Symbol was not null, already set to " + symbol + " by resolver, on " + node; } void setSymbol(T symbol) { assertSymbolNull(this.symbol, this); this.symbol = symbol; } }
1,170
23.914894
110
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTAnnotationTypeDeclaration.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.ast.Node; /** * The declaration of an annotation type. * This is a {@linkplain Node#isFindBoundary() find boundary} for tree traversal methods. * * <p>Note that in contrast to interface types, no {@linkplain ASTExtendsList extends clause} * is permitted, and an annotation type cannot be generic. * * <pre class="grammar"> * * AnnotationTypeDeclaration ::= {@link ASTModifierList ModifierList} * "@" "interface" * &lt;IDENTIFIER&gt; * {@link ASTAnnotationTypeBody AnnotationTypeBody} * * </pre> * */ public final class ASTAnnotationTypeDeclaration extends AbstractAnyTypeDeclaration { ASTAnnotationTypeDeclaration(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } @Override public boolean isInterface() { return true; } }
1,163
24.866667
93
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTAssignmentExpression.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; /** * Represents an assignment expression. * * <pre class="grammar"> * * AssignmentExpression ::= {@link ASTAssignableExpr AssignableExpr} {@link AssignmentOp} {@link ASTExpression Expression} * * </pre> */ public final class ASTAssignmentExpression extends AbstractJavaExpr implements InternalInterfaces.BinaryExpressionLike { private AssignmentOp operator; ASTAssignmentExpression(int id) { super(id); } void setOp(AssignmentOp op) { this.operator = op; } /** Returns the left-hand side, ie the expression being assigned to. */ @Override @NonNull public ASTAssignableExpr getLeftOperand() { return (ASTAssignableExpr) getChild(0); } /** * Returns whether this is a compound assignment (any operator except "="). */ public boolean isCompound() { return operator.isCompound(); } @Override @NonNull public AssignmentOp getOperator() { return operator; } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
1,339
21.711864
122
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTLoopStatement.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; /** * A loop statement. * * <pre class="grammar"> * * Statement ::= {@link ASTDoStatement DoStatement} * | {@link ASTForeachStatement ForeachStatement} * | {@link ASTForStatement ForStatement} * | {@link ASTWhileStatement WhileStatement} * * </pre> * * */ public interface ASTLoopStatement extends ASTStatement { /** Returns the statement that represents the body of this loop. */ default ASTStatement getBody() { return (ASTStatement) getLastChild(); } /** * Returns the node that represents the condition of this loop. * This may be any expression of type boolean. * * <p>If there is no specified guard, then returns null (in particular, * returns null if this is a foreach loop). */ default @Nullable ASTExpression getCondition() { return null; } }
1,069
23.318182
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/SymbolDeclaratorNode.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.java.symbols.JElementSymbol; /** * A node that declares a corresponding {@linkplain JElementSymbol symbol}. */ public interface SymbolDeclaratorNode extends JavaNode { /** Returns the symbol this node declares. */ JElementSymbol getSymbol(); }
421
22.444444
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/UnaryOp.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.Set; import org.checkerframework.checker.nullness.qual.Nullable; /** * A unary operator, either prefix or postfix. This is used by {@link ASTUnaryExpression UnaryExpression} * to abstract over the syntactic form of the operator. * * <pre class="grammar"> * * UnaryOp ::= PrefixOp | PostfixOp * * PrefixOp ::= "+" | "-" | "~" | "!" | "++" | "--" * * PostfixOp ::= "++" | "--" * * </pre> * * @see BinaryOp * @see AssignmentOp */ public enum UnaryOp implements InternalInterfaces.OperatorLike { /** Unary numeric promotion operator {@code "+"}. */ UNARY_PLUS("+"), /** Arithmetic negation operation {@code "-"}. */ UNARY_MINUS("-"), /** Bitwise complement operator {@code "~"}. */ COMPLEMENT("~"), /** Logical complement operator {@code "!"}. */ NEGATION("!"), /** Prefix increment operator {@code "++"}. */ PRE_INCREMENT("++"), /** Prefix decrement operator {@code "--"}. */ PRE_DECREMENT("--"), /** Postfix increment operator {@code "++"}. */ POST_INCREMENT("++"), /** Postfix decrement operator {@code "--"}. */ POST_DECREMENT("--"); private final String code; UnaryOp(String code) { this.code = code; } /** * Returns true if this operator is pure, ie the evaluation of * the unary expression doesn't produce side-effects. Only increment * and decrement operators are impure. * * <p>This can be used to fetch all increment or decrement operations, * regardless of whether they're postfix or prefix. E.g. * <pre>{@code * node.descendants(ASTUnaryExpression.class) * .filterNot(it -> it.getOperator().isPure()) * }</pre> */ public boolean isPure() { return this.ordinal() < PRE_INCREMENT.ordinal(); } /** Returns true if this is one of {@link #PRE_INCREMENT} or {@link #POST_INCREMENT}. */ public boolean isIncrement() { return this == PRE_INCREMENT || this == POST_INCREMENT; } /** Returns true if this is one of {@link #PRE_DECREMENT} or {@link #POST_DECREMENT}. */ public boolean isDecrement() { return this == PRE_DECREMENT || this == POST_DECREMENT; } /** Returns true if this is a prefix operator. */ public boolean isPrefix() { return this.ordinal() < POST_INCREMENT.ordinal(); } /** Returns true if this is a postfix operator. */ public boolean isPostfix() { return !isPrefix(); } @Override public String getToken() { return code; } @Override public String toString() { return this.code; } /** * Tests if the node is an {@link ASTUnaryExpression} with one of the given operators. */ public static boolean isUnaryExprWithOperator(@Nullable JavaNode e, Set<UnaryOp> operators) { if (e instanceof ASTUnaryExpression) { ASTUnaryExpression unary = (ASTUnaryExpression) e; return operators.contains(unary.getOperator()); } return false; } /** * Tests if the node is an {@link ASTUnaryExpression} with the given operator. */ public static boolean isUnaryExprWithOperator(@Nullable JavaNode e, UnaryOp operator) { if (e instanceof ASTUnaryExpression) { ASTUnaryExpression unary = (ASTUnaryExpression) e; return operator == unary.getOperator(); } return false; } }
3,571
27.576
105
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTPrimitiveType.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.java.types.JPrimitiveType; import net.sourceforge.pmd.lang.java.types.JPrimitiveType.PrimitiveTypeKind; /** * Represents a primitive type. * * <pre class="grammar"> * * PrimitiveType ::= {@link ASTAnnotation Annotation}* ("boolean" | "char" | "byte" | "short" | "int" | "long" | "float" | "double") * * </pre> */ public final class ASTPrimitiveType extends AbstractJavaTypeNode implements ASTType { private PrimitiveTypeKind kind; ASTPrimitiveType(int id) { super(id); } void setKind(PrimitiveTypeKind kind) { assert this.kind == null : "Cannot set kind multiple times"; this.kind = kind; } public PrimitiveTypeKind getKind() { assert kind != null : "Primitive kind not set for " + this; return kind; } @Override @Deprecated public String getImage() { return null; } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } @Override public @NonNull JPrimitiveType getTypeMirror() { return (JPrimitiveType) super.getTypeMirror(); } }
1,385
23.75
132
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTModuleOpensDirective.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.ast.NodeStream; /** * An "opens" directive of a {@linkplain ASTModuleDeclaration module declaration}. * * <pre class="grammar"> * * ModuleOpensDirective ::= * "opens" &lt;PACKAGE_NAME&gt; * ( "to" {@linkplain ASTModuleName ModuleName} ( "," {@linkplain ASTModuleName ModuleName})* )? * ";" * * </pre> */ public final class ASTModuleOpensDirective extends AbstractPackageNameModuleDirective { ASTModuleOpensDirective(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns a stream of the module names that are found after the "to" keyword. * May be empty */ public NodeStream<ASTModuleName> getTargetModules() { return children(ASTModuleName.class); } }
1,033
24.219512
100
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTSwitchExpression.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.ast.NodeStream; /** * A switch expression, as introduced in Java 12. This node only occurs * in the contexts where an expression is expected. In particular, * switch constructs occurring in statement position are parsed as a * {@linkplain ASTSwitchStatement SwitchStatement}, and not a * {@link ASTSwitchExpression SwitchExpression} within a * {@link ASTExpressionStatement ExpressionStatement}. That is because * switch statements are not required to be exhaustive, contrary * to switch expressions. * * <p>Their syntax is identical though, and described on {@link ASTSwitchLike}. */ public final class ASTSwitchExpression extends AbstractJavaExpr implements ASTExpression, ASTSwitchLike { ASTSwitchExpression(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns a stream of all expressions which can be the value of this * switch. Eg in the following, the yield expressions are marked by a * comment. * <pre>{@code * * switch (foo) { * case 1 -> 1; // <- <1> * case 2 -> 2; // <- <2> * default -> { * int i = foo * 2; * yield i * foo; // <- <i * foo> * } * } * * }</pre> * */ public NodeStream<ASTExpression> getYieldExpressions() { return NodeStream.forkJoin( getBranches(), br -> br.descendants(ASTYieldStatement.class) .filter(it -> it.getYieldTarget() == this) .map(ASTYieldStatement::getExpr), br -> br.asStream() .filterIs(ASTSwitchArrowBranch.class) .map(ASTSwitchArrowBranch::getRightHandSide) .filterIs(ASTExpression.class) ); } }
2,094
29.808824
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/AssignmentOp.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.ADD; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.AND; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.DIV; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.LEFT_SHIFT; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.MOD; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.MUL; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.OR; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.RIGHT_SHIFT; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.SUB; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.UNSIGNED_RIGHT_SHIFT; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.XOR; import static net.sourceforge.pmd.lang.java.ast.InternalInterfaces.OperatorLike; import org.checkerframework.checker.nullness.qual.Nullable; /** * An assignment operator for {@link ASTAssignmentExpression}. * * <pre class="grammar"> * * AssignmentOp ::= "=" | "*=" | "/=" | "%=" | "+=" | "-=" | "&lt;&lt;=" | "&gt;&gt;=" | "&gt;&gt;&gt;=" | "&amp;=" | "^=" | "|=" * * </pre> * * @see BinaryOp * @see UnaryOp */ public enum AssignmentOp implements OperatorLike { ASSIGN("=", null), AND_ASSIGN("&=", AND), OR_ASSIGN("|=", OR), XOR_ASSIGN("^=", XOR), ADD_ASSIGN("+=", ADD), SUB_ASSIGN("-=", SUB), MUL_ASSIGN("*=", MUL), DIV_ASSIGN("/=", DIV), MOD_ASSIGN("%=", MOD), LEFT_SHIFT_ASSIGN("<<=", LEFT_SHIFT), RIGHT_SHIFT_ASSIGN(">>=", RIGHT_SHIFT), UNSIGNED_RIGHT_SHIFT_ASSIGN(">>>=", UNSIGNED_RIGHT_SHIFT); private final String code; private final BinaryOp binaryOp; AssignmentOp(String code, @Nullable BinaryOp binaryOp) { this.code = code; this.binaryOp = binaryOp; } @Override public String getToken() { return code; } @Override public String toString() { return this.code; } /** * Returns true if this operator combines * a binary operator with the assignment. */ public boolean isCompound() { return this != ASSIGN; } /** * Returns the binary operator this corresponds to * if this is a compound operator, otherwise returns * null. */ @Nullable public BinaryOp getBinaryOp() { return binaryOp; } }
2,483
26.296703
129
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTMethodReference.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.symbols.JConstructorSymbol; import net.sourceforge.pmd.lang.java.types.JMethodSig; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.TypeSystem; /** * Method or constructor reference expression. * * <pre class="grammar"> * * MethodReference ::= {@link ASTExpression Expression} "::" {@link ASTTypeArguments TypeArguments}? &lt;IDENTIFIER&gt; * | {@link ASTTypeExpression TypeExpression} "::" {@link ASTTypeArguments TypeArguments}? "new" * * </pre> */ public final class ASTMethodReference extends AbstractJavaExpr implements ASTPrimaryExpression, QualifiableExpression, LeftRecursiveNode, MethodUsage, FunctionalExpression { private JMethodSig functionalMethod; private JMethodSig compileTimeDecl; ASTMethodReference(int id) { super(id); } @Override public void jjtClose() { super.jjtClose(); JavaNode lhs = getChild(0); // if constructor ref, then the LHS is unambiguously a type. if (lhs instanceof ASTAmbiguousName) { if (isConstructorReference()) { setChild(new ASTTypeExpression(((ASTAmbiguousName) lhs).forceTypeContext()), 0); } } else if (lhs instanceof ASTType) { setChild(new ASTTypeExpression((ASTType) lhs), 0); } } /** * Returns the LHS, whether it is a type or an expression. * Returns null if this is an unqualified method call. */ public TypeNode getLhs() { return AstImplUtil.getChildAs(this, 0, TypeNode.class); } /** * Returns true if this is a constructor reference, * e.g. {@code ArrayList::new}. */ public boolean isConstructorReference() { return JavaTokenKinds.NEW == getLastToken().kind; } /** * Returns the node to the left of the "::". This may be a * {@link ASTTypeExpression type expression}, or an * {@link ASTAmbiguousName ambiguous name}. * * <p>Note that if this is a {@linkplain #isConstructorReference() constructor reference}, * then this can only return a {@linkplain ASTTypeExpression type expression}. */ @Override public @NonNull ASTExpression getQualifier() { return (ASTExpression) getChild(0); } /** * Returns the explicit type arguments mentioned after the "::" if they exist. * Type arguments mentioned before the "::", if any, are contained within * the {@linkplain #getQualifier() lhs type}. */ public @Nullable ASTTypeArguments getExplicitTypeArguments() { return getFirstChildOfType(ASTTypeArguments.class); } /** * Returns the method name, or an {@link JConstructorSymbol#CTOR_NAME} * if this is a {@linkplain #isConstructorReference() constructor reference}. */ @Override public @NonNull String getMethodName() { return super.getImage(); } @Deprecated @Override public @Nullable String getImage() { return null; } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns the type of the functional interface. * E.g. in {@code stringStream.map(String::isEmpty)}, this is * {@code java.util.function.Function<java.lang.String, java.lang.Boolean>}. * * @see #getFunctionalMethod() * @see #getReferencedMethod() */ @Override public @NonNull JTypeMirror getTypeMirror() { return super.getTypeMirror(); } /** * Returns the method that is overridden in the functional interface. * E.g. in {@code stringStream.map(String::isEmpty)}, this is * {@code java.util.function.Function#apply(java.lang.String) -> java.lang.Boolean} * * @see #getReferencedMethod() * @see #getTypeMirror() */ @Override public JMethodSig getFunctionalMethod() { forceTypeResolution(); return assertNonNullAfterTypeRes(functionalMethod); } /** * Returns the method that is referenced. * E.g. in {@code stringStream.map(String::isEmpty)}, this is * {@code java.lang.String.isEmpty() -> boolean}. * * <p>This is called the <i>compile-time declaration</i> of the * method reference in the JLS. * * <p>If no such method can be found, returns {@link TypeSystem#UNRESOLVED_METHOD}. * * @see #getFunctionalMethod() * @see #getTypeMirror() */ public JMethodSig getReferencedMethod() { forceTypeResolution(); return assertNonNullAfterTypeRes(compileTimeDecl); } void setFunctionalMethod(JMethodSig methodType) { this.functionalMethod = methodType; } void setCompileTimeDecl(JMethodSig methodType) { this.compileTimeDecl = methodType; } }
5,219
30.071429
119
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/CommentAssignmentPass.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.GenericToken; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken; import net.sourceforge.pmd.lang.document.FileLocation; import net.sourceforge.pmd.util.DataMap; import net.sourceforge.pmd.util.DataMap.SimpleDataKey; final class CommentAssignmentPass { private static final SimpleDataKey<JavadocComment> FORMAL_COMMENT_KEY = DataMap.simpleDataKey("java.comment"); private CommentAssignmentPass() { // utility class } static @Nullable JavadocComment getComment(JavadocCommentOwner commentOwner) { return commentOwner.getUserMap().get(CommentAssignmentPass.FORMAL_COMMENT_KEY); } private static void setComment(JavadocCommentOwner commentableNode, JavadocComment comment) { commentableNode.getUserMap().set(FORMAL_COMMENT_KEY, comment); comment.setOwner(commentableNode); } public static void assignCommentsToDeclarations(ASTCompilationUnit root) { final List<JavaComment> comments = root.getComments(); if (comments.isEmpty()) { return; } outer: for (JavadocCommentOwner commentableNode : javadocOwners(root)) { JavaccToken firstToken = commentableNode.getFirstToken(); for (JavaccToken maybeComment : GenericToken.previousSpecials(firstToken)) { if (maybeComment.kind == JavaTokenKinds.FORMAL_COMMENT) { JavadocComment comment = new JavadocComment(maybeComment); // deduplicate the comment int idx = Collections.binarySearch(comments, comment, Comparator.comparing(JavaComment::getReportLocation, FileLocation.COORDS_COMPARATOR)); assert idx >= 0 : "Formal comment not found? " + comment; comment = (JavadocComment) comments.get(idx); setComment(commentableNode, comment); continue outer; } } } } private static NodeStream<JavadocCommentOwner> javadocOwners(ASTCompilationUnit root) { return root.descendants().crossFindBoundaries().filterIs(JavadocCommentOwner.class); } }
2,505
36.969697
160
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTModuleProvidesDirective.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.ast.NodeStream; /** * A "provides" directive of a {@linkplain ASTModuleDeclaration module declaration}. * * <pre class="grammar"> * * ModuleProvidesDirective ::= * "provides" {@linkplain ASTClassOrInterfaceType ClassType} * "with" {@linkplain ASTClassOrInterfaceType ClassType} ( "," {@linkplain ASTClassOrInterfaceType ClassType} )* * ";" * * </pre> */ public final class ASTModuleProvidesDirective extends ASTModuleDirective { ASTModuleProvidesDirective(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns the node representing the provided interface. */ public ASTClassOrInterfaceType getService() { return firstChild(ASTClassOrInterfaceType.class); } /** * Returns the nodes representing the service providers, that is, * the service implementations. */ public NodeStream<ASTClassOrInterfaceType> getServiceProviders() { return children(ASTClassOrInterfaceType.class).drop(1); } }
1,298
26.638298
116
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTList.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.ast.InternalInterfaces.AllChildrenAreOfType; import net.sourceforge.pmd.lang.java.ast.InternalInterfaces.AtLeastOneChildOfType; /** * Common supertype for nodes that act as a kind of list of other nodes. * This is mainly provided as a way to share API and not a structural * distinction in the AST. * * <p>This node can be converted to a list with {@link #toList()}. Often these * nodes are optional in their parent, and so might be null. The method * {@link ASTList#orEmpty(ASTList) orEmpty} helps in such cases. For example * <pre>{@code * // This will throw NullPointerException if the class is not generic. * for (ASTTypeParameter tparam : classDecl.getTypeParameters()) { * * } * }</pre> * * Instead of explicitly checking for null, which is annoying, use the * following idiom: * * <pre>{@code * for (ASTTypeParameter tparam : ASTList.orEmpty(classDecl.getTypeParameters())) { * * } * }</pre> * * * <p>Note that though it is usually the case that the node lists all * its children, there is no guarantee about that. For instance, * {@link ASTFormalParameters} excludes the {@linkplain ASTReceiverParameter receiver parameter}. * * @param <N> Type of node contained within this list node */ public abstract class ASTList<N extends JavaNode> extends AbstractJavaNode implements Iterable<N> { protected final Class<N> elementType; ASTList(int id, Class<N> kind) { super(id); this.elementType = kind; } /** * Returns the number of nodes in this list. This must be the number * of nodes yielded by the {@link #iterator()}. */ public int size() { return toStream().count(); } public boolean isEmpty() { return toStream().isEmpty(); } /** * Returns a list containing the element of this node. */ public List<N> toList() { return toStream().toList(); } /** * Returns a node stream containing the same element this node contains. */ public NodeStream<N> toStream() { return children(elementType); } @Override public Iterator<N> iterator() { return toStream().iterator(); } /** * @throws IndexOutOfBoundsException if not in range */ public N get(int i) { N n = toStream().get(i); if (n == null) { throw new IndexOutOfBoundsException("Index " + i + " for length " + size()); } return n; } /** * Returns an empty list if the parameter is null, otherwise returns * its {@link #toList()}. * * @param list List node * @param <N> Type of elements * * @return A non-null list */ public static <N extends JavaNode> @NonNull List<N> orEmpty(@Nullable ASTList<N> list) { return list == null ? Collections.emptyList() : list.toList(); } public static <N extends JavaNode> @NonNull NodeStream<N> orEmptyStream(@Nullable ASTList<N> list) { return list == null ? NodeStream.empty() : list.toStream(); } public static int sizeOrZero(@Nullable ASTList<?> list) { return list == null ? 0 : list.size(); } /** * Returns the element if there is exactly one, otherwise returns null. * * @param list List node * @param <N> Type of elements * * @return An element, or null. */ public static <N extends JavaNode> @Nullable N singleOrNull(@Nullable ASTList<N> list) { return list == null || list.size() != 1 ? null : list.get(0); } /** * Super type for *nonempty* lists that *only* have nodes of type {@code <T>} * as a child. */ abstract static class ASTNonEmptyList<T extends JavaNode> extends ASTMaybeEmptyListOf<T> implements AtLeastOneChildOfType<T> { ASTNonEmptyList(int id, Class<T> kind) { super(id, kind); } } /** * Super type for lists that *only* have nodes of type {@code <T>} * as a child. */ abstract static class ASTMaybeEmptyListOf<T extends JavaNode> extends ASTList<T> implements AllChildrenAreOfType<T> { ASTMaybeEmptyListOf(int id, Class<T> kind) { super(id, kind); } @Override public NodeStream<T> toStream() { return (NodeStream<T>) children(); } } }
4,766
27.716867
104
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTLambdaExpression.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.types.JMethodSig; import net.sourceforge.pmd.lang.java.types.JTypeMirror; /** * A lambda expression. * * * <pre class="grammar"> * * LambdaExpression ::= {@link ASTLambdaParameterList LambdaParameterList} "->" ( {@link ASTExpression Expression} | {@link ASTBlock Block} ) * * </pre> */ public final class ASTLambdaExpression extends AbstractJavaExpr implements FunctionalExpression { private JMethodSig functionalMethod; ASTLambdaExpression(int id) { super(id); } /** * Returns the type of the functional interface. * E.g. in {@code stringStream.map(s -> s.isEmpty())}, this is * {@code java.util.function.Function<java.lang.String, java.lang.Boolean>}. * * @see #getFunctionalMethod() */ @Override public @NonNull JTypeMirror getTypeMirror() { return super.getTypeMirror(); } /** * Returns the method that is overridden in the functional interface. * E.g. in {@code stringStream.map(s -> s.isEmpty())}, this is * {@code java.util.function.Function#apply(java.lang.String) -> * java.lang.Boolean} * * @see #getTypeMirror() */ @Override public JMethodSig getFunctionalMethod() { forceTypeResolution(); return assertNonNullAfterTypeRes(functionalMethod); } void setFunctionalMethod(@Nullable JMethodSig functionalMethod) { this.functionalMethod = functionalMethod; } public ASTLambdaParameterList getParameters() { return (ASTLambdaParameterList) getChild(0); } /** Returns true if this lambda has a block for body. */ public boolean isBlockBody() { return getChild(1) instanceof ASTBlock; } /** Returns true if this lambda has an expression for body. */ public boolean isExpressionBody() { return !isBlockBody(); } /** Returns the body of this expression, if it is a block. */ @Nullable public ASTBlock getBlock() { return AstImplUtil.getChildAs(this, 1, ASTBlock.class); } /** Returns the body of this expression, if it is an expression. */ @Nullable public ASTExpression getExpression() { return AstImplUtil.getChildAs(this, 1, ASTExpression.class); } /** * Returns the body of this lambda if it is a block. */ @Nullable public ASTBlock getBlockBody() { return NodeStream.of(getLastChild()).filterIs(ASTBlock.class).first(); } /** * Returns the body of this lambda if it is an expression. */ @Nullable public ASTExpression getExpressionBody() { return NodeStream.of(getLastChild()).filterIs(ASTExpression.class).first(); } @Override public boolean isFindBoundary() { return true; } /** * Returns the number of formal parameters of this lambda. */ public int getArity() { return getParameters().size(); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
3,407
26.264
141
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTSwitchArrowRHS.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * A node that can appear as the right-hand-side of a {@link ASTSwitchArrowBranch SwitchArrowRule}. * * <pre class="grammar"> * * SwitchArrowRightHandSide ::= {@link ASTExpression Expression} * | {@link ASTBlock Block} * | {@link ASTThrowStatement ThrowStatement} * * </pre> */ public interface ASTSwitchArrowRHS extends JavaNode { }
535
24.52381
99
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/TypeNode.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.annotation.DeprecatedUntil700; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.TypeSystem; import net.sourceforge.pmd.lang.java.types.TypingContext; /** * A node that has a statically known type. This includes e.g. * {@linkplain ASTType type}s, which are explicitly written types, * and {@linkplain ASTExpression expressions}, whose types is determined * from their form, or through type inference. */ public interface TypeNode extends JavaNode { /** * Returns the compile-time type of this node. For example, for a * string literal, returns the type mirror for {@link String}, for * a method call, returns the return type of the call, etc. * * <p>This method ignores conversions applied to the value of the * node because of its context. For example, in {@code 1 + ""}, the * numeric literal will have type {@code int}, but it is converted * to {@code String} by the surrounding concatenation expression. * Similarly, in {@code Collections.singletonList(1)}, the {@link ASTNumericLiteral} * node has type {@code int}, but the type of the method formal is * {@link Integer}, and boxing is applied at runtime. Possibly, an * API will be added to expose this information. * * @return The type mirror. Never returns null; if the type is unresolved, returns * {@link TypeSystem#UNKNOWN}. */ @NonNull default JTypeMirror getTypeMirror() { return getTypeMirror(TypingContext.DEFAULT); } JTypeMirror getTypeMirror(TypingContext typing); /** * Get the Java Class associated with this node. * * @return The Java Class, may return <code>null</code>. * * @deprecated This doesn't work. PMD doesn't load classes, it just * reads the bytecode. Compare the symbol of the {@link #getTypeMirror() type mirror} * instead. */ @Nullable @Deprecated @DeprecatedUntil700 default Class<?> getType() { return null; } }
2,339
34.454545
97
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTAssignableExpr.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; import net.sourceforge.pmd.lang.java.types.JVariableSig; /** * An expression that may be assigned by an {@linkplain ASTAssignmentExpression assignment expression}, * or incremented or decremented. In the JLS, the result of such expressions * is a <i>variable</i>, while other expressions evaluate to a <i>value</i>. * The distinction is equivalent to C-world <i>lvalue</i>, <i>rvalue</i>. * * * <pre class="grammar"> * * AssignableExpr ::= {@link ASTVariableAccess VariableAccess} * | {@link ASTFieldAccess FieldAccess} * | {@link ASTArrayAccess ArrayAccess} * * </pre> * * @author Clément Fournier */ public interface ASTAssignableExpr extends ASTPrimaryExpression { /** * Returns how this expression is accessed in the enclosing expression. * If this expression occurs as the left-hand-side of an {@linkplain ASTAssignmentExpression assignment}, * or as the target of an {@linkplain ASTUnaryExpression increment or decrement expression}, * this method returns {@link AccessType#WRITE}. Otherwise the value is just {@linkplain AccessType#READ read}. */ default @NonNull AccessType getAccessType() { Node parent = this.getParent(); if (parent instanceof ASTUnaryExpression && !((ASTUnaryExpression) parent).getOperator().isPure() || getIndexInParent() == 0 && parent instanceof ASTAssignmentExpression) { return AccessType.WRITE; } return AccessType.READ; } /** * An {@linkplain ASTAssignableExpr assignable expression} that has * a name, and refers to a symbol. * * <pre class="grammar"> * * NamedAssignableExpr ::= {@link ASTVariableAccess VariableAccess} * | {@link ASTFieldAccess FieldAccess} * * </pre> */ interface ASTNamedReferenceExpr extends ASTAssignableExpr { /** * Returns the name of the referenced variable. */ String getName(); // TODO, also figure out if it makes sense to have unresolved symbols for those // using null would be simpler... /** * Returns the signature of the referenced variable. This is * relevant for fields, as they may be inherited from some * parameterized supertype. */ @Nullable JVariableSig getSignature(); // TODO this is probably multiplying the api points for nothing. You have symbol + type with getTypeMirror and getReferencedSym /** * Returns the symbol referenced by this variable. */ default @Nullable JVariableSymbol getReferencedSym() { JVariableSig sig = getSignature(); return sig == null ? null : sig.getSymbol(); } } /** * Represents the type of access of an {@linkplain ASTAssignableExpr assignable expression}. */ enum AccessType { /** The value of the variable is read. */ READ, /** * The value is written to, possibly being read before or after. * Also see {@link JavaAstUtils#isVarAccessReadAndWrite(ASTNamedReferenceExpr)}. */ WRITE } }
3,610
33.066038
174
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTModuleRequiresDirective.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.Objects; import org.checkerframework.checker.nullness.qual.NonNull; /** * A "requires" directive of a {@linkplain ASTModuleDeclaration module declaration}. * * <pre class="grammar"> * * ModuleRequiresDirective ::= * "requires" ( "transitive" | "static" )? {@linkplain ASTModuleName ModuleName} ";" * * </pre> */ public final class ASTModuleRequiresDirective extends ASTModuleDirective { private boolean isStatic; private boolean isTransitive; ASTModuleRequiresDirective(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns the name of the required module. */ public @NonNull ASTModuleName getRequiredModule() { return Objects.requireNonNull(firstChild(ASTModuleName.class)); } public boolean isStatic() { return isStatic; } public boolean isTransitive() { return isTransitive; } void setTransitive() { isTransitive = true; } void setStatic() { isStatic = true; } }
1,295
21.344828
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTThrowsList.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.java.ast.ASTList.ASTNonEmptyList; /** * Throws clause of an {@link ASTConstructorDeclaration} or {@link ASTMethodDeclaration}. * * <pre class="grammar"> * * ThrowsList ::= "throws" {@link ASTClassOrInterfaceType ClassType} ("," {@link ASTClassOrInterfaceType ClassType})* * * </pre> */ public final class ASTThrowsList extends ASTNonEmptyList<ASTClassOrInterfaceType> { ASTThrowsList(int id) { super(id, ASTClassOrInterfaceType.class); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** Returns the method or constructor that owns this throws clause. */ public ASTMethodOrConstructorDeclaration getOwner() { return (ASTMethodOrConstructorDeclaration) getParent(); } }
989
28.117647
117
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/JavadocComment.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken; /** * A {@link JavaComment} that has Javadoc content. */ public final class JavadocComment extends JavaComment { private JavadocCommentOwner owner; JavadocComment(JavaccToken t) { super(t); assert t.kind == JavaTokenKinds.FORMAL_COMMENT; } void setOwner(JavadocCommentOwner owner) { this.owner = owner; } /** * Returns the owner of this comment. Null if this comment is * misplaced. */ public @Nullable JavadocCommentOwner getOwner() { return owner; } }
797
21.166667
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTBooleanLiteral.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; /** * The boolean literal, either "true" or "false". */ public final class ASTBooleanLiteral extends AbstractLiteral implements ASTLiteral { private boolean isTrue; ASTBooleanLiteral(int id) { super(id); } void setTrue() { isTrue = true; } public boolean isTrue() { return this.isTrue; } @Override public @NonNull Boolean getConstValue() { return isTrue; } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
788
18.725
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTForInit.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * The initialization clause of a {@linkplain ASTForStatement for loop}. * Note: ForInit nodes are necessary in the tree to differentiate them * from the update clause. They just confer a contextual role to their * child. * * <pre class="grammar"> * * ForInit ::= {@link ASTLocalVariableDeclaration LocalVariableDeclaration} * | {@link ASTStatementExpressionList StatementExpressionList} * * </pre> */ public final class ASTForInit extends AbstractJavaNode { ASTForInit(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** Returns the statement nested within this node. */ public ASTStatement getStatement() { return (ASTStatement) getFirstChild(); } }
980
24.815789
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTLocalVariableDeclaration.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.document.FileLocation; /** * Represents a local variable declaration. This is a {@linkplain ASTStatement statement}, * but the node is also used in {@linkplain ASTForInit for-loop initialisers} and * {@linkplain ASTForStatement foreach statements}. * * <p>This statement may define several variables, possibly of different types * (see {@link ASTVariableDeclaratorId#getType()}). The nodes corresponding to * the declared variables are accessible through {@link #getVarIds()}. * * <pre class="grammar"> * * LocalVariableDeclaration ::= {@link ASTModifierList LocalVarModifierList} {@linkplain ASTType Type} {@linkplain ASTVariableDeclarator VariableDeclarator} ( "," {@linkplain ASTVariableDeclarator VariableDeclarator} )* * * </pre> */ // TODO extend AbstractStatement public final class ASTLocalVariableDeclaration extends AbstractJavaNode implements Iterable<ASTVariableDeclaratorId>, ASTStatement, FinalizableNode, LeftRecursiveNode, // ModifierList is parsed separately in BlockStatement InternalInterfaces.MultiVariableIdOwner { ASTLocalVariableDeclaration(int id) { super(id); } @Override public @Nullable FileLocation getReportLocation() { // the first varId return getVarIds().firstOrThrow().getFirstToken().getReportLocation(); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } @Override public Visibility getVisibility() { return Visibility.V_LOCAL; } /** * If true, this local variable declaration represents a declaration, * which makes use of local variable type inference, e.g. java10 "var". * You can receive the inferred type via {@link ASTVariableDeclarator#getType()}. * * @see ASTVariableDeclaratorId#isTypeInferred() */ public boolean isTypeInferred() { return getTypeNode() == null; } /** * Gets the type node for this variable declaration statement. * With Java10 and local variable type inference, there might be * no type node at all. * * @return The type node or <code>null</code> * * @see #isTypeInferred() */ @Override public ASTType getTypeNode() { return getFirstChildOfType(ASTType.class); } }
2,623
31.395062
219
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTEnumDeclaration.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.ast.Node; /** * Represents an enum declaration. * This is a {@linkplain Node#isFindBoundary() find boundary} for tree traversal methods. * * <p>An enum declaration is implicitly final <i>unless it contains at * least one enum constant that has a class body</i>. A nested enum type * is implicitly static. * * <pre class="grammar"> * * EnumDeclaration ::= {@link ASTModifierList ModifierList} * "enum" * &lt;IDENTIFIER&gt; * {@linkplain ASTImplementsList ImplementsList}? * {@link ASTEnumBody EnumBody} * * </pre> */ public final class ASTEnumDeclaration extends AbstractAnyTypeDeclaration { ASTEnumDeclaration(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } @Override public ASTEnumBody getBody() { return (ASTEnumBody) getLastChild(); } }
1,174
24.543478
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/InternalInterfaces.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.Iterator; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.NodeStream; /** * Those are some interfaces that are not published, but are used to keep * uniform names on related concepts. Maybe it makes sense to publish some of * them at some point. */ @SuppressWarnings("PMD.MissingStaticMethodInNonInstantiatableClass") final class InternalInterfaces { private InternalInterfaces() { // utility class } interface OperatorLike { /** * Returns the token used to represent the type in source * code, e.g. {@code "+"} or {@code "*"}. */ String getToken(); } /** Just to share the method names. */ interface BinaryExpressionLike extends ASTExpression { /** Returns the left-hand-side operand. */ @NonNull default ASTExpression getLeftOperand() { return (ASTExpression) getChild(0); } /** Returns the right-hand side operand. */ @NonNull default ASTExpression getRightOperand() { return (ASTExpression) getChild(1); } /** Returns the operator. */ @NonNull OperatorLike getOperator(); } /** * Tags a node that has at least one child, then some methods never * return null. */ interface AtLeastOneChild extends JavaNode { /** Returns the first child of this node, never null. */ @Override @NonNull default JavaNode getFirstChild() { assert getNumChildren() > 0; return getChild(0); } /** Returns the last child of this node, never null. */ @Override @NonNull default JavaNode getLastChild() { assert getNumChildren() > 0; return getChild(getNumChildren() - 1); } } interface AllChildrenAreOfType<T extends JavaNode> extends JavaNode { @Override @Nullable default T getFirstChild() { if (getNumChildren() == 0) { return null; } return (T) getChild(0); } @Override @Nullable default T getLastChild() { if (getNumChildren() == 0) { return null; } return (T) getChild(getNumChildren() - 1); } } /** * Tags a node that has at least one child, then some methods never * return null. */ interface AtLeastOneChildOfType<T extends JavaNode> extends AllChildrenAreOfType<T> { /** Returns the first child of this node, never null. */ @Override @NonNull default T getFirstChild() { assert getNumChildren() > 0 : "No children for node implementing AtLeastOneChild " + this; return (T) getChild(0); } /** Returns the last child of this node, never null. */ @Override @NonNull default T getLastChild() { assert getNumChildren() > 0 : "No children for node implementing AtLeastOneChild " + this; return (T) getChild(getNumChildren() - 1); } } interface VariableIdOwner extends JavaNode { /** Returns the id of the declared variable. */ ASTVariableDeclaratorId getVarId(); } interface MultiVariableIdOwner extends JavaNode, Iterable<ASTVariableDeclaratorId>, AccessNode { /** * Returns a stream of the variable ids declared * by this node. */ default NodeStream<ASTVariableDeclaratorId> getVarIds() { return children(ASTVariableDeclarator.class).children(ASTVariableDeclaratorId.class); } @Override default Iterator<ASTVariableDeclaratorId> iterator() { return getVarIds().iterator(); } ASTType getTypeNode(); } }
4,099
25.11465
102
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/AbstractAnyTypeDeclaration.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.document.FileLocation; import net.sourceforge.pmd.lang.java.symbols.JClassSymbol; import net.sourceforge.pmd.lang.java.types.JClassType; import net.sourceforge.pmd.lang.rule.xpath.DeprecatedAttribute; /** * Abstract class for type declarations nodes. * This is a {@linkplain Node#isFindBoundary() find boundary} for tree traversal methods. */ abstract class AbstractAnyTypeDeclaration extends AbstractTypedSymbolDeclarator<JClassSymbol> implements ASTAnyTypeDeclaration, LeftRecursiveNode { private String binaryName; private @Nullable String canonicalName; AbstractAnyTypeDeclaration(int i) { super(i); } @Override public FileLocation getReportLocation() { if (isAnonymous()) { return super.getReportLocation(); } else { // report on the identifier, not the entire class. return getModifiers().getLastToken().getNext().getReportLocation(); } } /** * @deprecated Use {@link #getSimpleName()} */ @Deprecated @DeprecatedAttribute(replaceWith = "@SimpleName") @Override public String getImage() { return getSimpleName(); } @NonNull @Override public String getSimpleName() { assert super.getImage() != null : "Null simple name"; return super.getImage(); } @Override public @NonNull String getBinaryName() { assert binaryName != null : "Null binary name"; return binaryName; } @Override public @Nullable String getCanonicalName() { assert binaryName != null : "Canonical name wasn't set"; return canonicalName; } @Override public Visibility getVisibility() { return isLocal() ? Visibility.V_LOCAL : ASTAnyTypeDeclaration.super.getVisibility(); } void setBinaryName(String binaryName, @Nullable String canon) { assert binaryName != null : "Null binary name"; this.binaryName = binaryName; this.canonicalName = canon; } @Override public @NonNull JClassType getTypeMirror() { return (JClassType) super.getTypeMirror(); } @Override public boolean isFindBoundary() { return isNested(); } }
2,542
26.945055
147
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/OverrideResolutionPass.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.BitSet; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol; import net.sourceforge.pmd.lang.java.symbols.table.internal.SuperTypesEnumerator; import net.sourceforge.pmd.lang.java.types.JClassType; import net.sourceforge.pmd.lang.java.types.JMethodSig; import net.sourceforge.pmd.lang.java.types.TypeOps; /** * Populates method declarations with the method they override. * * @author Clément Fournier * @since 7.0.0 */ final class OverrideResolutionPass { private OverrideResolutionPass() { } static void resolveOverrides(ASTAnyTypeDeclaration node) { // collect methods that may override another method (non private, non static) RelevantMethodSet relevantMethods = new RelevantMethodSet(node.getTypeMirror()); for (ASTMethodDeclaration methodDecl : node.getDeclarations(ASTMethodDeclaration.class)) { relevantMethods.addIfRelevant(methodDecl); } if (relevantMethods.tracked.isEmpty()) { return; } // stream all methods of supertypes SuperTypesEnumerator.ALL_STRICT_SUPERTYPES .stream(node.getTypeMirror()) // Filter down to those that may be overridden by one of the possible violations // This considers name, arity, and accessibility // vvvvvvvvvvvvvvvvvvvvvvvvvvv .flatMap(st -> st.streamDeclaredMethods(relevantMethods::isRelevant)) // For those methods, a simple override-equivalence check is enough, // because we already know they're accessible, and declared in a supertype .forEach(relevantMethods::findMethodOverridingThisSig); } /** * This does a prefilter, so that we only collect methods of supertypes * that may be overridden by a sub method. For a method to be potentially * a super method, it must have same arity */ private static final class RelevantMethodSet { // name to considered arities private final Map<String, BitSet> map = new HashMap<>(); // nodes that may be violations private final Set<ASTMethodDeclaration> tracked = new LinkedHashSet<>(); private final JClassType site; private RelevantMethodSet(JClassType site) { this.site = site; } // add a method if it may be overriding another // this builds the data structure for isRelevant to work void addIfRelevant(ASTMethodDeclaration m) { if (m.getModifiers().hasAny(JModifier.STATIC, JModifier.PRIVATE)) { // cannot override anything return; } else if (m.isAnnotationPresent(Override.class)) { // will be overwritten if we find it m.setOverriddenMethod(m.getTypeSystem().UNRESOLVED_METHOD); } // then add it BitSet aritySet = map.computeIfAbsent(m.getName(), n -> new BitSet(m.getArity() + 1)); aritySet.set(m.getArity()); tracked.add(m); } // we use this to only consider methods that may produce a violation, // among the supertype methods boolean isRelevant(JMethodSymbol superMethod) { if (!TypeOps.isOverridableIn(superMethod, site.getSymbol())) { return false; } BitSet aritySet = map.get(superMethod.getSimpleName()); return aritySet != null && aritySet.get(superMethod.getArity()); } // if the superSig, which comes from a supertype, is overridden // by a relevant method, set the overridden method. void findMethodOverridingThisSig(JMethodSig superSig) { ASTMethodDeclaration subSig = null; for (ASTMethodDeclaration it : tracked) { // note: we don't use override-equivalence, the definition // of an override uses the concept of sub-signature instead, // which is slightly different. We could also use TypeOps.overrides // but at this point we already know much of what that method checks. // https://docs.oracle.com/javase/specs/jls/se15/html/jls-8.html#jls-8.4.8.1 if (TypeOps.isSubSignature(it.getGenericSignature(), superSig)) { subSig = it; // we assume there is a single relevant method that may match, // otherwise it would be a compile-time error break; } } if (subSig != null) { subSig.setOverriddenMethod(superSig); tracked.remove(subSig); // speedup the check for later } } } }
4,990
38.299213
98
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTPrimaryExpression.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Tags those {@link ASTExpression expressions} that are categorised as primary * by the JLS. * * <pre class="grammar"> * * PrimaryExpression ::= {@link ASTAssignableExpr AssignableExpr} * | {@link ASTLiteral Literal} * | {@link ASTClassLiteral ClassLiteral} * | {@link ASTMethodCall MethodCall} * | {@link ASTConstructorCall ConstructorCall} * | {@link ASTArrayAllocation ArrayAllocation} * | {@link ASTMethodReference MethodReference} * | {@link ASTThisExpression ThisExpression} * | {@link ASTSuperExpression SuperExpression} * * | {@link ASTAmbiguousName AmbiguousName} * | {@link ASTTypeExpression TypeExpression} * * </pre> * * */ public interface ASTPrimaryExpression extends ASTExpression { }
1,059
32.125
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTReceiverParameter.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; /** * Receiver parameter. A receiver parameter is syntactically part of a * {@linkplain ASTFormalParameters formal parameter list}, though it does * not declare a variable or affect the arity of the method in any way. * Its only purpose is to annotate the type of the object on which the * method call is issued. It was introduced with Java 8. * * <p>For example: * <pre> * class Foo { * abstract void foo(@Bar Foo this); * } * </pre> * * <p>Receiver parameters are only allowed on two types of declarations: * <ul> * <li>Instance method declarations of a class or interface (not annotation) type * <li>Constructor declaration of a non-static inner class. It then has * the type of the enclosing instance. * </ul> * In both cases it must be the first parameter of the formal parameter * list, and is entirely optional. * * <pre class="grammar"> * * ReceiverParameter ::= {@link ASTClassOrInterfaceType ClassOrInterfaceType} (&lt;IDENTIFIER&gt; ".")? "this" * * </pre> */ public final class ASTReceiverParameter extends AbstractJavaNode { ASTReceiverParameter(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns the type of the receiver parameter (eg {@code Foo} in {@code Foo this}. * In an instance method, that type must be the class or interface in which the method * is declared, and the name of the receiver parameter must be {@code this}. * * <p> In an inner class's constructor, the type of the receiver parameter * must be the class or interface which is the immediately enclosing type * declaration of the inner class, call it C, and the name of the parameter * must be {@code Identifier.this} where {@code Identifier} is the simple name of C. */ @NonNull public ASTClassOrInterfaceType getReceiverType() { return (ASTClassOrInterfaceType) getChild(0); } }
2,217
32.606061
110
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTStatement.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Represents a code statement. * * <pre class="grammar"> * * Statement ::= {@link ASTAssertStatement AssertStatement} * | {@link ASTBlock Block} * | {@link ASTBreakStatement BreakStatement} * | {@link ASTContinueStatement ContinueStatement} * | {@link ASTDoStatement DoStatement} * | {@link ASTEmptyStatement EmptyStatement} * | {@link ASTExplicitConstructorInvocation ExplicitConstructorInvocation} * | {@link ASTExpressionStatement ExpressionStatement} * | {@link ASTForeachStatement ForeachStatement} * | {@link ASTForStatement ForStatement} * | {@link ASTIfStatement IfStatement} * | {@link ASTLabeledStatement LabeledStatement} * | {@link ASTLocalClassStatement LocalClassStatement} * | {@link ASTLocalVariableDeclaration LocalVariableDeclaration} * | {@link ASTReturnStatement ReturnStatement} * | {@link ASTStatementExpressionList StatementExpressionList} * | {@link ASTSwitchStatement SwitchStatement} * | {@link ASTSynchronizedStatement SynchronizedStatement} * | {@link ASTThrowStatement ThrowStatement} * | {@link ASTTryStatement TryStatement} * | {@link ASTWhileStatement WhileStatement} * | {@link ASTYieldStatement YieldStatement} * * </pre> * * */ public interface ASTStatement extends JavaNode { }
1,634
38.878049
87
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTEmptyStatement.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * An empty statement (useless). * * <pre class="grammar"> * * EmptyStatement ::= ";" * * </pre> */ public final class ASTEmptyStatement extends AbstractStatement { ASTEmptyStatement(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
525
17.785714
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTDefaultValue.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Represents the {@code default} clause of an {@linkplain ASTMethodDeclaration annotation method}. * * <pre class="grammar"> * * DefaultValue ::= "default" {@link ASTMemberValue MemberValue} * * </pre> */ public final class ASTDefaultValue extends AbstractJavaNode { ASTDefaultValue(int id) { super(id); } /** * Returns the constant value nested in this node. */ public ASTMemberValue getConstant() { return (ASTMemberValue) getChild(0); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
791
21.628571
99
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTEnumConstant.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.document.FileLocation; import net.sourceforge.pmd.lang.java.types.OverloadSelectionResult; /** * Represents an enum constant declaration within an {@linkplain ASTEnumDeclaration enum type declaration}. * * <pre class="grammar"> * * EnumConstant ::= {@link ASTModifierList AnnotationList} {@link ASTVariableDeclaratorId VariableDeclaratorId} {@linkplain ASTArgumentList ArgumentList}? {@linkplain ASTAnonymousClassDeclaration AnonymousClassDeclaration}? * * </pre> */ public final class ASTEnumConstant extends AbstractJavaTypeNode implements Annotatable, InvocationNode, AccessNode, ASTBodyDeclaration, InternalInterfaces.VariableIdOwner, JavadocCommentOwner { private OverloadSelectionResult result; ASTEnumConstant(int id) { super(id); } @Override public FileLocation getReportLocation() { return getVarId().getFirstToken().getReportLocation(); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } @Override public ASTVariableDeclaratorId getVarId() { return getFirstChildOfType(ASTVariableDeclaratorId.class); } @Override public String getImage() { return getVarId().getImage(); } @Override @Nullable public ASTArgumentList getArguments() { return getFirstChildOfType(ASTArgumentList.class); } /** * Returns the name of the enum constant. */ public String getName() { return getImage(); } /** * Returns true if this enum constant defines a body, * which is compiled like an anonymous class. */ public boolean isAnonymousClass() { return getLastChild() instanceof ASTAnonymousClassDeclaration; } /** * Returns the anonymous class declaration, or null if * there is none. */ public ASTAnonymousClassDeclaration getAnonymousClass() { return AstImplUtil.getChildAs(this, getNumChildren() - 1, ASTAnonymousClassDeclaration.class); } @Override public @Nullable ASTTypeArguments getExplicitTypeArguments() { // no syntax for that return null; } void setOverload(OverloadSelectionResult result) { assert result != null; this.result = result; } @Override public OverloadSelectionResult getOverloadSelectionInfo() { forceTypeResolution(); return assertNonNullAfterTypeRes(result); } }
2,794
26.135922
223
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTModuleUsesDirective.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * A "uses" directive of a {@linkplain ASTModuleDeclaration module declaration}. * * <pre class="grammar"> * * ModuleUsesDirective ::= "uses" &lt;PACKAGE_NAME&gt; ";" * * </pre> */ public final class ASTModuleUsesDirective extends ASTModuleDirective { ASTModuleUsesDirective(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns the node representing the consumed service. */ public ASTClassOrInterfaceType getService() { return firstChild(ASTClassOrInterfaceType.class); } }
808
21.472222
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTForUpdate.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Update clause of a {@linkplain ASTForStatement for statement}. * * <pre class="grammar"> * * ForUpdate ::= {@linkplain ASTStatementExpressionList StatementExpressionList} * * </pre> */ public final class ASTForUpdate extends AbstractJavaNode { ASTForUpdate(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** Returns the expression list nested within this node. */ public ASTStatementExpressionList getExprList() { return (ASTStatementExpressionList) getChild(0); } }
785
22.117647
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTClassLiteral.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; /** * A class literal. Class literals are {@linkplain ASTPrimaryExpression primary expressions}, * but not proper {@linkplain ASTLiteral literals}, since they are represented by several tokens. * * <pre class="grammar"> * * ClassLiteral ::= {@link ASTType Type} "." "class" * * </pre> */ public final class ASTClassLiteral extends AbstractJavaExpr implements ASTPrimaryExpression { ASTClassLiteral(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns the type node (this may be a {@link ASTVoidType}). */ public @NonNull ASTType getTypeNode() { return (ASTType) getChild(0); } }
967
25.888889
97
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTBlock.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken; import net.sourceforge.pmd.lang.java.ast.ASTList.ASTMaybeEmptyListOf; import net.sourceforge.pmd.lang.java.ast.InternalInterfaces.AllChildrenAreOfType; /** * A block of code. This is a {@linkplain ASTStatement statement} that * contains other statements. * * <pre class="grammar"> * * Block ::= "{" {@link ASTStatement Statement}* "}" * * </pre> */ public final class ASTBlock extends ASTMaybeEmptyListOf<ASTStatement> implements ASTSwitchArrowRHS, ASTStatement, AllChildrenAreOfType<ASTStatement> { ASTBlock(int id) { super(id, ASTStatement.class); } @Override public <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } public boolean containsComment() { JavaccToken t = getLastToken().getPreviousComment(); while (t != null) { if (JavaComment.isComment(t)) { return true; } t = t.getPreviousComment(); } return false; } }
1,233
25.255319
88
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTAnnotation.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.Iterator; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.annotation.DeprecatedUntil700; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.types.JClassType; /** * Represents an annotation. * * <pre class="grammar"> * * Annotation ::= "@" {@link ASTClassOrInterfaceType ClassName} {@link ASTAnnotationMemberList AnnotationMemberList}? * * </pre> */ public final class ASTAnnotation extends AbstractJavaTypeNode implements TypeNode, ASTMemberValue, Iterable<ASTMemberValuePair> { ASTAnnotation(int id) { super(id); } /** * Returns the node that represents the name of the annotation. */ public ASTClassOrInterfaceType getTypeNode() { return (ASTClassOrInterfaceType) getChild(0); } @Override public @NonNull JClassType getTypeMirror() { return (JClassType) super.getTypeMirror(); } /** * Returns the name of the annotation as it is used, * eg {@code java.lang.Override} or {@code Override}. * * @deprecated Use {@link #getTypeMirror()} instead */ @Deprecated @DeprecatedUntil700 public String getAnnotationName() { return getTypeNode().getText().toString(); } /** * Returns the simple name of the annotation. */ public String getSimpleName() { return getTypeNode().getSimpleName(); } /** * Returns the list of members, or null if there is none. */ public @Nullable ASTAnnotationMemberList getMemberList() { return children().first(ASTAnnotationMemberList.class); } /** * Returns the stream of explicit members for this annotation. */ public NodeStream<ASTMemberValuePair> getMembers() { return children(ASTAnnotationMemberList.class).children(ASTMemberValuePair.class); } @Override public Iterator<ASTMemberValuePair> iterator() { return children(ASTMemberValuePair.class).iterator(); } /** * Return the expression values for the attribute with the given name. * This may flatten an array initializer. For example, for the attribute * named "value": * <pre>{@code * - @SuppressWarnings -> returns empty node stream * - @SuppressWarning("fallthrough") -> returns ["fallthrough"] * - @SuppressWarning(value={"fallthrough"}) -> returns ["fallthrough"] * - @SuppressWarning({"fallthrough", "rawtypes"}) -> returns ["fallthrough", "rawtypes"] * }</pre> */ public NodeStream<ASTMemberValue> getFlatValue(String attrName) { return NodeStream.of(getAttribute(attrName)) .flatMap(v -> v instanceof ASTMemberValueArrayInitializer ? v.children(ASTMemberValue.class) : NodeStream.of(v)); } /** * Returns the value of the attribute with the given name, returns * null if no such attribute was mentioned. For example, for the attribute * named "value": * <pre>{@code * - @SuppressWarnings -> returns null * - @SuppressWarning("fallthrough") -> returns "fallthrough" * - @SuppressWarning(value={"fallthrough"}) -> returns {"fallthrough"} * - @SuppressWarning({"fallthrough", "rawtypes"}) -> returns {"fallthrough", "rawtypes"} * }</pre> * * @param attrName Name of an attribute */ public @Nullable ASTMemberValue getAttribute(String attrName) { return getMembers().filter(pair -> pair.getName().equals(attrName)) .map(ASTMemberValuePair::getValue) .first(); } @Override public <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
4,047
30.874016
129
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ConstantFolder.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.apache.commons.lang3.tuple.Pair; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; import net.sourceforge.pmd.lang.java.types.JPrimitiveType; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.util.AssertionUtil; /** * Computes constant expression values. */ // strictfp because constant expressions are FP-strict (not sure if this is really important) final strictfp class ConstantFolder extends JavaVisitorBase<Void, Object> { static final ConstantFolder INSTANCE = new ConstantFolder(); private static final Pair<Object, Object> FAILED_BIN_PROMOTION = Pair.of(null, null); private ConstantFolder() { } @Override public Object visitJavaNode(JavaNode node, Void data) { return null; } @Override public @NonNull Number visitLiteral(ASTLiteral num, Void data) { throw new AssertionError("Literal nodes implement getConstValue directly"); } @Override public Object visit(ASTVariableAccess node, Void data) { return fetchConstFieldReference(node); } @Override public Object visit(ASTFieldAccess node, Void data) { return fetchConstFieldReference(node); } private @Nullable Object fetchConstFieldReference(ASTNamedReferenceExpr node) { JVariableSymbol symbol = node.getReferencedSym(); if (symbol instanceof JFieldSymbol) { return ((JFieldSymbol) symbol).getConstValue(); } return null; } @Override public Object visit(ASTConditionalExpression node, Void data) { Object condition = node.getCondition().getConstValue(); if (condition instanceof Boolean) { Object thenValue = node.getThenBranch().getConstValue(); Object elseValue = node.getElseBranch().getConstValue(); if (thenValue == null || elseValue == null) { return null; // not a constexpr } if ((Boolean) condition) { return thenValue; } else { return elseValue; } } return null; } @Override public Object visit(ASTCastExpression node, Void data) { JTypeMirror t = node.getCastType().getTypeMirror(); if (t.isNumeric()) { return numericCoercion(node.getOperand().getConstValue(), t); } else if (TypeTestUtil.isExactlyA(String.class, node.getCastType())) { return stringCoercion(node.getOperand().getConstValue()); } return null; } @Override public Object visit(ASTUnaryExpression node, Void data) { UnaryOp operator = node.getOperator(); if (!operator.isPure()) { return null; } ASTExpression operand = node.getOperand(); Object operandValue = operand.getConstValue(); if (operandValue == null) { return null; } switch (operator) { case UNARY_PLUS: return unaryPromotion(operandValue); case UNARY_MINUS: { Number promoted = unaryPromotion(operandValue); if (promoted == null) { return null; // compile-time error } else if (promoted instanceof Integer) { return -promoted.intValue(); } else if (promoted instanceof Long) { return -promoted.longValue(); } else if (promoted instanceof Float) { return -promoted.floatValue(); } else { assert promoted instanceof Double; return -promoted.doubleValue(); } } case COMPLEMENT: { Number promoted = unaryPromotion(operandValue); if (promoted instanceof Integer) { return ~promoted.intValue(); } else if (promoted instanceof Long) { return ~promoted.longValue(); } else { return null; // compile-time error } } case NEGATION: { return booleanInvert(operandValue); } default: // increment ops throw new AssertionError("unreachable"); } } @Override public strictfp Object visit(ASTInfixExpression node, Void data) { Object left = node.getLeftOperand().getConstValue(); Object right = node.getRightOperand().getConstValue(); if (left == null || right == null) { return null; } switch (node.getOperator()) { case CONDITIONAL_OR: { if (left instanceof Boolean && right instanceof Boolean) { return (Boolean) left || (Boolean) right; } return null; } case CONDITIONAL_AND: { if (left instanceof Boolean && right instanceof Boolean) { return (Boolean) left && (Boolean) right; } return null; } case OR: { Pair<Object, Object> promoted = booleanAwareBinaryPromotion(left, right); left = promoted.getLeft(); right = promoted.getRight(); if (left instanceof Integer) { return intValue(left) | intValue(right); } else if (left instanceof Long) { return longValue(left) | longValue(right); } else if (left instanceof Boolean) { return booleanValue(left) | booleanValue(right); } return null; } case XOR: { Pair<Object, Object> promoted = booleanAwareBinaryPromotion(left, right); left = promoted.getLeft(); right = promoted.getRight(); if (left instanceof Integer) { return intValue(left) ^ intValue(right); } else if (left instanceof Long) { return longValue(left) ^ longValue(right); } else if (left instanceof Boolean) { return booleanValue(left) ^ booleanValue(right); } return null; } case AND: { Pair<Object, Object> promoted = booleanAwareBinaryPromotion(left, right); left = promoted.getLeft(); right = promoted.getRight(); if (left instanceof Integer) { return intValue(left) & intValue(right); } else if (left instanceof Long) { return longValue(left) & longValue(right); } else if (left instanceof Boolean) { return booleanValue(left) & booleanValue(right); } return null; } case EQ: return eqResult(left, right); case NE: return booleanInvert(eqResult(left, right)); case LE: return compLE(left, right); case GT: return booleanInvert(compLE(left, right)); case LT: return compLT(left, right); case GE: return booleanInvert(compLT(left, right)); case INSTANCEOF: // disallowed, actually dead code because the // right operand is the type, which is no constexpr return null; // for shift operators, unary promotion is performed on operators separately case LEFT_SHIFT: { left = unaryPromotion(left); right = unaryPromotion(right); if (!(right instanceof Integer) && !(right instanceof Long)) { return null; // shift distance must be integral } // only use intValue for the left operand if (left instanceof Integer) { return intValue(left) << intValue(right); } else if (left instanceof Long) { return longValue(left) << intValue(right); } return null; } case RIGHT_SHIFT: { left = unaryPromotion(left); right = unaryPromotion(right); if (!(right instanceof Integer) && !(right instanceof Long)) { return null; // shift distance must be integral } // only use intValue for the left operand if (left instanceof Integer) { return intValue(left) >> intValue(right); } else if (left instanceof Long) { return longValue(left) >> intValue(right); } return null; } case UNSIGNED_RIGHT_SHIFT: { left = unaryPromotion(left); right = unaryPromotion(right); if (!(right instanceof Integer) && !(right instanceof Long)) { return null; // shift distance must be integral } // only use intValue for the left operand if (left instanceof Integer) { return intValue(left) >>> intValue(right); } else if (left instanceof Long) { return longValue(left) >>> intValue(right); } return null; } case ADD: { if (isConvertibleToNumber(left) && isConvertibleToNumber(right)) { Pair<Object, Object> promoted = binaryNumericPromotion(left, right); left = promoted.getLeft(); right = promoted.getRight(); if (left instanceof Integer) { return intValue(left) + intValue(right); } else if (left instanceof Long) { return longValue(left) + longValue(right); } else if (left instanceof Float) { return floatValue(left) + floatValue(right); } else { return doubleValue(left) + doubleValue(right); } } else if (left instanceof String) { // string concat return (String) left + right; } else if (right instanceof String) { // string concat return left + (String) right; } return null; } case SUB: { if (isConvertibleToNumber(left) && isConvertibleToNumber(right)) { Pair<Object, Object> promoted = binaryNumericPromotion(left, right); left = promoted.getLeft(); right = promoted.getRight(); if (left instanceof Integer) { return intValue(left) - intValue(right); } else if (left instanceof Long) { return longValue(left) - longValue(right); } else if (left instanceof Float) { return floatValue(left) - floatValue(right); } else { return doubleValue(left) - doubleValue(right); } } return null; } case MUL: { if (isConvertibleToNumber(left) && isConvertibleToNumber(right)) { Pair<Object, Object> promoted = binaryNumericPromotion(left, right); left = promoted.getLeft(); right = promoted.getRight(); if (left instanceof Integer) { return intValue(left) * intValue(right); } else if (left instanceof Long) { return longValue(left) * longValue(right); } else if (left instanceof Float) { return floatValue(left) * floatValue(right); } else { return doubleValue(left) * doubleValue(right); } } return null; } case DIV: { if (isConvertibleToNumber(left) && isConvertibleToNumber(right)) { Pair<Object, Object> promoted = binaryNumericPromotion(left, right); left = promoted.getLeft(); right = promoted.getRight(); if (left instanceof Integer) { return intValue(left) / intValue(right); } else if (left instanceof Long) { return longValue(left) / longValue(right); } else if (left instanceof Float) { return floatValue(left) / floatValue(right); } else { return doubleValue(left) / doubleValue(right); } } return null; } case MOD: { if (isConvertibleToNumber(left) && isConvertibleToNumber(right)) { Pair<Object, Object> promoted = binaryNumericPromotion(left, right); left = promoted.getLeft(); right = promoted.getRight(); if (left instanceof Integer) { return intValue(left) % intValue(right); } else if (left instanceof Long) { return longValue(left) % longValue(right); } else if (left instanceof Float) { return floatValue(left) % floatValue(right); } else { return doubleValue(left) % doubleValue(right); } } return null; } default: throw AssertionUtil.shouldNotReachHere("Unknown operator in " + node); } } private static @Nullable Object compLE(Object left, Object right) { if (isConvertibleToNumber(left) && isConvertibleToNumber(right)) { Pair<Object, Object> promoted = binaryNumericPromotion(left, right); left = promoted.getLeft(); right = promoted.getRight(); if (left instanceof Integer) { return intValue(left) <= intValue(right); } else if (left instanceof Long) { return longValue(left) <= longValue(right); } else if (left instanceof Float) { return floatValue(left) <= floatValue(right); } else if (left instanceof Double) { return doubleValue(left) <= doubleValue(right); } } return null; } private static @Nullable Boolean compLT(Object left, Object right) { if (isConvertibleToNumber(left) && isConvertibleToNumber(right)) { Pair<Object, Object> promoted = binaryNumericPromotion(left, right); left = promoted.getLeft(); right = promoted.getRight(); if (left instanceof Integer) { return intValue(left) < intValue(right); } else if (left instanceof Long) { return longValue(left) < longValue(right); } else if (left instanceof Float) { return floatValue(left) < floatValue(right); } else if (left instanceof Double) { return doubleValue(left) < doubleValue(right); } } return null; } private static @Nullable Boolean booleanInvert(@Nullable Object b) { if (b instanceof Boolean) { return !(Boolean) b; } return null; } private static @Nullable Boolean eqResult(Object left, Object right) { if (isConvertibleToNumber(left) && isConvertibleToNumber(right)) { Pair<Object, Object> promoted = binaryNumericPromotion(left, right); return promoted.getLeft().equals(promoted.getRight()); // fixme Double.NaN } else { return null; // not a constant expr on reference types } } private static boolean isConvertibleToNumber(Object o) { return o instanceof Number || o instanceof Character; } private static @Nullable Number unaryPromotion(Object t) { if (t instanceof Character) { return (int) (Character) t; } else if (t instanceof Number) { if (t instanceof Byte || t instanceof Short) { return intValue(t); } else { return (Number) t; } } return null; } /** * This returns a pair in which both numbers have the dynamic type. * Both right and left need to be {@link #isConvertibleToNumber(Object)}, * otherwise fails with ClassCastException. */ private static Pair<Object, Object> binaryNumericPromotion(Object left, Object right) { left = projectCharOntoInt(left); right = projectCharOntoInt(right); if (left instanceof Double || right instanceof Double) { return Pair.of(doubleValue(left), doubleValue(right)); } else if (left instanceof Float || right instanceof Float) { return Pair.of(floatValue(left), floatValue(right)); } else if (left instanceof Long || right instanceof Long) { return Pair.of(longValue(left), longValue(right)); } else { return Pair.of(intValue(left), intValue(right)); } } private static Pair<Object, Object> booleanAwareBinaryPromotion(Object left, Object right) { if (left instanceof Boolean || right instanceof Boolean) { if (left instanceof Boolean && right instanceof Boolean) { return Pair.of(left, right); } return FAILED_BIN_PROMOTION; } else if (!isConvertibleToNumber(left) || !isConvertibleToNumber(right)) { return FAILED_BIN_PROMOTION; } else { return binaryNumericPromotion(left, right); } } private static Object projectCharOntoInt(Object v) { if (v instanceof Character) { return (int) (Character) v; } return v; } private static Object numericCoercion(Object v, JTypeMirror target) { v = projectCharOntoInt(v); // map chars to a Number (widen it to int, which may be narrowed in the switch) if (target.isNumeric() && v instanceof Number) { switch (((JPrimitiveType) target).getKind()) { case BOOLEAN: throw new AssertionError("unreachable"); case CHAR: return (char) intValue(v); case BYTE: return (byte) intValue(v); case SHORT: return (short) intValue(v); case INT: return intValue(v); case LONG: return longValue(v); case FLOAT: return floatValue(v); case DOUBLE: return doubleValue(v); default: throw AssertionUtil.shouldNotReachHere("exhaustive enum"); } } return null; } private static Object stringCoercion(Object v) { if (v instanceof String) { return v; } return null; } private static boolean booleanValue(Object x) { return (Boolean) x; } private static int intValue(Object x) { return ((Number) x).intValue(); } private static long longValue(Object x) { return ((Number) x).longValue(); } private static float floatValue(Object x) { return ((Number) x).floatValue(); } private static double doubleValue(Object x) { return ((Number) x).doubleValue(); } }
19,590
35.346939
114
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTAnnotationTypeBody.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; public final class ASTAnnotationTypeBody extends ASTTypeBody { ASTAnnotationTypeBody(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
415
22.111111
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTMethodDeclaration.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken; import net.sourceforge.pmd.lang.document.FileLocation; import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol; import net.sourceforge.pmd.lang.java.types.JMethodSig; import net.sourceforge.pmd.lang.java.types.TypeSystem; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.lang.rule.xpath.DeprecatedAttribute; /** * A method declaration, in a class or interface declaration. Since 7.0, * this also represents annotation methods. Annotation methods have a * much more restricted grammar though, in particular: * <ul> * <li>They can't declare a {@linkplain #getThrowsList() throws clause} * <li>They can't declare {@linkplain #getTypeParameters() type parameters} * <li>Their {@linkplain #getFormalParameters() formal parameters} must be empty * <li>They can't be declared void * <li>They must be abstract * </ul> * They can however declare a {@link #getDefaultClause() default value}. * * <pre class="grammar"> * * MethodDeclaration ::= {@link ASTModifierList ModifierList} * {@link ASTTypeParameters TypeParameters}? * {@link ASTType Type} * &lt;IDENTIFIER&gt; * {@link ASTFormalParameters FormalParameters} * {@link ASTArrayDimensions ArrayDimensions}? * {@link ASTThrowsList ThrowsList}? * ({@link ASTBlock Block} | ";" ) * * </pre> */ public final class ASTMethodDeclaration extends AbstractMethodOrConstructorDeclaration<JMethodSymbol> { /** * Populated by {@link OverrideResolutionPass}. */ private JMethodSig overriddenMethod = null; ASTMethodDeclaration(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns true if this method is overridden. */ public boolean isOverridden() { return overriddenMethod != null; } /** * Returns the signature of the method this method overrides in a * supertype. Note that this method may be implementing several methods * of super-interfaces at once, in that case, an arbitrary one is returned. * * <p>If the method has an {@link Override} annotation, but we couldn't * resolve any method that is actually implemented, this will return * {@link TypeSystem#UNRESOLVED_METHOD}. */ public JMethodSig getOverriddenMethod() { return overriddenMethod; } void setOverriddenMethod(JMethodSig overriddenMethod) { this.overriddenMethod = overriddenMethod; } @Override public FileLocation getReportLocation() { // the method identifier JavaccToken ident = TokenUtils.nthPrevious(getModifiers().getLastToken(), getFormalParameters().getFirstToken(), 1); return ident.getReportLocation(); } /** * Returns the simple name of the method. * * @deprecated Use {@link #getName()} */ @Deprecated @DeprecatedAttribute(replaceWith = "@Name") public String getMethodName() { return getName(); } /** Returns the simple name of the method. */ @Override public String getName() { return getImage(); } /** * If this method declaration is an explicit record component accessor, * returns the corresponding record component. Otherwise returns null. */ public @Nullable ASTRecordComponent getAccessedRecordComponent() { if (getArity() != 0) { return null; } ASTRecordComponentList components = getEnclosingType().getRecordComponents(); if (components == null) { return null; } return components.toStream().first(it -> it.getVarId().getName().equals(this.getName())); } /** * Returns true if the result type of this method is {@code void}. */ public boolean isVoid() { return getResultTypeNode().isVoid(); } /** * Returns the default clause, if this is an annotation method declaration * that features one. Otherwise returns null. */ @Nullable public ASTDefaultValue getDefaultClause() { return AstImplUtil.getChildAs(this, getNumChildren() - 1, ASTDefaultValue.class); } /** * Returns the result type node of the method. This may be a {@link ASTVoidType}. */ public @NonNull ASTType getResultTypeNode() { // TODO rename to getResultType() return firstChild(ASTType.class); } /** * Returns the extra array dimensions that may be after the * formal parameters. */ @Nullable public ASTArrayDimensions getExtraDimensions() { return children(ASTArrayDimensions.class).first(); } /** * Returns whether this is a main method declaration. */ public boolean isMainMethod() { return this.hasModifiers(JModifier.PUBLIC, JModifier.STATIC) && "main".equals(this.getName()) && this.isVoid() && this.getArity() == 1 && TypeTestUtil.isExactlyA(String[].class, this.getFormalParameters().get(0)); } }
5,546
31.25
124
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTArrayInitializer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.Iterator; /** * An array initializer. May occur in two syntactic contexts: * <ul> * <li>The right-hand side of a {@linkplain ASTVariableDeclarator variable declarator} * <li>Inside an {@linkplain ASTArrayAllocation array allocation expression} * </ul> * * <pre class="grammar"> * * ArrayInitializer ::= "{" ( "," )? "}" * | "{" {@link ASTExpression Expression} ( "," {@link ASTExpression Expression} )* ( "," )? "}" * * </pre> * */ public final class ASTArrayInitializer extends AbstractJavaExpr implements ASTExpression, Iterable<ASTExpression> { ASTArrayInitializer(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Return the number of elements. */ public int length() { return getNumChildren(); } @Override public Iterator<ASTExpression> iterator() { return children(ASTExpression.class).iterator(); } }
1,198
22.98
115
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTCatchParameter.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.Collection; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.types.JIntersectionType; import net.sourceforge.pmd.lang.java.types.TypeSystem; /** * Formal parameter of a {@linkplain ASTCatchClause catch clause} * to represent the declared exception variable. * * <pre class="grammar"> * * CatchParameter ::= {@link ASTModifierList LocalVarModifierList} {@link ASTType Type} {@link ASTVariableDeclaratorId VariableDeclaratorId} * * </pre> */ public final class ASTCatchParameter extends AbstractJavaNode implements InternalInterfaces.VariableIdOwner, FinalizableNode { ASTCatchParameter(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns true if this is a multi-catch parameter, * that is, it catches several unrelated exception types * at the same time. For example: * * <pre>catch (IllegalStateException | IllegalArgumentException e) {}</pre> */ public boolean isMulticatch() { return getTypeNode() instanceof ASTUnionType; } @Override @NonNull public ASTVariableDeclaratorId getVarId() { return (ASTVariableDeclaratorId) getLastChild(); } /** Returns the name of this parameter. */ public String getName() { return getVarId().getName(); } /** * Returns the type node of this catch parameter. May be a * {@link ASTUnionType UnionType}. */ public ASTType getTypeNode() { return (ASTType) getChild(1); } /** * Returns a stream of all declared exception types (expanding a union * type if present). * * <p>Note that this is the only reliable way to inspect multi-catch clauses, * as the type mirror of a {@link ASTUnionType} is not itself a {@link JIntersectionType}, * but the {@link TypeSystem#lub(Collection) LUB} of the components. * Since exception types cannot be interfaces, the LUB always erases * to a single class supertype (eg {@link RuntimeException}). */ public NodeStream<ASTClassOrInterfaceType> getAllExceptionTypes() { ASTType typeNode = getTypeNode(); if (typeNode instanceof ASTUnionType) { return typeNode.children(ASTClassOrInterfaceType.class); } else { return NodeStream.of((ASTClassOrInterfaceType) typeNode); } } }
2,723
28.608696
140
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/JavaComment.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.stream.Stream; import net.sourceforge.pmd.lang.ast.GenericToken; import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken; import net.sourceforge.pmd.lang.ast.impl.javacc.JjtreeNode; import net.sourceforge.pmd.lang.document.Chars; import net.sourceforge.pmd.lang.document.FileLocation; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.reporting.Reportable; import net.sourceforge.pmd.util.IteratorUtil; /** * Wraps a comment token to provide some utilities. * This is not a node, it's not part of the tree anywhere, * just convenient. * * <p>This class represents any kind of comment. A specialized subclass * provides more API for Javadoc comments, see {@link JavadocComment}. */ public class JavaComment implements Reportable { //TODO maybe move part of this into pmd core private final JavaccToken token; JavaComment(JavaccToken t) { this.token = t; } @Override public FileLocation getReportLocation() { return getToken().getReportLocation(); } /** * @deprecated Use {@link #getText()} */ @Deprecated public String getImage() { return getToken().getImage(); } /** The token underlying this comment. */ public final JavaccToken getToken() { return token; } public boolean isSingleLine() { return token.kind == JavaTokenKinds.SINGLE_LINE_COMMENT; } public boolean hasJavadocContent() { return token.kind == JavaTokenKinds.FORMAL_COMMENT; } /** Returns the full text of the comment. */ public Chars getText() { return getToken().getImageCs(); } /** * Returns true if the given token has the kind * of a comment token (there are three such kinds). */ public static boolean isComment(JavaccToken token) { return JavaAstUtils.isComment(token); } /** * Removes the leading comment marker (like {@code *}) of each line * of the comment as well as the start marker ({@code //}, {@code /*} or {@code /**} * and the end markers (<code>&#x2a;/</code>). * * <p>Empty lines are removed. * * @return List of lines of the comments */ public Iterable<Chars> getFilteredLines() { return getFilteredLines(false); } public Iterable<Chars> getFilteredLines(boolean preserveEmptyLines) { if (preserveEmptyLines) { return () -> IteratorUtil.map(getText().lines().iterator(), JavaComment::removeCommentMarkup); } else { return () -> IteratorUtil.mapNotNull( getText().lines().iterator(), line -> { line = removeCommentMarkup(line); return line.isEmpty() ? null : line; } ); } } /** * True if this is a comment delimiter or an asterisk. This * tests the whole parameter and not a prefix/suffix. */ @SuppressWarnings("PMD.LiteralsFirstInComparisons") // a fp public static boolean isMarkupWord(Chars word) { return word.length() <= 3 && (word.contentEquals("*") || word.contentEquals("//") || word.contentEquals("/*") || word.contentEquals("*/") || word.contentEquals("/**")); } /** * Trim the start of the provided line to remove a comment * markup opener ({@code //, /*, /**, *}) or closer {@code * /}. */ public static Chars removeCommentMarkup(Chars line) { line = line.trim().removeSuffix("*/"); int subseqFrom = 0; if (line.startsWith('/', 0)) { if (line.startsWith("**", 1)) { subseqFrom = 3; } else if (line.startsWith('/', 1) || line.startsWith('*', 1)) { subseqFrom = 2; } } else if (line.startsWith('*', 0)) { subseqFrom = 1; } return line.subSequence(subseqFrom, line.length()).trim(); } private static Stream<JavaccToken> getSpecialCommentsIn(JjtreeNode<?> node) { return GenericToken.streamRange(node.getFirstToken(), node.getLastToken()) .flatMap(it -> IteratorUtil.toStream(GenericToken.previousSpecials(it).iterator())); } public static Stream<JavaComment> getLeadingComments(JavaNode node) { if (node instanceof AccessNode) { node = ((AccessNode) node).getModifiers(); } return getSpecialCommentsIn(node).filter(JavaComment::isComment) .map(JavaComment::toComment); } private static JavaComment toComment(JavaccToken tok) { switch (tok.kind) { case JavaTokenKinds.FORMAL_COMMENT: return new JavadocComment(tok); case JavaTokenKinds.MULTI_LINE_COMMENT: case JavaTokenKinds.SINGLE_LINE_COMMENT: return new JavaComment(tok); default: throw new IllegalArgumentException("Token is not a comment: " + tok); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof JavaComment)) { return false; } JavaComment that = (JavaComment) o; return token.equals(that.token); } @Override public int hashCode() { return token.hashCode(); } }
5,578
30.519774
111
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTClassOrInterfaceType.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken; import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol; import net.sourceforge.pmd.lang.java.types.JClassType; import net.sourceforge.pmd.util.AssertionUtil; // @formatter:off /** * Represents a class or interface type, possibly parameterised with type arguments. * * <p>This node corresponds to the JLS' <a href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-4.html#jls-ClassOrInterfaceType">ClassOrInterfaceType</a>, * and also to the related productions TypeIdentifier and TypeName. Merging those allow * to treat them uniformly. * * <pre class="grammar"> * * ClassOrInterfaceType ::= {@link ASTAnnotation Annotation}* &lt;IDENTIFIER&gt; {@link ASTTypeArguments TypeArguments}? * | ClassOrInterfaceType "." {@link ASTAnnotation Annotation}* &lt;IDENTIFIER&gt; {@link ASTTypeArguments TypeArguments}? * * </pre> * * @implNote * The parser may produce an AmbiguousName for the qualifier. * This is systematically removed by the disambiguation phase. */ // @formatter:on public final class ASTClassOrInterfaceType extends AbstractJavaTypeNode implements ASTReferenceType { // todo rename to ASTClassType private JTypeDeclSymbol symbol; private String simpleName; // Note that this is only populated during disambiguation, if // the ambiguous qualifier is resolved to a package name private boolean isFqcn; private JClassType implicitEnclosing; ASTClassOrInterfaceType(ASTAmbiguousName lhs, String simpleName) { super(JavaParserImplTreeConstants.JJTCLASSORINTERFACETYPE); assert lhs != null : "Null LHS"; this.addChild(lhs, 0); this.simpleName = simpleName; assertSimpleNameOk(); } ASTClassOrInterfaceType(ASTAmbiguousName simpleName) { super(JavaParserImplTreeConstants.JJTCLASSORINTERFACETYPE); this.simpleName = simpleName.getFirstToken().getImage(); assertSimpleNameOk(); } // Just for one usage in Symbol table @Deprecated public ASTClassOrInterfaceType(String simpleName) { super(JavaParserImplTreeConstants.JJTCLASSORINTERFACETYPE); this.simpleName = simpleName; } ASTClassOrInterfaceType(@Nullable ASTClassOrInterfaceType lhs, boolean isFqcn, JavaccToken firstToken, JavaccToken identifier) { super(JavaParserImplTreeConstants.JJTCLASSORINTERFACETYPE); this.setImage(identifier.getImage()); this.isFqcn = isFqcn; if (lhs != null) { this.addChild(lhs, 0); } this.setFirstToken(firstToken); this.setLastToken(identifier); } ASTClassOrInterfaceType(int id) { super(id); } @Override protected void setImage(String image) { this.simpleName = image; assertSimpleNameOk(); } @Deprecated @Override public String getImage() { return null; } private void assertSimpleNameOk() { assert this.simpleName != null && this.simpleName.indexOf('.') < 0 && AssertionUtil.isJavaIdentifier(this.simpleName) : "Invalid simple name '" + this.simpleName + "'"; } /** * Returns true if the type was written with a full package qualification. * For example, {@code java.lang.Override}. For nested types, only the * leftmost type is considered fully qualified. Eg in {@code p.Outer.Inner}, * this method will return true for the type corresponding to {@code p.Outer}, * but false for the enclosing {@code p.Outer.Inner}. */ public boolean isFullyQualified() { return isFqcn; } void setSymbol(JTypeDeclSymbol symbol) { this.symbol = symbol; } // this is just a transitory variable void setImplicitEnclosing(JClassType enclosing) { implicitEnclosing = enclosing; } JClassType getImplicitEnclosing() { return implicitEnclosing; } /** * Returns the type symbol this type refers to. This is never null * after disambiguation has been run. This is also very internal. */ JTypeDeclSymbol getReferencedSym() { return symbol; } /** * Gets the owner type of this type if it's not ambiguous. This is a * type we know for sure that this type is a member of. * * @return A type, or null if this is a base type */ @Nullable public ASTClassOrInterfaceType getQualifier() { return getFirstChildOfType(ASTClassOrInterfaceType.class); } /** * Returns the type arguments of this segment if some are specified. */ @Nullable public ASTTypeArguments getTypeArguments() { return getFirstChildOfType(ASTTypeArguments.class); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns the simple name of this type. Use the {@linkplain #getReferencedSym() symbol} * to get more information. */ public String getSimpleName() { return simpleName; } /** * Checks whether the type this node is referring to is declared within the * same compilation unit - either a class/interface or a enum type. You want * to check this, if {@link #getType()} is null. * * @return {@code true} if this node referencing a type in the same * compilation unit, {@code false} otherwise. * * @deprecated This may be removed once type resolution is afoot */ @Deprecated public boolean isReferenceToClassSameCompilationUnit() { ASTCompilationUnit root = getFirstParentOfType(ASTCompilationUnit.class); for (ASTClassOrInterfaceDeclaration c : root.findDescendantsOfType(ASTClassOrInterfaceDeclaration.class, true)) { if (c.hasImageEqualTo(getImage())) { return true; } } for (ASTEnumDeclaration e : root.findDescendantsOfType(ASTEnumDeclaration.class, true)) { if (e.hasImageEqualTo(getImage())) { return true; } } return false; } void setFullyQualified() { this.isFqcn = true; } }
6,455
31.119403
162
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTClassOrInterfaceDeclaration.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.List; import net.sourceforge.pmd.lang.ast.Node; /** * Represents class and interface declarations. * This is a {@linkplain Node#isFindBoundary() find boundary} for tree traversal methods. * * <pre class="grammar"> * * ClassOrInterfaceDeclaration ::= {@link ASTModifierList ModifierList} * ( "class" | "interface" ) * &lt;IDENTIFIER&gt; * {@link ASTTypeParameters TypeParameters}? * {@link ASTExtendsList ExtendsList}? * {@link ASTImplementsList ImplementsList}? * {@link ASTClassOrInterfaceBody ClassOrInterfaceBody} * * </pre> */ public final class ASTClassOrInterfaceDeclaration extends AbstractAnyTypeDeclaration { private boolean isInterface; ASTClassOrInterfaceDeclaration(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } @Override public boolean isPackagePrivate() { return super.isPackagePrivate() && !isLocal(); } @Override public boolean isInterface() { return this.isInterface; } @Override public boolean isRegularClass() { return !isInterface; } @Override public boolean isRegularInterface() { return isInterface; } void setInterface() { this.isInterface = true; } /** * Returns the superclass type node if this node is a class * declaration and explicitly declares an {@code extends} * clause. Superinterfaces of an interface are not considered. * * <p>Returns {@code null} otherwise. */ public ASTClassOrInterfaceType getSuperClassTypeNode() { if (isInterface()) { return null; } ASTExtendsList extendsList = getFirstChildOfType(ASTExtendsList.class); return extendsList == null ? null : extendsList.iterator().next(); } public List<ASTClassOrInterfaceType> getPermittedSubclasses() { return ASTList.orEmpty(children(ASTPermitsList.class).first()); } }
2,385
26.425287
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTPatternExpression.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.java.ast.InternalInterfaces.AtLeastOneChild; /** * Wraps a {@link ASTPattern} node but presents the interface of {@link ASTExpression}. * This is only used in the following contexts: * <ul> * <li>As the right-hand side of {@link BinaryOp#INSTANCEOF instanceof expressions}. * </ul> * * <pre class="grammar"> * * PatternExpression ::= {@link ASTPattern Pattern} * * </pre> */ public final class ASTPatternExpression extends AbstractJavaTypeNode implements ASTPrimaryExpression, AtLeastOneChild, LeftRecursiveNode { ASTPatternExpression(int id) { super(id); } ASTPatternExpression(ASTPattern wrapped) { this(JavaParserImplTreeConstants.JJTPATTERNEXPRESSION); this.addChild((AbstractJavaNode) wrapped, 0); copyTextCoordinates((AbstractJavaNode) wrapped); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** Gets the wrapped pattern. */ public ASTPattern getPattern() { return (ASTPattern) getChild(0); } /** Returns 0, patterns can never be parenthesized. */ @Override public int getParenthesisDepth() { return 0; } /** Returns false, patterns can never be parenthesized. */ @Override public boolean isParenthesized() { return false; } }
1,544
25.637931
138
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/JavadocCommentOwner.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; /** * A node that may own a javadoc comment. */ public interface JavadocCommentOwner extends JavaNode { // TODO can record components be documented individually? /** * Returns the javadoc comment that applies to this declaration. If * there is none, returns null. */ default @Nullable JavadocComment getJavadocComment() { return CommentAssignmentPass.getComment(this); } }
609
24.416667
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTLambdaParameter.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Formal parameter of a lambda expression. Child of {@link ASTLambdaParameterList}. * * <pre class="grammar"> * * LambdaParameter ::= {@link ASTModifierList LocalVarModifierList} ( "var" | {@link ASTType Type} ) {@link ASTVariableDeclaratorId VariableDeclaratorId} * | {@link ASTModifierList EmptyModifierList} {@link ASTVariableDeclaratorId VariableDeclaratorId} * * </pre> */ public final class ASTLambdaParameter extends AbstractJavaTypeNode implements InternalInterfaces.VariableIdOwner, FinalizableNode { ASTLambdaParameter(int id) { super(id); } /** * If true, this formal parameter represents one without explicit types. * This can appear as part of a lambda expression with java11 using "var". * * @see ASTVariableDeclaratorId#isTypeInferred() */ public boolean isTypeInferred() { return getTypeNode() == null; } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns the lambda that owns this parameter. */ public ASTLambdaExpression getOwner() { return (ASTLambdaExpression) getParent().getParent(); } /** * Returns the declarator ID of this formal parameter. */ @Override @NonNull public ASTVariableDeclaratorId getVarId() { return getFirstChildOfType(ASTVariableDeclaratorId.class); } /** Returns the type node of this formal parameter. */ @Nullable public ASTType getTypeNode() { return getFirstChildOfType(ASTType.class); } }
1,916
27.61194
153
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTRecordComponentList.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.java.ast.ASTList.ASTMaybeEmptyListOf; import net.sourceforge.pmd.lang.java.ast.InternalInterfaces.AllChildrenAreOfType; import net.sourceforge.pmd.lang.java.symbols.JConstructorSymbol; /** * Defines the state description of a {@linkplain ASTRecordDeclaration RecordDeclaration} (JDK 16 feature). * * <pre class="grammar"> * * RecordComponentList ::= "(" ( {@linkplain ASTRecordComponent RecordComponent} ( "," {@linkplain ASTRecordComponent RecordComponent} )* )? ")" * * </pre> */ public final class ASTRecordComponentList extends ASTMaybeEmptyListOf<ASTRecordComponent> implements SymbolDeclaratorNode, AllChildrenAreOfType<ASTRecordComponent> { private JConstructorSymbol symbol; ASTRecordComponentList(int id) { super(id, ASTRecordComponent.class); } /** * Returns true if the last component is varargs. */ public boolean isVarargs() { ASTRecordComponent lastChild = getLastChild(); return lastChild != null && lastChild.isVarargs(); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * This returns the symbol for the canonical constructor of the * record. There may be a compact record constructor declaration, * in which case they share the same symbol. */ @Override public JConstructorSymbol getSymbol() { // TODO deduplicate the symbol in case the canonical constructor // is explicitly declared somewhere. Needs a notion of override-equivalence, // to be provided by future PRs for type resolution assert symbol != null : "No symbol set for components of " + getParent(); return symbol; } void setSymbol(JConstructorSymbol symbol) { AbstractTypedSymbolDeclarator.assertSymbolNull(this.symbol, this); this.symbol = symbol; } }
2,093
32.774194
144
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/AbstractStatement.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; abstract class AbstractStatement extends AbstractJavaNode implements ASTStatement { AbstractStatement(int id) { super(id); } }
277
18.857143
83
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/AbstractJavaTypeNode.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.TypingContext; import net.sourceforge.pmd.lang.java.types.ast.LazyTypeResolver; import net.sourceforge.pmd.util.AssertionUtil; /** * An extension of the SimpleJavaNode which implements the TypeNode interface. * * @see AbstractJavaNode * @see TypeNode */ abstract class AbstractJavaTypeNode extends AbstractJavaNode implements TypeNode { private JTypeMirror typeMirror; AbstractJavaTypeNode(int i) { super(i); } void forceTypeResolution() { getTypeMirror(); } <T> T assertNonNullAfterTypeRes(T value) { assert value != null : "Something went wrong after type resolution of " + this; return value; } @Override public @NonNull JTypeMirror getTypeMirror() { return getTypeMirror(TypingContext.DEFAULT); } @Override public @NonNull JTypeMirror getTypeMirror(TypingContext context) { if (context.isEmpty() && typeMirror != null) { return typeMirror; } LazyTypeResolver resolver = getRoot().getLazyTypeResolver(); JTypeMirror result; try { result = this.acceptVisitor(resolver, context); assert result != null : "LazyTypeResolver returned null"; } catch (RuntimeException e) { throw AssertionUtil.contexted(e).addContextValue("Resolving type of", this); } catch (AssertionError e) { throw AssertionUtil.contexted(e).addContextValue("Resolving type of", this); } if (context.isEmpty() && typeMirror == null) { typeMirror = result; // cache it } return result; } JTypeMirror getTypeMirrorInternal() { return typeMirror; } void setTypeMirror(JTypeMirror mirror) { typeMirror = mirror; } }
2,073
26.653333
88
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTSwitchStatement.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Represents a {@code switch} statement. See {@link ASTSwitchLike} for * its grammar. */ public final class ASTSwitchStatement extends AbstractStatement implements ASTSwitchLike { ASTSwitchStatement(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
538
21.458333
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/AccessNode.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import static net.sourceforge.pmd.lang.java.ast.JModifier.STRICTFP; import java.util.Set; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.ast.NodeStream; /** * A node that owns a {@linkplain ASTModifierList modifier list}. * * <p>{@link AccessNode} methods take into account the syntactic context of the * declaration, e.g. {@link #isPublic()} will always return true for a field * declared inside an interface, regardless of whether the {@code public} * modifier was specified explicitly or not. If you want to know whether * the modifier was explicitly stated, use {@link #hasExplicitModifiers(JModifier, JModifier...)}. * * TODO make modifiers accessible from XPath * * Ideally we'd have two attributes, eg @EffectiveModifiers and @ExplicitModifiers, * which would each return a sequence, eg ("public", "static", "final") * * Ideally we'd have a way to add attributes that are not necessarily * getters on the node. It makes no sense in the Java API to expose * those getters on the node, it's more orthogonal to query getModifiers() directly. * * TODO rename to ModifierOwner, kept out from PR to reduce diff */ public interface AccessNode extends Annotatable { @Override default NodeStream<ASTAnnotation> getDeclaredAnnotations() { return getModifiers().children(ASTAnnotation.class); } /** * Returns the node representing the modifier list of this node. */ default @NonNull ASTModifierList getModifiers() { return firstChild(ASTModifierList.class); } /** * Returns the visibility corresponding to the {@link ASTModifierList#getEffectiveModifiers() effective modifiers}. * Eg a public method will have visibility {@link Visibility#V_PUBLIC public}, * a local class will have visibility {@link Visibility#V_LOCAL local}. * There cannot be any conflict with {@link #hasModifiers(JModifier, JModifier...)}} on * well-formed code (e.g. for any {@code n}, {@code (n.getVisibility() == V_PROTECTED) == * n.hasModifiers(PROTECTED)}) * * <p>TODO a public method of a private class can be considered to be private * we could probably add another method later on that takes this into account */ default Visibility getVisibility() { Set<JModifier> effective = getModifiers().getEffectiveModifiers(); if (effective.contains(JModifier.PUBLIC)) { return Visibility.V_PUBLIC; } else if (effective.contains(JModifier.PROTECTED)) { return Visibility.V_PROTECTED; } else if (effective.contains(JModifier.PRIVATE)) { return Visibility.V_PRIVATE; } else { return Visibility.V_PACKAGE; } } /** * Returns the "effective" visibility of a member. This is the minimum * visibility of its enclosing type declarations. For example, a public * method of a private class is "effectively private". * * <p>Local declarations keep local visibility, eg a local variable * somewhere in an anonymous class doesn't get anonymous visibility. */ default Visibility getEffectiveVisibility() { Visibility minv = getVisibility(); if (minv == Visibility.V_LOCAL) { return minv; } for (ASTAnyTypeDeclaration enclosing : ancestors(ASTAnyTypeDeclaration.class)) { minv = Visibility.min(minv, enclosing.getVisibility()); if (minv == Visibility.V_LOCAL) { return minv; } } return minv; } /** * Returns true if this node has <i>all</i> the given modifiers * either explicitly written or inferred through context. */ default boolean hasModifiers(JModifier mod1, JModifier... mod) { return getModifiers().hasAll(mod1, mod); } /** * Returns true if this node has <i>all</i> the given modifiers * explicitly written in the source. */ default boolean hasExplicitModifiers(JModifier mod1, JModifier... mod) { return getModifiers().hasAllExplicitly(mod1, mod); } // TODO remove all those, kept only for compatibility with rules // these are about effective modifiers @Deprecated default boolean isFinal() { return hasModifiers(JModifier.FINAL); } @Deprecated default boolean isAbstract() { return hasModifiers(JModifier.ABSTRACT); } @Deprecated default boolean isStrictfp() { return hasModifiers(STRICTFP); } @Deprecated default boolean isSynchronized() { return hasModifiers(JModifier.SYNCHRONIZED); } @Deprecated default boolean isNative() { return hasModifiers(JModifier.NATIVE); } @Deprecated default boolean isStatic() { return hasModifiers(JModifier.STATIC); } @Deprecated default boolean isVolatile() { return hasModifiers(JModifier.VOLATILE); } @Deprecated default boolean isTransient() { return hasModifiers(JModifier.TRANSIENT); } // these are about visibility @Deprecated default boolean isPrivate() { return getVisibility() == Visibility.V_PRIVATE; } @Deprecated default boolean isPublic() { return getVisibility() == Visibility.V_PUBLIC; } @Deprecated default boolean isProtected() { return getVisibility() == Visibility.V_PROTECTED; } @Deprecated default boolean isPackagePrivate() { return getVisibility() == Visibility.V_PACKAGE; } // these are about explicit modifiers @Deprecated default boolean isSyntacticallyAbstract() { return hasExplicitModifiers(JModifier.ABSTRACT); } @Deprecated default boolean isSyntacticallyPublic() { return hasExplicitModifiers(JModifier.PUBLIC); } @Deprecated default boolean isSyntacticallyStatic() { return hasExplicitModifiers(JModifier.STATIC); } @Deprecated default boolean isSyntacticallyFinal() { return hasExplicitModifiers(JModifier.FINAL); } /** * Represents the visibility of a declaration. * * <p>The ordering of the constants encodes a "contains" relationship, * ie, given two visibilities {@code v1} and {@code v2}, {@code v1 < v2} * means that {@code v2} is strictly more permissive than {@code v1}. */ enum Visibility { // Note: constants are prefixed with "V_" to avoid conflicts with JModifier /** Special visibility of anonymous classes, even more restricted than local. */ V_ANONYMOUS("anonymous"), /** Confined to a local scope, eg method parameters, local variables, local classes. */ V_LOCAL("local"), /** File-private. Corresponds to modifier {@link JModifier#PRIVATE}. */ V_PRIVATE("private"), /** Package-private. */ V_PACKAGE("package"), /** Package-private + visible to subclasses. Corresponds to modifier {@link JModifier#PROTECTED}. */ V_PROTECTED("protected"), /** Visible everywhere. Corresponds to modifier {@link JModifier#PUBLIC}. */ V_PUBLIC("public"); private final String myName; Visibility(String name) { this.myName = name; } @Override public String toString() { return myName; } /** * Returns true if this visibility is greater than or equal to * the parameter. */ public boolean isAtLeast(Visibility other) { return this.compareTo(other) >= 0; } /** * Returns true if this visibility is lower than or equal to the * parameter. */ public boolean isAtMost(Visibility other) { return this.compareTo(other) <= 0; } /** * The minimum of both visibilities. */ static Visibility min(Visibility v1, Visibility v2) { return v1.compareTo(v2) <= 0 ? v1 : v2; } } }
8,233
28.725632
119
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTSwitchGuard.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.annotation.Experimental; /** * A guard for refining a switch case in {@link ASTSwitchLabel}s. * This is a Java 19 Preview and Java 20 Preview language feature. * * <pre class="grammar"> * * SwitchLabel := "case" {@linkplain ASTPattern Pattern} SwitchGuard? * SwitchGuard ::= "when" {@linkplain ASTExpression Expression} * * </pre> * * @see <a href="https://openjdk.org/jeps/433">JEP 433: Pattern Matching for switch (Fourth Preview)</a> */ @Experimental public final class ASTSwitchGuard extends AbstractJavaNode { ASTSwitchGuard(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } public ASTExpression getGuard() { return (ASTExpression) getChild(0); } }
987
25
104
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTRecordComponent.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.java.ast.InternalInterfaces.VariableIdOwner; import net.sourceforge.pmd.lang.java.symbols.JClassSymbol; import net.sourceforge.pmd.lang.java.symbols.JConstructorSymbol; /** * Defines a single component of a {@linkplain ASTRecordDeclaration RecordDeclaration} (JDK 16 feature). * * <p>The varargs ellipsis {@code "..."} is parsed as an {@linkplain ASTArrayTypeDim array dimension} * in the type node. * * <p>Record components declare a field, and if a canonical constructor * is synthesized by the compiler, also a formal parameter (which is in * scope in the body of a {@linkplain ASTRecordConstructorDeclaration compact record constructor}). * They also may imply the declaration of an accessor method. * <ul> * <li>The symbol exposed by the {@link ASTVariableDeclaratorId} is the field * symbol. * <li> The formal parameter symbol is accessible in the formal parameter * list of the {@link JConstructorSymbol} for the {@linkplain ASTRecordComponentList#getSymbol() canonical constructor}. * <li>The symbol for the accessor method can be found in the {@link JClassSymbol#getDeclaredMethods() declared methods} * of the symbol for the record declaration. TODO when we support usage search this needs to be more straightforward * </ul> * * <pre class="grammar"> * * RecordComponent ::= {@linkplain ASTAnnotation Annotation}* {@linkplain ASTType Type} {@linkplain ASTVariableDeclaratorId VariableDeclaratorId} * * </pre> */ public final class ASTRecordComponent extends AbstractJavaNode implements AccessNode, VariableIdOwner { ASTRecordComponent(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns true if this component's corresponding formal parameter * in the canonical constructor of the record is varargs. The type * node of this component is in this case an {@link ASTArrayType}. */ public boolean isVarargs() { return getTypeNode() instanceof ASTArrayType && ((ASTArrayType) getTypeNode()).getDimensions().getLastChild().isVarargs(); } public ASTType getTypeNode() { return getFirstChildOfType(ASTType.class); } @Override public ASTVariableDeclaratorId getVarId() { return getFirstChildOfType(ASTVariableDeclaratorId.class); } }
2,562
37.253731
145
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTArrayTypeDim.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Represents an array dimension in an {@linkplain ASTArrayType array type}, * or in an {@linkplain ASTArrayAllocation array allocation expression}. * * <p>{@linkplain ASTArrayDimExpr ArrayDimExpr} represents array dimensions * that are initialized with a length, in array allocation expressions. * * <pre class="grammar"> * * ArrayTypeDim ::= {@link ASTAnnotation TypeAnnotation}* "[" "]" * * </pre> */ public class ASTArrayTypeDim extends AbstractJavaNode implements Annotatable { private boolean isVarargs; ASTArrayTypeDim(int id) { super(id); } /** * Returns true if this is a varargs dimension. Varargs parameters * are represented as an array type whose last dimension has this * attribute set to true. Querying {@link ASTFormalParameter#isVarargs()} * is more convenient. */ public boolean isVarargs() { return isVarargs; } void setVarargs() { isVarargs = true; } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
1,261
25.851064
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTInfixExpression.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.Objects; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.java.ast.InternalInterfaces.AtLeastOneChild; import net.sourceforge.pmd.lang.java.ast.InternalInterfaces.BinaryExpressionLike; /** * Represents a binary infix expression. {@linkplain ASTAssignmentExpression Assignment expressions} * are not represented by this node, because they're right-associative. * * <p>This node is used to represent expressions of different precedences. * The {@linkplain BinaryOp operator} is used to differentiate those expressions. * * <pre class="grammar"> * * InfixExpression ::= {@link ASTExpression Expression} {@link BinaryOp} {@link ASTExpression Expression} * * </pre> * * <p>Binary expressions are all left-associative, and are parsed left-recursively. * For example, the expression {@code 1 * 2 * 3 % 4} parses as the following tree: * * <figure> * <img src="doc-files/binaryExpr_70x.svg" /> * </figure> * * <p>In PMD 6.0.x, it would have parsed into the tree: * * <figure> * <img src="doc-files/binaryExpr_60x.svg" /> * </figure> */ public final class ASTInfixExpression extends AbstractJavaExpr implements BinaryExpressionLike, AtLeastOneChild { private BinaryOp operator; ASTInfixExpression(int i) { super(i); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } void setOp(BinaryOp op) { this.operator = Objects.requireNonNull(op); } /** * Returns the right-hand side operand. * * <p>If this is an {@linkplain BinaryOp#INSTANCEOF instanceof expression}, * then the right operand is a {@linkplain ASTTypeExpression TypeExpression}. */ @Override public ASTExpression getRightOperand() { return BinaryExpressionLike.super.getRightOperand(); } /** Returns the operator. */ @Override public @NonNull BinaryOp getOperator() { return operator; } // intentionally left-out @Override public void setImage(String image) { throw new UnsupportedOperationException(); } @Override public String getImage() { return null; } }
2,397
25.644444
113
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTStringLiteral.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.List; import java.util.stream.Collectors; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.document.Chars; import net.sourceforge.pmd.lang.rule.xpath.NoAttribute; import net.sourceforge.pmd.util.StringUtil; /** * Represents a string literal. The image of this node is the literal as it appeared * in the source ({@link #getText()}). {@link #getConstValue()} allows to recover * the actual runtime value, by processing escapes. */ public final class ASTStringLiteral extends AbstractLiteral implements ASTLiteral { private static final String TEXTBLOCK_DELIMITER = "\"\"\""; private boolean isTextBlock; ASTStringLiteral(int id) { super(id); } // todo deprecate this // it's ambiguous whether it returns getOriginalText or getTranslatedText @Override public String getImage() { return getText().toString(); } void setTextBlock() { this.isTextBlock = true; } /** Returns true if this is a text block (currently Java 13 preview feature). */ public boolean isTextBlock() { return isTextBlock; } /** True if the constant value is empty. Does not necessarily compute the constant value. */ public boolean isEmpty() { if (isTextBlock) { return getConstValue().isEmpty(); // could be a bunch of ignorable indents? } else { return getImage().length() == 2; // "" } } /** Length of the constant value in characters. */ public int length() { return getConstValue().length(); } /** * Returns a string where non-printable characters have been escaped * using Java-like escape codes (eg \n, \t, \u005cu00a0). */ // ^^^^^^ // this is a backslash, it's printed as \u00a0 @NoAttribute public @NonNull String toPrintableString() { return StringUtil.inDoubleQuotes(StringUtil.escapeJava(getConstValue())); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** Returns the value without delimiters and unescaped. */ @Override public @NonNull String getConstValue() { return (String) super.getConstValue(); // value is cached } @Override protected @NonNull String buildConstValue() { if (isTextBlock()) { return determineTextBlockContent(getText()); } else { return determineStringContent(getText()); } } static @NonNull String determineStringContent(Chars image) { Chars woDelims = image.subSequence(1, image.length() - 1); StringBuilder sb = new StringBuilder(woDelims.length()); interpretEscapeSequences(woDelims, sb, false); return sb.toString(); } static String determineTextBlockContent(Chars image) { List<Chars> lines = getContentLines(image); // remove common prefix StringUtil.trimIndentInPlace(lines); StringBuilder sb = new StringBuilder(image.length()); for (int i = 0; i < lines.size(); i++) { Chars line = lines.get(i); boolean isLastLine = i == lines.size() - 1; // this might return false if the line ends with a line continuation. boolean appendNl = interpretEscapeSequences(line, sb, !isLastLine); if (appendNl) { sb.append('\n'); } } return sb.toString(); } static String determineTextBlockContent(String image) { return determineTextBlockContent(Chars.wrap(image)); } /** * Returns the lines of the parameter minus the delimiters. */ private static @NonNull List<Chars> getContentLines(Chars chars) { List<Chars> lines = chars.lineStream().collect(Collectors.toList()); assert lines.size() >= 2 : "invalid text block syntax " + chars; // remove first line, it's just """ and some whitespace lines = lines.subList(1, lines.size()); // trim the """ off the last line. int lastIndex = lines.size() - 1; Chars lastLine = lines.get(lastIndex); assert lastLine.endsWith(TEXTBLOCK_DELIMITER); lines.set(lastIndex, lastLine.removeSuffix(TEXTBLOCK_DELIMITER)); return lines; } /** * Interpret escape sequences. This appends the interpreted contents * of 'line' into the StringBuilder. The line does not contain any * line terminators, instead, an implicit line terminator may be at * the end (parameter {@code isEndANewLine}), to interpret line * continuations. * * @param line Source line * @param out Output * @param isEndANewLine Whether the end of the line is a newline, * as in text blocks * * @return Whether a newline should be appended at the end. Returns * false if {@code isEndANewLine} and the line ends with a backslash, * as this is a line continuation. */ // See https://docs.oracle.com/javase/specs/jls/se17/html/jls-3.html#jls-EscapeSequence private static boolean interpretEscapeSequences(Chars line, StringBuilder out, boolean isEndANewLine) { // we need to interpret everything in one pass, so regex replacement is inappropriate int appended = 0; int i = 0; while (i < line.length()) { char c = line.charAt(i); if (c != '\\') { i++; continue; } if (i + 1 == line.length()) { // the last character of the line is a backslash if (isEndANewLine) { // then this is a line continuation line.appendChars(out, appended, i); return false; // shouldn't append newline } // otherwise we'll append the backslash when exiting the loop break; } char cnext = line.charAt(i + 1); switch (cnext) { case '\\': case 'n': case 't': case 'b': case 'r': case 'f': case 's': case '"': case '\'': // append up to and not including backslash line.appendChars(out, appended, i); // append the translation out.append(translateBackslashEscape(cnext)); // next time, start appending after the char i += 2; appended = i; continue; // octal digits case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': // append up to and not including backslash line.appendChars(out, appended, i); i = translateOctalEscape(line, i + 1, out); appended = i; continue; default: // unknown escape - do nothing - it stays i++; break; } } if (appended < line.length()) { // append until the end line.appendChars(out, appended, line.length()); } return isEndANewLine; } private static char translateBackslashEscape(char c) { switch (c) { case '\\': return '\\'; case 'n': return '\n'; case 't': return '\t'; case 'b': return '\b'; case 'r': return '\r'; case 'f': return '\f'; case 's': return ' '; case '"': return '"'; case '\'': return '\''; default: throw new IllegalArgumentException("Not a valid escape \\" + c); } } private static int translateOctalEscape(Chars src, final int firstDigitIndex, StringBuilder sb) { int i = firstDigitIndex; int result = src.charAt(i) - '0'; i++; if (src.length() > i && isOctalDigit(src.charAt(i))) { result = 8 * result + src.charAt(i) - '0'; i++; if (src.length() > i && isOctalDigit(src.charAt(i))) { result = 8 * result + src.charAt(i) - '0'; i++; } } sb.append((char) result); return i; } private static boolean isOctalDigit(char c) { return c >= '0' && c <= '7'; } }
8,730
32.580769
107
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTModuleName.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * The name of a module. Module names look like package names, eg * {@code java.base}. */ public final class ASTModuleName extends AbstractJavaNode { ASTModuleName(int id) { super(id); } @Override public <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } @Override @Deprecated public String getImage() { return null; } /** * Returns the name of the declared module. Module names look * like package names, eg {@code java.base}. */ public String getName() { return super.getImage(); } }
789
19.789474
88
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTArrayAllocation.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; /** * An array creation expression. The dimensions of the array type may * be initialized with a length expression (in which case they're * {@link ASTArrayDimExpr ArrayDimExpr} nodes). * * <pre class="grammar"> * * ArrayCreationExpression ::= "new" {@link ASTArrayType ArrayType} {@link ASTArrayInitializer ArrayInitializer}? * * </pre> */ public final class ASTArrayAllocation extends AbstractJavaExpr implements ASTPrimaryExpression { ASTArrayAllocation(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns the node representing the array type being instantiated. */ public ASTArrayType getTypeNode() { return (ASTArrayType) getChild(0); } /** Returns the initializer, if present. */ @Nullable public ASTArrayInitializer getArrayInitializer() { return AstImplUtil.getChildAs(this, getNumChildren() - 1, ASTArrayInitializer.class); } /** * Returns the number of dimensions of the created array. */ public int getArrayDepth() { return getTypeNode().getArrayDepth(); } }
1,421
24.854545
113
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTWhileStatement.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Represents a {@code while} loop. * * <pre class="grammar"> * * WhileStatement ::= "while" "(" {@linkplain ASTExpression Expression} ")" {@linkplain ASTStatement Statement} * * </pre> */ public final class ASTWhileStatement extends AbstractStatement implements ASTLoopStatement { ASTWhileStatement(int id) { super(id); } /** * Returns the node that represents the guard of this loop. * This may be any expression of type boolean. */ @Override public ASTExpression getCondition() { return (ASTExpression) getChild(0); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
882
21.641026
111
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTModifierList.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import static net.sourceforge.pmd.lang.java.ast.JModifier.ABSTRACT; import static net.sourceforge.pmd.lang.java.ast.JModifier.DEFAULT; import static net.sourceforge.pmd.lang.java.ast.JModifier.FINAL; import static net.sourceforge.pmd.lang.java.ast.JModifier.PRIVATE; import static net.sourceforge.pmd.lang.java.ast.JModifier.PUBLIC; import static net.sourceforge.pmd.lang.java.ast.JModifier.STATIC; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.Set; /** * List of modifiers of a declaration. * * <p>This class keeps track of two modifier sets: the {@linkplain #getExplicitModifiers() explicit} * one, which is the modifiers that appeared in the source, and the * {@linkplain #getEffectiveModifiers() effective} one, which includes * modifiers implicitly given by the context of the node. * * <pre class="grammar"> * * * * ModifierList ::= Modifier* * * Modifier ::= "public" | "private" | "protected" * | "final" | "abstract" | "static" | "strictfp" * | "synchronized" | "native" | "default" * | "volatile" | "transient" * | {@linkplain ASTAnnotation Annotation} * * * LocalVarModifierList ::= ( "final" | {@link ASTAnnotation Annotation} )* * * AnnotationList ::= {@link ASTAnnotation Annotation}* * * EmptyModifierList ::= () * * </pre> */ public final class ASTModifierList extends AbstractJavaNode { /** Might as well share it. */ static final Set<JModifier> JUST_FINAL = Collections.singleton(FINAL); private Set<JModifier> explicitModifiers; private Set<JModifier> effectiveModifiers; ASTModifierList(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } void setDeclaredModifiers(Set<JModifier> explicit) { this.explicitModifiers = explicit; } /** * Returns the set of modifiers written out in the source explicitly. * The returned set is unmodifiable. */ public Set<JModifier> getExplicitModifiers() { assert explicitModifiers != null : "Parser should have set the explicit modifiers"; return Collections.unmodifiableSet(explicitModifiers); } /** * Returns the {@linkplain #getExplicitModifiers() declared modifiers}, * plus the modifiers that are implicitly bestowed by the context or * the type of this declaration. E.g. an interface is implicitly abstract, * while an interface field is implicitly static. * The returned set is unmodifiable. */ public Set<JModifier> getEffectiveModifiers() { assert explicitModifiers != null : "Parser should have set the explicit modifiers"; if (effectiveModifiers == null) { Set<JModifier> mods = explicitModifiers.isEmpty() ? EnumSet.noneOf(JModifier.class) : EnumSet.copyOf(explicitModifiers); getOwner().acceptVisitor(EffectiveModifierVisitor.INSTANCE, mods); this.effectiveModifiers = Collections.unmodifiableSet(mods); } return effectiveModifiers; } /** Returns the node owning this modifier list. */ public Annotatable getOwner() { return (Annotatable) getParent(); // TODO } /** * Returns true if the effective modifiers contain all of the mentioned * modifiers. * * @param mod1 First mod * @param mods Other mods */ public boolean hasAll(JModifier mod1, JModifier... mods) { Set<JModifier> actual = getEffectiveModifiers(); return actual.contains(mod1) && (mods.length == 0 || actual.containsAll(Arrays.asList(mods))); } /** * Returns true if the explicit modifiers contain all of the mentioned * modifiers. * * @param mod1 First mod * @param mods Other mods */ public boolean hasAllExplicitly(JModifier mod1, JModifier... mods) { Set<JModifier> actual = getExplicitModifiers(); return actual.contains(mod1) && (mods.length == 0 || actual.containsAll(Arrays.asList(mods))); } /** * Returns true if the effective modifiers contain any of the mentioned * modifiers. * * @param mod1 First mod * @param mods Other mods */ public boolean hasAny(JModifier mod1, JModifier... mods) { Set<JModifier> actual = getEffectiveModifiers(); return actual.contains(mod1) || Arrays.stream(mods).anyMatch(actual::contains); } /** * Returns true if the explicit modifiers contain any of the mentioned * modifiers. * * @param mod1 First mod * @param mods Other mods */ public boolean hasAnyExplicitly(JModifier mod1, JModifier... mods) { Set<JModifier> actual = getExplicitModifiers(); return actual.contains(mod1) || Arrays.stream(mods).anyMatch(actual::contains); } /** * Populates effective modifiers from the declared ones. */ private static final class EffectiveModifierVisitor extends JavaVisitorBase<Set<JModifier>, Void> { private static final EffectiveModifierVisitor INSTANCE = new EffectiveModifierVisitor(); // TODO strictfp modifier is also implicitly given to descendants // TODO final modifier is implicitly given to direct subclasses of sealed interface/class @Override public Void visitJavaNode(JavaNode node, Set<JModifier> data) { return null; // default, don't recurse, no special modifiers. } @Override public Void visitTypeDecl(ASTAnyTypeDeclaration node, Set<JModifier> effective) { ASTAnyTypeDeclaration enclosing = node.getEnclosingType(); if (enclosing != null && enclosing.isInterface()) { effective.add(PUBLIC); effective.add(STATIC); } if (node.isInterface() || node.isAnnotation()) { effective.add(ABSTRACT); if (!node.isTopLevel()) { effective.add(STATIC); } } else if (!node.isTopLevel() && (node instanceof ASTEnumDeclaration || node instanceof ASTRecordDeclaration)) { effective.add(STATIC); } if (node instanceof ASTEnumDeclaration && node.getEnumConstants().none(ASTEnumConstant::isAnonymousClass) || node instanceof ASTRecordDeclaration) { effective.add(FINAL); } return null; } @Override public Void visit(ASTFieldDeclaration node, Set<JModifier> effective) { if (node.getEnclosingType().isInterface()) { effective.add(PUBLIC); effective.add(STATIC); effective.add(FINAL); } return null; } @Override public Void visit(ASTLocalVariableDeclaration node, Set<JModifier> effective) { // resources are implicitly final if (node.getParent() instanceof ASTResource) { effective.add(FINAL); } return null; } @Override public Void visit(ASTEnumConstant node, Set<JModifier> effective) { effective.add(PUBLIC); effective.add(STATIC); effective.add(FINAL); return null; } @Override public Void visit(ASTRecordComponent node, Set<JModifier> effective) { effective.add(PRIVATE); // field is private, an accessor method is generated effective.add(FINAL); return null; } @Override public Void visit(ASTAnonymousClassDeclaration node, Set<JModifier> effective) { ASTBodyDeclaration enclosing = node.ancestors(ASTBodyDeclaration.class).first(); assert enclosing != null && !(enclosing instanceof ASTAnyTypeDeclaration) : "Weird position for an anonymous class " + enclosing; if (enclosing instanceof ASTEnumConstant) { effective.add(STATIC); } else { if (enclosing instanceof AccessNode && ((AccessNode) enclosing).hasModifiers(STATIC) || enclosing instanceof ASTInitializer && ((ASTInitializer) enclosing).isStatic()) { effective.add(STATIC); } } return null; } @Override public Void visit(ASTConstructorDeclaration node, Set<JModifier> effective) { if (node.getEnclosingType().isEnum()) { effective.add(PRIVATE); } return null; } @Override public Void visit(ASTMethodDeclaration node, Set<JModifier> effective) { if (node.getEnclosingType().isInterface()) { Set<JModifier> declared = node.getModifiers().explicitModifiers; if (!declared.contains(PRIVATE)) { effective.add(PUBLIC); } if (!declared.contains(DEFAULT) && !declared.contains(STATIC)) { effective.add(ABSTRACT); } } return null; } } }
9,540
32.36014
104
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTTypeBody.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Body of a type declaration. * * <pre class="grammar"> * * TypeBody ::= {@link ASTClassOrInterfaceBody ClassOrInterfaceBody} * | {@link ASTEnumBody EnumBody} * | {@link ASTRecordBody RecordBody} * | {@link ASTAnnotationTypeBody AnnotationTypeBody} * * </pre> */ public abstract class ASTTypeBody extends ASTList<ASTBodyDeclaration> { ASTTypeBody(int id) { super(id, ASTBodyDeclaration.class); } }
596
21.961538
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTTypePattern.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.Objects; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.annotation.Experimental; /** * A type pattern (JDK16). This can be found on * the right-hand side of an {@link ASTInfixExpression InstanceOfExpression}, * in a {@link ASTPatternExpression PatternExpression}. * * <pre class="grammar"> * * TypePattern ::= ( "final" | {@linkplain ASTAnnotation Annotation} )* {@linkplain ASTType Type} {@link ASTVariableDeclaratorId VariableDeclaratorId} * * </pre> * * @see <a href="https://openjdk.java.net/jeps/394">JEP 394: Pattern Matching for instanceof</a> */ public final class ASTTypePattern extends AbstractJavaNode implements ASTPattern, AccessNode { private int parenDepth; ASTTypePattern(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Gets the type against which the expression is tested. */ public @NonNull ASTType getTypeNode() { return Objects.requireNonNull(firstChild(ASTType.class)); } /** Returns the declared variable. */ public @NonNull ASTVariableDeclaratorId getVarId() { return Objects.requireNonNull(firstChild(ASTVariableDeclaratorId.class)); } void bumpParenDepth() { parenDepth++; } @Override @Experimental public int getParenthesisDepth() { return parenDepth; } }
1,636
25.836066
150
java