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/symbols/table/internal/SymbolTableResolver.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.table.internal;
import static net.sourceforge.pmd.lang.java.symbols.table.internal.AbruptCompletionAnalysis.canCompleteNormally;
import static net.sourceforge.pmd.lang.java.symbols.table.internal.PatternBindingsUtil.bindersOfExpr;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.NodeStream;
import net.sourceforge.pmd.lang.java.ast.ASTAmbiguousName;
import net.sourceforge.pmd.lang.java.ast.ASTAnonymousClassDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTBlock;
import net.sourceforge.pmd.lang.java.ast.ASTBreakStatement;
import net.sourceforge.pmd.lang.java.ast.ASTCatchClause;
import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType;
import net.sourceforge.pmd.lang.java.ast.ASTCompactConstructorDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.ASTConditionalExpression;
import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTForStatement;
import net.sourceforge.pmd.lang.java.ast.ASTForeachStatement;
import net.sourceforge.pmd.lang.java.ast.ASTIfStatement;
import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTInfixExpression;
import net.sourceforge.pmd.lang.java.ast.ASTInitializer;
import net.sourceforge.pmd.lang.java.ast.ASTLabeledStatement;
import net.sourceforge.pmd.lang.java.ast.ASTLambdaExpression;
import net.sourceforge.pmd.lang.java.ast.ASTLambdaParameter;
import net.sourceforge.pmd.lang.java.ast.ASTLocalClassStatement;
import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTLoopStatement;
import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTModifierList;
import net.sourceforge.pmd.lang.java.ast.ASTResource;
import net.sourceforge.pmd.lang.java.ast.ASTResourceList;
import net.sourceforge.pmd.lang.java.ast.ASTStatement;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchArrowBranch;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchBranch;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchExpression;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchFallthroughBranch;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchLabel;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchLike;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchStatement;
import net.sourceforge.pmd.lang.java.ast.ASTTryStatement;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.ast.ASTWhileStatement;
import net.sourceforge.pmd.lang.java.ast.BinaryOp;
import net.sourceforge.pmd.lang.java.ast.InternalApiBridge;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.ast.JavaVisitorBase;
import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils;
import net.sourceforge.pmd.lang.java.internal.JavaAstProcessor;
import net.sourceforge.pmd.lang.java.symbols.table.JSymbolTable;
import net.sourceforge.pmd.lang.java.symbols.table.internal.PatternBindingsUtil.BindSet;
import net.sourceforge.pmd.lang.java.types.JClassType;
/**
* Visitor that builds all symbol table stacks for a compilation unit.
* It's bound to a compilation unit and cannot be reused for several ACUs.
*
* @since 7.0.0
*/
public final class SymbolTableResolver {
private SymbolTableResolver() {
// façade
}
public static void traverse(JavaAstProcessor processor, ASTCompilationUnit root) {
SymTableFactory helper = new SymTableFactory(root.getPackageName(), processor);
ReferenceCtx ctx = ReferenceCtx.root(processor, root);
Set<DeferredNode> todo = Collections.singleton(new DeferredNode(root, ctx, SymbolTableImpl.EMPTY));
do {
Set<DeferredNode> newDeferred = new HashSet<>();
for (DeferredNode deferred : todo) {
MyVisitor visitor = new MyVisitor(helper, todo, newDeferred);
visitor.traverse(deferred);
}
todo = newDeferred;
} while (!todo.isEmpty());
}
private static final class DeferredNode {
final JavaNode node;
// this is data used to resume the traversal
final ReferenceCtx enclosingCtx;
final JSymbolTable localStackTop;
private DeferredNode(JavaNode node, ReferenceCtx enclosingCtx, JSymbolTable localStackTop) {
this.node = node;
this.enclosingCtx = enclosingCtx;
this.localStackTop = localStackTop;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeferredNode that = (DeferredNode) o;
return node.equals(that.node);
}
@Override
public int hashCode() {
return Objects.hash(node);
}
}
private static class MyVisitor extends JavaVisitorBase<@NonNull ReferenceCtx, Void> {
private final SymTableFactory f;
private final Deque<JSymbolTable> stack = new ArrayDeque<>();
private final Deque<ASTAnyTypeDeclaration> enclosingType = new ArrayDeque<>();
private final Set<DeferredNode> deferredInPrevRound;
private final Set<DeferredNode> newDeferred;
private final StatementVisitor stmtVisitor = new StatementVisitor();
MyVisitor(SymTableFactory helper, Set<DeferredNode> deferredInPrevRound, Set<DeferredNode> newDeferred) {
f = helper;
this.deferredInPrevRound = deferredInPrevRound;
this.newDeferred = newDeferred;
}
/**
* Start the analysis.
*/
void traverse(DeferredNode task) {
assert stack.isEmpty()
: "Stack should be empty when starting the traversal";
stack.push(task.localStackTop);
task.node.acceptVisitor(this, task.enclosingCtx);
JSymbolTable last = stack.pop();
assert last == task.localStackTop // NOPMD CompareObjectsWithEquals
: "Unbalanced stack push/pop! Started with " + task.localStackTop + ", finished on " + last;
}
@Override
public Void visit(ASTClassOrInterfaceType node, @NonNull ReferenceCtx data) {
// all types are disambiguated in this resolver, because
// the symbols available inside the body of an anonymous class
// depend on the type of the superclass/superinterface (the Runnable in `new Runnable() { }`).
// This type may be
// 1. a diamond (`new Function<>() { ... }`),
// 2. qualified (`expr.new Inner() { ... }`)
// 3. both
// For case 2, resolution of the symbol of Inner needs full
// type resolution of the qualifying `expr`, which may depend
// on the disambiguation of arbitrary type nodes (eg method
// parameters, local var types).
// Which means, as early as in this visitor, we may need the
// symbols of all class types. For that reason we disambiguate
// them early.
// Todo test ambig names in expressions depended on by the qualifier
f.disambig(NodeStream.of(node), data);
return null;
}
@Override
public Void visit(ASTAmbiguousName node, @NonNull ReferenceCtx data) {
// see comment in visit(ClassType)
f.disambig(NodeStream.of(node), data);
return null;
}
@Override
public Void visit(ASTModifierList node, @NonNull ReferenceCtx ctx) {
// do nothing
return null;
}
@Override
public Void visit(ASTCompilationUnit node, @NonNull ReferenceCtx ctx) {
Map<Boolean, List<ASTImportDeclaration>> isImportOnDemand = node.children(ASTImportDeclaration.class)
.collect(Collectors.partitioningBy(ASTImportDeclaration::isImportOnDemand));
int pushed = 0;
pushed += pushOnStack(f.importsOnDemand(top(), isImportOnDemand.get(true)));
pushed += pushOnStack(f.javaLangSymTable(top()));
pushed += pushOnStack(f.samePackageSymTable(top()));
pushed += pushOnStack(f.singleImportsSymbolTable(top(), isImportOnDemand.get(false)));
NodeStream<ASTAnyTypeDeclaration> typeDecls = node.getTypeDeclarations();
// types declared inside the compilation unit
pushed += pushOnStack(f.typesInFile(top(), typeDecls));
setTopSymbolTable(node);
for (ASTAnyTypeDeclaration td : typeDecls) {
// preprocess all sibling types
processTypeHeader(td, ctx);
}
// All of the header symbol tables belong to the CompilationUnit
visitChildren(node, ctx);
popStack(pushed);
return null;
}
private void processTypeHeader(ASTAnyTypeDeclaration node, ReferenceCtx ctx) {
setTopSymbolTable(node.getModifiers());
int pushed = pushOnStack(f.selfType(top(), node.getTypeMirror()));
pushed += pushOnStack(f.typeHeader(top(), node.getSymbol()));
NodeStream<? extends JavaNode> notBody = node.children().drop(1).dropLast(1);
for (JavaNode it : notBody) {
setTopSymbolTable(it);
}
popStack(pushed - 1);
// resolve the supertypes, necessary for TypeMemberSymTable
f.disambig(notBody, ctx); // extends/implements
setTopSymbolTable(node);
popStack();
}
@Override
public Void visitTypeDecl(ASTAnyTypeDeclaration node, @NonNull ReferenceCtx ctx) {
int pushed = 0;
enclosingType.push(node);
ReferenceCtx bodyCtx = ctx.scopeDownToNested(node.getSymbol());
// the following is just for the body
pushed += pushOnStack(f.typeBody(top(), node.getTypeMirror()));
setTopSymbolTable(node.getBody());
// preprocess siblings
node.getDeclarations(ASTAnyTypeDeclaration.class)
.forEach(d -> processTypeHeader(d, bodyCtx));
// process fields first, their type is needed for JSymbolTable#resolveValue
f.disambig(node.getDeclarations(ASTFieldDeclaration.class)
.map(ASTFieldDeclaration::getTypeNode),
bodyCtx);
visitChildren(node.getBody(), bodyCtx);
enclosingType.pop();
popStack(pushed);
return null;
}
@Override
public Void visit(ASTAnonymousClassDeclaration node, @NonNull ReferenceCtx ctx) {
if (node.getParent() instanceof ASTConstructorCall) {
// deferred to later, the symbol table for its body depends
// on typeres of the ctor which may be qualified, and refer
// to stuff that are declared later in the compilation unit,
// and not yet disambiged.
DeferredNode deferredSpec = new DeferredNode(node, ctx, top());
if (!deferredInPrevRound.contains(deferredSpec)) {
newDeferred.add(deferredSpec);
return null;
}
// otherwise fallthrough
}
return visitTypeDecl(node, ctx);
}
@Override
public Void visitMethodOrCtor(ASTMethodOrConstructorDeclaration node, @NonNull ReferenceCtx ctx) {
setTopSymbolTable(node.getModifiers());
int pushed = pushOnStack(f.bodyDeclaration(top(), enclosing(), node.getFormalParameters(), node.getTypeParameters()));
setTopSymbolTableAndVisitAllChildren(node, ctx);
popStack(pushed);
return null;
}
@Override
public Void visit(ASTInitializer node, @NonNull ReferenceCtx ctx) {
int pushed = pushOnStack(f.bodyDeclaration(top(), enclosing(), null, null));
setTopSymbolTableAndVisitAllChildren(node, ctx);
popStack(pushed);
return null;
}
@Override
public Void visit(ASTCompactConstructorDeclaration node, @NonNull ReferenceCtx ctx) {
setTopSymbolTable(node.getModifiers());
int pushed = pushOnStack(f.recordCtor(top(), enclosing(), node.getSymbol()));
setTopSymbolTableAndVisitAllChildren(node, ctx);
popStack(pushed);
return null;
}
@Override
public Void visit(ASTLambdaExpression node, @NonNull ReferenceCtx ctx) {
int pushed = pushOnStack(f.localVarSymTable(top(), enclosing(), formalsOf(node)));
setTopSymbolTableAndVisitAllChildren(node, ctx);
popStack(pushed);
return null;
}
@Override
public Void visit(ASTBlock node, @NonNull ReferenceCtx ctx) {
int pushed = visitBlockLike(node, ctx);
popStack(pushed);
return null;
}
@Override
public Void visit(ASTSwitchStatement node, @NonNull ReferenceCtx ctx) {
return visitSwitch(node, ctx);
}
@Override
public Void visit(ASTSwitchExpression node, @NonNull ReferenceCtx ctx) {
return visitSwitch(node, ctx);
}
private Void visitSwitch(ASTSwitchLike node, @NonNull ReferenceCtx ctx) {
setTopSymbolTable(node);
node.getTestedExpression().acceptVisitor(this, ctx);
int pushed = 0;
for (ASTSwitchBranch branch : node.getBranches()) {
ASTSwitchLabel label = branch.getLabel();
// collect all bindings. Maybe it's illegal to use composite label with bindings, idk
BindSet bindings =
label.getExprList().reduce(BindSet.EMPTY,
(bindSet, expr) -> bindSet.union(bindersOfExpr(expr)));
// visit guarded patterns in label
setTopSymbolTableAndVisit(label, ctx);
if (branch instanceof ASTSwitchArrowBranch) {
pushed = pushOnStack(f.localVarSymTable(top(), enclosing(), bindings.getTrueBindings()));
setTopSymbolTableAndVisit(((ASTSwitchArrowBranch) branch).getRightHandSide(), ctx);
popStack(pushed);
pushed = 0;
} else if (branch instanceof ASTSwitchFallthroughBranch) {
pushed += pushOnStack(f.localVarSymTable(top(), enclosing(), bindings.getTrueBindings()));
pushed += visitBlockLike(((ASTSwitchFallthroughBranch) branch).getStatements(), ctx);
}
}
popStack(pushed);
return null;
}
/**
* Note: caller is responsible for popping.
*/
private int visitBlockLike(Iterable<? extends ASTStatement> node, @NonNull ReferenceCtx ctx) {
/*
* Process the statements of a block in a sequence. Each local
* var/class declaration is only in scope for the following
* statements (and its own initializer).
*/
int pushed = 0;
for (ASTStatement st : node) {
if (st instanceof ASTLocalVariableDeclaration) {
pushed += processLocalVarDecl((ASTLocalVariableDeclaration) st, ctx);
// note we don't pop here, all those variables will be popped at the end of the block
} else if (st instanceof ASTLocalClassStatement) {
ASTAnyTypeDeclaration local = ((ASTLocalClassStatement) st).getDeclaration();
pushed += pushOnStack(f.localTypeSymTable(top(), local.getTypeMirror()));
processTypeHeader(local, ctx);
}
setTopSymbolTable(st);
// those vars are the one produced by pattern bindings/ local var decls
PSet<ASTVariableDeclaratorId> newVars = st.acceptVisitor(this.stmtVisitor, ctx);
pushed += pushOnStack(f.localVarSymTable(top(), enclosing(), newVars));
}
return pushed;
}
/**
* Note: caller is responsible for popping.
*/
private int processLocalVarDecl(ASTLocalVariableDeclaration st, @NonNull ReferenceCtx ctx) {
// each variable is visible in its own initializer and the ones of the following variables
int pushed = 0;
for (ASTVariableDeclarator declarator : st.children(ASTVariableDeclarator.class)) {
ASTVariableDeclaratorId varId = declarator.getVarId();
pushed += pushOnStack(f.localVarSymTable(top(), enclosing(), varId.getSymbol()));
// visit initializer
setTopSymbolTableAndVisit(declarator.getInitializer(), ctx);
}
return pushed;
}
@Override
public Void visit(ASTForeachStatement node, @NonNull ReferenceCtx ctx) {
// the varId is only in scope in the body and not the iterable expr
setTopSymbolTableAndVisit(node.getIterableExpr(), ctx);
ASTVariableDeclaratorId varId = node.getVarId();
setTopSymbolTableAndVisit(varId.getTypeNode(), ctx);
int pushed = pushOnStack(f.localVarSymTable(top(), enclosing(), varId.getSymbol()));
ASTStatement body = node.getBody();
// unless it's a block the body statement may never set a
// symbol table that would have this table as parent,
// so the table would be dangling
setTopSymbolTableAndVisit(body, ctx);
popStack(pushed);
return null;
}
@Override
public Void visit(ASTTryStatement node, @NonNull ReferenceCtx ctx) {
ASTResourceList resources = node.getResources();
if (resources != null) {
NodeStream<ASTStatement> union =
NodeStream.union(
stmtsOfResources(resources),
// use the body instead of unwrapping it so
// that it has the correct symbol table too
NodeStream.of(node.getBody())
);
popStack(visitBlockLike(union, ctx));
for (Node child : node.getBody().asStream().followingSiblings()) {
child.acceptVisitor(this, ctx);
}
} else {
visitChildren(node, ctx);
}
return null;
}
@Override
public Void visit(ASTCatchClause node, @NonNull ReferenceCtx ctx) {
int pushed = pushOnStack(f.localVarSymTable(top(), enclosing(), node.getParameter().getVarId().getSymbol()));
setTopSymbolTableAndVisitAllChildren(node, ctx);
popStack(pushed);
return null;
}
@Override
public Void visit(ASTInfixExpression node, @NonNull ReferenceCtx ctx) {
// need to account for pattern bindings.
// visit left operand first. Maybe it introduces bindings in the rigt operand.
node.getLeftOperand().acceptVisitor(this, ctx);
BinaryOp op = node.getOperator();
if (op == BinaryOp.CONDITIONAL_AND) {
PSet<ASTVariableDeclaratorId> trueBindings = bindersOfExpr(node.getLeftOperand()).getTrueBindings();
if (!trueBindings.isEmpty()) {
int pushed = pushOnStack(f.localVarSymTable(top(), enclosing(), trueBindings));
setTopSymbolTableAndVisit(node.getRightOperand(), ctx);
popStack(pushed);
return null;
}
} else if (op == BinaryOp.CONDITIONAL_OR) {
PSet<ASTVariableDeclaratorId> falseBindings = bindersOfExpr(node.getLeftOperand()).getFalseBindings();
if (!falseBindings.isEmpty()) {
int pushed = pushOnStack(f.localVarSymTable(top(), enclosing(), falseBindings));
setTopSymbolTableAndVisit(node.getRightOperand(), ctx);
popStack(pushed);
return null;
}
}
// not a special case, finish visiting right operand
return node.getRightOperand().acceptVisitor(this, ctx);
}
@Override
public Void visit(ASTConditionalExpression node, @NonNull ReferenceCtx ctx) {
// need to account for pattern bindings.
ASTExpression condition = node.getCondition();
condition.acceptVisitor(this, ctx);
BindSet binders = bindersOfExpr(condition);
if (binders.isEmpty()) {
node.getThenBranch().acceptVisitor(this, ctx);
node.getElseBranch().acceptVisitor(this, ctx);
} else {
int pushed = pushOnStack(f.localVarSymTable(top(), enclosing(), binders.getTrueBindings()));
setTopSymbolTableAndVisit(node.getThenBranch(), ctx);
popStack(pushed);
pushed = pushOnStack(f.localVarSymTable(top(), enclosing(), binders.getFalseBindings()));
setTopSymbolTableAndVisit(node.getElseBranch(), ctx);
popStack(pushed);
}
return null;
}
/**
* Handles statements. Every visit method should
* <ul>
* <li>Visit the statement and its <i>entire</i> subtree according to the
* scoping rules of the statement (eg, a for statement may declare
* some variables in its initializers). Note that the subtree should be visited
* with the enclosing instance of {@link MyVisitor}, not the statement visitor itself.
* <li>Pop any new symbol tables it pushes.
* <li>return the set of variables that are <i>introduced</i> by the statement (in following statements)
* as defined in the JLS: https://docs.oracle.com/javase/specs/jls/se17/html/jls-6.html#jls-6.3.2
* This is used to implement scoping of pat variables in blocks.
* <li>
* </ul>
*
* <p>{@link #visitBlockLike(Iterable, ReferenceCtx)} calls this to process a block scope.
*
* <p>Statements that have no special rules concerning pat bindings can
* implement a visit method in the MyVisitor instance, this visitor will
* default to that implementation.
*/
class StatementVisitor extends JavaVisitorBase<ReferenceCtx, PSet<ASTVariableDeclaratorId>> {
@Override
public PSet<ASTVariableDeclaratorId> visitJavaNode(JavaNode node, ReferenceCtx ctx) {
throw new IllegalStateException("I only expect statements, got " + node);
}
@Override
public PSet<ASTVariableDeclaratorId> visitStatement(ASTStatement node, ReferenceCtx ctx) {
// Default to calling the method on the outer class,
// which will recurse
node.acceptVisitor(MyVisitor.this, ctx);
return BindSet.noBindings();
}
@Override
public PSet<ASTVariableDeclaratorId> visit(ASTLabeledStatement node, @NonNull ReferenceCtx ctx) {
// A pattern variable is introduced by a labeled statement
// if and only if it is introduced by its immediately contained Statement.
return node.getStatement().acceptVisitor(this, ctx);
}
@Override
public PSet<ASTVariableDeclaratorId> visit(ASTIfStatement node, ReferenceCtx ctx) {
BindSet bindSet = bindersOfExpr(node.getCondition());
ASTStatement thenBranch = node.getThenBranch();
ASTStatement elseBranch = node.getElseBranch();
MyVisitor.this.setTopSymbolTableAndVisit(node.getCondition(), ctx);
// the true bindings of the condition are in scope in the then branch
int pushed = pushOnStack(f.localVarSymTable(top(), enclosing(), bindSet.getTrueBindings()));
setTopSymbolTableAndVisit(thenBranch, ctx);
popStack(pushed);
if (elseBranch != null) {
// if there is an else, the false bindings are in scope in the else branch
pushed = pushOnStack(f.localVarSymTable(top(), enclosing(), bindSet.getFalseBindings()));
setTopSymbolTableAndVisit(elseBranch, ctx);
popStack(pushed);
}
if (!bindSet.isEmpty()) {
// avoid computing canCompleteNormally if possible
boolean thenCanCompleteNormally = canCompleteNormally(thenBranch);
boolean elseCanCompleteNormally = elseBranch == null || canCompleteNormally(elseBranch);
// the bindings are visible in the statements following this if/else
// if one of those conditions match
if (thenCanCompleteNormally && !elseCanCompleteNormally) {
return bindSet.getTrueBindings();
} else if (!thenCanCompleteNormally && elseCanCompleteNormally) {
return bindSet.getFalseBindings();
}
}
return BindSet.noBindings();
}
@Override
public PSet<ASTVariableDeclaratorId> visit(ASTWhileStatement node, ReferenceCtx ctx) {
BindSet bindSet = bindersOfExpr(node.getCondition());
MyVisitor.this.setTopSymbolTableAndVisit(node.getCondition(), ctx);
int pushed = pushOnStack(f.localVarSymTable(top(), enclosing(), NodeStream.fromIterable(bindSet.getTrueBindings())));
setTopSymbolTableAndVisit(node.getBody(), ctx);
popStack(pushed);
if (hasNoBreakContainingStmt(node)) {
return bindSet.getFalseBindings();
}
return BindSet.noBindings();
}
@Override
public PSet<ASTVariableDeclaratorId> visit(ASTForStatement node, @NonNull ReferenceCtx ctx) {
int pushed = 0;
ASTStatement init = node.getInit();
if (init instanceof ASTLocalVariableDeclaration) {
pushed += processLocalVarDecl((ASTLocalVariableDeclaration) init, ctx);
} else {
setTopSymbolTableAndVisit(init, ctx);
}
ASTExpression condition = node.getCondition();
MyVisitor.this.setTopSymbolTableAndVisit(node.getCondition(), ctx);
BindSet bindSet = bindersOfExpr(condition);
pushed += pushOnStack(f.localVarSymTable(top(), enclosing(), bindSet.getTrueBindings()));
setTopSymbolTableAndVisit(node.getUpdate(), ctx);
setTopSymbolTableAndVisit(node.getBody(), ctx);
popStack(pushed);
if (bindSet.getFalseBindings().isEmpty()) {
return BindSet.noBindings();
} else {
// A pattern variable is introduced by a basic for statement iff
// (i) it is introduced by the condition expression when false and
// (ii) the contained statement, S, does not contain a reachable
// break statement whose break target contains S (§14.15).
if (hasNoBreakContainingStmt(node)) {
return bindSet.getFalseBindings();
} else {
return BindSet.noBindings();
}
}
}
private boolean hasNoBreakContainingStmt(ASTLoopStatement node) {
Set<JavaNode> containingStatements = node.ancestorsOrSelf()
.filter(JavaAstUtils::mayBeBreakTarget)
.collect(Collectors.toSet());
return node.getBody()
.descendants(ASTBreakStatement.class)
.none(it -> containingStatements.contains(it.getTarget()));
}
// shadow the methods of the outer class to visit with this visitor.
@SuppressWarnings("PMD.UnusedPrivateMethod")
private void setTopSymbolTableAndVisitAllChildren(JavaNode node, @NonNull ReferenceCtx ctx) {
if (node == null) {
return;
}
setTopSymbolTable(node);
visitChildren(node, ctx);
}
private void setTopSymbolTableAndVisit(JavaNode node, @NonNull ReferenceCtx ctx) {
if (node == null) {
return;
}
setTopSymbolTable(node);
node.acceptVisitor(this, ctx);
}
}
// <editor-fold defaultstate="collapsed" desc="Stack manipulation routines">
private void setTopSymbolTable(JavaNode node) {
InternalApiBridge.setSymbolTable(node, top());
}
private JClassType enclosing() {
return enclosingType.getFirst().getTypeMirror();
}
// this does not visit the given node, only its children
private void setTopSymbolTableAndVisitAllChildren(JavaNode node, @NonNull ReferenceCtx ctx) {
if (node == null) {
return;
}
setTopSymbolTable(node);
visitChildren(node, ctx);
}
private void setTopSymbolTableAndVisit(JavaNode node, @NonNull ReferenceCtx ctx) {
if (node == null) {
return;
}
setTopSymbolTable(node);
node.acceptVisitor(this, ctx);
}
private int pushOnStack(JSymbolTable table) {
if (table == top()) { // NOPMD CompareObjectsWithEquals
return 0; // and don't set the stack top
}
stack.push(table);
return 1;
}
private JSymbolTable popStack() {
return stack.pop();
}
private void popStack(int times) {
assert stack.size() > times : "Stack is too small (" + times + ") " + stack;
while (times-- > 0) {
popStack();
}
}
private JSymbolTable top() {
return stack.getFirst();
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Convenience methods">
static NodeStream<ASTLocalVariableDeclaration> stmtsOfResources(ASTResourceList node) {
return node.toStream().map(ASTResource::asLocalVariableDeclaration);
}
static NodeStream<ASTVariableDeclaratorId> formalsOf(ASTLambdaExpression node) {
return node.getParameters().toStream().map(ASTLambdaParameter::getVarId);
}
// </editor-fold>
}
}
| 32,270 | 41.184314 | 152 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/internal/SuperTypesEnumerator.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.table.internal;
import static java.util.Collections.emptySet;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.util.IteratorUtil;
import net.sourceforge.pmd.util.IteratorUtil.AbstractIterator;
/**
* Strategies to enumerate a type hierarchy.
*/
public enum SuperTypesEnumerator {
JUST_SELF {
@Override
public Iterator<JClassType> iterator(JClassType t) {
return IteratorUtil.singletonIterator(t);
}
},
/**
* Superclasses of t, including t, in innermost to outermost. If t
* is an interface, contains t, and Object.
*/
SUPERCLASSES_AND_SELF {
@Override
public Iterator<JClassType> iterator(JClassType t) {
return IteratorUtil.generate(t, JClassType::getSuperClass);
}
},
/**
* All direct strict supertypes, starting with the superclass if
* it exists. This includes Object if the search starts on an interface.
*/
DIRECT_STRICT_SUPERTYPES {
@Override
public Iterator<JClassType> iterator(JClassType t) {
return iterable(t).iterator();
}
@Override
public Iterable<JClassType> iterable(JClassType t) {
@Nullable JClassType sup = t.getSuperClass();
List<JClassType> superItfs = t.getSuperInterfaces();
@SuppressWarnings("PMD.LooseCoupling") // the set should keep insertion order
LinkedHashSet<JClassType> set;
if (sup != null) {
set = new LinkedHashSet<>(superItfs.size() + 1);
set.add(sup);
} else {
if (superItfs.isEmpty()) {
return emptySet();
}
set = new LinkedHashSet<>(superItfs.size());
}
set.addAll(superItfs);
return set;
}
},
/**
* Restriction of {@link #ALL_SUPERTYPES_INCLUDING_SELF} to just the
* strict supertypes. This includes Object if the search starts
* on an interface.
*/
ALL_STRICT_SUPERTYPES {
@Override
public Iterator<JClassType> iterator(JClassType t) {
Iterator<JClassType> iter = ALL_SUPERTYPES_INCLUDING_SELF.iterator(t);
IteratorUtil.advance(iter, 1);
return iter;
}
},
/**
* Walks supertypes depth-first, without duplicates. This includes
* Object if the search starts on an interface. For example for the following:
* <pre>{@code
*
* interface I1 { } // yields I1, Object
*
* interface I2 extends I1 { } // yields I2, Object, I1
*
* class Sup implements I2 { } // yields Sup, Object, I2, I1
*
* class Sub extends Sup implements I1 { } // yields Sub, Sup, Object, I2, I1
*
* }</pre>
*/
ALL_SUPERTYPES_INCLUDING_SELF {
@Override
public Iterator<JClassType> iterator(JClassType t) {
return new SuperTypeWalker(t);
}
};
public abstract Iterator<JClassType> iterator(JClassType t);
public Stream<JClassType> stream(JClassType t) {
return StreamSupport.stream(iterable(t).spliterator(), false);
}
public Iterable<JClassType> iterable(JClassType t) {
return () -> iterator(t);
}
private static class SuperTypeWalker extends AbstractIterator<JClassType> {
final Set<JClassType> seen = new HashSet<>();
final Deque<JClassType> todo = new ArrayDeque<>(2);
SuperTypeWalker(JClassType start) {
todo.push(start);
}
@Override
protected void computeNext() {
if (todo.isEmpty()) {
done();
} else {
JClassType top = todo.pollFirst();
setNext(top);
enqueue(top);
}
}
private void enqueue(final JClassType c) {
JClassType sup = c.getSuperClass();
if (sup != null && seen.add(sup)) {
todo.addFirst(sup);
}
for (final JClassType iface : c.getSuperInterfaces()) {
if (seen.add(iface)) {
todo.addLast(iface);
}
}
}
}
}
| 4,700 | 28.198758 | 89 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/internal/AbruptCompletionAnalysis.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.table.internal;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;
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.ASTBlock;
import net.sourceforge.pmd.lang.java.ast.ASTBreakStatement;
import net.sourceforge.pmd.lang.java.ast.ASTCatchClause;
import net.sourceforge.pmd.lang.java.ast.ASTContinueStatement;
import net.sourceforge.pmd.lang.java.ast.ASTDoStatement;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTFinallyClause;
import net.sourceforge.pmd.lang.java.ast.ASTForStatement;
import net.sourceforge.pmd.lang.java.ast.ASTForeachStatement;
import net.sourceforge.pmd.lang.java.ast.ASTIfStatement;
import net.sourceforge.pmd.lang.java.ast.ASTLabeledStatement;
import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement;
import net.sourceforge.pmd.lang.java.ast.ASTStatement;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchArrowBranch;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchArrowRHS;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchBranch;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchFallthroughBranch;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchStatement;
import net.sourceforge.pmd.lang.java.ast.ASTSynchronizedStatement;
import net.sourceforge.pmd.lang.java.ast.ASTThrowStatement;
import net.sourceforge.pmd.lang.java.ast.ASTTryStatement;
import net.sourceforge.pmd.lang.java.ast.ASTWhileStatement;
import net.sourceforge.pmd.lang.java.ast.ASTYieldStatement;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.ast.JavaVisitorBase;
import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils;
import net.sourceforge.pmd.lang.java.symbols.table.internal.AbruptCompletionAnalysis.ReachabilityVisitor.VisitResult;
import net.sourceforge.pmd.util.AssertionUtil;
/**
* Implementation of {@link #canCompleteNormally(ASTStatement)}, which
* is used to implement scoping of pattern variables.
*
* @see <a href="https://docs.oracle.com/javase/specs/jls/se17/html/jls-14.html#jls-14.22">Java Language Specification</a>
*/
final class AbruptCompletionAnalysis {
private AbruptCompletionAnalysis() {
// util class
}
/**
* Returns whether the statement can complete normally, assuming
* it is reachable. For instance, an expression statement may
* complete normally, while a return or throw always complete abruptly.
*/
static boolean canCompleteNormally(ASTStatement stmt) {
return stmt.acceptVisitor(new ReachabilityVisitor(), new SubtreeState(f -> VisitResult.Continue));
}
/**
* This visitor implements a reachability analysis: it only visits
* reachable statements in a given subtree (assuming the first
* statement visited is reachable). Statements are not visited in
* a particular order, the only guarantee is that reachable statements
* are visited. Note that the right-hand side of switch arrow branches
* is not visited unless it is a statement.
*
* The return value of the visitor is whether the visited statement
* can complete normally.
*/
static final class ReachabilityVisitor extends JavaVisitorBase<SubtreeState, Boolean> {
enum VisitResult {
Continue,
Abort
}
static class VisitAbortedException extends RuntimeException {
static final VisitAbortedException INSTANCE = new VisitAbortedException();
}
@Override
public Boolean visit(ASTBlock node, SubtreeState data) {
recordReachableNode(node, data);
return blockCanCompleteNormally(node, data);
}
private boolean blockCanCompleteNormally(Iterable<ASTStatement> node, SubtreeState data) {
for (ASTStatement statement : node) {
boolean canCompleteNormally = statement.acceptVisitor(this, new SubtreeState(data));
if (!canCompleteNormally) {
// and further statements are unreachable
return false;
}
}
return true;
}
@Override
public Boolean visitJavaNode(JavaNode node, SubtreeState data) {
throw AssertionUtil.shouldNotReachHere("Cannot visit non-statements");
}
@Override
public Boolean visitStatement(ASTStatement node, SubtreeState data) {
// assert, empty stmt
recordReachableNode(node, data);
return true;
}
@Override
public Boolean visit(ASTThrowStatement node, SubtreeState data) {
recordReachableNode(node, data);
return false;
}
@Override
public Boolean visit(ASTReturnStatement node, SubtreeState data) {
recordReachableNode(node, data);
return false;
}
@Override
public Boolean visit(ASTBreakStatement node, SubtreeState data) {
recordReachableNode(node, data);
data.addBreak(node);
return false;
}
@Override
public Boolean visit(ASTYieldStatement node, SubtreeState data) {
recordReachableNode(node, data);
data.addYield(node);
return false;
}
@Override
public Boolean visit(ASTContinueStatement node, SubtreeState data) {
recordReachableNode(node, data);
data.addContinue(node);
return false;
}
@Override
public Boolean visit(ASTIfStatement node, SubtreeState data) {
recordReachableNode(node, data);
boolean thenCanCompleteNormally = node.getThenBranch().acceptVisitor(this, data);
boolean elseCanCompleteNormally = node.getElseBranch() == null
|| node.getElseBranch().acceptVisitor(this, data);
return thenCanCompleteNormally || elseCanCompleteNormally;
}
@Override
public Boolean visit(ASTSynchronizedStatement node, SubtreeState data) {
recordReachableNode(node, data);
return node.getBody().acceptVisitor(this, data);
}
@Override
public Boolean visit(ASTLabeledStatement node, SubtreeState data) {
recordReachableNode(node, data);
boolean stmtCanCompleteNormally = node.getStatement().acceptVisitor(this, data);
return stmtCanCompleteNormally || data.containsBreak(node);
}
@Override
public Boolean visit(ASTForeachStatement node, SubtreeState data) {
recordReachableNode(node, data);
node.getBody().acceptVisitor(this, data);
return true;
}
@Override
public Boolean visit(ASTDoStatement node, SubtreeState data) {
recordReachableNode(node, data);
boolean bodyCompletesNormally = node.getBody().acceptVisitor(this, data);
boolean isNotDoWhileTrue = !JavaAstUtils.isBooleanLiteral(node.getCondition(), true);
return isNotDoWhileTrue && (bodyCompletesNormally || data.containsContinue(node))
|| data.containsBreak(node);
}
@Override
public Boolean visit(ASTSwitchStatement node, SubtreeState data) {
// note: exhaustive enum switches are NOT considered exhaustive
// for the purposes of liveness analysis, only the presence of a
// default case matters. Otherwise liveness analysis would depend
// on type resolution and bad things would happen.
boolean isExhaustive = node.hasDefaultCase();
boolean completesNormally = true;
boolean first = true;
for (ASTSwitchBranch branch : node.getBranches()) {
boolean branchCompletesNormally;
if (branch instanceof ASTSwitchArrowBranch) {
ASTSwitchArrowRHS rhs = ((ASTSwitchArrowBranch) branch).getRightHandSide();
branchCompletesNormally = switchArrowBranchCompletesNormally(new SubtreeState(data), node, rhs);
} else if (branch instanceof ASTSwitchFallthroughBranch) {
NodeStream<ASTStatement> statements = ((ASTSwitchFallthroughBranch) branch).getStatements();
SubtreeState branchState = new SubtreeState(data);
branchCompletesNormally = blockCanCompleteNormally(statements, branchState)
|| branchState.containsBreak(node);
} else {
throw AssertionUtil.shouldNotReachHere("Not a branch type :" + branch);
}
if (isExhaustive && first) {
completesNormally = branchCompletesNormally;
first = false;
} else {
completesNormally = completesNormally || branchCompletesNormally;
}
}
return completesNormally;
}
private boolean switchArrowBranchCompletesNormally(SubtreeState state, ASTSwitchStatement switchStmt, ASTSwitchArrowRHS rhs) {
if (rhs instanceof ASTExpression) {
return true;
} else if (rhs instanceof ASTThrowStatement) {
return false;
} else if (rhs instanceof ASTBlock) {
return ((ASTBlock) rhs).acceptVisitor(this, state) || state.containsBreak(switchStmt);
} else {
throw AssertionUtil.shouldNotReachHere("not a branch RHS: " + rhs);
}
}
@Override
public Boolean visit(ASTWhileStatement node, SubtreeState data) {
recordReachableNode(node, data);
node.getBody().acceptVisitor(this, data);
boolean isNotWhileTrue = !JavaAstUtils.isBooleanLiteral(node.getCondition(), true);
return isNotWhileTrue || data.containsBreak(node);
}
@Override
public Boolean visit(ASTForStatement node, SubtreeState data) {
recordReachableNode(node, data);
node.getBody().acceptVisitor(this, data);
boolean isNotForTrue = node.getCondition() != null
&& !JavaAstUtils.isBooleanLiteral(node.getCondition(), true);
return isNotForTrue || data.containsBreak(node);
}
@Override
public Boolean visit(ASTTryStatement node, SubtreeState data) {
recordReachableNode(node, data);
ASTFinallyClause finallyClause = node.getFinallyClause();
boolean finallyCompletesNormally = true;
if (finallyClause != null) {
finallyCompletesNormally = finallyClause.getBody().acceptVisitor(this, new SubtreeState(data));
}
SubtreeState bodyState = tryClauseState(data, finallyCompletesNormally);
boolean bodyCompletesNormally = node.getBody().acceptVisitor(this, bodyState);
/*
Todo catch clauses are not automatically reachable.
A catch block C is reachable iff both of the following are true:
- Either the type of C's parameter is an unchecked exception type
or Exception or a superclass of Exception, or some expression
or throw statement in the try block is reachable and can throw
a checked exception whose type is assignment compatible (§5.2)
with the type of C's parameter. (An expression is reachable iff
the innermost statement containing it is reachable.)
- There is no earlier catch block A in the try statement such that
the type of C's parameter is the same as, or a subclass of,
the type of A's parameter.
*/
boolean anyCatchClauseCompletesNormally = false;
for (ASTCatchClause catchClause : node.getCatchClauses()) {
SubtreeState subtree = tryClauseState(data, finallyCompletesNormally);
anyCatchClauseCompletesNormally |= catchClause.getBody().acceptVisitor(this, subtree);
}
return finallyCompletesNormally
&& (bodyCompletesNormally || anyCatchClauseCompletesNormally);
}
private SubtreeState tryClauseState(SubtreeState data, boolean finallyCompletesNormally) {
SubtreeState bodyState = new SubtreeState(data);
if (!finallyCompletesNormally) {
bodyState.ignoreBreaksAndContinues = true;
}
return bodyState;
}
private void recordReachableNode(ASTStatement node, SubtreeState data) {
if (data.shouldContinue.apply(node) == VisitResult.Abort) {
throw abortVisit();
}
}
private static @NonNull VisitAbortedException abortVisit() {
return VisitAbortedException.INSTANCE;
}
}
/**
* Tracks exploration state of a subtree. A new one is created for
* independent subtrees (eg in the handling for blocks). Children
* state instances forward events to their parent (as these events
* are part of the subtree of their parents).
*/
private static class SubtreeState {
private final @Nullable SubtreeState parent;
public boolean ignoreBreaksAndContinues;
private Set<JavaNode> breakTargets = Collections.emptySet();
private Set<ASTStatement> continueTargets = Collections.emptySet();
private final Function<? super ASTStatement, VisitResult> shouldContinue;
SubtreeState(Function<? super ASTStatement, VisitResult> shouldContinue) {
this.parent = null;
this.shouldContinue = shouldContinue;
}
SubtreeState(SubtreeState parent) {
this.parent = parent;
this.shouldContinue = parent.shouldContinue;
}
public boolean isIgnoreBreaksAndContinues() {
return ignoreBreaksAndContinues || parent != null && parent.isIgnoreBreaksAndContinues();
}
boolean containsBreak(ASTStatement stmt) {
return breakTargets.contains(stmt);
}
boolean containsContinue(ASTStatement stmt) {
return continueTargets.contains(stmt);
}
void addBreak(ASTBreakStatement breakStatement) {
addBreakImpl(breakStatement.getTarget());
}
void addYield(ASTYieldStatement yieldStmt) {
addBreakImpl(yieldStmt.getYieldTarget());
}
private void addBreakImpl(JavaNode breakTargetStatement) {
if (isIgnoreBreaksAndContinues()) {
return;
}
if (breakTargets.isEmpty()) {
breakTargets = new HashSet<>();
}
breakTargets.add(breakTargetStatement);
if (parent != null) {
parent.addBreakImpl(breakTargetStatement);
}
}
void addContinue(ASTContinueStatement continueStatement) {
if (isIgnoreBreaksAndContinues()) {
return;
}
if (continueTargets.isEmpty()) {
continueTargets = new HashSet<>();
}
continueTargets.add(continueStatement.getTarget());
if (parent != null) {
parent.addContinue(continueStatement);
}
}
}
}
| 15,734 | 38.634761 | 134 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/internal/SymbolTableImpl.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.table.internal;
import net.sourceforge.pmd.lang.java.symbols.table.JSymbolTable;
import net.sourceforge.pmd.lang.java.symbols.table.ScopeInfo;
import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.ShadowChain;
import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.ShadowChainBuilder;
import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.ShadowChainNode;
import net.sourceforge.pmd.lang.java.types.JMethodSig;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.JVariableSig;
final class SymbolTableImpl implements JSymbolTable {
static final JSymbolTable EMPTY = new SymbolTableImpl(ShadowChainBuilder.rootGroup(), ShadowChainBuilder.rootGroup(), ShadowChainBuilder.rootGroup());
private final ShadowChainNode<JVariableSig, ScopeInfo> vars;
private final ShadowChainNode<JTypeMirror, ScopeInfo> types;
private final ShadowChainNode<JMethodSig, ScopeInfo> methods;
SymbolTableImpl(ShadowChainNode<JVariableSig, ScopeInfo> vars,
ShadowChainNode<JTypeMirror, ScopeInfo> types,
ShadowChainNode<JMethodSig, ScopeInfo> methods) {
this.vars = vars;
this.types = types;
this.methods = methods;
}
@Override
public ShadowChain<JVariableSig, ScopeInfo> variables() {
return vars.asChain();
}
@Override
public ShadowChain<JTypeMirror, ScopeInfo> types() {
return types.asChain();
}
@Override
public ShadowChain<JMethodSig, ScopeInfo> methods() {
return methods.asChain();
}
@Override
public String toString() {
return "NSymTableImpl{"
+ "vars=" + vars
+ ", types=" + types
+ ", methods=" + methods
+ '}';
}
static JSymbolTable withVars(JSymbolTable parent, ShadowChainNode<JVariableSig, ScopeInfo> vars) {
return new SymbolTableImpl(vars, parent.types().asNode(), parent.methods().asNode());
}
static JSymbolTable withTypes(JSymbolTable parent, ShadowChainNode<JTypeMirror, ScopeInfo> types) {
return new SymbolTableImpl(parent.variables().asNode(), types, parent.methods().asNode());
}
}
| 2,336 | 35.515625 | 154 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/internal/PatternBindingsUtil.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.table.internal;
import org.pcollections.HashTreePSet;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTInfixExpression;
import net.sourceforge.pmd.lang.java.ast.ASTPattern;
import net.sourceforge.pmd.lang.java.ast.ASTPatternExpression;
import net.sourceforge.pmd.lang.java.ast.ASTRecordPattern;
import net.sourceforge.pmd.lang.java.ast.ASTTypePattern;
import net.sourceforge.pmd.lang.java.ast.ASTUnaryExpression;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.ast.BinaryOp;
import net.sourceforge.pmd.lang.java.ast.UnaryOp;
import net.sourceforge.pmd.util.AssertionUtil;
/**
* Utilities to resolve scope of pattern binding variables.
*
* @see <a href="https://docs.oracle.com/javase/specs/jls/se17/html/jls-6.html#jls-6.3.1">Java Language Specification</a>
*/
final class PatternBindingsUtil {
private PatternBindingsUtil() {
// util class
}
/**
* Returns the binding set declared by the expression. Note that
* only some expressions contribute bindings, and every other form
* of expression does not contribute anything (meaning, all subexpressions
* are not processed).
*/
static BindSet bindersOfExpr(ASTExpression e) {
/*
JLS 17§6.3.1
If an expression is not a conditional-and expression, conditional-or
expression, logical complement expression, conditional expression,
instanceof expression, switch expression, or parenthesized
expression, then no scope rules apply.
*/
if (e instanceof ASTUnaryExpression) {
ASTUnaryExpression unary = (ASTUnaryExpression) e;
return unary.getOperator() == UnaryOp.NEGATION
? bindersOfExpr(unary.getOperand()).negate()
: BindSet.EMPTY;
} else if (e instanceof ASTInfixExpression) {
BinaryOp op = ((ASTInfixExpression) e).getOperator();
ASTExpression left = ((ASTInfixExpression) e).getLeftOperand();
ASTExpression right = ((ASTInfixExpression) e).getRightOperand();
if (op == BinaryOp.INSTANCEOF && right instanceof ASTPatternExpression) {
return bindersOfPattern(((ASTPatternExpression) right).getPattern());
} else if (op == BinaryOp.CONDITIONAL_AND) { // &&
// A pattern variable is introduced by a && b when true iff either
// (i) it is introduced by a when true or
// (ii) it is introduced by b when true.
return BindSet.whenTrue(
bindersOfExpr(left).trueBindings.plusAll(bindersOfExpr(right).trueBindings)
);
} else if (op == BinaryOp.CONDITIONAL_OR) { // ||
// A pattern variable is introduced by a || b when false iff either
// (i) it is introduced by a when false or
// (ii) it is introduced by b when false.
return BindSet.whenFalse(
bindersOfExpr(left).falseBindings.plusAll(bindersOfExpr(right).falseBindings)
);
} else {
return BindSet.EMPTY;
}
} else if (e instanceof ASTPatternExpression) {
return bindersOfPattern(((ASTPatternExpression) e).getPattern());
}
return BindSet.EMPTY;
}
static BindSet bindersOfPattern(ASTPattern pattern) {
if (pattern instanceof ASTTypePattern) {
return BindSet.whenTrue(HashTreePSet.singleton(((ASTTypePattern) pattern).getVarId()));
} else if (pattern instanceof ASTRecordPattern) {
// record pattern might not bind a variable for the whole record...
ASTVariableDeclaratorId varId = ((ASTRecordPattern) pattern).getVarId();
if (varId == null) {
return BindSet.whenTrue(BindSet.noBindings());
}
return BindSet.whenTrue(HashTreePSet.singleton(varId));
} else {
throw AssertionUtil.shouldNotReachHere("no other instances of pattern should exist: " + pattern);
}
}
/**
* A set of bindings contributed by a (boolean) expression. Different
* bindings are introduced if the expr evaluates to false or true, which
* is relevant for the scope of bindings introduced in if stmt conditions.
*/
static final class BindSet {
static final BindSet EMPTY = new BindSet(HashTreePSet.empty(),
HashTreePSet.empty());
private final PSet<ASTVariableDeclaratorId> trueBindings;
private final PSet<ASTVariableDeclaratorId> falseBindings;
public BindSet union(BindSet bindSet) {
if (this.isEmpty()) {
return bindSet;
} else if (bindSet.isEmpty()) {
return this;
}
return new BindSet(
trueBindings.plusAll(bindSet.trueBindings),
falseBindings.plusAll(bindSet.falseBindings)
);
}
static PSet<ASTVariableDeclaratorId> noBindings() {
return HashTreePSet.empty();
}
BindSet(PSet<ASTVariableDeclaratorId> trueBindings,
PSet<ASTVariableDeclaratorId> falseBindings) {
this.trueBindings = trueBindings;
this.falseBindings = falseBindings;
}
public PSet<ASTVariableDeclaratorId> getTrueBindings() {
return trueBindings;
}
public PSet<ASTVariableDeclaratorId> getFalseBindings() {
return falseBindings;
}
BindSet negate() {
return isEmpty() ? this : new BindSet(falseBindings, trueBindings);
}
boolean isEmpty() {
return this == EMPTY;
}
BindSet addBinding(ASTVariableDeclaratorId e) {
return new BindSet(trueBindings.plus(e), falseBindings);
}
static BindSet whenTrue(PSet<ASTVariableDeclaratorId> bindings) {
return new BindSet(bindings, HashTreePSet.empty());
}
static BindSet whenFalse(PSet<ASTVariableDeclaratorId> bindings) {
return new BindSet(HashTreePSet.empty(), bindings);
}
}
}
| 6,479 | 36.894737 | 121 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/internal/SymTableFactory.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.table.internal;
import static net.sourceforge.pmd.lang.java.symbols.table.ScopeInfo.FORMAL_PARAM;
import static net.sourceforge.pmd.lang.java.symbols.table.ScopeInfo.SAME_FILE;
import static net.sourceforge.pmd.util.AssertionUtil.isValidJavaPackageName;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BinaryOperator;
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.ast.NodeStream;
import net.sourceforge.pmd.lang.ast.SemanticErrorReporter;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTFormalParameters;
import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTList;
import net.sourceforge.pmd.lang.java.ast.ASTTypeParameter;
import net.sourceforge.pmd.lang.java.ast.ASTTypeParameters;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.ast.InternalApiBridge;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
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.JFormalParamSymbol;
import net.sourceforge.pmd.lang.java.symbols.JLocalVariableSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolResolver;
import net.sourceforge.pmd.lang.java.symbols.table.JSymbolTable;
import net.sourceforge.pmd.lang.java.symbols.table.ScopeInfo;
import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.NameResolver;
import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.ShadowChainBuilder;
import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.ShadowChainNode;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.JMethodSig;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.JTypeVar;
import net.sourceforge.pmd.lang.java.types.JVariableSig;
import net.sourceforge.pmd.util.CollectionUtil;
final class SymTableFactory {
private final String thisPackage;
private final JavaAstProcessor processor;
static final ShadowChainBuilder<JTypeMirror, ScopeInfo> TYPES = new ShadowChainBuilder<JTypeMirror, ScopeInfo>() {
@Override
public String getSimpleName(JTypeMirror type) {
if (type instanceof JClassType) {
return ((JClassType) type).getSymbol().getSimpleName();
} else if (type instanceof JTypeVar) {
JTypeDeclSymbol sym = type.getSymbol();
assert sym != null : "Must contain named symbols";
return sym.getSimpleName();
}
throw new AssertionError("Cannot contain type " + type);
}
};
static final ShadowChainBuilder<JVariableSig, ScopeInfo> VARS = new ShadowChainBuilder<JVariableSig, ScopeInfo>() {
@Override
public String getSimpleName(JVariableSig sym) {
return sym.getSymbol().getSimpleName();
}
};
static final ShadowChainBuilder<JMethodSig, ScopeInfo> METHODS = new ShadowChainBuilder<JMethodSig, ScopeInfo>() {
@Override
public String getSimpleName(JMethodSig sym) {
return sym.getName();
}
};
SymTableFactory(String thisPackage, JavaAstProcessor processor) {
this.thisPackage = thisPackage;
this.processor = processor;
}
// <editor-fold defaultstate="collapsed" desc="Utilities for classloading">
public void disambig(NodeStream<? extends JavaNode> nodes, ReferenceCtx context) {
InternalApiBridge.disambigWithCtx(nodes, context);
}
SemanticErrorReporter getLogger() {
return processor.getLogger();
}
JClassSymbol loadClassReportFailure(JavaNode location, String fqcn) {
JClassSymbol loaded = loadClassOrFail(fqcn);
if (loaded == null) {
getLogger().warning(location, JavaSemanticErrors.CANNOT_RESOLVE_SYMBOL, fqcn);
}
return loaded;
}
/** @see SymbolResolver#resolveClassFromCanonicalName(String) */
@Nullable
JClassSymbol loadClassOrFail(String fqcn) {
return processor.getSymResolver().resolveClassFromCanonicalName(fqcn);
}
// </editor-fold>
private @NonNull JSymbolTable buildTable(JSymbolTable parent,
ShadowChainNode<JVariableSig, ScopeInfo> vars,
ShadowChainNode<JMethodSig, ScopeInfo> methods,
ShadowChainNode<JTypeMirror, ScopeInfo> types) {
if (vars == parent.variables() && methods == parent.methods() && types == parent.types()) { // NOPMD CompareObjectsWithEquals
return parent;
} else {
return new SymbolTableImpl(vars, types, methods);
}
}
private ShadowChainNode<JTypeMirror, ScopeInfo> typeNode(JSymbolTable parent) {
return parent.types().asNode();
}
private ShadowChainNode<JVariableSig, ScopeInfo> varNode(JSymbolTable parent) {
return parent.variables().asNode();
}
private ShadowChainNode<JMethodSig, ScopeInfo> methodNode(JSymbolTable parent) {
return parent.methods().asNode();
}
JSymbolTable importsOnDemand(JSymbolTable parent, Collection<ASTImportDeclaration> importsOnDemand) {
if (importsOnDemand.isEmpty()) {
return parent;
}
ShadowChainBuilder<JTypeMirror, ScopeInfo>.ResolverBuilder importedTypes = TYPES.new ResolverBuilder();
ShadowChainBuilder<JVariableSig, ScopeInfo>.ResolverBuilder importedFields = VARS.new ResolverBuilder();
List<JClassType> importedMethodContainers = new ArrayList<>();
Set<String> lazyImportedPackagesAndTypes = new LinkedHashSet<>();
fillImportOnDemands(importsOnDemand, importedTypes, importedFields, importedMethodContainers, lazyImportedPackagesAndTypes);
NameResolver<JMethodSig> methodResolver =
NameResolver.composite(CollectionUtil.map(importedMethodContainers, c -> JavaResolvers.staticImportOnDemandMethodResolver(c, thisPackage)));
ShadowChainNode<JVariableSig, ScopeInfo> vars = VARS.shadow(varNode(parent), ScopeInfo.IMPORT_ON_DEMAND, importedFields);
ShadowChainNode<JMethodSig, ScopeInfo> methods = METHODS.shadow(methodNode(parent), ScopeInfo.IMPORT_ON_DEMAND, methodResolver);
ShadowChainNode<JTypeMirror, ScopeInfo> types;
if (lazyImportedPackagesAndTypes.isEmpty()) {
// then we don't need to use the lazy impl
types = TYPES.shadow(typeNode(parent), ScopeInfo.IMPORT_ON_DEMAND, importedTypes);
} else {
types = TYPES.shadowWithCache(
typeNode(parent),
ScopeInfo.IMPORT_ON_DEMAND,
importedTypes.getMutableMap(),
JavaResolvers.importedOnDemand(lazyImportedPackagesAndTypes, processor.getSymResolver(), thisPackage)
);
}
return buildTable(parent, vars, methods, types);
}
private void fillImportOnDemands(Iterable<ASTImportDeclaration> importsOnDemand,
ShadowChainBuilder<JTypeMirror, ?>.ResolverBuilder importedTypes,
ShadowChainBuilder<JVariableSig, ?>.ResolverBuilder importedFields,
List<JClassType> importedMethodContainers,
Set<String> importedPackagesAndTypes) {
for (ASTImportDeclaration anImport : importsOnDemand) {
assert anImport.isImportOnDemand() : "Expected import on demand: " + anImport;
if (anImport.isStatic()) {
// Static-Import-on-Demand Declaration
// A static-import-on-demand declaration allows all accessible static members of a named type to be imported as needed.
// includes types members, methods & fields
@Nullable JClassSymbol containerClass = loadClassReportFailure(anImport, anImport.getImportedName());
if (containerClass != null) {
// populate the inherited state
JClassType containerType = (JClassType) containerClass.getTypeSystem().typeOf(containerClass, false);
Pair<ShadowChainBuilder<JTypeMirror, ?>.ResolverBuilder, ShadowChainBuilder<JVariableSig, ?>.ResolverBuilder> pair =
JavaResolvers.importOnDemandMembersResolvers(containerType, thisPackage);
importedTypes.absorb(pair.getLeft());
importedFields.absorb(pair.getRight());
importedMethodContainers.add(containerType);
}
// can't be resolved sorry
} else {
// Type-Import-on-Demand Declaration
// This is of the kind <packageName>.*;
importedPackagesAndTypes.add(anImport.getPackageName());
}
}
}
JSymbolTable singleImportsSymbolTable(JSymbolTable parent, Collection<ASTImportDeclaration> singleImports) {
if (singleImports.isEmpty()) {
return parent;
}
ShadowChainBuilder<JTypeMirror, ScopeInfo>.ResolverBuilder importedTypes = TYPES.new ResolverBuilder();
List<NameResolver<? extends JTypeMirror>> importedStaticTypes = new ArrayList<>();
List<NameResolver<? extends JVariableSig>> importedStaticFields = new ArrayList<>();
List<NameResolver<? extends JMethodSig>> importedStaticMethods = new ArrayList<>();
fillSingleImports(singleImports, importedTypes);
fillSingleStaticImports(singleImports, importedStaticTypes, importedStaticFields, importedStaticMethods);
return buildTable(
parent,
VARS.shadow(varNode(parent), ScopeInfo.SINGLE_IMPORT, NameResolver.composite(importedStaticFields)),
METHODS.shadow(methodNode(parent), ScopeInfo.SINGLE_IMPORT, NameResolver.composite(importedStaticMethods)),
TYPES.augment(
TYPES.shadow(typeNode(parent), ScopeInfo.SINGLE_IMPORT, importedTypes.build()),
false,
ScopeInfo.SINGLE_IMPORT,
NameResolver.composite(importedStaticTypes)
)
);
}
private void fillSingleImports(Iterable<ASTImportDeclaration> singleImports,
ShadowChainBuilder<JTypeMirror, ?>.ResolverBuilder importedTypes) {
for (ASTImportDeclaration anImport : singleImports) {
if (anImport.isImportOnDemand()) {
throw new IllegalArgumentException(anImport.toString());
}
if (!anImport.isStatic()) {
// Single-Type-Import Declaration
JClassSymbol type = processor.findSymbolCannotFail(anImport, anImport.getImportedName());
importedTypes.append(type.getTypeSystem().typeOf(type, false));
}
}
}
private void fillSingleStaticImports(Iterable<ASTImportDeclaration> singleImports,
List<NameResolver<? extends JTypeMirror>> importedTypes,
List<NameResolver<? extends JVariableSig>> importedFields,
List<NameResolver<? extends JMethodSig>> importedStaticMethods) {
for (ASTImportDeclaration anImport : singleImports) {
if (anImport.isImportOnDemand()) {
throw new IllegalArgumentException(anImport.toString());
}
String simpleName = anImport.getImportedSimpleName();
String name = anImport.getImportedName();
if (anImport.isStatic()) {
// Single-Static-Import Declaration
// types, fields or methods having the same name
int idx = name.lastIndexOf('.');
if (idx < 0) {
continue; // invalid syntax
}
String className = name.substring(0, idx);
JClassSymbol containerClass = loadClassReportFailure(anImport, className);
if (containerClass == null) {
// the auxclasspath is wrong
// bc static imports can't import toplevel types
// already reported
continue;
}
JClassType containerType = (JClassType) containerClass.getTypeSystem().declaration(containerClass);
importedStaticMethods.add(JavaResolvers.staticImportMethodResolver(containerType, thisPackage, simpleName));
importedFields.add(JavaResolvers.staticImportFieldResolver(containerType, thisPackage, simpleName));
importedTypes.add(JavaResolvers.staticImportClassResolver(containerType, thisPackage, simpleName));
}
}
}
JSymbolTable javaLangSymTable(JSymbolTable parent) {
return typesInPackage(parent, "java.lang", ScopeInfo.JAVA_LANG);
}
JSymbolTable samePackageSymTable(JSymbolTable parent) {
return typesInPackage(parent, thisPackage, ScopeInfo.SAME_PACKAGE);
}
@NonNull
private JSymbolTable typesInPackage(JSymbolTable parent, String packageName, ScopeInfo scopeTag) {
assert isValidJavaPackageName(packageName) : "Not a package name: " + packageName;
return SymbolTableImpl.withTypes(
parent,
TYPES.augmentWithCache(typeNode(parent), true, scopeTag, JavaResolvers.packageResolver(processor.getSymResolver(), packageName))
);
}
JSymbolTable typeBody(JSymbolTable parent, @NonNull JClassType t) {
Pair<NameResolver<JTypeMirror>, NameResolver<JVariableSig>> inherited = JavaResolvers.inheritedMembersResolvers(t);
JClassSymbol sym = t.getSymbol();
ShadowChainNode<JTypeMirror, ScopeInfo> types = typeNode(parent);
if (!sym.isAnonymousClass()) {
types = TYPES.shadow(types, ScopeInfo.ENCLOSING_TYPE, t); // self name
}
types = TYPES.shadow(types, ScopeInfo.INHERITED, inherited.getLeft()); // inherited classes (note they shadow the enclosing type)
types = TYPES.shadow(types, ScopeInfo.ENCLOSING_TYPE_MEMBER, TYPES.groupByName(t.getDeclaredClasses())); // inner classes declared here
types = TYPES.shadow(types, ScopeInfo.TYPE_PARAM, TYPES.groupByName(sym.getTypeParameters())); // type parameters
ShadowChainNode<JVariableSig, ScopeInfo> fields = varNode(parent);
fields = VARS.shadow(fields, ScopeInfo.INHERITED, inherited.getRight());
fields = VARS.shadow(fields, ScopeInfo.ENCLOSING_TYPE_MEMBER, VARS.groupByName(t.getDeclaredFields()));
ShadowChainNode<JMethodSig, ScopeInfo> methods = methodNode(parent);
BinaryOperator<List<JMethodSig>> merger = JavaResolvers.methodMerger(Modifier.isStatic(t.getSymbol().getModifiers()));
methods = METHODS.augmentWithCache(methods, false, ScopeInfo.METHOD_MEMBER, JavaResolvers.subtypeMethodResolver(t), merger);
return buildTable(parent, fields, methods, types);
}
JSymbolTable typesInFile(JSymbolTable parent, NodeStream<ASTAnyTypeDeclaration> decls) {
return SymbolTableImpl.withTypes(parent, TYPES.shadow(typeNode(parent), SAME_FILE, TYPES.groupByName(decls, ASTAnyTypeDeclaration::getTypeMirror)));
}
JSymbolTable selfType(JSymbolTable parent, JClassType sym) {
return SymbolTableImpl.withTypes(parent, TYPES.shadow(typeNode(parent), ScopeInfo.ENCLOSING_TYPE_MEMBER, TYPES.groupByName(sym)));
}
JSymbolTable typeHeader(JSymbolTable parent, JClassSymbol sym) {
return SymbolTableImpl.withTypes(parent, TYPES.shadow(typeNode(parent), ScopeInfo.TYPE_PARAM, TYPES.groupByName(sym.getTypeParameters())));
}
/**
* Symbol table for a body declaration. This places a shadowing
* group for variables, ie, nested variable shadowing groups will
* be merged into it but not into the parent. This implements shadowing
* of fields by local variables and formals.
*/
JSymbolTable bodyDeclaration(JSymbolTable parent, JClassType enclosing, @Nullable ASTFormalParameters formals, @Nullable ASTTypeParameters tparams) {
return new SymbolTableImpl(
VARS.shadow(varNode(parent), ScopeInfo.FORMAL_PARAM, VARS.groupByName(ASTList.orEmptyStream(formals), fp -> {
JVariableSymbol sym = fp.getVarId().getSymbol();
return sym.getTypeSystem().sigOf(enclosing, (JFormalParamSymbol) sym);
})),
TYPES.shadow(typeNode(parent), ScopeInfo.TYPE_PARAM, TYPES.groupByName(ASTList.orEmptyStream(tparams), ASTTypeParameter::getTypeMirror)),
methodNode(parent)
);
}
JSymbolTable recordCtor(JSymbolTable parent, JClassType recordType, JConstructorSymbol symbol) {
return SymbolTableImpl.withVars(parent, VARS.shadow(varNode(parent), FORMAL_PARAM, VARS.groupByName(symbol.getFormalParameters(), s -> s.getTypeSystem().sigOf(recordType, s))));
}
/**
* Local vars are merged into the parent shadowing group. They don't
* shadow other local vars, they conflict with them.
*/
JSymbolTable localVarSymTable(JSymbolTable parent, JClassType enclosing, Iterable<ASTVariableDeclaratorId> ids) {
List<JVariableSig> sigs = new ArrayList<>();
for (ASTVariableDeclaratorId id : ids) {
sigs.add(id.getTypeSystem().sigOf(enclosing, (JLocalVariableSymbol) id.getSymbol()));
}
return SymbolTableImpl.withVars(parent, VARS.augment(varNode(parent), false, ScopeInfo.LOCAL, VARS.groupByName(sigs)));
}
JSymbolTable localVarSymTable(JSymbolTable parent, JClassType enclosing, JVariableSymbol id) {
return SymbolTableImpl.withVars(parent, VARS.augment(varNode(parent), false, ScopeInfo.LOCAL, id.getTypeSystem().sigOf(enclosing, (JLocalVariableSymbol) id)));
}
JSymbolTable localTypeSymTable(JSymbolTable parent, JClassType sym) {
// TODO is this really not a shadow barrier?
return SymbolTableImpl.withTypes(parent, TYPES.augment(typeNode(parent), false, ScopeInfo.LOCAL, sym));
}
}
| 18,984 | 45.992574 | 185 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/FakeSymAnnot.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
/**
* Pretends to be an annotation with no explicit attributes.
*
* @author Clément Fournier
*/
public class FakeSymAnnot implements SymAnnot {
private final JClassSymbol annotationClass;
public FakeSymAnnot(JClassSymbol annotationClass) {
this.annotationClass = annotationClass;
assert annotationClass.isAnnotation() : "Not an annotation " + annotationClass;
}
@Override
public @Nullable SymbolicValue getAttribute(String attrName) {
return annotationClass.getDefaultAnnotationAttributeValue(attrName);
}
@Override
public @NonNull JClassSymbol getAnnotationSymbol() {
return annotationClass;
}
@Override
public String toString() {
return SymbolToStrings.FAKE.toString(this);
}
@Override
public boolean equals(Object o) {
return SymbolEquality.ANNOTATION.equals(this, o);
}
@Override
public int hashCode() {
return SymbolEquality.ANNOTATION.hash(this);
}
}
| 1,450 | 26.377358 | 87 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/UnresolvedClassStore.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal;
import java.util.HashMap;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
/**
* Keeps track of unresolved classes, can update some information about
* unresolved classes if needed. For example, creating a {@link JClassType}
* with a wrong number of type arguments is not allowed. If the symbol
* is unresolved, we don't have access to the type vars or their count.
* For that reason, the first time we encounter a parameterized class
* type, we set its arity, ie the number of type params it expects.
* Inconsistent numbers of type arguments are reported as errors in the
* disambiguation pass (but zero type arguments is always allowed, that
* could be a raw type) to not throw off errors later during type resolution.
*
* <p>Not thread-safe. One instance is created by file (in JavaAstProcessor),
* so these symbols are not global.
*/
public final class UnresolvedClassStore {
private final Map<String, UnresolvedClassImpl> unresolved = new HashMap<>();
private final TypeSystem ts;
public UnresolvedClassStore(TypeSystem ts) {
this.ts = ts;
}
/**
* Produces an unresolved class symbol from the given canonical name.
*
* @param canonicalName Canonical name of the returned symbol
* @param typeArity Number of type arguments parameterizing the reference.
* Type parameter symbols will be created to represent them.
* This may also mutate an existing unresolved reference.
*
* @throws NullPointerException If the name is null
*/
public @NonNull JClassSymbol makeUnresolvedReference(@Nullable String canonicalName, int typeArity) {
UnresolvedClassImpl unresolved = this.unresolved.computeIfAbsent(
canonicalName,
n -> new FlexibleUnresolvedClassImpl(this.ts, null, n)
);
unresolved.setTypeParameterCount(typeArity);
return unresolved;
}
public @NonNull JClassSymbol makeUnresolvedReference(JClassSymbol qualifier, String simpleName, int typeArity) {
if (qualifier instanceof UnresolvedClassImpl) {
UnresolvedClassImpl child = ((UnresolvedClassImpl) qualifier).getOrCreateUnresolvedChildClass(simpleName);
child.setTypeParameterCount(typeArity);
this.unresolved.putIfAbsent(child.getCanonicalName(), child);
return child;
}
return makeUnresolvedReference(qualifier.getCanonicalName() + '.' + simpleName, typeArity);
}
}
| 2,912 | 38.90411 | 118 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/SymbolToStrings.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal;
import java.util.stream.Collectors;
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.JFieldSymbol;
import net.sourceforge.pmd.lang.java.symbols.JFormalParamSymbol;
import net.sourceforge.pmd.lang.java.symbols.JLocalVariableSymbol;
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.SymbolVisitor;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
public class SymbolToStrings {
public static final SymbolToStrings SHARED = new SymbolToStrings("");
public static final SymbolToStrings FAKE = new SymbolToStrings("fake");
public static final SymbolToStrings ASM = new SymbolToStrings("asm");
public static final SymbolToStrings AST = new SymbolToStrings("ast");
private final ToStringVisitor visitor;
public SymbolToStrings(String impl) {
this.visitor = new ToStringVisitor(impl);
}
public String toString(JElementSymbol symbol) {
return symbol.acceptVisitor(visitor, new StringBuilder()).toString();
}
public String toString(SymAnnot annot) {
String attrs;
if (annot.getAttributeNames().isEmpty()) {
attrs = "";
} else {
attrs = annot.getAttributeNames()
.stream()
.map(name -> name + "=" + annot.getAttribute(name))
.collect(Collectors.joining(", ", "(", ")"));
}
return "@" + annot.getBinaryName() + attrs;
}
private static final class ToStringVisitor implements SymbolVisitor<StringBuilder, StringBuilder> {
private final String impl;
private ToStringVisitor(String impl) {
this.impl = impl;
}
private StringBuilder withImpl(StringBuilder builder, String kind, Object first, Object... rest) {
if (!impl.isEmpty()) {
builder.append(impl).append(':');
}
builder.append(kind).append('(').append(first);
for (Object s : rest) {
builder.append(", ").append(s);
}
return builder.append(')');
}
@Override
public StringBuilder visitSymbol(JElementSymbol sym, StringBuilder builder) {
throw new IllegalStateException("Unknown symbol " + sym.getClass());
}
@Override
public StringBuilder visitClass(JClassSymbol sym, StringBuilder param) {
String kind;
if (sym.isUnresolved()) {
kind = "unresolved";
} else if (sym.isEnum()) {
kind = "enum";
} else if (sym.isAnnotation()) {
kind = "annot";
} else if (sym.isRecord()) {
kind = "record";
} else {
kind = "class";
}
return withImpl(param, kind, sym.getBinaryName());
}
@Override
public StringBuilder visitArray(JClassSymbol sym, JTypeDeclSymbol component, StringBuilder param) {
param.append("array(");
return component.acceptVisitor(this, param).append(")");
}
@Override
public StringBuilder visitTypeParam(JTypeParameterSymbol sym, StringBuilder param) {
return withImpl(param, "tparam", sym.getSimpleName(), sym.getDeclaringSymbol());
}
@Override
public StringBuilder visitCtor(JConstructorSymbol sym, StringBuilder param) {
return withImpl(param, "ctor", sym.getEnclosingClass());
}
@Override
public StringBuilder visitMethod(JMethodSymbol sym, StringBuilder param) {
return withImpl(param, "method", sym.getSimpleName(), sym.getEnclosingClass());
}
@Override
public StringBuilder visitField(JFieldSymbol sym, StringBuilder param) {
return withImpl(param, "field", sym.getSimpleName(), sym.getEnclosingClass());
}
@Override
public StringBuilder visitLocal(JLocalVariableSymbol sym, StringBuilder param) {
return withImpl(param, "local", sym.getSimpleName());
}
@Override
public StringBuilder visitFormal(JFormalParamSymbol sym, StringBuilder param) {
return withImpl(param, "formal", sym.getSimpleName());
}
}
}
| 4,769 | 35.412214 | 107 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/FlexibleUnresolvedClassImpl.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal;
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.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeParameterOwnerSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeParameterSymbol;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.JTypeVar;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
/**
* Unresolved <i>external reference</i> to a class.
*
* @see JClassSymbol#isUnresolved()
*/
final class FlexibleUnresolvedClassImpl extends UnresolvedClassImpl {
private static final int UNKNOWN_ARITY = 0;
private int arity = UNKNOWN_ARITY;
private List<JTypeVar> tparams = Collections.emptyList();
private List<UnresolvedClassImpl> childClasses = Collections.emptyList();
FlexibleUnresolvedClassImpl(TypeSystem ts,
@Nullable JClassSymbol enclosing,
String canonicalName) {
super(ts, enclosing, canonicalName);
}
/**
* Set the number of type parameters of this type. If the arity was
* already set to a value different from {@value #UNKNOWN_ARITY},
* this does nothing: the unresolved type appears several times with
* inconsistent arities, which must be reported later.
*
* @param newArity New number of type parameters
*/
@Override
void setTypeParameterCount(int newArity) {
if (arity == UNKNOWN_ARITY) {
this.arity = newArity;
List<JTypeVar> newParams = new ArrayList<>(newArity);
for (int i = 0; i < newArity; i++) {
newParams.add(new FakeTypeParam("T" + i, getTypeSystem(), this).getTypeMirror());
}
this.tparams = Collections.unmodifiableList(newParams);
}
}
@Override
UnresolvedClassImpl getOrCreateUnresolvedChildClass(String simpleName) {
if (childClasses.isEmpty()) {
childClasses = new ArrayList<>(); // make it mutable
}
for (UnresolvedClassImpl childClass : childClasses) {
if (childClass.nameEquals(simpleName)) {
return childClass;
}
}
FlexibleUnresolvedClassImpl newChild =
new FlexibleUnresolvedClassImpl(getTypeSystem(), this, getCanonicalName() + '.' + simpleName);
childClasses.add(newChild);
return newChild;
}
@Override
public List<JClassSymbol> getDeclaredClasses() {
return Collections.unmodifiableList(childClasses);
}
@Override
public List<JTypeVar> getTypeParameters() {
return tparams;
}
private static final class FakeTypeParam implements JTypeParameterSymbol {
private final String name;
private final JTypeParameterOwnerSymbol owner;
private final JTypeVar tvar;
private FakeTypeParam(String name, TypeSystem ts, JTypeParameterOwnerSymbol owner) {
this.name = name;
this.owner = owner;
this.tvar = ts.newTypeVar(this);
}
@Override
public TypeSystem getTypeSystem() {
return tvar.getTypeSystem();
}
@Override
public JTypeVar getTypeMirror() {
return tvar;
}
@Override
public JTypeMirror computeUpperBound() {
return getTypeSystem().OBJECT;
}
@Override
public @NonNull String getSimpleName() {
return name;
}
@Override
public JTypeParameterOwnerSymbol getDeclaringSymbol() {
return owner;
}
}
}
| 3,932 | 30.464 | 106 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/SymbolEquality.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal;
import java.util.Objects;
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.JFieldSymbol;
import net.sourceforge.pmd.lang.java.symbols.JFormalParamSymbol;
import net.sourceforge.pmd.lang.java.symbols.JLocalVariableSymbol;
import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeParameterSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolVisitor;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
/**
* Routines to share logic for equality, respecting the contract of
* {@link JElementSymbol#equals(Object)}.
*
* <p>Despite this two equal symbols may not hold the same amount of
* information... Reflection symbols are nice, but they also add some
* synthetic stuff (eg implicit formal parameters, bridge methods),
* which we must either filter-out or replicate in AST symbols. This is TODO
*/
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public final class SymbolEquality {
private SymbolEquality() {
// util class
}
public static final EqAndHash<JTypeParameterSymbol> TYPE_PARAM = new EqAndHash<JTypeParameterSymbol>() {
@Override
public int hash(JTypeParameterSymbol t1) {
return 31 * t1.getDeclaringSymbol().hashCode() + t1.getSimpleName().hashCode();
}
@Override
public boolean equals(JTypeParameterSymbol m1, Object o) {
if (m1 == o) {
return true;
}
if (!(o instanceof JTypeParameterSymbol)) {
return false;
}
JTypeParameterSymbol m2 = (JTypeParameterSymbol) o;
return m1.nameEquals(m2.getSimpleName())
&& m1.getDeclaringSymbol().equals(m2.getDeclaringSymbol());
}
};
public static final EqAndHash<JMethodSymbol> METHOD = new EqAndHash<JMethodSymbol>() {
@Override
public int hash(JMethodSymbol t1) {
return t1.getArity() * t1.getModifiers() + 31 * t1.getSimpleName().hashCode();
}
@Override
public boolean equals(JMethodSymbol m1, Object o) {
if (m1 == o) {
return true;
}
if (!(o instanceof JMethodSymbol)) {
return false;
}
JMethodSymbol m2 = (JMethodSymbol) o;
// FIXME arity check is not enough for overloads
return m1.getModifiers() == m2.getModifiers()
&& m1.getArity() == m2.getArity()
&& Objects.equals(m1.getSimpleName(), m2.getSimpleName())
&& m1.getEnclosingClass().equals(m2.getEnclosingClass());
}
};
public static final EqAndHash<JConstructorSymbol> CONSTRUCTOR = new EqAndHash<JConstructorSymbol>() {
@Override
public int hash(JConstructorSymbol t1) {
return t1.getArity() * t1.getModifiers() + 31 * t1.getSimpleName().hashCode();
}
@Override
public boolean equals(JConstructorSymbol m1, Object o) {
if (m1 == o) {
return true;
}
if (!(o instanceof JConstructorSymbol)) {
return false;
}
JConstructorSymbol m2 = (JConstructorSymbol) o;
// FIXME arity check is not enough for overloads
return m1.getModifiers() == m2.getModifiers()
&& m1.getArity() == m2.getArity()
&& Objects.equals(m1.getSimpleName(), m2.getSimpleName())
&& m1.getEnclosingClass().equals(m2.getEnclosingClass());
}
};
public static final EqAndHash<JClassSymbol> CLASS = new EqAndHash<JClassSymbol>() {
@Override
public int hash(JClassSymbol t1) {
return t1.getBinaryName().hashCode();
}
@Override
public boolean equals(JClassSymbol m1, Object o) {
if (m1 == o) {
return true;
}
if (!(o instanceof JClassSymbol)) {
return false;
}
JClassSymbol m2 = (JClassSymbol) o;
return m1.getBinaryName().equals(m2.getBinaryName());
}
};
public static final EqAndHash<JFieldSymbol> FIELD = new EqAndHash<JFieldSymbol>() {
@Override
public int hash(JFieldSymbol t1) {
return 31 * t1.getEnclosingClass().hashCode() + t1.getSimpleName().hashCode();
}
@Override
public boolean equals(JFieldSymbol f1, Object o) {
if (!(o instanceof JFieldSymbol)) {
return false;
}
JFieldSymbol f2 = (JFieldSymbol) o;
return f1.nameEquals(f2.getSimpleName())
&& f1.getEnclosingClass().equals(f2.getEnclosingClass());
}
};
public static final EqAndHash<SymAnnot> ANNOTATION = new EqAndHash<SymAnnot>() {
@Override
public int hash(SymAnnot t1) {
return t1.getBinaryName().hashCode();
}
@Override
public boolean equals(SymAnnot f1, Object o) {
if (!(o instanceof SymAnnot)) {
return false;
}
SymAnnot f2 = (SymAnnot) o;
return f1.getBinaryName().equals(f2.getBinaryName());
}
};
public static final EqAndHash<JFormalParamSymbol> FORMAL_PARAM = new EqAndHash<JFormalParamSymbol>() {
@Override
public int hash(JFormalParamSymbol t1) {
return 31 * t1.getDeclaringSymbol().hashCode() + t1.getSimpleName().hashCode();
}
@Override
public boolean equals(JFormalParamSymbol f1, Object o) {
if (!(o instanceof JFormalParamSymbol)) {
return false;
}
JFormalParamSymbol f2 = (JFormalParamSymbol) o;
return f1.nameEquals(f2.getSimpleName())
&& f1.getDeclaringSymbol().equals(f2.getDeclaringSymbol());
}
};
private static final EqAndHash<Object> IDENTITY = new EqAndHash<Object>() {
@Override
public int hash(Object t1) {
return System.identityHashCode(t1);
}
@Override
public boolean equals(Object t1, Object t2) {
return t1 == t2;
}
};
/**
* Strategy to perform equals/hashcode for a type T. There are libraries
* for that, whatever.
*/
public abstract static class EqAndHash<T> {
public abstract int hash(T t1);
public abstract boolean equals(T t1, Object t2);
}
public static <T extends JElementSymbol> boolean equals(T e1, Object e2) {
if (e1 == e2) {
return true;
} else if (e2 == null) {
return false;
}
@SuppressWarnings("unchecked")
EqAndHash<T> eqAndHash = (EqAndHash<T>) e1.acceptVisitor(EqAndHashVisitor.INSTANCE, null);
return eqAndHash.equals(e1, e2);
}
public static <T extends JElementSymbol> int hash(T e1) {
@SuppressWarnings("unchecked")
EqAndHash<T> eqAndHash = (EqAndHash<T>) e1.acceptVisitor(EqAndHashVisitor.INSTANCE, null);
return eqAndHash.hash(e1);
}
private static final class EqAndHashVisitor implements SymbolVisitor<EqAndHash<?>, Void> {
static final EqAndHashVisitor INSTANCE = new EqAndHashVisitor();
@Override
public EqAndHash<?> visitSymbol(JElementSymbol sym, Void aVoid) {
throw new IllegalStateException("Unknown symbol " + sym.getClass());
}
@Override
public EqAndHash<?> visitClass(JClassSymbol sym, Void param) {
return CLASS;
}
@Override
public EqAndHash<?> visitTypeParam(JTypeParameterSymbol sym, Void param) {
return TYPE_PARAM;
}
@Override
public EqAndHash<?> visitCtor(JConstructorSymbol sym, Void param) {
return CONSTRUCTOR;
}
@Override
public EqAndHash<?> visitMethod(JMethodSymbol sym, Void param) {
return METHOD;
}
@Override
public EqAndHash<?> visitField(JFieldSymbol sym, Void param) {
return FIELD;
}
@Override
public EqAndHash<?> visitLocal(JLocalVariableSymbol sym, Void param) {
return IDENTITY;
}
@Override
public EqAndHash<?> visitFormal(JFormalParamSymbol sym, Void param) {
return FORMAL_PARAM;
}
}
}
| 8,777 | 31.63197 | 108 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/ImplicitMemberSymbols.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JConstructorSymbol;
import net.sourceforge.pmd.lang.java.symbols.JExecutableSymbol;
import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol;
import net.sourceforge.pmd.lang.java.symbols.JFormalParamSymbol;
import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.JTypeVar;
import net.sourceforge.pmd.lang.java.types.Substitution;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* Members inserted by the compiler, eg default constructor, etc. They
* would be absent from the source, but are reflected by the {@link Class}.
*/
public final class ImplicitMemberSymbols {
private static final int VISIBILITY_MASK = Modifier.PRIVATE | Modifier.PUBLIC | Modifier.PROTECTED;
/** This is the private access flag for varargs modifiers. */
private static final int VARARGS_MOD = 0x00000080;
private ImplicitMemberSymbols() {
}
public static JMethodSymbol enumValueOf(JClassSymbol enumSym) {
assert enumSym.isEnum() : "Not an enum symbol " + enumSym;
return new FakeMethodSym(
enumSym,
"valueOf",
Modifier.PUBLIC | Modifier.STATIC,
TypeSystem::declaration,
singletonList(t -> new FakeFormalParamSym(t, "name", (ts, s) -> ts.declaration(ts.getClassSymbol(String.class))))
);
}
public static JMethodSymbol enumValues(JClassSymbol enumSym) {
assert enumSym.isEnum() : "Not an enum symbol " + enumSym;
return new FakeMethodSym(
enumSym,
"values",
Modifier.PUBLIC | Modifier.STATIC,
(ts, c) -> ts.arrayType(ts.declaration(c)),
emptyList()
);
}
public static JConstructorSymbol defaultCtor(JClassSymbol sym) {
assert sym != null;
// Enum constructors have 2 additional implicit parameters, for the name and ordinal
// Inner classes have 1 additional implicit param, for the outer instance
// They are not reflected by the symbol
int modifiers = sym.isEnum() ? Modifier.PRIVATE
: sym.getModifiers() & VISIBILITY_MASK;
return new FakeCtorSym(sym, modifiers, emptyList());
}
public static JMethodSymbol arrayClone(JClassSymbol arraySym) {
assert arraySym.isArray() : "Not an array symbol " + arraySym;
return new FakeMethodSym(
arraySym,
"clone",
Modifier.PUBLIC | Modifier.FINAL,
TypeSystem::declaration,
emptyList()
);
}
public static JConstructorSymbol arrayConstructor(JClassSymbol arraySym) {
assert arraySym.isArray() : "Not an array symbol " + arraySym;
return new FakeCtorSym(
arraySym,
Modifier.PUBLIC | Modifier.FINAL,
singletonList(c -> new FakeFormalParamSym(c, "arg0", (ts, sym) -> ts.INT))
);
}
/** Symbol for the canonical record constructor. */
public static JConstructorSymbol recordConstructor(JClassSymbol recordSym,
List<JFieldSymbol> recordComponents,
boolean isVarargs) {
assert recordSym.isRecord() : "Not a record symbol " + recordSym;
int modifiers = isVarargs ? Modifier.PUBLIC | VARARGS_MOD
: Modifier.PUBLIC;
return new FakeCtorSym(
recordSym,
modifiers,
CollectionUtil.map(
recordComponents,
f -> c -> new FakeFormalParamSym(c, f.getSimpleName(), f.tryGetNode(), (ts, sym) -> f.getTypeMirror(Substitution.EMPTY))
)
);
}
/**
* Symbol for a record component accessor.
* Only synthesized if it is not explicitly declared.
*/
public static JMethodSymbol recordAccessor(JClassSymbol recordSym, JFieldSymbol recordComponent) {
// See https://cr.openjdk.java.net/~gbierman/jep359/jep359-20200115/specs/records-jls.html#jls-8.10.3
assert recordSym.isRecord() : "Not a record symbol " + recordSym;
return new FakeMethodSym(
recordSym,
recordComponent.getSimpleName(),
Modifier.PUBLIC,
(ts, encl) -> recordComponent.getTypeMirror(Substitution.EMPTY),
emptyList()
);
}
public static JFieldSymbol arrayLengthField(JClassSymbol arraySym) {
assert arraySym.isArray() : "Not an array symbol " + arraySym;
return new FakeFieldSym(
arraySym,
"length",
Modifier.PUBLIC | Modifier.FINAL,
(ts, s) -> ts.INT
);
}
private abstract static class FakeExecutableSymBase<T extends JExecutableSymbol> implements JExecutableSymbol {
private final JClassSymbol owner;
private final String name;
private final int modifiers;
private final List<JFormalParamSymbol> formals;
FakeExecutableSymBase(JClassSymbol owner,
String name,
int modifiers,
List<Function<T, JFormalParamSymbol>> formals) {
this.owner = owner;
this.name = name;
this.modifiers = modifiers;
this.formals = CollectionUtil.map(formals, f -> f.apply((T) this));
}
@Override
public TypeSystem getTypeSystem() {
return owner.getTypeSystem();
}
@Override
public List<JTypeMirror> getFormalParameterTypes(Substitution subst) {
return CollectionUtil.map(formals, p -> p.getTypeMirror(subst));
}
@Override
public List<JTypeMirror> getThrownExceptionTypes(Substitution subst) {
return emptyList();
}
@Override
public List<JTypeVar> getTypeParameters() {
return emptyList();
}
@Override
public String getSimpleName() {
return name;
}
@Override
public List<JFormalParamSymbol> getFormalParameters() {
return formals;
}
@Override
public boolean isVarargs() {
return (modifiers & VARARGS_MOD) != 0;
}
@Override
public int getArity() {
return formals.size();
}
@Override
public @Nullable JTypeMirror getAnnotatedReceiverType(Substitution subst) {
if (!this.hasReceiver()) {
return null;
}
return getTypeSystem().declaration(owner).subst(subst);
}
@Override
public int getModifiers() {
return modifiers;
}
@Override
public @NonNull JClassSymbol getEnclosingClass() {
return owner;
}
@Override
public String toString() {
return SymbolToStrings.FAKE.toString(this);
}
}
private static final class FakeMethodSym extends FakeExecutableSymBase<JMethodSymbol> implements JMethodSymbol {
private final BiFunction<? super TypeSystem, ? super JClassSymbol, ? extends JTypeMirror> returnType;
FakeMethodSym(JClassSymbol owner,
String name,
int modifiers,
BiFunction<? super TypeSystem, ? super JClassSymbol, ? extends JTypeMirror> returnType,
List<Function<JMethodSymbol, JFormalParamSymbol>> formals) {
super(owner, name, modifiers, formals);
this.returnType = returnType;
}
@Override
public boolean isBridge() {
return false;
}
@Override
public JTypeMirror getReturnType(Substitution subst) {
return returnType.apply(getTypeSystem(), getEnclosingClass());
}
@Override
public boolean equals(Object o) {
return SymbolEquality.METHOD.equals(this, o);
}
@Override
public int hashCode() {
return SymbolEquality.METHOD.hash(this);
}
}
private static final class FakeCtorSym extends FakeExecutableSymBase<JConstructorSymbol> implements JConstructorSymbol {
FakeCtorSym(JClassSymbol owner,
int modifiers,
List<Function<JConstructorSymbol, JFormalParamSymbol>> formals) {
super(owner, JConstructorSymbol.CTOR_NAME, modifiers, formals);
}
@Override
public boolean equals(Object o) {
return SymbolEquality.CONSTRUCTOR.equals(this, o);
}
@Override
public int hashCode() {
return SymbolEquality.CONSTRUCTOR.hash(this);
}
}
private static final class FakeFormalParamSym implements JFormalParamSymbol {
private final JExecutableSymbol owner;
private final String name;
private final ASTVariableDeclaratorId node;
private final BiFunction<? super TypeSystem, ? super JFormalParamSymbol, ? extends JTypeMirror> type;
private FakeFormalParamSym(JExecutableSymbol owner, String name, BiFunction<? super TypeSystem, ? super JFormalParamSymbol, ? extends JTypeMirror> type) {
this(owner, name, null, type);
}
private FakeFormalParamSym(JExecutableSymbol owner, String name, @Nullable ASTVariableDeclaratorId node, BiFunction<? super TypeSystem, ? super JFormalParamSymbol, ? extends JTypeMirror> type) {
this.owner = owner;
this.name = name;
this.node = node;
this.type = type;
}
@Override
public @Nullable ASTVariableDeclaratorId tryGetNode() {
return node;
}
@Override
public TypeSystem getTypeSystem() {
return owner.getTypeSystem();
}
@Override
public JTypeMirror getTypeMirror(Substitution subst) {
return type.apply(getTypeSystem(), this).subst(subst);
}
@Override
public JExecutableSymbol getDeclaringSymbol() {
return owner;
}
@Override
public boolean isFinal() {
return false;
}
@Override
public String getSimpleName() {
return name;
}
@Override
public String toString() {
return SymbolToStrings.FAKE.toString(this);
}
@Override
public boolean equals(Object o) {
return SymbolEquality.FORMAL_PARAM.equals(this, o);
}
@Override
public int hashCode() {
return SymbolEquality.FORMAL_PARAM.hash(this);
}
}
private static final class FakeFieldSym implements JFieldSymbol {
private final JClassSymbol owner;
private final String name;
private final int modifiers;
private final BiFunction<? super TypeSystem, ? super JClassSymbol, ? extends JTypeMirror> type;
FakeFieldSym(JClassSymbol owner, String name, int modifiers, BiFunction<? super TypeSystem, ? super JClassSymbol, ? extends JTypeMirror> type) {
this.owner = owner;
this.name = name;
this.modifiers = modifiers;
this.type = type;
}
@Override
public TypeSystem getTypeSystem() {
return owner.getTypeSystem();
}
@Override
public JTypeMirror getTypeMirror(Substitution subst) {
return type.apply(getTypeSystem(), owner).subst(subst);
}
@Override
public String getSimpleName() {
return name;
}
@Override
public int getModifiers() {
return modifiers;
}
@Override
public boolean isEnumConstant() {
return false;
}
@Override
public @NonNull JClassSymbol getEnclosingClass() {
return owner;
}
@Override
public String toString() {
return SymbolToStrings.FAKE.toString(this);
}
@Override
public boolean equals(Object o) {
return SymbolEquality.FIELD.equals(this, o);
}
@Override
public int hashCode() {
return SymbolEquality.FIELD.hash(this);
}
}
}
| 13,125 | 30.628916 | 202 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/UnresolvedClassImpl.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal;
import java.lang.reflect.Modifier;
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.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JConstructorSymbol;
import net.sourceforge.pmd.lang.java.symbols.JExecutableSymbol;
import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol;
import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.JTypeVar;
import net.sourceforge.pmd.lang.java.types.Substitution;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
/**
* Unresolved <i>external reference</i> to a class.
*
* @see JClassSymbol#isUnresolved()
*/
abstract class UnresolvedClassImpl implements JClassSymbol {
private final TypeSystem ts;
private final @Nullable JClassSymbol enclosing;
private final String canonicalName;
UnresolvedClassImpl(TypeSystem ts, @Nullable JClassSymbol enclosing, String canonicalName) {
this.ts = ts;
this.enclosing = enclosing;
this.canonicalName = canonicalName;
}
@Override
public TypeSystem getTypeSystem() {
return ts;
}
/**
* Set the number of type parameters of this type. Does nothing if
* it is already set.
*/
abstract void setTypeParameterCount(int newArity);
abstract UnresolvedClassImpl getOrCreateUnresolvedChildClass(String simpleName);
@Override
public List<JTypeVar> getTypeParameters() {
return Collections.emptyList();
}
@Override
public boolean isUnresolved() {
return true;
}
@Override
public @Nullable JExecutableSymbol getEnclosingMethod() {
return null;
}
@Override
public boolean isPrimitive() {
return false;
}
@Override
public @NonNull String getBinaryName() {
return canonicalName;
}
@NonNull
@Override
public String getSimpleName() {
int idx = canonicalName.lastIndexOf('.');
if (idx < 0) {
return canonicalName;
} else {
return canonicalName.substring(idx + 1);
}
}
@Override
public String getCanonicalName() {
return canonicalName;
}
@Override
public @NonNull String getPackageName() {
int idx = canonicalName.lastIndexOf('.');
if (idx < 0) {
return canonicalName;
} else {
return canonicalName.substring(0, idx);
}
}
@Nullable
@Override
public JClassSymbol getSuperclass() {
return getTypeSystem().OBJECT.getSymbol();
}
@Override
public List<JClassType> getSuperInterfaceTypes(Substitution substitution) {
return Collections.emptyList();
}
@Override
public List<JClassSymbol> getSuperInterfaces() {
return Collections.emptyList();
}
@Override
public @Nullable JClassType getSuperclassType(Substitution substitution) {
return getTypeSystem().OBJECT;
}
@Override
public List<JClassSymbol> getDeclaredClasses() {
return Collections.emptyList();
}
@Override
public boolean isInterface() {
return false;
}
@Override
public boolean isEnum() {
return false;
}
@Override
public boolean isRecord() {
return false;
}
@Override
public boolean isAnnotation() {
return false;
}
@Override
public boolean isAnonymousClass() {
return false;
}
@Override
public boolean isLocalClass() {
return false;
}
@Override
public boolean isArray() {
return false;
}
@Override
public JClassSymbol getEnclosingClass() {
return enclosing;
}
@Override
public int getModifiers() {
return Modifier.PUBLIC;
}
@Nullable
@Override
public JTypeDeclSymbol getArrayComponent() {
return null;
}
@Override
public List<JMethodSymbol> getDeclaredMethods() {
return Collections.emptyList();
}
@Override
public List<JConstructorSymbol> getConstructors() {
return Collections.emptyList();
}
@Override
public List<JFieldSymbol> getDeclaredFields() {
return Collections.emptyList();
}
@Override
public String toString() {
return SymbolToStrings.SHARED.toString(this);
}
@Override
public boolean equals(Object o) {
return SymbolEquality.equals(this, o);
}
@Override
public int hashCode() {
return SymbolEquality.hash(this);
}
}
| 4,953 | 21.518182 | 96 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/ast/AstSymFactory.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.ast;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.internal.JavaAstProcessor;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeParameterOwnerSymbol;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
final class AstSymFactory {
private final TypeSystem ts;
private final JavaAstProcessor processor;
AstSymFactory(JavaAstProcessor processor) {
this.ts = processor.getTypeSystem();
this.processor = processor;
}
JClassType recordSuperclass() {
return (JClassType) ts.declaration(processor.findSymbolCannotFail("java.lang.Record"));
}
JClassType enumSuperclass(JClassSymbol enumT) {
return (JClassType) ts.parameterise(processor.findSymbolCannotFail("java.lang.Enum"),
listOf(ts.declaration(enumT)));
}
JClassSymbol annotationSym() {
return processor.findSymbolCannotFail("java.lang.annotation.Annotation");
}
JClassType annotationType() {
return (JClassType) ts.declaration(annotationSym());
}
public TypeSystem types() {
return ts;
}
// keep in mind, creating a symbol sets it on the node (see constructor of AbstractAstBackedSymbol)
/**
* Builds, sets and returns the symbol for the given local variable.
*/
void setLocalVarSymbol(ASTVariableDeclaratorId id) {
assert !id.isField() && !id.isEnumConstant() : "Local var symbol is not appropriate for fields";
assert !id.isFormalParameter()
|| id.isLambdaParameter()
|| id.isExceptionBlockParameter() : "Local var symbol is not appropriate for method parameters";
new AstLocalVarSym(id, this);
}
/**
* Builds, sets and returns the symbol for the given class.
*/
JClassSymbol setClassSymbol(@Nullable JTypeParameterOwnerSymbol enclosing, ASTAnyTypeDeclaration klass) {
if (enclosing instanceof JClassSymbol && klass.isNested()) {
JClassSymbol inner = ((JClassSymbol) enclosing).getDeclaredClass(klass.getSimpleName());
assert inner != null : "Inner class symbol was not created for " + klass;
return inner;
}
return new AstClassSym(klass, this, enclosing);
}
}
| 2,747 | 32.108434 | 109 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/ast/AstCtorSym.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.ast;
import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JConstructorSymbol;
/**
* @author Clément Fournier
*/
final class AstCtorSym extends AbstractAstExecSymbol<ASTConstructorDeclaration> implements JConstructorSymbol {
AstCtorSym(ASTConstructorDeclaration node, AstSymFactory factory, JClassSymbol owner) {
super(node, factory, owner);
}
}
| 629 | 29 | 111 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/ast/AstSymbolMakerVisitor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.ast;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.mutable.MutableInt;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter;
import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.ast.InternalApiBridge;
import net.sourceforge.pmd.lang.java.ast.JavaVisitorBase;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeParameterOwnerSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolResolver;
/**
* Populates symbols on declaration nodes. Cannot be reused.
*/
final class AstSymbolMakerVisitor extends JavaVisitorBase<AstSymFactory, Void> {
private static final String NO_CANONICAL_NAME = "<impossible/name>";
// these map simple name to count of local classes with that name in the given class
private final Deque<Map<String, Integer>> currentLocalIndices = new ArrayDeque<>();
// these are counts of anon classes in the enclosing class
private final Deque<MutableInt> anonymousCounters = new ArrayDeque<>();
// these are binary names, eg may contain pack.Foo, pack.Foo$Nested, pack.Foo$Nested$1Local
private final Deque<String> enclosingBinaryNames = new ArrayDeque<>();
// these are canonical names. Contains NO_CANONICAL_NAME if the enclosing decl has no canonical name
private final Deque<String> enclosingCanonicalNames = new ArrayDeque<>();
// these are symbols, NOT 1-to-1 with the type name stack because may contain method/ctor symbols
private final Deque<JTypeParameterOwnerSymbol> enclosingSymbols = new ArrayDeque<>();
/** Package name of the current file. */
private final String packageName;
private final Map<String, JClassSymbol> byCanonicalName = new HashMap<>();
private final Map<String, JClassSymbol> byBinaryName = new HashMap<>();
AstSymbolMakerVisitor(ASTCompilationUnit node) {
// update the package list
packageName = node.getPackageName();
}
public SymbolResolver makeKnownSymbolResolver() {
return new MapSymResolver(byCanonicalName, byBinaryName);
}
@Override
public Void visit(ASTVariableDeclaratorId node, AstSymFactory data) {
if (isTrueLocalVar(node)) {
data.setLocalVarSymbol(node);
} else {
// in the other cases, building the method/ctor/class symbols already set the symbols
assert node.getSymbol() != null : "Symbol was null for " + node;
}
return super.visit(node, data);
}
private boolean isTrueLocalVar(ASTVariableDeclaratorId node) {
return !(node.isField()
|| node.isEnumConstant()
|| node.isRecordComponent()
|| node.getParent() instanceof ASTFormalParameter);
}
@Override
public Void visitTypeDecl(ASTAnyTypeDeclaration node, AstSymFactory data) {
String binaryName = makeBinaryName(node);
@Nullable String canonicalName = makeCanonicalName(node, binaryName);
InternalApiBridge.setQname(node, binaryName, canonicalName);
JClassSymbol sym = data.setClassSymbol(enclosingSymbols.peek(), node);
byBinaryName.put(binaryName, sym);
if (canonicalName != null) {
byCanonicalName.put(canonicalName, sym);
}
enclosingBinaryNames.push(binaryName);
enclosingCanonicalNames.push(canonicalName == null ? NO_CANONICAL_NAME : canonicalName);
enclosingSymbols.push(sym);
anonymousCounters.push(new MutableInt(0));
currentLocalIndices.push(new HashMap<>());
visitChildren(node, data);
currentLocalIndices.pop();
anonymousCounters.pop();
enclosingSymbols.pop();
enclosingBinaryNames.pop();
enclosingCanonicalNames.pop();
return null;
}
@NonNull
private String makeBinaryName(ASTAnyTypeDeclaration node) {
String simpleName = node.getSimpleName();
if (node.isLocal()) {
simpleName = getNextIndexFromHistogram(currentLocalIndices.getFirst(), node.getSimpleName(), 1)
+ simpleName;
} else if (node.isAnonymous()) {
simpleName = "" + anonymousCounters.getFirst().incrementAndGet();
}
String enclosing = enclosingBinaryNames.peek();
return enclosing != null ? enclosing + "$" + simpleName
: packageName.isEmpty() ? simpleName
: packageName + "." + simpleName;
}
@Nullable
private String makeCanonicalName(ASTAnyTypeDeclaration node, String binaryName) {
if (node.isAnonymous() || node.isLocal()) {
return null;
}
if (enclosingCanonicalNames.isEmpty()) {
// toplevel
return binaryName;
}
String enclCanon = enclosingCanonicalNames.getFirst();
return NO_CANONICAL_NAME.equals(enclCanon)
? null // enclosing has no canonical name, so this one doesn't either
: enclCanon + '.' + node.getSimpleName();
}
@Override
public Void visitMethodOrCtor(ASTMethodOrConstructorDeclaration node, AstSymFactory data) {
enclosingSymbols.push(node.getSymbol());
visitChildren(node, data);
enclosingSymbols.pop();
return null;
}
/**
* Gets the next available index based on a key and a histogram (map of keys to int counters).
* If the key doesn't exist, we add a new entry with the startIndex.
*
* <p>Used for lambda and anonymous class counters
*
* @param histogram The histogram map
* @param key The key to access
* @param startIndex First index given out when the key doesn't exist
*
* @return The next free index
*/
private static <T> int getNextIndexFromHistogram(Map<T, Integer> histogram, T key, int startIndex) {
Integer count = histogram.get(key);
if (count == null) {
histogram.put(key, startIndex);
return startIndex;
} else {
histogram.put(key, count + 1);
return count + 1;
}
}
}
| 6,718 | 36.747191 | 107 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/ast/AstFormalParamSym.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.ast;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.symbols.JExecutableSymbol;
import net.sourceforge.pmd.lang.java.symbols.JFormalParamSymbol;
/**
* @author Clément Fournier
*/
final class AstFormalParamSym extends AbstractAstVariableSym implements JFormalParamSymbol {
private final AbstractAstExecSymbol<?> owner;
AstFormalParamSym(ASTVariableDeclaratorId node, AstSymFactory factory, AbstractAstExecSymbol<?> owner) {
super(node, factory);
this.owner = owner;
}
@Override
public JExecutableSymbol getDeclaringSymbol() {
return owner;
}
}
| 797 | 26.517241 | 108 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/ast/AstMethodSym.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.ast;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTType;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.Substitution;
import net.sourceforge.pmd.lang.java.types.TypeOps;
/**
* @author Clément Fournier
*/
final class AstMethodSym
extends AbstractAstExecSymbol<ASTMethodDeclaration>
implements JMethodSymbol {
AstMethodSym(ASTMethodDeclaration node, AstSymFactory factory, JClassSymbol owner) {
super(node, factory, owner);
}
@Override
public boolean isBridge() {
return false;
}
@Override
public JTypeMirror getReturnType(Substitution subst) {
ASTType rt = node.getResultTypeNode();
return TypeOps.subst(rt.getTypeMirror(), subst);
}
@Override
public String getSimpleName() {
return node.getName();
}
@Override
public @Nullable SymbolicValue getDefaultAnnotationValue() {
if (node.getDefaultClause() != null) {
return AstSymbolicAnnot.ofNode(node.getDefaultClause().getConstant());
}
return null;
}
}
| 1,554 | 27.796296 | 88 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/ast/AstLocalVarSym.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.ast;
import static net.sourceforge.pmd.lang.java.types.TypeOps.subst;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.symbols.JLocalVariableSymbol;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.Substitution;
/**
* @author Clément Fournier
*/
public final class AstLocalVarSym extends AbstractAstVariableSym implements JLocalVariableSymbol {
AstLocalVarSym(ASTVariableDeclaratorId node, AstSymFactory factory) {
super(node, factory);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (!(o instanceof AstLocalVarSym)) {
return false;
}
return node.equals(((AstLocalVarSym) o).node);
}
@Override
public int hashCode() {
return node.hashCode();
}
@Override
public JTypeMirror getTypeMirror(Substitution subst) {
return subst(node.getTypeMirror(), subst);
}
}
| 1,175 | 26.348837 | 98 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/ast/AstFieldSym.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.ast;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.ast.JModifier;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.Substitution;
import net.sourceforge.pmd.lang.java.types.TypeOps;
final class AstFieldSym extends AbstractAstVariableSym implements JFieldSymbol {
private final JClassSymbol owner;
AstFieldSym(ASTVariableDeclaratorId node,
AstSymFactory factory,
JClassSymbol owner) {
super(node, factory);
this.owner = owner;
}
@Override
public int getModifiers() {
return JModifier.toReflect(node.getModifiers().getEffectiveModifiers());
}
@Override
public @Nullable Object getConstValue() {
if (node.hasModifiers(JModifier.STATIC, JModifier.FINAL)) {
ASTExpression init = node.getInitializer();
return init == null ? null : init.getConstValue();
}
return null;
}
@Override
public boolean isEnumConstant() {
return node.isEnumConstant();
}
@Override
public @NonNull JClassSymbol getEnclosingClass() {
return owner;
}
@Override
public JTypeMirror getTypeMirror(Substitution subst) {
// enum constants ha
return TypeOps.subst(node.getTypeMirror(), subst);
}
}
| 1,819 | 29.333333 | 80 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/ast/AbstractAstBackedSymbol.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.ast;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.java.ast.InternalApiBridge;
import net.sourceforge.pmd.lang.java.ast.SymbolDeclaratorNode;
import net.sourceforge.pmd.lang.java.symbols.JElementSymbol;
import net.sourceforge.pmd.lang.java.symbols.internal.SymbolEquality;
import net.sourceforge.pmd.lang.java.symbols.internal.SymbolToStrings;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
/**
* @author Clément Fournier
*/
abstract class AbstractAstBackedSymbol<T extends SymbolDeclaratorNode> implements JElementSymbol {
protected final T node;
protected final AstSymFactory factory;
protected AbstractAstBackedSymbol(T node, AstSymFactory factory) {
this.node = node;
this.factory = factory;
InternalApiBridge.setSymbol(node, this);
}
@Override
public TypeSystem getTypeSystem() {
return node.getTypeSystem();
}
@Override
public @NonNull T tryGetNode() {
return node;
}
@Override
public String toString() {
return SymbolToStrings.AST.toString(this);
}
@Override
public boolean equals(Object o) {
return SymbolEquality.equals(this, o);
}
@Override
public int hashCode() {
return SymbolEquality.hash(this);
}
}
| 1,461 | 25.581818 | 98 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/ast/AbstractAstAnnotableSym.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.ast;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.java.ast.Annotatable;
import net.sourceforge.pmd.lang.java.ast.SymbolDeclaratorNode;
import net.sourceforge.pmd.lang.java.symbols.AnnotableSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
/**
* @author Clément Fournier
*/
abstract class AbstractAstAnnotableSym<T extends SymbolDeclaratorNode & Annotatable>
extends AbstractAstBackedSymbol<T> implements AnnotableSymbol {
private PSet<SymAnnot> annots;
AbstractAstAnnotableSym(T node, AstSymFactory factory) {
super(node, factory);
}
@Override
public PSet<SymAnnot> getDeclaredAnnotations() {
if (annots == null) {
annots = SymbolResolutionPass.buildSymbolicAnnotations(node.getDeclaredAnnotations());
}
return annots;
}
}
| 991 | 27.342857 | 98 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/ast/AstTypeParamSym.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.ast;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.java.ast.ASTType;
import net.sourceforge.pmd.lang.java.ast.ASTTypeParameter;
import net.sourceforge.pmd.lang.java.symbols.JTypeParameterOwnerSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeParameterSymbol;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.JTypeVar;
final class AstTypeParamSym
extends AbstractAstAnnotableSym<ASTTypeParameter>
implements JTypeParameterSymbol {
private final JTypeVar tvar;
private final AbstractAstTParamOwner<?> owner;
AstTypeParamSym(ASTTypeParameter node, AstSymFactory factory, AbstractAstTParamOwner<?> owner) {
super(node, factory);
this.owner = owner;
this.tvar = factory.types().newTypeVar(this);
}
@Override
public JTypeVar getTypeMirror() {
return tvar;
}
@Override
public JTypeMirror computeUpperBound() {
ASTType bound = node.getTypeBoundNode();
return bound == null ? node.getTypeSystem().OBJECT
: bound.getTypeMirror();
}
@Override
public JTypeParameterOwnerSymbol getDeclaringSymbol() {
return owner;
}
@NonNull
@Override
public String getSimpleName() {
return node.getName();
}
}
| 1,507 | 27.45283 | 100 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/ast/AbstractAstTParamOwner.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.ast;
import static net.sourceforge.pmd.util.CollectionUtil.map;
import java.util.Collections;
import java.util.List;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.java.ast.ASTList;
import net.sourceforge.pmd.lang.java.ast.AccessNode;
import net.sourceforge.pmd.lang.java.ast.JModifier;
import net.sourceforge.pmd.lang.java.ast.TypeParamOwnerNode;
import net.sourceforge.pmd.lang.java.symbols.JTypeParameterOwnerSymbol;
import net.sourceforge.pmd.lang.java.types.JTypeVar;
/**
* @author Clément Fournier
*/
abstract class AbstractAstTParamOwner<T extends TypeParamOwnerNode & AccessNode>
extends AbstractAstAnnotableSym<T> implements JTypeParameterOwnerSymbol {
private final List<JTypeVar> tparams;
private final int modifiers;
AbstractAstTParamOwner(T node, AstSymFactory factory) {
super(node, factory);
this.modifiers = JModifier.toReflect(node.getModifiers().getEffectiveModifiers());
this.tparams = Collections.unmodifiableList(map(
ASTList.orEmpty(node.getTypeParameters()),
it -> new AstTypeParamSym(it, factory, this).getTypeMirror()
));
}
@Override
public int getModifiers() {
return modifiers;
}
@Override
public List<JTypeVar> getTypeParameters() {
return tparams;
}
@Override
public @NonNull String getPackageName() {
return node.getRoot().getPackageName();
}
}
| 1,611 | 28.309091 | 90 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/ast/AstClassSym.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.ast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.pcollections.HashTreePSet;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTBodyDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType;
import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall;
import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTEnumConstant;
import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTRecordComponent;
import net.sourceforge.pmd.lang.java.ast.ASTRecordComponentList;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.ast.InternalApiBridge;
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.JExecutableSymbol;
import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol;
import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeParameterOwnerSymbol;
import net.sourceforge.pmd.lang.java.symbols.internal.ImplicitMemberSymbols;
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.TypeOps;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
import net.sourceforge.pmd.util.CollectionUtil;
final class AstClassSym
extends AbstractAstTParamOwner<ASTAnyTypeDeclaration>
implements JClassSymbol {
private final @Nullable JTypeParameterOwnerSymbol enclosing;
private final List<JClassSymbol> declaredClasses;
private final List<JMethodSymbol> declaredMethods;
private final List<JConstructorSymbol> declaredCtors;
private final List<JFieldSymbol> declaredFields;
private final List<JFieldSymbol> enumConstants; // subset of declaredFields
private final PSet<String> annotAttributes;
AstClassSym(ASTAnyTypeDeclaration node,
AstSymFactory factory,
@Nullable JTypeParameterOwnerSymbol enclosing) {
super(node, factory);
this.enclosing = enclosing;
// evaluate everything strictly
// this populates symbols on the relevant AST nodes
final List<JClassSymbol> myClasses = new ArrayList<>();
final List<JMethodSymbol> myMethods = new ArrayList<>();
final List<JConstructorSymbol> myCtors = new ArrayList<>();
final List<JFieldSymbol> myFields = new ArrayList<>();
final List<JFieldSymbol> enumConstants;
final List<JFieldSymbol> recordComponents;
if (isRecord()) {
ASTRecordComponentList components = Objects.requireNonNull(node.getRecordComponents(),
"Null component list for " + node);
recordComponents = mapComponentsToMutableList(factory, components);
myFields.addAll(recordComponents);
JConstructorSymbol canonicalRecordCtor = ImplicitMemberSymbols.recordConstructor(this, recordComponents, components.isVarargs());
myCtors.add(canonicalRecordCtor);
InternalApiBridge.setSymbol(components, canonicalRecordCtor);
} else {
recordComponents = Collections.emptyList();
}
if (isEnum()) {
enumConstants = new ArrayList<>();
node.getEnumConstants()
.forEach(constant -> {
AstFieldSym fieldSym = new AstFieldSym(constant.getVarId(), factory, this);
enumConstants.add(fieldSym);
myFields.add(fieldSym);
});
} else {
enumConstants = null;
}
for (ASTBodyDeclaration dnode : node.getDeclarations()) {
if (dnode instanceof ASTAnyTypeDeclaration) {
myClasses.add(new AstClassSym((ASTAnyTypeDeclaration) dnode, factory, this));
} else if (dnode instanceof ASTMethodDeclaration) {
if (!recordComponents.isEmpty() && ((ASTMethodDeclaration) dnode).getArity() == 0) {
// filter out record component, so that the accessor is not generated
recordComponents.removeIf(f -> f.nameEquals(((ASTMethodDeclaration) dnode).getName()));
}
myMethods.add(new AstMethodSym((ASTMethodDeclaration) dnode, factory, this));
} else if (dnode instanceof ASTConstructorDeclaration) {
myCtors.add(new AstCtorSym((ASTConstructorDeclaration) dnode, factory, this));
} else if (dnode instanceof ASTFieldDeclaration) {
for (ASTVariableDeclaratorId varId : ((ASTFieldDeclaration) dnode).getVarIds()) {
myFields.add(new AstFieldSym(varId, factory, this));
}
}
}
if (!recordComponents.isEmpty()) {
// then the recordsComponents contains all record components
// for which we must synthesize an accessor (explicitly declared
// accessors have been filtered out)
for (JFieldSymbol component : recordComponents) {
myMethods.add(ImplicitMemberSymbols.recordAccessor(this, component));
}
}
if (myCtors.isEmpty() && isClass() && !isAnonymousClass()) {
myCtors.add(ImplicitMemberSymbols.defaultCtor(this));
}
if (this.isEnum()) {
myMethods.add(ImplicitMemberSymbols.enumValues(this));
myMethods.add(ImplicitMemberSymbols.enumValueOf(this));
}
this.declaredClasses = Collections.unmodifiableList(myClasses);
this.declaredMethods = Collections.unmodifiableList(myMethods);
this.declaredCtors = Collections.unmodifiableList(myCtors);
this.declaredFields = Collections.unmodifiableList(myFields);
this.enumConstants = CollectionUtil.makeUnmodifiableAndNonNull(enumConstants);
this.annotAttributes = isAnnotation()
? getDeclaredMethods().stream().filter(JMethodSymbol::isAnnotationAttribute).map(JElementSymbol::getSimpleName).collect(CollectionUtil.toPersistentSet())
: HashTreePSet.empty();
}
private List<JFieldSymbol> mapComponentsToMutableList(AstSymFactory factory, ASTRecordComponentList components) {
List<JFieldSymbol> list = new ArrayList<>();
for (ASTRecordComponent comp : components) {
list.add(new AstFieldSym(comp.getVarId(), factory, this));
}
return list;
}
@Override
public @NonNull String getSimpleName() {
return node.getSimpleName();
}
@Override
public @NonNull String getBinaryName() {
return node.getBinaryName();
}
@Override
public @Nullable String getCanonicalName() {
return node.getCanonicalName();
}
@Override
public boolean isUnresolved() {
return false;
}
@Override
public @Nullable JClassSymbol getEnclosingClass() {
if (enclosing instanceof JClassSymbol) {
return (JClassSymbol) enclosing;
} else if (enclosing instanceof JExecutableSymbol) {
return enclosing.getEnclosingClass();
}
assert enclosing == null;
return null;
}
@Override
public @Nullable JExecutableSymbol getEnclosingMethod() {
return enclosing instanceof JExecutableSymbol ? (JExecutableSymbol) enclosing : null;
}
@Override
public List<JClassSymbol> getDeclaredClasses() {
return declaredClasses;
}
@Override
public List<JMethodSymbol> getDeclaredMethods() {
return declaredMethods;
}
@Override
public List<JConstructorSymbol> getConstructors() {
return declaredCtors;
}
@Override
public List<JFieldSymbol> getDeclaredFields() {
return declaredFields;
}
@Override
public @NonNull List<JFieldSymbol> getEnumConstants() {
return enumConstants;
}
@Override
public @Nullable JClassType getSuperclassType(Substitution substitution) {
TypeSystem ts = getTypeSystem();
if (node.isEnum()) {
return factory.enumSuperclass(this);
} else if (node instanceof ASTClassOrInterfaceDeclaration) {
ASTClassOrInterfaceType superClass = ((ASTClassOrInterfaceDeclaration) node).getSuperClassTypeNode();
return superClass == null
? ts.OBJECT
// this cast relies on the fact that the superclass is not a type variable
: (JClassType) TypeOps.subst(superClass.getTypeMirror(), substitution);
} else if (isAnonymousClass()) {
if (node.getParent() instanceof ASTEnumConstant) {
return node.getEnclosingType().getTypeMirror().subst(substitution);
} else if (node.getParent() instanceof ASTConstructorCall) {
@NonNull JTypeMirror sym = ((ASTConstructorCall) node.getParent()).getTypeMirror();
return sym instanceof JClassType && !sym.isInterface()
? (JClassType) sym
: factory.types().OBJECT;
}
} else if (isRecord()) {
return factory.recordSuperclass();
} else if (isAnnotation()) {
return ts.OBJECT;
}
return null;
}
@Override
public @Nullable JClassSymbol getSuperclass() {
// notice this relies on the fact that the extends clause
// (or the type node of the constructor call, for an anonymous class),
// was disambiguated early
// We special case anonymous classes so as not to trigger overload resolution
if (isAnonymousClass() && node.getParent() instanceof ASTConstructorCall) {
@NonNull JTypeMirror sym = ((ASTConstructorCall) node.getParent()).getTypeNode().getTypeMirror();
return sym instanceof JClassType && !sym.isInterface()
? ((JClassType) sym).getSymbol()
: factory.types().OBJECT.getSymbol();
}
JClassType sup = getSuperclassType(Substitution.EMPTY);
return sup == null ? null : sup.getSymbol();
}
@Override
public List<JClassSymbol> getSuperInterfaces() {
List<JClassSymbol> itfs = CollectionUtil.mapNotNull(
node.getSuperInterfaceTypeNodes(),
n -> {
// we play safe here, but the symbol is either a JClassSymbol
// or a JTypeParameterSymbol, with the latter case being a
// compile-time error
JTypeDeclSymbol sym = n.getTypeMirror().getSymbol();
return sym instanceof JClassSymbol ? (JClassSymbol) sym : null;
}
);
if (isAnnotation()) {
itfs = CollectionUtil.concatView(Collections.singletonList(factory.annotationSym()), itfs);
}
return itfs;
}
@Override
public List<JClassType> getSuperInterfaceTypes(Substitution subst) {
List<JClassType> itfs = CollectionUtil.map(node.getSuperInterfaceTypeNodes(), n -> (JClassType) TypeOps.subst(n.getTypeMirror(), subst));
if (isAnnotation()) {
itfs = CollectionUtil.concatView(Collections.singletonList(factory.annotationType()), itfs);
}
return itfs;
}
@Override
public @Nullable JTypeDeclSymbol getArrayComponent() {
return null;
}
@Override
public boolean isArray() {
return false;
}
@Override
public boolean isPrimitive() {
return false;
}
@Override
public boolean isInterface() {
return node.isInterface();
}
@Override
public boolean isEnum() {
return node.isEnum();
}
@Override
public boolean isRecord() {
return node.isRecord();
}
@Override
public boolean isAnnotation() {
return node.isAnnotation();
}
@Override
public boolean isLocalClass() {
return node.isLocal();
}
@Override
public boolean isAnonymousClass() {
return node.isAnonymous();
}
@Override
public PSet<String> getAnnotationAttributeNames() {
return annotAttributes;
}
}
| 13,101 | 35.19337 | 184 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/ast/SymbolResolutionPass.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.ast;
import java.util.Objects;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.ast.NodeStream;
import net.sourceforge.pmd.lang.java.ast.ASTAnnotation;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.InternalApiBridge;
import net.sourceforge.pmd.lang.java.ast.SymbolDeclaratorNode;
import net.sourceforge.pmd.lang.java.internal.JavaAstProcessor;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolResolver;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* Populates symbols on declaration nodes.
*/
public final class SymbolResolutionPass {
private SymbolResolutionPass() {
// façade
}
/**
* Traverse the given compilation unit, creating symbols on all
* {@link SymbolDeclaratorNode}s.
*
* @param processor Processor
* @param root Root node
*
* @return A symbol resolver for all encountered type declarations.
* This is used to avoid hitting the classloader for local declarations.
*/
public static SymbolResolver traverse(JavaAstProcessor processor, ASTCompilationUnit root) {
AstSymbolMakerVisitor visitor = new AstSymbolMakerVisitor(root);
root.acceptVisitor(visitor, new AstSymFactory(processor));
return visitor.makeKnownSymbolResolver();
}
/**
* Converts between nodes to {@link SymAnnot}. Annotations that could not be converted,
* eg because they are written with invalid code, are discarded.
*/
public static PSet<SymAnnot> buildSymbolicAnnotations(NodeStream<ASTAnnotation> annotations) {
return annotations.toStream()
.map(SymbolResolutionPass::toValidAnnotation)
.filter(Objects::nonNull)
.collect(CollectionUtil.toPersistentSet());
}
private static @Nullable SymAnnot toValidAnnotation(ASTAnnotation node) {
JTypeDeclSymbol sym = InternalApiBridge.getReferencedSym(node.getTypeNode());
if (sym instanceof JClassSymbol) {
return new AstSymbolicAnnot(node, (JClassSymbol) sym);
}
return null;
}
}
| 2,555 | 36.043478 | 98 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/ast/AbstractAstExecSymbol.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.ast;
import java.util.List;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.ASTList;
import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTReceiverParameter;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JExecutableSymbol;
import net.sourceforge.pmd.lang.java.symbols.JFormalParamSymbol;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.Substitution;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* @author Clément Fournier
*/
abstract class AbstractAstExecSymbol<T extends ASTMethodOrConstructorDeclaration>
extends AbstractAstTParamOwner<T>
implements JExecutableSymbol {
private final JClassSymbol owner;
private final List<JFormalParamSymbol> formals;
protected AbstractAstExecSymbol(T node, AstSymFactory factory, JClassSymbol owner) {
super(node, factory);
this.owner = owner;
this.formals = CollectionUtil.map(
node.getFormalParameters(),
p -> new AstFormalParamSym(p.getVarId(), factory, this)
);
}
@Override
public List<JFormalParamSymbol> getFormalParameters() {
return formals;
}
@Override
public List<JTypeMirror> getFormalParameterTypes(Substitution subst) {
return CollectionUtil.map(getFormalParameters(), i -> i.getTypeMirror(subst));
}
@Override
public List<JTypeMirror> getThrownExceptionTypes(Substitution subst) {
return CollectionUtil.map(
ASTList.orEmpty(node.getThrowsList()),
t -> t.getTypeMirror().subst(subst)
);
}
@Override
public @Nullable JTypeMirror getAnnotatedReceiverType(Substitution subst) {
if (!this.hasReceiver()) {
return null;
}
ASTReceiverParameter receiver = node.getFormalParameters().getReceiverParameter();
if (receiver == null) {
return getTypeSystem().declaration(getEnclosingClass()).subst(subst);
}
return receiver.getReceiverType().getTypeMirror().subst(subst);
}
@Override
public @NonNull JClassSymbol getEnclosingClass() {
return owner;
}
@Override
public boolean isVarargs() {
return node.isVarargs();
}
@Override
public int getArity() {
return formals.size();
}
}
| 2,688 | 28.877778 | 90 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/ast/AstSymbolicAnnot.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.ast;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.ASTAnnotation;
import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr;
import net.sourceforge.pmd.lang.java.ast.ASTClassLiteral;
import net.sourceforge.pmd.lang.java.ast.ASTMemberValue;
import net.sourceforge.pmd.lang.java.ast.ASTMemberValueArrayInitializer;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue;
import net.sourceforge.pmd.lang.java.symbols.internal.SymbolEquality;
import net.sourceforge.pmd.lang.java.symbols.internal.SymbolToStrings;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
/**
*
*/
class AstSymbolicAnnot implements SymbolicValue.SymAnnot {
private final ASTAnnotation node;
private final JClassSymbol sym;
AstSymbolicAnnot(@NonNull ASTAnnotation node, @NonNull JClassSymbol sym) {
this.node = node;
this.sym = Objects.requireNonNull(sym);
}
@Override
public @Nullable SymbolicValue getAttribute(String attrName) {
ASTMemberValue explicitAttr = node.getAttribute(attrName);
if (explicitAttr != null) {
return ofNode(explicitAttr);
}
return getAnnotationSymbol().getDefaultAnnotationAttributeValue(attrName);
}
@Override
public @NonNull JClassSymbol getAnnotationSymbol() {
return sym;
}
@Override
public String getSimpleName() {
return node.getSimpleName();
}
@Override
public boolean equals(Object o) {
return SymbolEquality.ANNOTATION.equals(this, o);
}
@Override
public int hashCode() {
return SymbolEquality.ANNOTATION.hash(this);
}
@Override
public String toString() {
return SymbolToStrings.AST.toString(this);
}
static SymbolicValue ofNode(ASTMemberValue valueNode) {
if (valueNode == null) {
return null;
}
{ // note: this returns null for enums, annotations, and classes
Object constValue = valueNode.getConstValue();
if (constValue != null) {
return SymbolicValue.of(valueNode.getTypeSystem(), constValue);
}
}
if (valueNode instanceof ASTMemberValueArrayInitializer) {
// array
List<SymbolicValue> elements = new ArrayList<>(valueNode.getNumChildren());
for (ASTMemberValue elt : (ASTMemberValueArrayInitializer) valueNode) {
SymbolicValue symElt = ofNode(elt);
if (symElt == null) {
return null;
}
elements.add(symElt);
}
return SymArray.forElements(elements);
} else if (valueNode instanceof ASTClassLiteral) {
// class
JTypeDeclSymbol symbol = ((ASTClassLiteral) valueNode).getTypeNode().getTypeMirror().getSymbol();
if (symbol instanceof JClassSymbol) {
return SymClass.ofBinaryName(symbol.getTypeSystem(), ((JClassSymbol) symbol).getBinaryName());
}
} else if (valueNode instanceof ASTNamedReferenceExpr) {
// enum constants
ASTNamedReferenceExpr refExpr = (ASTNamedReferenceExpr) valueNode;
JTypeMirror t = refExpr.getTypeMirror();
if (t instanceof JClassType && ((JClassType) t).getSymbol().isEnum()) {
return SymEnum.fromBinaryName(t.getTypeSystem(),
((JClassType) t).getSymbol().getBinaryName(),
refExpr.getName());
}
}
return null;
}
}
| 4,113 | 34.162393 | 110 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/ast/AbstractAstVariableSym.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.ast;
import static net.sourceforge.pmd.lang.java.types.TypeOps.subst;
import net.sourceforge.pmd.lang.java.ast.ASTType;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.Substitution;
/**
* @author Clément Fournier
*/
abstract class AbstractAstVariableSym
extends AbstractAstAnnotableSym<ASTVariableDeclaratorId>
implements JVariableSymbol {
AbstractAstVariableSym(ASTVariableDeclaratorId node, AstSymFactory factory) {
super(node, factory);
}
@Override
public boolean isFinal() {
return node.isFinal();
}
@Override
public String getSimpleName() {
return node.getName();
}
@Override
public JTypeMirror getTypeMirror(Substitution subst) {
ASTType typeNode = node.getTypeNode();
/*
Overridden on LocalVarSym.
This gives up on inferred types until a LazyTypeResolver has
been set for the compilation unit.
Thankfully, the type of local vars is never requested by
anything before that moment.
*/
assert typeNode != null : "This implementation expects explicit types (" + this + ")";
return subst(node.getTypeMirror(), subst);
}
}
| 1,538 | 28.596154 | 94 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/ast/MapSymResolver.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.ast;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolResolver;
/**
* A symbol resolver that knows about a few hand-picked symbols.
*/
final class MapSymResolver implements SymbolResolver {
private final Map<String, JClassSymbol> byCanonicalName;
private final Map<String, JClassSymbol> byBinaryName;
MapSymResolver(Map<String, JClassSymbol> byCanonicalName,
Map<String, JClassSymbol> byBinaryName) {
this.byCanonicalName = byCanonicalName;
this.byBinaryName = byBinaryName;
}
@Override
public @Nullable JClassSymbol resolveClassFromBinaryName(@NonNull String binaryName) {
return byBinaryName.get(binaryName);
}
@Override
public @Nullable JClassSymbol resolveClassFromCanonicalName(@NonNull String canonicalName) {
return byCanonicalName.get(canonicalName);
}
}
| 1,209 | 30.025641 | 96 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/TypeAnnotationReceiver.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.objectweb.asm.TypePath;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
interface TypeAnnotationReceiver {
void acceptTypeAnnotation(int typeRef, @Nullable TypePath path, SymAnnot annot);
}
| 439 | 24.882353 | 84 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/AsmSymbolResolver.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import java.net.URL;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.objectweb.asm.Opcodes;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolResolver;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.Loader.FailedLoader;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.Loader.UrlLoader;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
import net.sourceforge.pmd.util.AssertionUtil;
/**
* A {@link SymbolResolver} that reads class files to produce symbols.
*/
public class AsmSymbolResolver implements SymbolResolver {
static final int ASM_API_V = Opcodes.ASM9;
private final TypeSystem ts;
private final Classpath classLoader;
private final SignatureParser typeLoader;
private final ConcurrentMap<String, ClassStub> knownStubs = new ConcurrentHashMap<>();
/**
* Sentinel for when we fail finding a URL. This allows using a single map,
* instead of caching failure cases separately.
*/
private final ClassStub failed;
public AsmSymbolResolver(TypeSystem ts, Classpath classLoader) {
this.ts = ts;
this.classLoader = classLoader;
this.typeLoader = new SignatureParser(this);
this.failed = new ClassStub(this, "/*failed-lookup*/", FailedLoader.INSTANCE, 0);
}
@Override
public @Nullable JClassSymbol resolveClassFromBinaryName(@NonNull String binaryName) {
AssertionUtil.requireParamNotNull("binaryName", binaryName);
String internalName = getInternalName(binaryName);
ClassStub found = knownStubs.computeIfAbsent(internalName, iname -> {
@Nullable URL url = getUrlOfInternalName(iname);
if (url == null) {
return failed;
}
return new ClassStub(this, iname, new UrlLoader(url), ClassStub.UNKNOWN_ARITY);
});
if (!found.hasCanonicalName()) {
// note: this check needs to be done outside of computeIfAbsent
// to prevent recursive updates of the knownStubs map.
knownStubs.put(internalName, failed);
found = failed;
}
return found == failed ? null : found; // NOPMD CompareObjectsWithEquals
}
SignatureParser getSigParser() {
return typeLoader;
}
TypeSystem getTypeSystem() {
return ts;
}
static @NonNull String getInternalName(@NonNull String binaryName) {
return binaryName.replace('.', '/');
}
@Nullable
URL getUrlOfInternalName(String internalName) {
return classLoader.findResource(internalName + ".class");
}
/*
These methods return an unresolved symbol if the url is not found.
*/
@Nullable ClassStub resolveFromInternalNameCannotFail(@Nullable String internalName) {
if (internalName == null) {
return null;
}
return resolveFromInternalNameCannotFail(internalName, ClassStub.UNKNOWN_ARITY);
}
@SuppressWarnings("PMD.CompareObjectsWithEquals") // ClassStub
@NonNull ClassStub resolveFromInternalNameCannotFail(@NonNull String internalName, int observedArity) {
return knownStubs.compute(internalName, (iname, prev) -> {
if (prev != failed && prev != null) {
return prev;
}
@Nullable URL url = getUrlOfInternalName(iname);
Loader loader = url == null ? FailedLoader.INSTANCE : new UrlLoader(url);
return new ClassStub(this, iname, loader, observedArity);
});
}
}
| 3,892 | 33.149123 | 107 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/SymbolicValueBuilder.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Type;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymArray;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymEnum;
abstract class SymbolicValueBuilder extends AnnotationVisitor {
private final AsmSymbolResolver resolver;
SymbolicValueBuilder(AsmSymbolResolver resolver) {
super(AsmSymbolResolver.ASM_API_V);
this.resolver = resolver;
}
AsmSymbolResolver getResolver() {
return resolver;
}
protected abstract void acceptValue(String name, SymbolicValue v);
@Override
public void visitEnum(String name, String descriptor, String value) {
acceptValue(name, SymEnum.fromTypeDescriptor(resolver.getTypeSystem(), descriptor, value));
}
@Override
public void visit(String name, Object value) {
if (value instanceof Type) {
acceptValue(name, SymbolicValue.SymClass.ofBinaryName(resolver.getTypeSystem(), ((Type) value).getClassName()));
} else {
acceptValue(name, SymbolicValue.of(resolver.getTypeSystem(), value));
}
}
@Override
public AnnotationVisitor visitArray(String name) {
return new ArrayValueBuilder(resolver, new ArrayList<>(), v -> acceptValue(name, v));
}
static class ArrayValueBuilder extends SymbolicValueBuilder {
private final List<SymbolicValue> arrayElements;
private final Consumer<SymbolicValue> finisher;
ArrayValueBuilder(AsmSymbolResolver resolver, List<SymbolicValue> arrayElements, Consumer<SymbolicValue> finisher) {
super(resolver);
this.arrayElements = arrayElements;
this.finisher = finisher;
}
@Override
protected void acceptValue(String name, SymbolicValue v) {
arrayElements.add(v);
}
@Override
public void visitEnd() {
finisher.accept(SymArray.forElements(arrayElements));
}
}
}
| 2,311 | 29.826667 | 124 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/TypeParamsParser.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import static net.sourceforge.pmd.lang.java.symbols.internal.asm.TypeSigParser.identifier;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.pmd.lang.java.types.JTypeVar;
final class TypeParamsParser {
private TypeParamsParser() {
}
static boolean hasTypeParams(String descriptor) {
return descriptor.charAt(0) == '<';
}
static int typeParams(final int start, BaseTypeParamsBuilder b) {
int cur = b.consumeChar(start, '<', "type parameters");
do {
int idStart = cur;
cur = identifier(cur, b, null);
String tvarName = b.bufferToString(idStart, cur);
final int boundStart = cur;
cur = scanTypeBound(cur, b);
b.addTypeParam(tvarName, b.bufferToString(boundStart, cur));
} while (b.charAt(cur) != '>');
cur = b.consumeChar(cur, '>');
return cur;
}
/**
* This just skips the bound entirely, they will be parsed lazily
* later (because they may be self-referential).
*/
private static int scanTypeBound(final int start, SignatureScanner b) {
int cur = b.consumeChar(start, ':', "class bound");
char next = b.charAt(cur);
if (next == '[' || next == 'L' || next == 'T') {
// If the character after the ':' class bound marker is not the start of a
// ReferenceTypeSignature, it means the class bound is empty (which is a valid case).
cur = skipReferenceType(cur, b);
}
while (b.charAt(cur) == ':') {
cur = b.consumeChar(cur, ':');
cur = skipReferenceType(cur, b);
}
return cur;
}
static int skipReferenceType(final int start, SignatureScanner b) {
int cur = start;
int targDepth = 0;
char c;
while (cur < b.end) {
c = b.charAt(cur);
switch (c) {
case 'T':
cur = b.nextIndexOf(cur, ';');
continue;
case '.':
case 'L':
cur = b.nextIndexOfAny(cur, ';', '<');
continue;
case '<':
targDepth++;
cur++;
break;
case '>':
targDepth--;
cur++;
break;
case ';':
if (targDepth == 0) {
return cur + 1;
}
cur++;
break;
case '[':
case '+':
case '-':
case '*':
// pass
cur++;
break;
default:
throw b.expected("reference type part TL<;>[+-*.", cur);
}
}
return cur;
}
/**
* Boilerplate interface used to mock a builder for testing.
*/
abstract static class BaseTypeParamsBuilder extends SignatureScanner {
BaseTypeParamsBuilder(String descriptor) {
super(descriptor);
}
abstract void addTypeParam(String id, String bound);
}
static class TypeParametersBuilder extends BaseTypeParamsBuilder {
private final GenericSigBase<?> sig;
private final List<JTypeVar> ownTypeParams = new ArrayList<>(1);
TypeParametersBuilder(GenericSigBase<?> sig, String descriptor) {
super(descriptor);
this.sig = sig;
assert hasTypeParams(descriptor) : "No type parameters in this signature";
}
List<JTypeVar> getOwnerTypeParams() {
return ownTypeParams;
}
@Override
void addTypeParam(String id, String bound) {
ownTypeParams.add(new TParamStub(id, sig, bound).getTypeMirror());
}
}
}
| 3,952 | 26.838028 | 97 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/TypeSigParser.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import static java.util.Collections.emptyList;
import java.util.ArrayList;
import java.util.List;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.GenericSigBase.LazyMethodType;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.LexicalScope;
import net.sourceforge.pmd.lang.java.types.SubstVar;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
/**
* Implementation of the signature parser.
*/
final class TypeSigParser {
private TypeSigParser() {
// utility class
}
static int classHeader(final int start, TypeScanner b) {
int cur = classType(start, b); // superclass
JTypeMirror superClass = b.pop();
if (b.charAt(cur) == 'L') {
List<JTypeMirror> superItfs = new ArrayList<>(1);
do {
cur = classType(cur, b);
superItfs.add(b.pop());
} while (b.charAt(cur) == 'L');
b.pushList(superItfs);
} else {
b.pushList(emptyList());
}
b.push(superClass);
return cur;
}
static int methodType(LazyMethodType type, final int start, TypeScanner b) {
int cur = parameterTypes(start, b);
type.setParameterTypes(b.popList());
cur = typeSignature(cur, b, true); // return type
type.setReturnType(b.pop());
cur = throwsSignaturesOpt(cur, b);
type.setExceptionTypes(b.popList());
return cur;
}
private static int parameterTypes(int start, TypeScanner b) {
int cur = b.consumeChar(start, '(', "parameter types");
if (b.charAt(cur) == ')') {
b.pushList(emptyList()); // empty parameters
} else {
List<JTypeMirror> params = new ArrayList<>(1);
do {
cur = typeSignature(cur, b);
params.add(b.pop());
} while (b.charAt(cur) != ')');
b.pushList(params);
}
cur = b.consumeChar(cur, ')');
return cur;
}
private static int throwsSignaturesOpt(final int start, TypeScanner b) {
int cur = start;
if (b.charAt(cur) == '^') {
List<JTypeMirror> thrown = new ArrayList<>(1);
do {
cur = b.consumeChar(cur, '^', "throws signature");
char next = b.charAt(cur);
if (next != 'T' && next != 'L') {
// shouldn't be a base type
throw b.expected("an exception type", cur);
}
cur = typeSignature(cur, b);
thrown.add(b.pop());
} while (b.charAt(cur) == '^');
b.pushList(thrown);
} else {
b.pushList(emptyList());
}
return cur;
}
static int typeVarBound(final int start, TypeScanner b) {
List<JTypeMirror> bounds = new ArrayList<>();
int cur = b.consumeChar(start, ':', "class bound");
char next = b.charAt(cur);
if (next == '[' || next == 'L' || next == 'T') {
// If the character after the ':' class bound marker is not the start of a
// ReferenceTypeSignature, it means the class bound is empty (which is a valid case).
cur = typeSignature(cur, b);
bounds.add(b.pop());
}
while (b.charAt(cur) == ':') {
cur = b.consumeChar(cur, ':');
cur = typeSignature(cur, b);
bounds.add(b.pop());
}
if (bounds.isEmpty()) {
b.push(b.ts.OBJECT);
} else {
b.push(b.ts.glb(bounds));
}
return cur;
}
static int typeSignature(final int start, TypeScanner b) {
return typeSignature(start, b, false);
}
private static int typeSignature(final int start, TypeScanner b, boolean acceptVoid) {
char firstChar = b.charAt(start);
switch (firstChar) {
case 'V':
if (!acceptVoid) {
throw b.expected("a type, got void", start);
}
// intentional fallthrough
case 'Z':
case 'C':
case 'B':
case 'S':
case 'I':
case 'F':
case 'J':
case 'D':
b.push(b.getBaseType(firstChar));
return start + 1;
case '[':
return arrayType(start, b);
case 'L':
return classType(start, b);
case 'T':
return typeVar(start, b);
default:
throw b.expected("type", start);
}
}
private static int classType(final int start, TypeScanner b) {
StringBuilder internalName = new StringBuilder();
int cur = b.consumeChar(start, 'L', "object type");
cur = classId(cur, b, internalName);
cur = typeArgsOpt(cur, b);
JClassType t = b.makeClassType(internalName.toString(), b.popList());
while (b.charAt(cur) == '.') {
internalName.append('$');
cur += 1;
cur = identifier(cur, b, internalName);
cur = typeArgsOpt(cur, b);
t = b.parameterize(t, internalName.toString(), b.popList());
}
b.push(t);
return b.consumeChar(cur, ';', "semicolon");
}
private static int typeArgsOpt(final int start, TypeScanner b) {
if (b.charAt(start) == '<') {
List<JTypeMirror> l = new ArrayList<>(2);
int cur = b.consumeChar(start, '<');
while (b.charAt(cur) != '>') {
cur = typeArg(cur, b);
l.add(b.pop());
}
cur = b.consumeChar(cur, '>');
b.pushList(l);
return cur;
} else {
b.pushList(emptyList());
return start;
}
}
private static int typeArg(final int start, TypeScanner b) {
int cur = start;
char firstChar = b.charAt(cur);
switch (firstChar) {
case '*':
b.push(b.ts.UNBOUNDED_WILD);
return cur + 1;
case '+':
case '-':
cur = typeSignature(cur + 1, b);
b.push(b.ts.wildcard(firstChar == '+', b.pop()));
return cur;
default:
return typeSignature(cur, b);
}
}
private static int arrayType(final int start, TypeScanner b) {
int cur = b.consumeChar(start, '[', "array type");
cur = typeSignature(cur, b);
b.push(b.ts.arrayType(b.pop()));
return cur;
}
private static int typeVar(final int start, TypeScanner b) {
int cur = b.consumeChar(start, 'T', "type variable");
StringBuilder nameBuilder = new StringBuilder();
cur = identifier(cur, b, nameBuilder);
cur = b.consumeChar(cur, ';');
b.push(b.lookupTvar(nameBuilder.toString()));
return cur;
}
private static int classId(final int start, SignatureScanner b, StringBuilder internalName) {
int cur = start;
cur = identifier(cur, b, null);
while (b.charAt(cur) == '/') { // package specifier
cur = cur + 1; // the slash
cur = identifier(cur, b, null);
}
b.dumpChars(start, cur, internalName);
return cur;
}
static int identifier(final int start, SignatureScanner b, @Nullable StringBuilder sb) {
int cur = start;
if (!isIdentifierChar(b.charAt(cur))) {
throw b.expected("identifier", cur);
}
do {
cur++;
} while (isIdentifierChar(b.charAt(cur)));
if (sb != null) {
b.dumpChars(start, cur, sb);
}
return cur;
}
private static boolean isIdentifierChar(char c) {
switch (c) {
case '.':
case ';':
case ':':
case '[':
case '/':
case '<':
case '>':
case 0:
return false;
default:
return true;
}
}
interface ParseFunction {
int parse(int offset, TypeScanner scanner);
}
abstract static class TypeScanner extends SignatureScanner {
// 1-element "stacks", push must be followed by pop
private @Nullable JTypeMirror type;
private @Nullable List<JTypeMirror> list;
private final TypeSystem ts;
private final LexicalScope lexicalScope;
TypeScanner(TypeSystem ts, LexicalScope lexicalScope, String descriptor) {
super(descriptor);
this.ts = ts;
this.lexicalScope = lexicalScope;
}
TypeScanner(TypeSystem ts, LexicalScope lexicalScope, String chars, int start, int end) {
super(chars, start, end);
this.ts = ts;
this.lexicalScope = lexicalScope;
}
void pushList(List<JTypeMirror> l) {
assert this.list == null;
assert l != null;
this.list = l;
}
void push(JTypeMirror mirror) {
assert this.type == null;
assert mirror != null;
this.type = mirror;
}
JTypeMirror pop() {
assert this.type != null;
JTypeMirror t = this.type;
this.type = null;
return t;
}
List<JTypeMirror> popList() {
assert this.list != null;
List<JTypeMirror> l = this.list;
this.list = null;
return l;
}
/**
* Makes a class symbol from its internal name. This should return
* non-null, if the symbol is not found (linkage error) then return
* an unresolved symbol.
*/
@NonNull
public abstract JClassSymbol makeClassSymbol(String internalName, int observedArity);
public JTypeMirror getBaseType(char baseType) {
switch (baseType) {
case 'V': return ts.NO_TYPE;
case 'Z': return ts.BOOLEAN;
case 'C': return ts.CHAR;
case 'B': return ts.BYTE;
case 'S': return ts.SHORT;
case 'I': return ts.INT;
case 'F': return ts.FLOAT;
case 'J': return ts.LONG;
case 'D': return ts.DOUBLE;
default: throw new IllegalArgumentException("'" + baseType + "' is not a valid base type descriptor");
}
}
public JTypeMirror lookupTvar(String name) {
@Nullable SubstVar mapped = lexicalScope.apply(name);
if (mapped == null) {
throw new IllegalArgumentException(
"The lexical scope " + lexicalScope + " does not contain an entry for type variable " + name
);
}
return mapped;
}
public JClassType makeClassType(String internalName, List<JTypeMirror> targs) {
return (JClassType) ts.parameterise(makeClassSymbol(internalName, targs.size()), targs);
}
public JClassType parameterize(JClassType owner, String internalName, List<JTypeMirror> targs) {
return owner.selectInner(makeClassSymbol(internalName, targs.size()), targs);
}
}
}
| 11,536 | 29.847594 | 114 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/SymbolicAnnotationImpl.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import java.lang.annotation.RetentionPolicy;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.lang.java.symbols.internal.SymbolEquality;
import net.sourceforge.pmd.lang.java.symbols.internal.SymbolToStrings;
/**
* An annotation parsed from a class file.
*/
final class SymbolicAnnotationImpl implements SymAnnot {
private final JClassSymbol typeStub;
/** Many annotations have no attributes so this remains the singleton emptyMap in this case. */
private @NonNull Map<String, SymbolicValue> explicitAttrs = Collections.emptyMap();
private final boolean runtimeVisible;
SymbolicAnnotationImpl(AsmSymbolResolver resolver, boolean runtimeVisible, String descriptor) {
this.runtimeVisible = runtimeVisible;
this.typeStub = resolver.resolveFromInternalNameCannotFail(ClassNamesUtil.classDescriptorToInternalName(descriptor));
}
void addAttribute(String name, SymbolicValue value) {
if (explicitAttrs.isEmpty()) {
explicitAttrs = new HashMap<>(); // make it modifiable
}
explicitAttrs.put(name, value);
}
@Override
public @Nullable SymbolicValue getAttribute(String attrName) {
SymbolicValue value = explicitAttrs.get(attrName);
if (value != null) {
return value;
}
return typeStub.getDefaultAnnotationAttributeValue(attrName);
}
@Override
public RetentionPolicy getRetention() {
return runtimeVisible ? RetentionPolicy.RUNTIME
: RetentionPolicy.CLASS;
}
@Override
public @NonNull JClassSymbol getAnnotationSymbol() {
return typeStub;
}
@Override
public boolean equals(Object o) {
return SymbolEquality.ANNOTATION.equals(this, o);
}
@Override
public int hashCode() {
return SymbolEquality.ANNOTATION.hash(this);
}
@Override
public String toString() {
return SymbolToStrings.ASM.toString(this);
}
}
| 2,488 | 30.910256 | 125 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/Loader.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
abstract class Loader {
@Nullable
abstract InputStream getInputStream() throws IOException;
static class FailedLoader extends Loader {
static final FailedLoader INSTANCE = new FailedLoader();
@Override
@Nullable InputStream getInputStream() {
return null;
}
@Override
public String toString() {
return "(failed loader)";
}
}
static class UrlLoader extends Loader {
private final @NonNull URL url;
UrlLoader(@NonNull URL url) {
assert url != null : "Null url";
this.url = url;
}
@Override
@Nullable
InputStream getInputStream() throws IOException {
return url.openStream();
}
@Override
public String toString() {
return "(URL loader)";
}
}
}
| 1,237 | 18.967742 | 79 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/TypeAnnotationHelper.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.objectweb.asm.TypePath;
import org.objectweb.asm.TypeReference;
import org.pcollections.ConsPStack;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.lang.java.types.JArrayType;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.JWildcardType;
/**
* @author Clément Fournier
*/
final class TypeAnnotationHelper {
private TypeAnnotationHelper() {
// utility class
}
/** Accumulate type annotations to be applied on a single type. */
static final class TypeAnnotationSet {
private final List<Pair<@Nullable TypePath, SymAnnot>> pathAndAnnot = new ArrayList<>();
void add(@Nullable TypePath path, SymAnnot annot) {
pathAndAnnot.add(Pair.of(path, annot));
}
/**
* Transform the given type to apply type annotations. Returns
* the type decorated with type annotations in the right places.
*/
JTypeMirror decorate(@NonNull JTypeMirror base) {
for (Pair<@Nullable TypePath, SymAnnot> pair : pathAndAnnot) {
base = applySinglePath(base, pair.getLeft(), pair.getRight());
}
return base;
}
}
/**
* Accumulate type annotations to be applied on a more complex signature than just a field.
* This includes method signatures and class signatures.
*/
static final class TypeAnnotationSetWithReferences {
private final List<Triple<TypeReference, @Nullable TypePath, SymAnnot>> pathAndAnnot = new ArrayList<>();
void add(TypeReference reference, @Nullable TypePath path, SymAnnot annot) {
pathAndAnnot.add(Triple.of(reference, path, annot));
}
/** Return true if the parameter returns true on any parameter. */
boolean forEach(TypeAnnotationConsumer consumer) {
boolean result = false;
for (Triple<TypeReference, TypePath, SymAnnot> triple : pathAndAnnot) {
result |= consumer.acceptAnnotation(triple.getLeft(), triple.getMiddle(), triple.getRight());
}
return result;
}
@Override
public String toString() {
return pathAndAnnot.toString();
}
@FunctionalInterface
interface TypeAnnotationConsumer {
/** Add an annotation at the given path and type ref. */
boolean acceptAnnotation(TypeReference tyRef, @Nullable TypePath path, SymAnnot annot);
}
}
/**
* Add one type annotation into the given type at the location given
* by the given path.
*/
static JTypeMirror applySinglePath(@NonNull JTypeMirror base, @Nullable TypePath path, SymAnnot annot) {
return resolvePathStep(base, path, 0, annot);
}
private static JTypeMirror resolvePathStep(JTypeMirror t, @Nullable TypePath path, int i, SymAnnot annot) {
if (t instanceof JClassType && ((JClassType) t).getEnclosingType() != null) {
return handleEnclosingType((JClassType) t, path, i, annot);
}
return resolvePathStepNoInner(t, path, i, annot);
}
private static JTypeMirror resolvePathStepNoInner(JTypeMirror t, @Nullable TypePath path, int i, SymAnnot annot) {
assert path == null || path.getLength() == i
|| path.getStep(i) != TypePath.INNER_TYPE;
if (path == null || i == path.getLength()) {
return t.addAnnotation(annot);
}
switch (path.getStep(i)) {
case TypePath.TYPE_ARGUMENT:
if (t instanceof JClassType) {
int typeArgIndex = path.getStepArgument(i);
JTypeMirror arg = ((JClassType) t).getTypeArgs().get(typeArgIndex);
JTypeMirror newArg = resolvePathStep(arg, path, i + 1, annot);
List<JTypeMirror> newArgs = replaceAtIndex(((JClassType) t).getTypeArgs(), typeArgIndex, newArg);
return ((JClassType) t).withTypeArguments(newArgs);
}
throw new IllegalArgumentException("Expected class type: " + t);
case TypePath.ARRAY_ELEMENT:
if (t instanceof JArrayType) {
JTypeMirror component = ((JArrayType) t).getComponentType();
JTypeMirror newComponent = resolvePathStep(component, path, i + 1, annot);
return t.getTypeSystem().arrayType(newComponent).withAnnotations(t.getTypeAnnotations());
}
throw new IllegalArgumentException("Expected array type: " + t);
case TypePath.INNER_TYPE:
throw new IllegalStateException("Should be handled elsewhere"); // there's an assert above too
case TypePath.WILDCARD_BOUND:
if (t instanceof JWildcardType) {
JWildcardType wild = (JWildcardType) t;
JTypeMirror newBound = resolvePathStep(wild.getBound(), path, i + 1, annot);
return wild.getTypeSystem().wildcard(wild.isUpperBound(), newBound).withAnnotations(wild.getTypeAnnotations());
}
throw new IllegalArgumentException("Expected wilcard type: " + t);
default:
throw new IllegalArgumentException("Illegal path step for annotation TypePath" + i);
}
}
private static JClassType handleEnclosingType(JClassType t, @Nullable TypePath path, int i, SymAnnot annot) {
// We need to resolve the inner types left to right as given in the path.
// Because JClassType is left-recursive its structure does not match the
// structure of the path.
final JClassType selectedT;
// this list is in inner to outer order
// eg for A.B.C, the list is [A.B.C, A.B, A]
List<JClassType> enclosingTypes = getEnclosingTypes(t);
int selectionDepth = 0;
while (path != null && path.getStep(i + selectionDepth) == TypePath.INNER_TYPE) {
selectionDepth++;
}
final int selectedTypeIndex = enclosingTypes.size() - 1 - selectionDepth;
selectedT = enclosingTypes.get(selectedTypeIndex);
// interpret the rest of the path as with this type as context
JClassType rebuiltType = (JClassType) resolvePathStepNoInner(selectedT, path, i + selectionDepth, annot);
// Then, we may need to rebuild the type by adding the remaining segments.
for (int j = selectedTypeIndex - 1; j >= 0; j--) {
JClassType nextInner = enclosingTypes.get(j);
rebuiltType = rebuiltType.selectInner(nextInner.getSymbol(), nextInner.getTypeArgs(), nextInner.getTypeAnnotations());
}
return rebuiltType;
}
/** Returns a list containing the given type and all its enclosing types, in reverse order. */
private static List<JClassType> getEnclosingTypes(JClassType t) {
List<JClassType> enclosing = new ArrayList<>(1);
do {
enclosing.add(t);
t = t.getEnclosingType();
} while (t != null);
return enclosing;
}
static @NonNull List<JTypeMirror> replaceAtIndex(List<JTypeMirror> typeArgs, int typeArgIndex, JTypeMirror newArg) {
if (typeArgs.size() == 1 && typeArgIndex == 0) {
return ConsPStack.singleton(newArg);
}
return ConsPStack.from(typeArgs).with(typeArgIndex, newArg);
}
}
| 7,828 | 41.091398 | 130 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/SignatureScanner.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import org.apache.commons.lang3.StringUtils;
import net.sourceforge.pmd.util.AssertionUtil;
/**
* Base class to scan a type signature.
*/
class SignatureScanner {
protected final String chars;
protected final int start;
protected final int end; // exclusive
SignatureScanner(String descriptor) {
if (descriptor == null || descriptor.isEmpty()) {
throw new IllegalArgumentException("Type descriptor \"" + descriptor + "\" is empty or null");
}
this.chars = descriptor;
this.start = 0;
this.end = descriptor.length();
}
SignatureScanner(String chars, int start, int end) {
assert chars != null;
AssertionUtil.assertValidStringRange(chars, start, end);
this.chars = chars;
this.start = start;
this.end = end;
}
public char charAt(int off) {
return off < end ? chars.charAt(off) : 0;
}
public void dumpChars(int start, int end, StringBuilder builder) {
builder.append(chars, start, end);
}
public int consumeChar(int start, char l, String s) {
if (charAt(start) != l) {
throw expected(s, start);
}
return start + 1;
}
public int consumeChar(int start, char l) {
return consumeChar(start, l, "" + l);
}
public int nextIndexOf(final int start, char stop) {
int cur = start;
while (cur < end && charAt(cur) != stop) {
cur++;
}
return cur;
}
public int nextIndexOfAny(final int start, char stop, char stop2) {
int cur = start;
while (cur < end) {
char c = charAt(cur);
if (c == stop || c == stop2) {
break;
}
cur++;
}
return cur;
}
public RuntimeException expected(String expectedWhat, int pos) {
final String indent = " ";
String sb = "Expected " + expectedWhat + ":\n"
+ indent + bufferToString() + "\n"
+ indent + StringUtils.repeat(' ', pos - start) + '^' + "\n";
return new InvalidTypeSignatureException(sb);
}
public void expectEoI(int e) {
consumeChar(e, (char) 0, "end of input");
}
public String bufferToString() {
return bufferToString(start, end);
}
public String bufferToString(int start, int end) {
if (start == end) {
return "";
}
return chars.substring(start, end);
}
@Override
public String toString() {
return "TypeBuilder{sig=" + bufferToString() + '}';
}
}
| 2,762 | 24.583333 | 106 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/ClassNamesUtil.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import org.apache.commons.lang3.NotImplementedException;
/**
* When dealing with classes we have to handle a bunch of different
* kinds of names. From higher level to lower level:
* <ul>
* <li>Canonical name: {@code a.b.C.D}
* <li>Binary name: {@code a.b.C$D}
* <li>Internal name: {@code a/b/C$D}
* </ul>
*
* <p>Canonical names are on the Java language level. They are how you
* type a reference to a class from an another arbitrary class. Some classes
* may not even have one, eg local classes cannot be referenced from outside
* their scope.
*
* <p>Binary names lift the ambiguity between inner class selection and
* package name that exists in canonical names. They're more convenient
* to work with when loading classes. They're typically the kind of name
* you find when using reflective APIs.
*
* <p>Internal names are burned into class files are they allow getting
* a file path to the referenced class file just by appending {@code .class}.
* They are only useful at the level of class files, eg when using ASM.
*
* <p><i>Type descriptors</i> are another class of "names" that use internal names,
* but are more general, as they can represent all kinds of types. Eg the
* type descriptor for class {@code a.b.C.D} is {@code La/b/C$D;}, the one of
* {@code boolean} is {@code Z}, and the one of {@code boolean[]} is {@code [Z}.
*
* <p><i>Type signatures</i> are a superset of type descriptors that can
* also represent generic types. These need to be parsed when reading info
* from a class file.
*/
public final class ClassNamesUtil {
private ClassNamesUtil() {
// utility class
}
public static String getTypeDescriptor(Class<?> klass) {
if (klass.isPrimitive()) {
throw new NotImplementedException("Doesn't handle primitive types");
} else if (klass.isArray()) {
return "[" + getTypeDescriptor(klass.getComponentType());
} else {
return "L" + getInternalName(klass) + ";";
}
}
public static String getInternalName(Class<?> klass) {
return klass.getName().replace('.', '/');
}
public static String internalToBinaryName(String internal) {
return internal.replace('/', '.');
}
public static String classDescriptorToBinaryName(String descriptor) {
return internalToBinaryName(classDescriptorToInternalName(descriptor));
}
public static String classDescriptorToInternalName(String descriptor) {
return descriptor.substring(1, descriptor.length() - 1); // remove L and ;
}
public static String binaryToInternal(String binary) {
return binary.replace('.', '/');
}
}
| 2,830 | 34.835443 | 83 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/SignatureParser.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import java.util.List;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.GenericSigBase.LazyClassSignature;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.GenericSigBase.LazyMethodType;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.TypeParamsParser.TypeParametersBuilder;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.TypeSigParser.ParseFunction;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.TypeSigParser.TypeScanner;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.JTypeVar;
import net.sourceforge.pmd.lang.java.types.LexicalScope;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* Parses type signatures. This is basically convenience wrappers for
* the different signature parsers ({@link TypeParamsParser},
* {@link TypeSigParser}).
*/
class SignatureParser {
private final AsmSymbolResolver loader;
SignatureParser(AsmSymbolResolver loader) {
this.loader = loader;
}
TypeSystem getTypeSystem() {
return loader.getTypeSystem();
}
public JTypeMirror parseFieldType(LexicalScope scope, String signature) {
TypeScanner b = new MyTypeBuilder(scope, signature);
parseFully(b, TypeSigParser::typeSignature);
return b.pop();
}
public JTypeMirror parseTypeVarBound(LexicalScope scope, String boundSig) {
MyTypeBuilder b = new MyTypeBuilder(scope, boundSig);
parseFully(b, TypeSigParser::typeVarBound);
return b.pop();
}
public void parseClassSignature(LazyClassSignature type, String genericSig) {
TypeScanner b = typeParamsWrapper(type, genericSig);
parseFully(b, TypeSigParser::classHeader);
type.setSuperInterfaces((List) b.popList());
type.setSuperClass((JClassType) b.pop());
}
public void parseMethodType(LazyMethodType type, String genericSig) {
TypeScanner b = typeParamsWrapper(type, genericSig);
int eof = TypeSigParser.methodType(type, b.start, b);
b.expectEoI(eof);
}
/**
* Parses the (optional) type parameters prefixing the given signature,
* and set the resulting type params on the owner. Returns a type scanner
* positioned at the start of the rest of the signature, with a
* full lexical scope.
*
* <p>Type var bounds are parsed lazily, since they may refer to type
* parameters that are further right in the signature. So we build
* first a lexical scope, then the type var bound can
*/
private TypeScanner typeParamsWrapper(GenericSigBase<?> owner, String sig) {
if (TypeParamsParser.hasTypeParams(sig)) {
TypeParametersBuilder b = new TypeParametersBuilder(owner, sig);
int tparamsEnd = TypeParamsParser.typeParams(b.start, b);
List<JTypeVar> sigTypeParams = b.getOwnerTypeParams();
owner.setTypeParams(sigTypeParams);
LexicalScope lexScope = owner.getEnclosingTypeParams().andThen(sigTypeParams);
// the new type builder has the owner's type parameters in scope
return new MyTypeBuilder(lexScope, b.chars, tparamsEnd, b.end);
} else {
owner.setTypeParams(CollectionUtil.emptyList());
return new MyTypeBuilder(owner.getEnclosingTypeParams(), sig);
}
}
private static void parseFully(TypeScanner scanner, ParseFunction parser) {
int endOffset = parser.parse(scanner.start, scanner);
scanner.expectEoI(endOffset);
}
private class MyTypeBuilder extends TypeSigParser.TypeScanner {
MyTypeBuilder(LexicalScope lexicalScope, String descriptor) {
super(getTypeSystem(), lexicalScope, descriptor);
}
MyTypeBuilder(LexicalScope lexicalScope, String chars, int start, int end) {
super(getTypeSystem(), lexicalScope, chars, start, end);
}
@Override
public @NonNull JClassSymbol makeClassSymbol(String internalName, int observedArity) {
return loader.resolveFromInternalNameCannotFail(internalName, observedArity);
}
}
}
| 4,528 | 36.741667 | 97 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/ExecutableStub.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.TypePath;
import org.pcollections.HashTreePSet;
import org.pcollections.IntTreePMap;
import org.pcollections.PMap;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.java.symbols.JConstructorSymbol;
import net.sourceforge.pmd.lang.java.symbols.JExecutableSymbol;
import net.sourceforge.pmd.lang.java.symbols.JFormalParamSymbol;
import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.lang.java.symbols.internal.SymbolEquality;
import net.sourceforge.pmd.lang.java.symbols.internal.SymbolToStrings;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.GenericSigBase.LazyMethodType;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.JTypeVar;
import net.sourceforge.pmd.lang.java.types.Substitution;
import net.sourceforge.pmd.lang.java.types.TypeOps;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
abstract class ExecutableStub extends MemberStubBase implements JExecutableSymbol, TypeAnnotationReceiver {
private final String descriptor;
protected final LazyMethodType type;
private List<JFormalParamSymbol> params;
private PMap<Integer, PSet<SymAnnot>> parameterAnnotations = IntTreePMap.empty();
protected ExecutableStub(ClassStub owner,
String simpleName,
int accessFlags,
String descriptor,
@Nullable String signature,
@Nullable String[] exceptions,
boolean skipFirstParam) {
super(owner, simpleName, accessFlags);
this.descriptor = descriptor;
this.type = new LazyMethodType(this, descriptor, signature, exceptions, skipFirstParam);
}
boolean matches(String name, String descriptor) {
return this.nameEquals(name) && descriptor.equals(this.descriptor);
}
@Override
public List<JTypeVar> getTypeParameters() {
return type.getTypeParams();
}
@Override
public List<JFormalParamSymbol> getFormalParameters() {
if (params == null) {
List<JTypeMirror> ptypes = type.getParameterTypes();
List<JFormalParamSymbol> newParams = new ArrayList<>(ptypes.size());
for (int i = 0; i < ptypes.size(); i++) {
newParams.add(new FormalParamStub(ptypes.get(i), i));
}
params = Collections.unmodifiableList(newParams);
}
return params;
}
@Override
public boolean isVarargs() {
return (getModifiers() & Opcodes.ACC_VARARGS) != 0;
}
@Override
public int getArity() {
return type.getParameterTypes().size();
}
PSet<SymAnnot> getFormalParameterAnnotations(int parameterIndex) {
return parameterAnnotations.getOrDefault(parameterIndex, HashTreePSet.empty());
}
@Override
public @Nullable JTypeMirror getAnnotatedReceiverType(Substitution subst) {
if (!this.hasReceiver()) {
return null;
}
JTypeMirror receiver = getTypeSystem().declaration(getEnclosingClass()).subst(subst);
return type.applyReceiverAnnotations(receiver);
}
@Override
public List<JTypeMirror> getFormalParameterTypes(Substitution subst) {
return TypeOps.subst(type.getParameterTypes(), subst);
}
@Override
public List<JTypeMirror> getThrownExceptionTypes(Substitution subst) {
return TypeOps.subst(type.getExceptionTypes(), subst);
}
void setDefaultAnnotValue(@Nullable SymbolicValue defaultAnnotValue) {
// overridden by MethodStub
}
@Override
public void acceptTypeAnnotation(int typeRef, @Nullable TypePath path, SymAnnot annot) {
type.acceptTypeAnnotation(typeRef, path, annot);
}
void addParameterAnnotation(int paramIndex, SymbolicValue.SymAnnot annot) {
PSet<SymAnnot> newAnnots = parameterAnnotations.getOrDefault(paramIndex, HashTreePSet.empty()).plus(annot);
parameterAnnotations = parameterAnnotations.plus(paramIndex, newAnnots);
}
/**
* Formal parameter symbols obtained from the class have no info
* about name or whether it's final. This info is missing from
* classfiles when they're not compiled with debug symbols.
*/
class FormalParamStub implements JFormalParamSymbol {
private final JTypeMirror type;
private final int index;
FormalParamStub(JTypeMirror type, int index) {
this.type = type;
this.index = index;
}
@Override
public JExecutableSymbol getDeclaringSymbol() {
return ExecutableStub.this;
}
@Override
public boolean isFinal() {
return false;
}
@Override
public JTypeMirror getTypeMirror(Substitution subst) {
return type.subst(subst);
}
@Override
public String getSimpleName() {
return "";
}
@Override
public TypeSystem getTypeSystem() {
return ExecutableStub.this.getTypeSystem();
}
@Override
public PSet<SymAnnot> getDeclaredAnnotations() {
return ExecutableStub.this.getFormalParameterAnnotations(index);
}
}
/**
* Formal parameter symbols obtained from the class have no info
* about name or whether it's final. This is because due to ASM's
* design, parsing this information would entail parsing a lot of
* other information we don't care about, and so this would be
* wasteful. It's unlikely anyone cares about this anyway.
*
* <p>If classes are compiled without debug symbols that info
* is NOT in the classfile anyway.
*/
static class MethodStub extends ExecutableStub implements JMethodSymbol {
private @Nullable SymbolicValue defaultAnnotValue;
protected MethodStub(ClassStub owner,
String simpleName,
int accessFlags,
String descriptor,
@Nullable String signature,
@Nullable String[] exceptions) {
super(owner, simpleName, accessFlags, descriptor, signature, exceptions, false);
}
@Override
public boolean isBridge() {
return (getModifiers() & Opcodes.ACC_BRIDGE) != 0;
}
@Override
public JTypeMirror getReturnType(Substitution subst) {
return type.getReturnType().subst(subst);
}
@Override
public String toString() {
return SymbolToStrings.ASM.toString(this);
}
@Override
public int hashCode() {
return SymbolEquality.METHOD.hash(this);
}
@Override
public boolean equals(Object obj) {
return SymbolEquality.METHOD.equals(this, obj);
}
@Override
public @Nullable SymbolicValue getDefaultAnnotationValue() {
return defaultAnnotValue;
}
@Override
void setDefaultAnnotValue(@Nullable SymbolicValue defaultAnnotValue) {
this.defaultAnnotValue = defaultAnnotValue;
}
}
static class CtorStub extends ExecutableStub implements JConstructorSymbol {
protected CtorStub(ClassStub owner,
int accessFlags,
String descriptor,
@Nullable String signature,
@Nullable String[] exceptions,
boolean isInnerNonStaticClass) {
super(owner, JConstructorSymbol.CTOR_NAME, accessFlags, descriptor, signature, exceptions, isInnerNonStaticClass);
}
@Override
public String toString() {
return SymbolToStrings.ASM.toString(this);
}
@Override
public int hashCode() {
return SymbolEquality.CONSTRUCTOR.hash(this);
}
@Override
public boolean equals(Object obj) {
return SymbolEquality.CONSTRUCTOR.equals(this, obj);
}
}
}
| 8,661 | 32.70428 | 126 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/ParseLock.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A simple double-checked initializer, that parses something (a class,
* or a type signature).
*/
@SuppressWarnings({"PMD.AvoidUsingVolatile", "PMD.AvoidCatchingThrowable"})
abstract class ParseLock {
private static final Logger LOG = LoggerFactory.getLogger(ParseLock.class);
private volatile ParseStatus status = ParseStatus.NOT_PARSED;
public void ensureParsed() {
getFinalStatus();
}
private ParseStatus getFinalStatus() {
ParseStatus status = this.status;
if (!status.isFinished) {
synchronized (this) {
status = this.status;
if (status == ParseStatus.NOT_PARSED) {
this.status = ParseStatus.BEING_PARSED;
try {
boolean success = doParse();
status = success ? ParseStatus.FULL : ParseStatus.FAILED;
this.status = status;
finishParse(!success);
} catch (Throwable t) {
status = ParseStatus.FAILED;
this.status = status;
LOG.error(t.toString(), t);
finishParse(true);
}
assert status.isFinished : "Inconsistent status " + status;
assert postCondition() : "Post condition not satisfied after parsing sig " + this;
} else if (status == ParseStatus.BEING_PARSED && !canReenter()) {
throw new IllegalStateException("Thread is reentering the parse lock");
}
}
}
return status;
}
protected boolean canReenter() {
return false;
}
public boolean isFailed() {
return getFinalStatus() == ParseStatus.FAILED;
}
// will be called in the critical section after parse is done
protected void finishParse(boolean failed) {
// by default do nothing
}
/** Returns true if parse is successful. */
protected abstract boolean doParse() throws Throwable; // SUPPRESS CHECKSTYLE IllegalThrows
/** Checked by an assert after parse. */
protected boolean postCondition() {
return true;
}
@Override
public String toString() {
return "ParseLock{status=" + status + '}';
}
private enum ParseStatus {
NOT_PARSED(false),
BEING_PARSED(false),
FULL(true),
FAILED(true);
final boolean isFinished;
ParseStatus(boolean finished) {
this.isFinished = finished;
}
}
}
| 2,819 | 29.652174 | 102 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/AnnotationOwner.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
interface AnnotationOwner {
void addAnnotation(SymAnnot annot);
}
| 291 | 19.857143 | 79 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/TParamStub.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.pcollections.HashTreePSet;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.java.symbols.JTypeParameterOwnerSymbol;
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.SymbolEquality;
import net.sourceforge.pmd.lang.java.symbols.internal.SymbolToStrings;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.JTypeVar;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
class TParamStub implements JTypeParameterSymbol {
private final String name;
private final JTypeParameterOwnerSymbol owner;
private final JTypeVar typeVar;
private final String boundSignature;
private final SignatureParser sigParser;
private PSet<SymAnnot> annotations = HashTreePSet.empty();
TParamStub(String name, GenericSigBase<?> sig, String bound) {
this.name = name;
this.owner = sig.ctx;
this.sigParser = sig.typeLoader();
this.boundSignature = bound;
TypeSystem ts = sig.ctx.getTypeSystem();
this.typeVar = ts.newTypeVar(this);
}
@Override
public @NonNull String getSimpleName() {
return name;
}
@Override
public JTypeMirror computeUpperBound() {
// Note: type annotations on the bound are added when applying
// type annots collected on the enclosing symbol. See usages of
// this method.
return sigParser.parseTypeVarBound(owner.getLexicalScope(), boundSignature);
}
@Override
public JTypeParameterOwnerSymbol getDeclaringSymbol() {
return owner;
}
@Override
public PSet<SymAnnot> getDeclaredAnnotations() {
return annotations;
}
void addAnnotation(SymAnnot annot) {
annotations = annotations.plus(annot);
}
@Override
public JTypeVar getTypeMirror() {
return typeVar;
}
@Override
public TypeSystem getTypeSystem() {
return owner.getTypeSystem();
}
@Override
public String toString() {
return SymbolToStrings.ASM.toString(this);
}
@Override
public int hashCode() {
return SymbolEquality.TYPE_PARAM.hash(this);
}
@Override
public boolean equals(Object obj) {
return SymbolEquality.TYPE_PARAM.equals(this, obj);
}
}
| 2,631 | 27.301075 | 84 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/LazyTypeSig.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.objectweb.asm.TypePath;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.TypeAnnotationHelper.TypeAnnotationSet;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.Substitution;
class LazyTypeSig {
private final String sig;
private final ClassStub ctx;
private JTypeMirror parsed;
private TypeAnnotationSet typeAnnots;
LazyTypeSig(ClassStub ctx,
String descriptor,
@Nullable String signature) {
this.ctx = ctx;
this.sig = signature == null ? descriptor : signature;
}
JTypeMirror get() {
if (parsed == null) {
parsed = ctx.sigParser().parseFieldType(ctx.getLexicalScope(), sig);
if (typeAnnots != null) {
parsed = typeAnnots.decorate(parsed);
typeAnnots = null; // forget about them
}
}
return parsed;
}
JTypeMirror get(Substitution subst) {
return get().subst(subst);
}
@Override
public String toString() {
return sig;
}
public void addTypeAnnotation(@Nullable TypePath path, SymAnnot annot) {
if (parsed != null) {
throw new IllegalStateException("Must add annotations before the field type is parsed.");
}
if (typeAnnots == null) {
typeAnnots = new TypeAnnotationSet();
}
typeAnnots.add(path, annot);
}
}
| 1,746 | 26.730159 | 101 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/ClassStub.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Opcodes;
import org.pcollections.HashTreePSet;
import org.pcollections.PSet;
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.JExecutableSymbol;
import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol;
import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeParameterOwnerSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.lang.java.symbols.internal.SymbolEquality;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.ExecutableStub.CtorStub;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.ExecutableStub.MethodStub;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.GenericSigBase.LazyClassSignature;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.JTypeVar;
import net.sourceforge.pmd.lang.java.types.LexicalScope;
import net.sourceforge.pmd.lang.java.types.Substitution;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
import net.sourceforge.pmd.util.CollectionUtil;
final class ClassStub implements JClassSymbol, AsmStub, AnnotationOwner {
static final int UNKNOWN_ARITY = 0;
private final AsmSymbolResolver resolver;
private final Names names;
// all the following are lazy and depend on the parse lock
private int accessFlags;
private EnclosingInfo enclosingInfo;
private LazyClassSignature signature;
private LexicalScope scope;
private List<JFieldSymbol> fields = new ArrayList<>();
private List<JClassSymbol> memberClasses = new ArrayList<>();
private List<JMethodSymbol> methods = new ArrayList<>();
private List<JConstructorSymbol> ctors = new ArrayList<>();
private List<JFieldSymbol> enumConstants = null;
private PSet<SymAnnot> annotations = HashTreePSet.empty();
private PSet<String> annotAttributes;
private final ParseLock parseLock;
/** Note that '.' is forbidden because in internal names they're replaced by slashes '/'. */
private static final Pattern INTERNAL_NAME_FORBIDDEN_CHARS = Pattern.compile("[;<>\\[.]");
private static boolean isValidInternalName(String internalName) {
return !internalName.isEmpty() && !INTERNAL_NAME_FORBIDDEN_CHARS.matcher(internalName).find();
}
ClassStub(AsmSymbolResolver resolver, String internalName, @NonNull Loader loader, int observedArity) {
assert isValidInternalName(internalName) : internalName;
this.resolver = resolver;
this.names = new Names(internalName);
this.parseLock = new ParseLock() {
// note to devs: to debug the parsing logic you might have
// to replace the implementation of toString temporarily,
// otherwise an IDE could call toString just to show the item
// in the debugger view (which could cause parsing of the class file).
@Override
protected boolean doParse() throws IOException {
try (InputStream instream = loader.getInputStream()) {
if (instream != null) {
ClassReader classReader = new ClassReader(instream);
ClassStubBuilder builder = new ClassStubBuilder(ClassStub.this, resolver);
classReader.accept(builder, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
return true;
} else {
return false;
}
}
}
@Override
protected void finishParse(boolean failed) {
if (enclosingInfo == null) {
// this may be normal
enclosingInfo = EnclosingInfo.NO_ENCLOSING;
}
if (signature == null) {
assert failed : "No signature, but the parse hasn't failed? investigate";
signature = LazyClassSignature.defaultWhenUnresolved(ClassStub.this, observedArity);
}
methods = Collections.unmodifiableList(methods);
ctors = Collections.unmodifiableList(ctors);
fields = Collections.unmodifiableList(fields);
memberClasses = Collections.unmodifiableList(memberClasses);
enumConstants = CollectionUtil.makeUnmodifiableAndNonNull(enumConstants);
if (EnclosingInfo.NO_ENCLOSING.equals(enclosingInfo)) {
if (names.canonicalName == null || names.simpleName == null) {
// This happens if the simple name contains dollars,
// in which case we might have an enclosing class, and
// we can only tell now (no enclosingInfo) that that's
// not the case.
names.finishOuterClass();
}
}
annotAttributes = (accessFlags & Opcodes.ACC_ANNOTATION) != 0
? getDeclaredMethods().stream().filter(JMethodSymbol::isAnnotationAttribute)
.map(JElementSymbol::getSimpleName)
.collect(CollectionUtil.toPersistentSet())
: HashTreePSet.empty();
}
@Override
protected boolean postCondition() {
return signature != null && enclosingInfo != null;
}
};
}
@Override
public AsmSymbolResolver getResolver() {
return resolver;
}
// <editor-fold defaultstate="collapsed" desc="Setters used during loading">
void setHeader(@Nullable String signature,
@Nullable String superName,
String[] interfaces) {
this.signature = new LazyClassSignature(this, signature, superName, interfaces);
}
/**
* Called if this is an inner class (their simple name cannot be
* derived from splitting the internal/binary name on dollars, as
* the simple name may itself contain dollars).
*/
void setSimpleName(String simpleName) {
this.names.simpleName = simpleName;
}
void setModifiers(int accessFlags, boolean fromClassInfo) {
/*
A different set of modifiers is contained in the ClassInfo
structure and the InnerClasses structure. See
https://docs.oracle.com/javase/specs/jvms/se13/html/jvms-4.html#jvms-4.1-200-E.1
https://docs.oracle.com/javase/specs/jvms/se13/html/jvms-4.html#jvms-4.7.6-300-D.1-D.1
Here is the diff (+ lines (resp. - lines) are only available
in InnerClasses (resp. ClassInfo), the rest are available in both)
ACC_PUBLIC 0x0001 Declared public; may be accessed from outside its package.
+ ACC_PRIVATE 0x0002 Marked private in source.
+ ACC_PROTECTED 0x0004 Marked protected in source.
+ ACC_STATIC 0x0008 Marked or implicitly static in source.
ACC_FINAL 0x0010 Declared final; no subclasses allowed.
- ACC_SUPER 0x0020 Treat superclass methods specially when invoked by the invokespecial instruction.
ACC_INTERFACE 0x0200 Is an interface, not a class.
ACC_ABSTRACT 0x0400 Declared abstract; must not be instantiated.
ACC_SYNTHETIC 0x1000 Declared synthetic; not present in the source code.
ACC_ANNOTATION 0x2000 Declared as an annotation type.
ACC_ENUM 0x4000 Declared as an enum type.
- ACC_MODULE 0x8000 Is a module, not a class or interface.
If this stub is a nested class, then we don't have all its
modifiers just with the ClassInfo, the actual source-declared
visibility (if not public) is only in the InnerClasses, as
well as its ACC_STATIC.
Also ACC_SUPER conflicts with ACC_SYNCHRONIZED, which
Modifier.toString would reflect.
Since the differences are disjoint we can just OR the two
sets of flags.
*/
int myAccess = this.accessFlags;
if (fromClassInfo) {
// we don't care about ACC_SUPER and it conflicts
// with ACC_SYNCHRONIZED
accessFlags = accessFlags & ~Opcodes.ACC_SUPER;
} else if ((myAccess & Opcodes.ACC_PUBLIC) != 0
&& (accessFlags & Opcodes.ACC_PROTECTED) != 0) {
// ClassInfo mentions ACC_PUBLIC even if the real
// visibility is protected
// We remove the public to avoid a "public protected" combination
myAccess = myAccess & ~Opcodes.ACC_PUBLIC;
}
this.accessFlags = myAccess | accessFlags;
if ((accessFlags & Opcodes.ACC_ENUM) != 0) {
this.enumConstants = new ArrayList<>();
}
}
void setOuterClass(ClassStub outer, @Nullable String methodName, @Nullable String methodDescriptor) {
if (enclosingInfo == null) {
if (outer == null) {
assert methodName == null && methodDescriptor == null
: "Enclosing method requires enclosing class";
this.enclosingInfo = EnclosingInfo.NO_ENCLOSING;
} else {
this.enclosingInfo = new EnclosingInfo(outer, methodName, methodDescriptor);
}
}
}
void addField(FieldStub fieldStub) {
fields.add(fieldStub);
if (fieldStub.isEnumConstant() && enumConstants != null) {
enumConstants.add(fieldStub);
}
}
void addMemberClass(ClassStub classStub) {
classStub.setOuterClass(this, null, null);
memberClasses.add(classStub);
}
void addMethod(MethodStub methodStub) {
methods.add(methodStub);
}
void addCtor(CtorStub methodStub) {
ctors.add(methodStub);
}
@Override
public void addAnnotation(SymAnnot annot) {
annotations = annotations.plus(annot);
}
// </editor-fold>
@Override
public @Nullable JClassSymbol getSuperclass() {
parseLock.ensureParsed();
return signature.getRawSuper();
}
@Override
public List<JClassSymbol> getSuperInterfaces() {
parseLock.ensureParsed();
return signature.getRawItfs();
}
@Override
public @Nullable JClassType getSuperclassType(Substitution substitution) {
parseLock.ensureParsed();
return signature.getSuperType(substitution);
}
@Override
public List<JClassType> getSuperInterfaceTypes(Substitution substitution) {
parseLock.ensureParsed();
return signature.getSuperItfs(substitution);
}
@Override
public List<JTypeVar> getTypeParameters() {
parseLock.ensureParsed();
return signature.getTypeParams();
}
@Override
public boolean isGeneric() {
parseLock.ensureParsed();
return signature.isGeneric();
}
@Override
public LexicalScope getLexicalScope() {
if (scope == null) {
scope = JClassSymbol.super.getLexicalScope();
}
return scope;
}
@Override
public List<JFieldSymbol> getDeclaredFields() {
parseLock.ensureParsed();
return fields;
}
@Override
public List<JMethodSymbol> getDeclaredMethods() {
parseLock.ensureParsed();
return methods;
}
@Override
public List<JConstructorSymbol> getConstructors() {
parseLock.ensureParsed();
return ctors;
}
@Override
public List<JClassSymbol> getDeclaredClasses() {
parseLock.ensureParsed();
return memberClasses;
}
@Override
public PSet<SymAnnot> getDeclaredAnnotations() {
parseLock.ensureParsed();
return annotations;
}
@Override
public PSet<String> getAnnotationAttributeNames() {
parseLock.ensureParsed();
return annotAttributes;
}
@Override
public @Nullable SymbolicValue getDefaultAnnotationAttributeValue(String attrName) {
parseLock.ensureParsed();
if (!annotAttributes.contains(attrName)) {
// this is a shortcut, because the default impl checks each method
return null;
}
return JClassSymbol.super.getDefaultAnnotationAttributeValue(attrName);
}
@Override
public @Nullable JClassSymbol getEnclosingClass() {
parseLock.ensureParsed();
return enclosingInfo.getEnclosingClass();
}
@Override
public @Nullable JExecutableSymbol getEnclosingMethod() {
parseLock.ensureParsed();
return enclosingInfo.getEnclosingMethod();
}
@Override
public @NonNull List<JFieldSymbol> getEnumConstants() {
parseLock.ensureParsed();
return enumConstants;
}
@Override
public JTypeParameterOwnerSymbol getEnclosingTypeParameterOwner() {
parseLock.ensureParsed();
return enclosingInfo.getEnclosing();
}
@Override
public String toString() {
// do not use SymbolToString as it triggers the class parsing,
// making tests undebuggable
return getInternalName();
}
@Override
public int hashCode() {
return SymbolEquality.CLASS.hash(this);
}
@Override
public boolean equals(Object obj) {
return SymbolEquality.CLASS.equals(this, obj);
}
// <editor-fold defaultstate="collapsed" desc="Names">
public String getInternalName() {
return getNames().internalName;
}
private Names getNames() {
return names;
}
@Override
public @NonNull String getBinaryName() {
return getNames().binaryName;
}
/**
* Simpler check than computing the canonical name.
*/
boolean hasCanonicalName() {
if (names.canonicalName != null) {
return true;
}
parseLock.ensureParsed();
if (isAnonymousClass() || isLocalClass()) {
return false;
}
JClassSymbol enclosing = getEnclosingClass();
return enclosing == null // top-level class
|| enclosing instanceof ClassStub
&& ((ClassStub) enclosing).hasCanonicalName();
}
@Override
public String getCanonicalName() {
String canoName = names.canonicalName;
if (canoName == null) {
canoName = computeCanonicalName();
names.canonicalName = canoName;
}
return canoName;
}
private @Nullable String computeCanonicalName() {
parseLock.ensureParsed();
if (names.canonicalName != null) {
return names.canonicalName;
}
JClassSymbol enclosing = getEnclosingClass();
if (enclosing == null) {
return names.packageName + '.' + getSimpleName();
}
String outerName = enclosing.getCanonicalName();
if (outerName == null) {
return null;
}
return outerName + '.' + getSimpleName();
}
@Override
public @NonNull String getPackageName() {
return getNames().packageName;
}
@Override
public @NonNull String getSimpleName() {
String mySimpleName = names.simpleName;
if (mySimpleName == null) {
parseLock.ensureParsed();
return Objects.requireNonNull(names.simpleName, "Null simple name after parsing");
}
return mySimpleName;
}
@Override
public TypeSystem getTypeSystem() {
return getResolver().getTypeSystem();
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Modifier info">
@Override
public boolean isUnresolved() {
return parseLock.isFailed();
}
@Override
public boolean isArray() {
return false;
}
@Override
public boolean isPrimitive() {
return false;
}
@Override
public @Nullable JTypeDeclSymbol getArrayComponent() {
return null;
}
@Override
public int getModifiers() {
parseLock.ensureParsed();
return accessFlags;
}
@Override
public boolean isAbstract() {
return (getModifiers() & Opcodes.ACC_ABSTRACT) != 0;
}
@Override
public boolean isEnum() {
return (getModifiers() & Opcodes.ACC_ENUM) != 0;
}
@Override
public boolean isAnnotation() {
return (getModifiers() & Opcodes.ACC_ANNOTATION) != 0;
}
@Override
public boolean isInterface() {
return (getModifiers() & Opcodes.ACC_INTERFACE) != 0;
}
@Override
public boolean isClass() {
return (getModifiers() & (Opcodes.ACC_INTERFACE | Opcodes.ACC_ANNOTATION)) == 0;
}
@Override
public boolean isRecord() {
JClassSymbol sup = getSuperclass();
return sup != null && "java.lang.Record".equals(sup.getBinaryName());
}
@Override
public boolean isLocalClass() {
return enclosingInfo.isLocal();
}
@Override
public boolean isAnonymousClass() {
return getSimpleName().isEmpty();
}
// </editor-fold>
static class Names {
final String binaryName;
final String internalName;
final String packageName;
/** If null, the class requires parsing to find out the actual canonical name. */
@Nullable String canonicalName;
/** If null, the class requires parsing to find out the actual simple name. */
@Nullable String simpleName;
Names(String internalName) {
assert isValidInternalName(internalName) : internalName;
int packageEnd = internalName.lastIndexOf('/');
this.internalName = internalName;
this.binaryName = internalName.replace('/', '.');
if (packageEnd == -1) {
this.packageName = "";
} else {
this.packageName = binaryName.substring(0, packageEnd);
}
if (binaryName.indexOf('$', packageEnd + 1) >= 0) {
// Contains a dollar in class name (after package)
// Requires parsing to find out the actual simple name,
// this might be an inner class, or simply a class with
// a dollar in its name.
// ASSUMPTION: all JVM languages use the $ convention
// to separate inner classes. Java compilers do so but
// not necessarily true of all compilers/languages.
this.canonicalName = null;
this.simpleName = null;
} else {
// fast path
this.canonicalName = binaryName;
this.simpleName = binaryName.substring(packageEnd + 1);
}
}
public void finishOuterClass() {
int packageEnd = internalName.lastIndexOf('/');
this.simpleName = binaryName.substring(packageEnd + 1); // if -1, start from 0
this.canonicalName = binaryName;
}
}
static class EnclosingInfo {
static final EnclosingInfo NO_ENCLOSING = new EnclosingInfo(null, null, null);
private final @Nullable JClassSymbol stub;
private final @Nullable String methodName;
private final @Nullable String methodDescriptor;
EnclosingInfo(@Nullable JClassSymbol stub, @Nullable String methodName, @Nullable String methodDescriptor) {
this.stub = stub;
this.methodName = methodName;
this.methodDescriptor = methodDescriptor;
}
boolean isLocal() {
return methodName != null || methodDescriptor != null;
}
public @Nullable JClassSymbol getEnclosingClass() {
return stub;
}
public @Nullable MethodStub getEnclosingMethod() {
if (stub instanceof ClassStub && methodName != null) {
ClassStub stub1 = (ClassStub) stub;
stub1.parseLock.ensureParsed();
for (JMethodSymbol m : stub1.methods) {
MethodStub ms = (MethodStub) m;
if (ms.matches(methodName, methodDescriptor)) {
return ms;
}
}
}
return null;
}
JTypeParameterOwnerSymbol getEnclosing() {
if (methodName != null) {
return getEnclosingMethod();
} else {
return getEnclosingClass();
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EnclosingInfo that = (EnclosingInfo) o;
return Objects.equals(stub, that.stub)
&& Objects.equals(methodName, that.methodName)
&& Objects.equals(methodDescriptor, that.methodDescriptor);
}
@Override
public int hashCode() {
return Objects.hash(stub, methodName, methodDescriptor);
}
}
}
| 22,088 | 32.518968 | 126 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/AnnotationBuilderVisitor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.objectweb.asm.TypePath;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue;
class AnnotationBuilderVisitor extends SymbolicValueBuilder {
final SymbolicAnnotationImpl annot;
private final AnnotationOwner owner;
AnnotationBuilderVisitor(AnnotationOwner owner, AsmSymbolResolver resolver, boolean visible, String descriptor) {
super(resolver);
this.annot = new SymbolicAnnotationImpl(resolver, visible, descriptor);
this.owner = owner;
}
@Override
protected void acceptValue(String name, SymbolicValue v) {
annot.addAttribute(name, v);
}
@Override
public void visitEnd() {
owner.addAnnotation(annot);
}
static class TypeAnnotBuilderImpl extends SymbolicValueBuilder {
private final TypeAnnotationReceiver owner;
private final int typeRef;
private final @Nullable TypePath path;
private final SymbolicAnnotationImpl annot;
TypeAnnotBuilderImpl(AsmSymbolResolver resolver,
TypeAnnotationReceiver owner,
int typeRef,
@Nullable TypePath path,
boolean visible,
String descriptor) {
super(resolver);
this.owner = owner;
this.typeRef = typeRef;
this.path = path;
this.annot = new SymbolicAnnotationImpl(resolver, visible, descriptor);
}
@Override
protected void acceptValue(String name, SymbolicValue v) {
annot.addAttribute(name, v);
}
@Override
public void visitEnd() {
owner.acceptTypeAnnotation(typeRef, path, annot);
}
}
}
| 1,971 | 29.8125 | 117 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/ClassStubBuilder.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.TypePath;
import org.objectweb.asm.TypeReference;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.ExecutableStub.CtorStub;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.ExecutableStub.MethodStub;
/**
* Populates a {@link ClassStub} by reading a class file. Some info is
* known by the ClassStub without parsing (like its internal name), so
* we defer parsing until later. The class should be parsed only once.
*/
class ClassStubBuilder extends ClassVisitor {
private final ClassStub myStub;
private final String myInternalName;
private final AsmSymbolResolver resolver;
private boolean isInnerNonStaticClass = false;
ClassStubBuilder(ClassStub stub, AsmSymbolResolver resolver) {
super(AsmSymbolResolver.ASM_API_V);
this.myStub = stub;
this.myInternalName = stub.getInternalName();
this.resolver = resolver;
}
@Override
public void visit(int version, int access, String internalName, @Nullable String signature, String superName, String[] interfaces) {
myStub.setModifiers(access, true);
myStub.setHeader(signature, superName, interfaces);
}
@Override
public AnnotationBuilderVisitor visitAnnotation(String descriptor, boolean visible) {
return new AnnotationBuilderVisitor(myStub, resolver, visible, descriptor);
}
@Override
public void visitOuterClass(String ownerInternalName, @Nullable String methodName, @Nullable String methodDescriptor) {
isInnerNonStaticClass = true;
// only for enclosing method
ClassStub outer = resolver.resolveFromInternalNameCannotFail(ownerInternalName);
myStub.setOuterClass(outer, methodName, methodDescriptor);
}
@Override
public FieldVisitor visitField(int access, String name, String descriptor, @Nullable String signature, @Nullable Object value) {
FieldStub field = new FieldStub(myStub, name, access, descriptor, signature, value);
myStub.addField(field);
return new FieldVisitor(AsmSymbolResolver.ASM_API_V) {
@Override
public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) {
return new AnnotationBuilderVisitor(field, resolver, visible, descriptor);
}
@Override
public AnnotationVisitor visitTypeAnnotation(int typeRef, @Nullable TypePath typePath, String descriptor, boolean visible) {
assert new TypeReference(typeRef).getSort() == TypeReference.FIELD : typeRef;
return new AnnotationBuilderVisitor.TypeAnnotBuilderImpl(resolver, field, typeRef, typePath, visible, descriptor);
}
};
}
/**
* Visits information about an inner class. This inner class is not necessarily a member of the
* class being visited.
*
* <p>Spec: https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.6
*
* @param innerInternalName the internal name of an inner class (see {@link Type#getInternalName()}).
* @param outerName the internal name of the class to which the inner class belongs (see {@link
* Type#getInternalName()}). May be {@literal null} for not member classes.
* @param innerSimpleName the (simple) name of the inner class inside its enclosing class. May be
* {@literal null} for anonymous inner classes.
* @param access the access flags of the inner class as originally
* declared in the enclosing class.
*/
@Override
public void visitInnerClass(String innerInternalName, @Nullable String outerName, @Nullable String innerSimpleName, int access) {
if (myInternalName.equals(outerName) && innerSimpleName != null) { // not anonymous
ClassStub member = resolver.resolveFromInternalNameCannotFail(innerInternalName, ClassStub.UNKNOWN_ARITY);
member.setSimpleName(innerSimpleName);
member.setModifiers(access, false);
myStub.addMemberClass(member);
} else if (myInternalName.equals(innerInternalName) && outerName != null) {
// then it's specifying the enclosing class
// (myStub is the inner class)
ClassStub outer = resolver.resolveFromInternalNameCannotFail(outerName);
myStub.setSimpleName(innerSimpleName);
myStub.setModifiers(access, false);
myStub.setOuterClass(outer, null, null);
isInnerNonStaticClass = (Opcodes.ACC_STATIC & access) == 0;
}
}
@Override
public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
if ((access & (Opcodes.ACC_SYNTHETIC | Opcodes.ACC_BRIDGE)) != 0) {
// ignore synthetic methods
return null;
}
if ("<clinit>".equals(name)) {
return null;
}
ExecutableStub execStub;
if ("<init>".equals(name)) {
CtorStub ctor = new CtorStub(myStub, access, descriptor, signature, exceptions, isInnerNonStaticClass);
myStub.addCtor(ctor);
execStub = ctor;
} else {
MethodStub method = new MethodStub(myStub, name, access, descriptor, signature, exceptions);
myStub.addMethod(method);
execStub = method;
}
return new MethodInfoVisitor(execStub);
}
}
| 5,936 | 43.30597 | 136 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/AsmStub.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
/**
* Common interface for symbols wrapping a class file "stub".
* The class is parsed with ASM, only the signature information
* is retained, hence the name stub.
*/
interface AsmStub {
/** Resolver that produced this instance. The resolver is global. */
AsmSymbolResolver getResolver();
/** Object that can parse type signatures (necessary for eg field types). */
default SignatureParser sigParser() {
return getResolver().getSigParser();
}
}
| 632 | 23.346154 | 80 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/GenericSigBase.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang3.Validate;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.TypePath;
import org.objectweb.asm.TypeReference;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeParameterOwnerSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.TypeAnnotationHelper.TypeAnnotationSet;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.TypeAnnotationHelper.TypeAnnotationSetWithReferences;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.JIntersectionType;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.JTypeVar;
import net.sourceforge.pmd.lang.java.types.LexicalScope;
import net.sourceforge.pmd.lang.java.types.Substitution;
import net.sourceforge.pmd.lang.java.types.TypeOps;
import net.sourceforge.pmd.util.CollectionUtil;
abstract class GenericSigBase<T extends JTypeParameterOwnerSymbol & AsmStub> {
/*
Signatures must be parsed lazily, because at the point we see them
in the file, the enclosing class might not yet have been encountered
(and since its type parameters are in scope in the signature we must
wait for it).
*/
protected final T ctx;
protected List<JTypeVar> typeParameters;
private final ParseLock lock;
protected GenericSigBase(T ctx) {
this.ctx = ctx;
this.lock = new ParseLock() {
@Override
protected boolean doParse() {
GenericSigBase.this.doParse();
return true;
}
@Override
protected boolean postCondition() {
return GenericSigBase.this.postCondition();
}
@Override
protected boolean canReenter() {
return typeParameters != null;
}
};
}
LexicalScope getEnclosingTypeParams() {
JTypeParameterOwnerSymbol enclosing = ctx.getEnclosingTypeParameterOwner();
return enclosing == null ? LexicalScope.EMPTY : enclosing.getLexicalScope();
}
protected final void ensureParsed() {
lock.ensureParsed();
}
protected abstract void doParse();
protected abstract boolean postCondition();
protected abstract boolean isGeneric();
public void setTypeParams(List<JTypeVar> tvars) {
assert this.typeParameters == null : "Type params were already parsed for " + this;
this.typeParameters = tvars;
}
public List<JTypeVar> getTypeParams() {
ensureParsed();
return typeParameters;
}
public SignatureParser typeLoader() {
return ctx.sigParser();
}
static class LazyClassSignature extends GenericSigBase<ClassStub> {
private static final String OBJECT_INTERNAL_NAME = "java/lang/Object";
private static final String OBJECT_SIG = "L" + OBJECT_INTERNAL_NAME + ";";
private static final String OBJECT_BOUND = ":" + OBJECT_SIG;
private final @Nullable String signature;
private @Nullable JClassType superType;
private List<JClassType> superItfs;
private final List<JClassSymbol> rawItfs;
private final @Nullable JClassSymbol rawSuper;
LazyClassSignature(ClassStub ctx,
@Nullable String signature, // null if doesn't use generics in header
@Nullable String superInternalName, // null if this is the Object class
String[] interfaces) {
super(ctx);
this.signature = signature;
this.rawItfs = CollectionUtil.map(interfaces, ctx.getResolver()::resolveFromInternalNameCannotFail);
this.rawSuper = ctx.getResolver().resolveFromInternalNameCannotFail(superInternalName);
}
static LazyClassSignature defaultWhenUnresolved(ClassStub ctx, int observedArity) {
String sig = sigWithNTypeParams(observedArity);
return new LazyClassSignature(ctx, sig, OBJECT_INTERNAL_NAME, null);
}
private static @NonNull String sigWithNTypeParams(int observedArity) {
assert observedArity >= 0;
// use constants for common values
switch (observedArity) {
case 0: return OBJECT_SIG;
case 1: return "<T0" + OBJECT_BOUND + ">" + OBJECT_SIG;
case 2: return "<T0" + OBJECT_BOUND + "T1" + OBJECT_BOUND + ">" + OBJECT_SIG;
default: return Stream.iterate(0, i -> i + 1)
.limit(observedArity)
.map(i -> "T" + i + OBJECT_BOUND)
.collect(Collectors.joining("", "<", ">" + OBJECT_SIG));
}
}
@Override
protected void doParse() {
if (signature == null) {
this.superType = rawSuper == null ? null // the Object class
: (JClassType) ctx.getTypeSystem().rawType(rawSuper);
this.superItfs = CollectionUtil.map(rawItfs, klass -> (JClassType) ctx.getTypeSystem().rawType(klass));
setTypeParams(Collections.emptyList());
} else {
ctx.sigParser().parseClassSignature(this, signature);
}
}
@Override
protected boolean isGeneric() {
return signature != null && TypeParamsParser.hasTypeParams(signature);
}
@Override
protected boolean postCondition() {
return (superItfs != null && superType != null || signature == null) && typeParameters != null;
}
void setSuperInterfaces(List<JClassType> supers) {
Validate.validState(superItfs == null);
superItfs = supers;
}
void setSuperClass(JClassType sup) {
Validate.validState(this.superType == null);
this.superType = sup;
}
public JClassType getSuperType(Substitution subst) {
ensureParsed();
return superType == null ? null : superType.subst(subst);
}
public List<JClassType> getSuperItfs(Substitution subst) {
ensureParsed();
return TypeOps.substClasses(superItfs, subst);
}
public @Nullable JClassSymbol getRawSuper() {
return rawSuper;
}
public List<JClassSymbol> getRawItfs() {
return rawItfs;
}
@Override
public String toString() {
return signature;
}
}
/**
* Method or constructor type.
*/
static class LazyMethodType extends GenericSigBase<ExecutableStub> implements TypeAnnotationReceiver {
private final @NonNull String signature;
private @Nullable TypeAnnotationSet receiverAnnotations;
private List<JTypeMirror> parameterTypes;
private List<JTypeMirror> exceptionTypes;
private JTypeMirror returnType;
private @Nullable TypeAnnotationSetWithReferences typeAnnots;
private @Nullable String[] rawExceptions;
/** Used for constructors of inner non-static classes. */
private final boolean skipFirstParam;
// TODO exceptions. Couple of notes:
// - the descriptor never contains thrown exceptions
// - the signature might not contain the thrown exception types (if they do not depend on type variables)
// - the exceptions array also contains unchecked exceptions
//
// See https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.9.1
// TODO test cases
// <E extends Exception> void foo() throws E; // descriptor "()V" signature "<TE;>()V^TE;" exceptions: ???
// <E> void foo(E e) throws Exception; // descriptor "(Ljava.lang.Object;)V" signature "<TE;>(TE;)V" exceptions: [ "java/lang/Exception" ]
// void foo() throws Exception; // descriptor "()V" signature null exceptions: [ "java/lang/Exception" ]
LazyMethodType(ExecutableStub ctx,
@NonNull String descriptor,
@Nullable String genericSig,
@Nullable String[] exceptions,
boolean skipFirstParam) {
super(ctx);
this.signature = genericSig != null ? genericSig : descriptor;
// generic signatures already omit the synthetic param
this.skipFirstParam = skipFirstParam && genericSig == null;
this.rawExceptions = exceptions;
}
@Override
protected void doParse() {
ctx.sigParser().parseMethodType(this, signature);
if (rawExceptions != null && this.exceptionTypes.isEmpty()) {
// the descriptor did not contain exceptions. They're in this string array.
this.exceptionTypes = Arrays.stream(rawExceptions)
.map(ctx.getResolver()::resolveFromInternalNameCannotFail)
.map(ctx.getTypeSystem()::rawType)
.collect(CollectionUtil.toUnmodifiableList());
}
if (typeAnnots != null) {
// apply type annotations here
// this may change type parameters
boolean typeParamsWereMutated = typeAnnots.forEach(this::acceptAnnotationAfterParse);
if (typeParamsWereMutated) {
// Some type parameters were mutated. We need to replace
// the old tparams with the annotated ones in all other
// types of this signature.
// This substitution looks like the identity mapping.
// It actually does work, because JTypeVar#equals considers only the symbol
// and not the type annotations. So unannotated tvars in the type will be
// matched with the annotated tvar that has the same symbol.
Substitution subst = Substitution.mapping(typeParameters, typeParameters);
this.returnType = this.returnType.subst(subst);
this.parameterTypes = TypeOps.subst(parameterTypes, subst);
this.exceptionTypes = TypeOps.subst(exceptionTypes, subst);
}
}
// null this transient data out
this.rawExceptions = null;
this.typeAnnots = null;
}
public JTypeMirror applyReceiverAnnotations(JTypeMirror typeMirror) {
if (receiverAnnotations == null) {
return typeMirror;
}
return receiverAnnotations.decorate(typeMirror);
}
@Override
protected boolean postCondition() {
return parameterTypes != null && exceptionTypes != null && returnType != null;
}
@Override
protected boolean isGeneric() {
return TypeParamsParser.hasTypeParams(signature);
}
void setParameterTypes(List<JTypeMirror> params) {
Validate.validState(parameterTypes == null);
parameterTypes = skipFirstParam ? params.subList(1, params.size())
: params;
}
void setExceptionTypes(List<JTypeMirror> exs) {
Validate.validState(exceptionTypes == null);
exceptionTypes = exs;
}
void setReturnType(JTypeMirror returnType) {
Validate.validState(this.returnType == null);
this.returnType = returnType;
}
public List<JTypeMirror> getParameterTypes() {
ensureParsed();
return parameterTypes;
}
public List<JTypeMirror> getExceptionTypes() {
ensureParsed();
return exceptionTypes;
}
public JTypeMirror getReturnType() {
ensureParsed();
return returnType;
}
@Override
public String toString() {
return signature;
}
@Override
public void acceptTypeAnnotation(int typeRefInt, @Nullable TypePath path, SymAnnot annot) {
// Accumulate type annotations for later
// They shouldn't be applied right now because the descriptor maybe has not been parsed yet.
if (typeAnnots == null) {
typeAnnots = new TypeAnnotationSetWithReferences();
}
typeAnnots.add(new TypeReference(typeRefInt), path, annot);
}
/**
* See {@link MethodVisitor#visitTypeAnnotation(int, TypePath, String, boolean)} for possible
* values of typeRef sort (they're each case of the switch).
* Returns true if type parameters have been mutated.
*/
boolean acceptAnnotationAfterParse(TypeReference tyRef, @Nullable TypePath path, SymAnnot annot) {
switch (tyRef.getSort()) {
case TypeReference.METHOD_RETURN: {
assert returnType != null : "Return type is not set";
returnType = TypeAnnotationHelper.applySinglePath(returnType, path, annot);
return false;
}
case TypeReference.METHOD_FORMAL_PARAMETER: {
assert parameterTypes != null : "Parameter types are not set";
int idx = tyRef.getFormalParameterIndex();
JTypeMirror annotatedFormal = TypeAnnotationHelper.applySinglePath(parameterTypes.get(idx), path, annot);
parameterTypes = TypeAnnotationHelper.replaceAtIndex(parameterTypes, idx, annotatedFormal);
return false;
}
case TypeReference.THROWS: {
assert exceptionTypes != null : "Exception types are not set";
int idx = tyRef.getExceptionIndex();
JTypeMirror annotatedFormal = TypeAnnotationHelper.applySinglePath(exceptionTypes.get(idx), path, annot);
exceptionTypes = TypeAnnotationHelper.replaceAtIndex(exceptionTypes, idx, annotatedFormal);
return false;
}
case TypeReference.METHOD_TYPE_PARAMETER: {
assert typeParameters != null;
assert path == null : "unexpected path " + path;
int idx = tyRef.getTypeParameterIndex();
// Here we add to the symbol, not the type var.
// This ensures that all occurrences of the type var
// share these annotations (symbol is unique, contrary to jtypevar)
((TParamStub) typeParameters.get(idx).getSymbol()).addAnnotation(annot);
return false;
}
case TypeReference.METHOD_TYPE_PARAMETER_BOUND: {
assert typeParameters != null;
int tparamIdx = tyRef.getTypeParameterIndex();
int boundIdx = tyRef.getTypeParameterBoundIndex();
JTypeVar tparam = typeParameters.get(tparamIdx);
final JTypeMirror newUb = computeNewUpperBound(path, annot, boundIdx, tparam.getUpperBound());
typeParameters.set(tparamIdx, tparam.withUpperBound(newUb));
return true;
}
case TypeReference.METHOD_RECEIVER: {
if (receiverAnnotations == null) {
receiverAnnotations = new TypeAnnotationSet();
}
receiverAnnotations.add(path, annot);
return false;
}
default:
throw new IllegalArgumentException(
"Invalid type reference for method or ctor type annotation: " + tyRef.getSort());
}
}
private static JTypeMirror computeNewUpperBound(@Nullable TypePath path, SymAnnot annot, int boundIdx, JTypeMirror ub) {
final JTypeMirror newUb;
if (ub instanceof JIntersectionType) {
JIntersectionType intersection = (JIntersectionType) ub;
// Object is pruned from the component list
boundIdx = intersection.getPrimaryBound().isTop() ? boundIdx - 1 : boundIdx;
List<JTypeMirror> components = new ArrayList<>(intersection.getComponents());
JTypeMirror bound = components.get(boundIdx);
JTypeMirror newBound = TypeAnnotationHelper.applySinglePath(bound, path, annot);
components.set(boundIdx, newBound);
JTypeMirror newIntersection = intersection.getTypeSystem().glb(components);
newUb = newIntersection;
} else {
newUb = TypeAnnotationHelper.applySinglePath(ub, path, annot);
}
return newUb;
}
}
}
| 17,489 | 40.445498 | 171 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/MemberStubBase.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.pcollections.HashTreePSet;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.java.symbols.JAccessibleElementSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
abstract class MemberStubBase implements JAccessibleElementSymbol, AsmStub, AnnotationOwner {
private final ClassStub classStub;
private final String simpleName;
private final int accessFlags;
private PSet<SymAnnot> annotations = HashTreePSet.empty();
protected MemberStubBase(ClassStub classStub, String simpleName, int accessFlags) {
this.classStub = classStub;
this.simpleName = simpleName;
this.accessFlags = accessFlags;
}
@Override
public String getSimpleName() {
return simpleName;
}
@Override
public TypeSystem getTypeSystem() {
return classStub.getTypeSystem();
}
@Override
public AsmSymbolResolver getResolver() {
return classStub.getResolver();
}
@Override
public int getModifiers() {
return accessFlags;
}
@Override
public @NonNull ClassStub getEnclosingClass() {
return classStub;
}
@Override
public void addAnnotation(SymAnnot annot) {
annotations = annotations.plus(annot);
}
@Override
public PSet<SymAnnot> getDeclaredAnnotations() {
return annotations;
}
}
| 1,646 | 24.338462 | 93 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/InvalidTypeSignatureException.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
class InvalidTypeSignatureException extends IllegalArgumentException {
InvalidTypeSignatureException(String s) {
super(s);
}
}
| 293 | 21.615385 | 79 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/FieldStub.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.TypePath;
import org.objectweb.asm.TypeReference;
import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.lang.java.symbols.internal.SymbolEquality;
import net.sourceforge.pmd.lang.java.symbols.internal.SymbolToStrings;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.Substitution;
class FieldStub extends MemberStubBase implements JFieldSymbol, TypeAnnotationReceiver {
private final LazyTypeSig type;
private final @Nullable Object constValue;
FieldStub(ClassStub classStub,
String name,
int accessFlags,
String descriptor,
String signature,
@Nullable Object constValue) {
super(classStub, name, accessFlags);
this.type = new LazyTypeSig(classStub, descriptor, signature);
this.constValue = constValue;
}
@Override
public void acceptTypeAnnotation(int typeRef, @Nullable TypePath path, SymAnnot annot) {
assert new TypeReference(typeRef).getSort() == TypeReference.FIELD : typeRef;
this.type.addTypeAnnotation(path, annot);
}
@Override
public @Nullable Object getConstValue() {
return constValue;
}
@Override
public boolean isEnumConstant() {
return (getModifiers() & Opcodes.ACC_ENUM) != 0;
}
@Override
public JTypeMirror getTypeMirror(Substitution subst) {
return type.get(subst);
}
@Override
public String toString() {
return SymbolToStrings.ASM.toString(this);
}
@Override
public int hashCode() {
return SymbolEquality.FIELD.hash(this);
}
@Override
public boolean equals(Object obj) {
return SymbolEquality.FIELD.equals(this, obj);
}
}
| 2,130 | 28.597222 | 92 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/MethodInfoVisitor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.TypePath;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue;
class MethodInfoVisitor extends MethodVisitor {
private final ExecutableStub execStub;
private SymbolicValue defaultAnnotValue;
MethodInfoVisitor(ExecutableStub execStub) {
super(AsmSymbolResolver.ASM_API_V);
this.execStub = execStub;
}
@Override
public AnnotationVisitor visitAnnotationDefault() {
return new SymbolicValueBuilder(execStub.getResolver()) {
@Override
protected void acceptValue(String name, SymbolicValue v) {
defaultAnnotValue = v;
}
};
}
@Override
public AnnotationVisitor visitParameterAnnotation(int parameter, String descriptor, boolean visible) {
return new SymbolicValueBuilder(execStub.getResolver()) {
private final SymbolicAnnotationImpl annot = new SymbolicAnnotationImpl(getResolver(), visible, descriptor);
@Override
protected void acceptValue(String name, SymbolicValue v) {
annot.addAttribute(name, v);
}
@Override
public void visitEnd() {
execStub.addParameterAnnotation(parameter, annot);
}
};
}
@Override
public void visitEnd() {
execStub.setDefaultAnnotValue(defaultAnnotValue);
super.visitEnd();
}
@Override
public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) {
return new AnnotationBuilderVisitor(execStub, execStub.getResolver(), visible, descriptor);
}
@Override
public AnnotationVisitor visitTypeAnnotation(int typeRef, TypePath typePath, String descriptor, boolean visible) {
return new AnnotationBuilderVisitor.TypeAnnotBuilderImpl(execStub.getResolver(), execStub, typeRef, typePath, visible, descriptor);
}
}
| 2,147 | 30.588235 | 139 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/Classpath.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal.asm;
import java.net.URL;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Classpath abstraction. PMD's symbol resolver uses the classpath to
* find class files.
*/
@FunctionalInterface
public interface Classpath {
/**
* Returns a URL to load the given resource if it exists in this classpath.
* Otherwise returns null. This will typically be used to find Java class files.
* A typical input would be {@code java/lang/String.class}.
*
* @param resourcePath Resource path, as described in {@link ClassLoader#getResource(String)}
*
* @return A URL if the resource exists, otherwise null
*/
@Nullable URL findResource(String resourcePath);
// <editor-fold defaultstate="collapsed" desc="Transformation methods (defaults)">
/**
* Return a classpath that will ignore the given classpath entries,
* even if they are present in this classpath. Every call to {@link #findResource(String)}
* is otherwise delegated to this one.
*
* @param deletedEntries Set of resource paths to exclude
*/
default Classpath exclude(Set<String> deletedEntries) {
return resourcePath -> deletedEntries.contains(resourcePath) ? null : findResource(resourcePath);
}
default Classpath delegateTo(Classpath c) {
return path -> {
URL p = findResource(path);
if (p != null) {
return p;
}
return c.findResource(path);
};
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Creator methods">
/**
* Returns a classpath instance that uses {@link ClassLoader#getResource(String)}
* to find resources.
*/
static Classpath forClassLoader(ClassLoader classLoader) {
return classLoader::getResource;
}
static Classpath contextClasspath() {
return forClassLoader(Thread.currentThread().getContextClassLoader());
}
// </editor-fold>
}
| 2,160 | 28.60274 | 105 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTTypeParameter.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.JTypeParameterSymbol;
import net.sourceforge.pmd.lang.java.types.JTypeVar;
/**
* Represents a type parameter declaration of a method, constructor, class or interface declaration.
*
* <p>The bound of a type parameter may only be an upper bound ("extends").
* The bound is represented by the type node directly. The type node may
* be an {@link ASTIntersectionType intersection type}.
*
* <pre class="grammar">
*
* TypeParameter ::= {@link ASTAnnotation Annotation}* <IDENTIFIER> ( "extends" {@link ASTReferenceType Type} )?
*
* </pre>
*
* @see <a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-4.html#jls-4.4">JLS</a>
*/
public final class ASTTypeParameter extends AbstractTypedSymbolDeclarator<JTypeParameterSymbol> implements Annotatable {
ASTTypeParameter(int id) {
super(id);
}
/**
* Returns the name of the type variable introduced by this declaration.
*/
public String getName() {
return getImage();
}
/**
* Returns true if this type parameter is bounded,
* in which case {@link #getTypeBoundNode()} doesn't
* return {@code null}.
*/
public boolean hasTypeBound() {
return getTypeBoundNode() != null;
}
/**
* Returns the type bound node of this parameter,
* or null if it is not bounded.
*/
@Nullable
public ASTType getTypeBoundNode() {
return getFirstChildOfType(ASTType.class);
}
/**
* Returns the node to which this type parameter belongs.
*/
public TypeParamOwnerNode getOwner() {
return (TypeParamOwnerNode) getParent().getParent();
}
@Override
public @NonNull JTypeVar getTypeMirror() {
return (JTypeVar) super.getTypeMirror();
}
@Override
protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 2,214 | 27.037975 | 120 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/Annotatable.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.apache.commons.lang3.StringUtils;
import net.sourceforge.pmd.lang.ast.NodeStream;
import net.sourceforge.pmd.lang.java.types.TypeTestUtil;
/**
* Marks nodes that can be annotated. {@linkplain ASTAnnotation Annotations}
* are most often the first few children of the node they apply to.
* E.g. in {@code @Positive int}, the {@code @Positive} annotation is
* a child of the {@link ASTPrimitiveType PrimitiveType} node. This
* contrasts with PMD 6.0 grammar, where the annotations were most often
* the preceding siblings.
*/
public interface Annotatable extends JavaNode {
/**
* Returns all annotations present on this node.
*/
default NodeStream<ASTAnnotation> getDeclaredAnnotations() {
return children(ASTAnnotation.class);
}
/**
* Returns true if an annotation with the given qualified name is
* applied to this node.
*
* @param annotQualifiedName Note: for now, canonical names are tolerated, this may be changed in PMD 7.
*/
default boolean isAnnotationPresent(String annotQualifiedName) {
return getDeclaredAnnotations().any(t -> TypeTestUtil.isA(StringUtils.deleteWhitespace(annotQualifiedName), t));
}
/**
* Returns true if an annotation with the given type is
* applied to this node.
*/
default boolean isAnnotationPresent(Class<?> type) {
return getDeclaredAnnotations().any(t -> TypeTestUtil.isA(type, t));
}
/**
* Returns a specific annotation on this node, or null if absent.
*
* @param binaryName
* Binary name of the annotation type.
* Note: for now, canonical names are tolerated, this may be changed in PMD 7.
*/
default ASTAnnotation getAnnotation(String binaryName) {
return getDeclaredAnnotations().filter(t -> TypeTestUtil.isA(StringUtils.deleteWhitespace(binaryName), t)).first();
}
/**
* Checks whether any annotation is present on this node.
*
* @param binaryNames
* Collection that contains binary names of annotations.
* Note: for now, canonical names are tolerated, this may be changed in PMD 7.
* @return <code>true</code> if any annotation is present on this node, else <code>false</code>
*/
default boolean isAnyAnnotationPresent(Collection<String> binaryNames) {
for (String annotQualifiedName : binaryNames) {
if (isAnnotationPresent(annotQualifiedName)) {
return true;
}
}
return false;
}
}
| 2,729 | 33.125 | 123 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTPackageDeclaration.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
/**
* Package declaration at the top of a {@linkplain ASTCompilationUnit source file}.
* Since 7.0, there is no Name node anymore. Use {@link #getName()} instead.
*
*
* <pre class="grammar">
*
* PackageDeclaration ::= {@link ASTModifierList AnnotationList} "package" Name ";"
*
* </pre>
*
*/
public final class ASTPackageDeclaration extends AbstractJavaNode implements Annotatable, ASTTopLevelDeclaration, JavadocCommentOwner {
ASTPackageDeclaration(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 package.
*
* @since 6.30.0
*/
public String getName() {
return super.getImage();
}
@Override
public String getImage() {
// the image was null before 7.0, best keep it that way
return null;
}
}
| 1,084 | 22.085106 | 135 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/AbstractJavaExpr.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;
abstract class AbstractJavaExpr extends AbstractJavaTypeNode implements ASTExpression {
private static final Object NOT_COMPUTED = new Object(); // null is sentinel value too
private int parenDepth;
private Object constValue = NOT_COMPUTED;
AbstractJavaExpr(int i) {
super(i);
}
void bumpParenDepth() {
parenDepth++;
}
@Override
public int getParenthesisDepth() {
return parenDepth;
}
@Override
public @Nullable Object getConstValue() {
if (constValue == NOT_COMPUTED) { // NOPMD we want identity semantics
constValue = null; // remove the sentinel, so that we don't reenter on cycle
constValue = buildConstValue();
}
return constValue;
}
protected @Nullable Object buildConstValue() {
return acceptVisitor(ConstantFolder.INSTANCE, null);
}
}
| 1,084 | 24.232558 | 90 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTArrayDimensions.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;
/**
* Represents array type dimensions. This node may occur in several contexts:
* <ul>
* <li>In an {@linkplain ASTArrayType array type}</li>
* <li>As the {@linkplain ASTMethodDeclaration#getExtraDimensions() extra dimensions of a method declaration},
* after the formal parameter list. For example:
* <pre>public int newIntArray(int length) [];</pre>
* </li>
* <li>As the {@linkplain ASTVariableDeclaratorId#getExtraDimensions() extra dimensions of a variable declarator id},
* in a {@linkplain ASTVariableDeclarator variable declarator}. For example:
* <pre>public int a[], b[][];</pre>
* </li>
* </ul>
*
* <p>Some dimensions may be initialized with an expression, but only in
* the array type of an {@linkplain ASTArrayAllocation array allocation expression}.
*
* <pre class="grammar">
*
* ArrayDimensions ::= {@link ASTArrayTypeDim ArrayTypeDim}+ {@link ASTArrayDimExpr ArrayDimExpr}*
*
* </pre>
*/
public final class ASTArrayDimensions extends ASTNonEmptyList<ASTArrayTypeDim> {
ASTArrayDimensions(int id) {
super(id, ASTArrayTypeDim.class);
}
@Override
protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 1,447 | 31.177778 | 117 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTUnionType.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;
import net.sourceforge.pmd.lang.java.ast.InternalInterfaces.AtLeastOneChildOfType;
/**
* Represents the type node of a multi-catch statement. This node is used
* to make the grammar of {@link ASTCatchParameter CatchParameter} more
* straightforward. Note though, that the Java type system does not feature
* union types at all. The type of this node is defined as the least upper-bound
* of all its components.
*
* <pre class="grammar">
*
* UnionType ::= {@link ASTClassOrInterfaceType ClassType} ("|" {@link ASTClassOrInterfaceType ClassType})+
*
* </pre>
*
* @see ASTCatchParameter#getAllExceptionTypes()
*/
public final class ASTUnionType extends AbstractJavaTypeNode
implements ASTReferenceType,
AtLeastOneChildOfType<ASTClassOrInterfaceType>,
Iterable<ASTClassOrInterfaceType> {
ASTUnionType(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 component types. */
public NodeStream<ASTClassOrInterfaceType> getComponents() {
return children(ASTClassOrInterfaceType.class);
}
@Override
public Iterator<ASTClassOrInterfaceType> iterator() {
return children(ASTClassOrInterfaceType.class).iterator();
}
}
| 1,575 | 28.735849 | 107 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTFieldAccess.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.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr;
import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol;
import net.sourceforge.pmd.lang.java.types.JVariableSig.FieldSig;
/**
* A field access expression.
*
* <pre class="grammar">
*
* FieldAccess ::= {@link ASTExpression Expression} "." <IDENTIFIER>
*
* </pre>
*/
public final class ASTFieldAccess extends AbstractJavaExpr implements ASTNamedReferenceExpr, QualifiableExpression {
private FieldSig typedSym;
ASTFieldAccess(int id) {
super(id);
}
/**
* Promotes an ambiguous name to the LHS of this node.
*/
ASTFieldAccess(ASTAmbiguousName lhs, String fieldName) {
super(JavaParserImplTreeConstants.JJTFIELDACCESS);
assert fieldName != null;
this.addChild(lhs, 0);
this.setImage(fieldName);
}
ASTFieldAccess(ASTExpression lhs, JavaccToken identifier) {
super(JavaParserImplTreeConstants.JJTFIELDACCESS);
TokenUtils.expectKind(identifier, JavaTokenKinds.IDENTIFIER);
this.addChild((AbstractJavaNode) lhs, 0);
this.setImage(identifier.getImage());
this.setFirstToken(lhs.getFirstToken());
this.setLastToken(identifier);
}
@Override
public @NonNull ASTExpression getQualifier() {
return (ASTExpression) getChild(0);
}
@Override
public String getName() {
return getImage();
}
@Override
public @Nullable FieldSig getSignature() {
forceTypeResolution();
return typedSym;
}
@Override
public @Nullable JFieldSymbol getReferencedSym() {
return (JFieldSymbol) ASTNamedReferenceExpr.super.getReferencedSym();
}
void setTypedSym(@Nullable FieldSig sig) {
this.typedSym = sig;
}
@Override
protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 2,283 | 26.190476 | 116 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTAnonymousClassDeclaration.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;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
/**
* An anonymous class declaration. This can occur in a {@linkplain ASTConstructorCall class instance creation
* expression}
* or in an {@linkplain ASTEnumConstant enum constant declaration}.
* This is a {@linkplain Node#isFindBoundary() find boundary} for tree traversal methods.
*
*
* <pre class="grammar">
*
* AnonymousClassDeclaration ::= {@link ASTModifierList EmptyModifierList} {@link ASTClassOrInterfaceBody}
*
* </pre>
*/
public final class ASTAnonymousClassDeclaration extends AbstractAnyTypeDeclaration {
ASTAnonymousClassDeclaration(int id) {
super(id);
}
@Override
public @NonNull String getSimpleName() {
return "";
}
@Override
public boolean isFindBoundary() {
return true;
}
@Override
public @NonNull NodeStream<ASTClassOrInterfaceType> getSuperInterfaceTypeNodes() {
if (getParent() instanceof ASTConstructorCall) {
ASTConstructorCall ctor = (ASTConstructorCall) getParent();
@NonNull JTypeMirror type = ctor.getTypeMirror();
if (type.isInterface()) {
return NodeStream.of(ctor.getTypeNode());
}
}
return NodeStream.empty();
}
@Override
public Visibility getVisibility() {
return Visibility.V_ANONYMOUS;
}
@Override
protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 1,817 | 26.545455 | 109 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTLocalClassStatement.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 statement that contains a local class declaration. Note that this
* is not a declaration itself.
*
* <pre class="grammar">
*
* LocalClassStatement ::= {@link ASTAnyTypeDeclaration TypeDeclaration}
*
* </pre>
*/
public final class ASTLocalClassStatement extends AbstractStatement {
ASTLocalClassStatement(int id) {
super(id);
}
ASTLocalClassStatement(ASTAnyTypeDeclaration tdecl) {
super(JavaParserImplTreeConstants.JJTLOCALCLASSSTATEMENT);
assert tdecl != null;
addChild((AbstractJavaNode) tdecl, 0);
setFirstToken(tdecl.getFirstToken());
setLastToken(tdecl.getLastToken());
}
@Override
protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
/**
* Returns the contained declaration.
*/
public @NonNull ASTAnyTypeDeclaration getDeclaration() {
return (ASTAnyTypeDeclaration) getChild(0);
}
@Override
public boolean isFindBoundary() {
return true;
}
}
| 1,268 | 23.882353 | 91 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTThrowStatement.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
/**
* A {@code throw} statement.
*
* <pre class="grammar">
*
* ThrowStatement ::= "throw" {@link ASTExpression Expression} ";"
*
* </pre>
*/
public final class ASTThrowStatement extends AbstractStatement implements ASTSwitchArrowRHS {
ASTThrowStatement(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 for the thrown exception.
*/
public ASTExpression getExpr() {
return (ASTExpression) getFirstChild();
}
}
| 757 | 20.055556 | 93 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTNullLiteral.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 null literal.
*
* <pre class="grammar">
*
* NullLiteral ::= "null"
*
* </pre>
*/
public final class ASTNullLiteral extends AbstractLiteral implements ASTLiteral {
ASTNullLiteral(int id) {
super(id);
}
@Override
public <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
@Override
public boolean isCompileTimeConstant() {
return false;
}
@Override
public @Nullable Object getConstValue() {
return null;
}
}
| 760 | 18.512821 | 88 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/AbstractPackageNameModuleDirective.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
public abstract class AbstractPackageNameModuleDirective extends ASTModuleDirective {
AbstractPackageNameModuleDirective(int id) {
super(id);
}
public final String getPackageName() {
return super.getImage();
}
@Override
@Deprecated
public final String getImage() {
return null;
}
final void setPackageName(String name) {
super.setImage(name);
}
}
| 556 | 19.62963 | 85 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/package-info.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
/**
* Contains the classes and interfaces modelling the Java AST.
*
* <p>Note: from 6.16.0 on, the following usages have been deprecated:
* <ul>
* <li>Manual instantiation of nodes. Constructors of node classes are
* deprecated and marked {@link net.sourceforge.pmd.annotation.InternalApi}.
* Nodes should only be obtained from the parser, which for rules,
* means that never need to instantiate node themselves. Those
* constructors will be made package private with 7.0.0.
* <li>Subclassing of base node classes, or usage of their type.
* Version 7.0.0 will bring a new set of abstractions that will
* be public API, but the base classes are and will stay internal.
* You should not couple your code to them.
* <p>In the meantime you should use interfaces like {@link net.sourceforge.pmd.lang.java.ast.JavaNode}
* or {@link net.sourceforge.pmd.lang.ast.Node}, or the other published
* interfaces in this package, to refer to nodes generically.
* </li>
* <li>Setters found in any node class or interface. Rules should consider
* the AST immutable. We will make those setters package private
* with 7.0.0.
* </li>
* </ul>
*
*/
package net.sourceforge.pmd.lang.java.ast;
| 1,352 | 41.28125 | 107 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTInitializer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
/**
* A class or instance initializer. Don't confuse with {@link ASTVariableInitializer}.
*
* <pre class="grammar">
*
* Initializer ::= "static"? {@link ASTBlock Block}
*
* </pre>
*
*/
public final class ASTInitializer extends AbstractJavaNode implements ASTBodyDeclaration {
private boolean isStatic;
ASTInitializer(int id) {
super(id);
}
@Override
protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
public boolean isStatic() {
return isStatic;
}
void setStatic() {
isStatic = true;
}
/**
* Returns the body of this initializer.
*/
public ASTBlock getBody() {
return (ASTBlock) getChild(0);
}
}
| 922 | 18.229167 | 91 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTContinueStatement.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.Function;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.ast.NodeStream;
/**
* A continue statement, that jumps to the next iteration of an enclosing loop.
*
* <pre class="grammar">
*
* ContinueStatement ::= "continue" <IDENTIFIER>? ";"
*
* </pre>
*/
public final class ASTContinueStatement extends AbstractStatement {
private static final Function<Object, ASTLoopStatement> CONTINUE_TARGET_MAPPER =
NodeStream.asInstanceOf(ASTLoopStatement.class);
ASTContinueStatement(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 label, or null if there is none.
*/
public @Nullable String getLabel() {
return getImage();
}
/**
* Returns the statement that is the target of this break. This can
* be a loop, or an {@link ASTLabeledStatement}.
*/
public ASTStatement getTarget() {
String myLabel = this.getLabel();
if (myLabel == null) {
return ancestors().map(CONTINUE_TARGET_MAPPER).first();
}
return ancestors(ASTLabeledStatement.class)
.filter(it -> it.getLabel().equals(myLabel))
.first();
}
}
| 1,516 | 23.868852 | 91 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTThisExpression.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 "this" expression. Related to the {@link ASTSuperExpression "super"} pseudo-expression.
*
* <pre class="grammar">
*
* ThisExpression ::= "this"
* | {@link ASTClassOrInterfaceType TypeName} "." "this"
*
* </pre>
*/
public final class ASTThisExpression extends AbstractJavaExpr implements ASTPrimaryExpression {
ASTThisExpression(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);
}
}
| 914 | 23.72973 | 95 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTTypeArguments.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;
/**
* Represents a list of type arguments. This is different from {@linkplain ASTTypeParameters type parameters}!
*
* <pre class="grammar">
*
* TypeArguments ::= "<" {@linkplain ASTReferenceType TypeArgument} ( "," {@linkplain ASTReferenceType TypeArgument} )* ">"
* | "<" ">"
* </pre>
*/
public final class ASTTypeArguments extends ASTMaybeEmptyListOf<ASTType> {
ASTTypeArguments(int id) {
super(id, ASTType.class);
}
@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 diamond, that is, the
* actual type arguments are inferred. In this case
* this list has no children.
*/
public boolean isDiamond() {
return size() == 0;
}
}
| 1,067 | 25.04878 | 130 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/MethodUsage.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.JConstructorSymbol;
/**
* A node that uses another method or constructor. Those are
* {@link InvocationNode#getMethodType() InvocationNode}s and
* {@link ASTMethodReference#getReferencedMethod() MethodReference}.
*
* TODO should these method be named the same, and added to this interface?
*/
public interface MethodUsage extends JavaNode {
/**
* Returns the name of the called method. If this is a constructor
* call, returns {@link JConstructorSymbol#CTOR_NAME}.
*/
default @NonNull String getMethodName() {
return JConstructorSymbol.CTOR_NAME;
}
}
| 831 | 28.714286 | 79 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTCharLiteral.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.StringEscapeUtils;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* Represents a character literal. The image of this node can be the literal as it appeared
* in the source, but JavaCC performs its own unescaping and some escapes may be lost. At the
* very least it has delimiters. {@link #getConstValue()} allows to recover the actual runtime value.
*/
public final class ASTCharLiteral extends AbstractLiteral implements ASTLiteral {
ASTCharLiteral(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 char value of this literal.
*/
@Override
public @NonNull Character getConstValue() {
String image = getImage();
String woDelims = image.substring(1, image.length() - 1);
return StringEscapeUtils.unescapeJava(woDelims).charAt(0);
}
}
| 1,136 | 26.731707 | 101 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTConstructorCall.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;
/**
* A class instance creation expression. Represents both {@linkplain #isQualifiedInstanceCreation() qualified}
* and unqualified instance creation. May declare an anonymous class body.
*
*
* <pre class="grammar">
*
* ConstructorCall ::= UnqualifiedAlloc
* | {@link ASTExpression Expression} "." UnqualifiedAlloc
*
* UnqualifiedAlloc ::=
* "new" {@link ASTTypeArguments TypeArguments}? {@link ASTClassOrInterfaceType ClassOrInterfaceType} {@link ASTArgumentList ArgumentList} {@link ASTAnonymousClassDeclaration AnonymousClassDeclaration}?
*
* </pre>
*/
public final class ASTConstructorCall extends AbstractInvocationExpr
implements ASTPrimaryExpression,
QualifiableExpression,
LeftRecursiveNode,
InvocationNode {
ASTConstructorCall(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 expression begins with a primary expression.
* Such an expression creates an instance of inner member classes and
* their anonymous subclasses. For example, {@code new Outer().new Inner()}
* evaluates to an instance of the Inner class, which is nested inside
* the new instance of Outer.
*/
public boolean isQualifiedInstanceCreation() {
return getChild(0) instanceof ASTExpression;
}
/**
* Returns the outer instance expression, if this is a {@linkplain #isQualifiedInstanceCreation() qualified}
* constructor call. Otherwise returns null. This can never be a
* {@linkplain ASTTypeExpression type expression}, and is never
* {@linkplain ASTAmbiguousName ambiguous}.
*/
@Override
public @Nullable ASTExpression getQualifier() {
return QualifiableExpression.super.getQualifier();
}
@Override
public @Nullable ASTTypeArguments getExplicitTypeArguments() {
return getFirstChildOfType(ASTTypeArguments.class);
}
@Override
public @NonNull ASTArgumentList getArguments() {
JavaNode child = getLastChild();
if (child instanceof ASTAnonymousClassDeclaration) {
return (ASTArgumentList) getChild(getNumChildren() - 2);
}
return (ASTArgumentList) child;
}
/** Returns true if type arguments to the constructed instance's type are inferred. */
public boolean usesDiamondTypeArgs() {
ASTTypeArguments targs = getTypeNode().getTypeArguments();
return targs != null && targs.isDiamond();
}
/**
* Returns the type node.
*/
public ASTClassOrInterfaceType getTypeNode() {
return getFirstChildOfType(ASTClassOrInterfaceType.class);
}
/**
* Returns true if this expression defines a body,
* which is compiled to an anonymous class. If this
* method returns false.
*/
public boolean isAnonymousClass() {
return getChild(getNumChildren() - 1) instanceof ASTAnonymousClassDeclaration;
}
@Nullable
public ASTAnonymousClassDeclaration getAnonymousClassDeclaration() {
return isAnonymousClass()
? (ASTAnonymousClassDeclaration) getChild(getNumChildren() - 1)
: null;
}
}
| 3,601 | 31.45045 | 207 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/JavaParserVisitorAdapter.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.DeprecatedUntil700;
import net.sourceforge.pmd.lang.ast.Node;
/**
* An adapter for {@link JavaParserVisitor}.
*
* @deprecated Use {@link JavaVisitorBase}
*/
@Deprecated
@DeprecatedUntil700
public class JavaParserVisitorAdapter extends JavaVisitorBase<Object, Object> implements JavaParserVisitor {
@Override
protected Object visitChildren(Node node, Object data) {
super.visitChildren(node, data);
return data;
}
}
| 621 | 22.923077 | 108 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTSwitchFallthroughBranch.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 fallthrough switch branch. This contains exactly one label, and zero
* or more statements. Fallthrough must be handled by looking at the siblings.
* For example, in the following, the branch for {@code case 1:} has no statements,
* while the branch for {@code case 2:} has two.
*
* <pre>{@code
*
* switch (foo) {
* case 1:
* case 2:
* do1Or2();
* break;
* default:
* doDefault();
* break;
* }
*
* }</pre>
*
*
* <pre class="grammar">
*
* SwitchFallthroughBranch ::= {@link ASTSwitchLabel SwitchLabel} ":" {@link ASTStatement Statement}*
*
* </pre>
*/
public final class ASTSwitchFallthroughBranch extends AbstractJavaNode
implements ASTSwitchBranch {
ASTSwitchFallthroughBranch(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 list of statements dominated by the labels. This list is possibly empty.
*/
public NodeStream<ASTStatement> getStatements() {
return children(ASTStatement.class);
}
}
| 1,332 | 22.803571 | 101 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/AbstractJavaNode.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.AstVisitor;
import net.sourceforge.pmd.lang.ast.impl.javacc.AbstractJjtreeNode;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken;
import net.sourceforge.pmd.lang.java.symbols.table.JSymbolTable;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
abstract class AbstractJavaNode extends AbstractJjtreeNode<AbstractJavaNode, JavaNode> implements JavaNode {
protected JSymbolTable symbolTable;
private ASTCompilationUnit root;
AbstractJavaNode(int id) {
super(id);
}
@Override
public void jjtClose() {
super.jjtClose();
if (this instanceof LeftRecursiveNode && getNumChildren() > 0) {
fitTokensToChildren(0);
}
}
// override those to make them accessible in this package
@Override
@SuppressWarnings("unchecked")
public final <P, R> R acceptVisitor(AstVisitor<? super P, ? extends R> visitor, P data) {
if (visitor instanceof JavaVisitor) {
return this.acceptVisitor((JavaVisitor<? super P, ? extends R>) visitor, data);
}
return visitor.cannotVisit(this, data);
}
protected abstract <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data);
// override those to make them accessible in this package
@Override
protected void addChild(AbstractJavaNode child, int index) {
super.addChild(child, index);
}
@Override // override to make it accessible to tests that build nodes (which have been removed on java-grammar)
protected void insertChild(AbstractJavaNode child, int index) {
super.insertChild(child, index);
}
@Override
protected void removeChildAtIndex(int childIndex) {
super.removeChildAtIndex(childIndex);
}
@Override
protected void setImage(String image) {
super.setImage(image);
}
@Override
protected void setFirstToken(JavaccToken token) {
super.setFirstToken(token);
}
@Override
protected void setLastToken(JavaccToken token) {
super.setLastToken(token);
}
@Override
protected void setChild(AbstractJavaNode child, int index) {
super.setChild(child, index);
}
void setSymbolTable(JSymbolTable table) {
this.symbolTable = table;
}
@Override
public @NonNull JSymbolTable getSymbolTable() {
if (symbolTable == null) {
return getParent().getSymbolTable();
}
return symbolTable;
}
@Override
public TypeSystem getTypeSystem() {
return getRoot().getTypeSystem();
}
@Override
public final @NonNull ASTCompilationUnit getRoot() {
// storing a reference on each node ensures that each path is roamed
// at most once.
if (root == null) {
setRoot(getParent().getRoot());
}
return root;
}
/**
* Shift the start and end tokens by the given offsets.
* @throws IllegalStateException if the right shift identifies
* a token that is left of this node
*/
void shiftTokens(int leftShift, int rightShift) {
if (leftShift != 0) {
setFirstToken(findTokenSiblingInThisNode(getFirstToken(), leftShift));
}
if (rightShift != 0) {
setLastToken(findTokenSiblingInThisNode(getLastToken(), rightShift));
}
}
private JavaccToken findTokenSiblingInThisNode(JavaccToken token, int shift) {
if (shift == 0) {
return token;
} else if (shift < 0) {
// expects a positive shift
return TokenUtils.nthPrevious(getFirstToken(), token, -shift);
} else {
return TokenUtils.nthFollower(token, shift);
}
}
void copyTextCoordinates(AbstractJavaNode copy) {
setFirstToken(copy.getFirstToken());
setLastToken(copy.getLastToken());
}
@Override
public final String getXPathNodeName() {
return JavaParserImplTreeConstants.jjtNodeName[id];
}
void setRoot(ASTCompilationUnit root) {
this.root = root;
}
}
| 4,312 | 27.189542 | 115 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTFormalParameter.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.ast.InternalInterfaces.VariableIdOwner;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.TypingContext;
/**
* Formal parameter node for a {@linkplain ASTFormalParameters formal parameter list}.
* This is distinct from {@linkplain ASTLambdaParameter lambda parameters}.
*
* <p>The varargs ellipsis {@code "..."} is parsed as an {@linkplain ASTArrayTypeDim array dimension}
* in the type node.
*
* <pre class="grammar">
*
* FormalParameter ::= {@link ASTModifierList LocalVarModifierList} {@link ASTType Type} {@link ASTVariableDeclaratorId VariableDeclaratorId}
*
* </pre>
*/
public final class ASTFormalParameter extends AbstractJavaNode
implements FinalizableNode,
TypeNode,
Annotatable,
VariableIdOwner {
ASTFormalParameter(int id) {
super(id);
}
@Override
public Visibility getVisibility() {
return Visibility.V_LOCAL;
}
/**
* Returns the list of formal parameters containing this param.
*/
public ASTFormalParameters getOwnerList() {
return (ASTFormalParameters) getParent();
}
/**
* Returns true if this node is a varargs parameter. Then, the type
* node is an {@link ASTArrayType ArrayType}, and its last dimension
* {@linkplain ASTArrayTypeDim#isVarargs() is varargs}.
*/
public boolean isVarargs() {
ASTType tn = getTypeNode();
return tn instanceof ASTArrayType
&& ((ASTArrayType) tn).getDimensions().getLastChild().isVarargs();
}
@Override
protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
/**
* Returns the declarator ID of this formal parameter.
*/
@Override
public @NonNull ASTVariableDeclaratorId getVarId() {
return firstChild(ASTVariableDeclaratorId.class);
}
/**
* Returns the type node of this formal parameter.
*
* <p>If this formal parameter is varargs, the type node is an {@link ASTArrayType}.
*/
public ASTType getTypeNode() {
return firstChild(ASTType.class);
}
// Honestly FormalParameter shouldn't be a TypeNode.
// The node that represents the variable is the variable ID.
@Override
public @NonNull JTypeMirror getTypeMirror(TypingContext ctx) {
return getVarId().getTypeMirror(ctx);
}
}
| 2,692 | 27.648936 | 141 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTSwitchLike.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;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
/**
* Common supertype for {@linkplain ASTSwitchStatement switch statements}
* and {@linkplain ASTSwitchExpression switch expressions}. Their grammar
* is identical, and is described below. The difference is that switch
* expressions need to be exhaustive.
*
* <pre class="grammar">
*
* SwitchLike ::= {@link ASTSwitchExpression SwitchExpression}
* | {@link ASTSwitchStatement SwitchStatement}
*
* ::= "switch" "(" {@link ASTExpression Expression} ")" SwitchBlock
*
* SwitchBlock ::= SwitchArrowBlock | SwitchNormalBlock
*
* SwitchArrowBlock ::= "{" {@link ASTSwitchArrowBranch SwitchArrowBranch}* "}"
* SwitchNormalBlock ::= "{" {@linkplain ASTSwitchFallthroughBranch SwitchFallthroughBranch}* "}"
*
* </pre>
*/
public interface ASTSwitchLike extends JavaNode, Iterable<ASTSwitchBranch> {
/**
* Returns true if this switch has a {@code default} case.
*/
default boolean hasDefaultCase() {
return getBranches().any(it -> it.getLabel().isDefault());
}
/**
* Returns a stream of all branches of this switch.
*/
default NodeStream<ASTSwitchBranch> getBranches() {
return children(ASTSwitchBranch.class);
}
/**
* Gets the expression tested by this switch.
* This is the expression between the parentheses.
*/
default ASTExpression getTestedExpression() {
return (ASTExpression) getChild(0);
}
/**
* Returns true if this switch statement tests an expression
* having an enum type and all the constants of this type
* are covered by a switch case. Returns false if the type of
* the tested expression could not be resolved.
*/
default boolean isExhaustiveEnumSwitch() {
JTypeDeclSymbol symbol = getTestedExpression().getTypeMirror().getSymbol();
if (symbol instanceof JClassSymbol && ((JClassSymbol) symbol).isEnum()) {
long numConstants = ((JClassSymbol) symbol).getEnumConstants().size();
// we assume there's no duplicate labels
int numLabels = getBranches().sumByInt(it -> it.getLabel().getNumChildren());
return numLabels == numConstants;
}
return false;
}
/**
* Returns true if this switch statement tests an expression
* having an enum type.
*/
default boolean isEnumSwitch() {
JTypeDeclSymbol type = getTestedExpression().getTypeMirror().getSymbol();
return type instanceof JClassSymbol && ((JClassSymbol) type).isEnum();
}
@Override
default Iterator<ASTSwitchBranch> iterator() {
return children(ASTSwitchBranch.class).iterator();
}
/**
* Returns true if this a switch which uses fallthrough branches
* (old school {@code case label: break;}) and not arrow branches.
* If the switch has no branches, returns false.
*/
default boolean isFallthroughSwitch() {
return getBranches().filterIs(ASTSwitchFallthroughBranch.class).nonEmpty();
}
}
| 3,371 | 31.737864 | 97 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/LeftRecursiveNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
/**
* Marker interface for left-recursive nodes. Those nodes are injected
* with children after jjtOpen is called, which means their text bounds
* need to be adapted in {@link AbstractJavaNode#jjtClose()}.
*
* <p>This is only relevant to node construction and is package private.
*
* @author Clément Fournier
*/
interface LeftRecursiveNode {
// no methods should ever be added
}
| 523 | 26.578947 | 79 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTForeachStatement.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 a "foreach"-loop on an {@link Iterable}.
*
* <pre class="grammar">
*
* ForeachStatement ::= "for" "(" ( {@linkplain ASTLocalVariableDeclaration LocalVariableDeclaration} | {@linkplain ASTRecordPattern RecordPattern} ) ":" {@linkplain ASTExpression Expression} ")" {@linkplain ASTStatement Statement}
*
* </pre>
*
* <p>Note: Using a {@linkplain ASTRecordPattern RecordPattern} in an enhanced for statement is a Java 20 Preview feature</p>
*
* @see <a href="https://openjdk.org/jeps/432">JEP 432: Record Patterns (Second Preview)</a>
*/
public final class ASTForeachStatement extends AbstractStatement implements InternalInterfaces.VariableIdOwner, ASTLoopStatement {
ASTForeachStatement(int id) {
super(id);
}
@Override
protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
@Override
@NonNull
public ASTVariableDeclaratorId getVarId() {
// in case of destructuring record patterns, there might be multiple vars
return getFirstChild().descendants(ASTVariableDeclaratorId.class).first();
}
/**
* Returns the expression that evaluates to the {@link Iterable}
* being looped upon.
*/
@NonNull
public ASTExpression getIterableExpr() {
return getFirstChildOfType(ASTExpression.class);
}
}
| 1,589 | 29 | 231 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTLiteral.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
/**
* A lexical literal. This is an expression that is represented by exactly
* one token. This interface is implemented by several nodes.
*
* <pre class="grammar">
*
* Literal ::= {@link ASTNumericLiteral NumericLiteral}
* | {@link ASTStringLiteral StringLiteral}
* | {@link ASTCharLiteral CharLiteral}
* | {@link ASTBooleanLiteral BooleanLiteral}
* | {@link ASTNullLiteral NullLiteral}
*
* </pre>
*/
public interface ASTLiteral extends ASTPrimaryExpression {
// Those methods are deprecated as they're not so useful, and introduce
// unwanted XPath attributes
/**
* Returns true if this is a {@linkplain ASTStringLiteral string literal}.
*/
@Deprecated
default boolean isStringLiteral() {
return this instanceof ASTStringLiteral;
}
/**
* Returns true if this is a {@linkplain ASTCharLiteral character literal}.
*/
@Deprecated
default boolean isCharLiteral() {
return this instanceof ASTCharLiteral;
}
/**
* Returns true if this is the {@linkplain ASTNullLiteral null literal}.
*/
@Deprecated
default boolean isNullLiteral() {
return this instanceof ASTNullLiteral;
}
/**
* Returns true if this is a {@linkplain ASTBooleanLiteral boolean literal}.
*/
@Deprecated
default boolean isBooleanLiteral() {
return this instanceof ASTBooleanLiteral;
}
/**
* Returns true if this is a {@linkplain ASTNumericLiteral numeric literal}
* of any kind.
*/
@Deprecated
default boolean isNumericLiteral() {
return this instanceof ASTNumericLiteral;
}
/**
* Returns true if this is an {@linkplain ASTNumericLiteral integer literal}.
*/
@Deprecated
default boolean isIntLiteral() {
return false;
}
/**
* Returns true if this is a {@linkplain ASTNumericLiteral long integer literal}.
*/
@Deprecated
default boolean isLongLiteral() {
return false;
}
/**
* Returns true if this is a {@linkplain ASTNumericLiteral float literal}.
*/
@Deprecated
default boolean isFloatLiteral() {
return false;
}
/**
* Returns true if this is a {@linkplain ASTNumericLiteral double literal}.
*/
@Deprecated
default boolean isDoubleLiteral() {
return false;
}
}
| 2,545 | 22.794393 | 85 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/JavaParserVisitor.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.DeprecatedUntil700;
import net.sourceforge.pmd.lang.ast.Node;
/**
* Backwards-compatibility only.
*
* @deprecated Use {@link JavaVisitor}
*/
@Deprecated
@DeprecatedUntil700
public interface JavaParserVisitor extends JavaVisitor<Object, Object> {
@Override
default Object visitNode(Node node, Object param) {
for (Node child: node.children()) {
child.acceptVisitor(this, param);
}
return param;
}
// REMOVE ME
// deprecated stuff kept for compatibility with existing visitors, not matched by anything
@Deprecated
default Object visit(ASTExpression node, Object data) {
return null;
}
@Deprecated
default Object visit(ASTLiteral node, Object data) {
return null;
}
@Deprecated
default Object visit(ASTType node, Object data) {
return null;
}
@Deprecated
default Object visit(ASTReferenceType node, Object data) {
return null;
}
default Object visit(ASTStatement node, Object data) {
return null;
}
@Deprecated
default Object visit(ASTPrimaryExpression node, Object data) {
return null;
}
}
| 1,346 | 20.725806 | 94 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/AstDisambiguationPass.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.symbols.table.internal.JavaSemanticErrors.CANNOT_RESOLVE_AMBIGUOUS_NAME;
import java.util.Iterator;
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.ast.NodeStream;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken;
import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.symbols.table.JSymbolTable;
import net.sourceforge.pmd.lang.java.symbols.table.internal.JavaSemanticErrors;
import net.sourceforge.pmd.lang.java.symbols.table.internal.ReferenceCtx;
import net.sourceforge.pmd.lang.java.types.JClassType;
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.ast.LazyTypeResolver;
/**
* This implements name disambiguation following <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls-6.5.2">JLS§6.5.2</a>.
* (see also <a href="https://docs.oracle.com/javase/specs/jls/se13/html/jls-6.html#jls-6.4.2">JLS§6.4.2 - Obscuring</a>)
*/
final class AstDisambiguationPass {
private AstDisambiguationPass() {
// façade
}
/**
* Disambiguate the subtrees rooted at the given nodes. After this:
* <ul>
* <li>All ClassOrInterfaceTypes either see their ambiguous LHS
* promoted to a ClassOrInterfaceType, or demoted to a package
* name (removed from the tree)
* <li>All ClassOrInterfaceTypes have a non-null symbol, even if
* it is unresolved EXCEPT the ones of a qualified constructor call.
* Those references are resolved lazily by {@link LazyTypeResolver},
* because they depend on the full type resolution of the qualifier
* expression, and that resolution may use things that are not yet
* disambiguated
* <li>There may still be AmbiguousNames, but only in expressions,
* for the worst kind of ambiguity
* </ul>
*/
public static void disambigWithCtx(NodeStream<? extends JavaNode> nodes, ReferenceCtx ctx) {
assert ctx != null : "Null context";
nodes.forEach(it -> it.acceptVisitor(DisambigVisitor.INSTANCE, ctx));
}
// those ignore JTypeParameterSymbol, for error handling logic to be uniform
private static void checkParentIsMember(ReferenceCtx ctx, ASTClassOrInterfaceType resolvedType, ASTClassOrInterfaceType parent) {
JTypeDeclSymbol sym = resolvedType.getReferencedSym();
JClassSymbol parentClass = ctx.findTypeMember(sym, parent.getSimpleName(), parent);
if (parentClass == null) {
ctx.reportUnresolvedMember(parent, ReferenceCtx.Fallback.TYPE, parent.getSimpleName(), sym);
int numTypeArgs = ASTList.sizeOrZero(parent.getTypeArguments());
parentClass = ctx.makeUnresolvedReference(sym, parent.getSimpleName(), numTypeArgs);
}
parent.setSymbol(parentClass);
}
private static @Nullable JClassType enclosingType(JTypeMirror typeResult) {
return typeResult instanceof JClassType ? ((JClassType) typeResult).getEnclosingType() : null;
}
private static final class DisambigVisitor extends JavaVisitorBase<ReferenceCtx, Void> {
public static final DisambigVisitor INSTANCE = new DisambigVisitor();
@Override
protected Void visitChildren(Node node, ReferenceCtx data) {
// note that this differs from the default impl, because
// the default declares last = node.getNumChildren()
// at the beginning of the loop, but in this visitor the
// number of children may change.
for (int i = 0; i < node.getNumChildren(); i++) {
node.getChild(i).acceptVisitor(this, data);
}
return null;
}
@Override
public Void visitTypeDecl(ASTAnyTypeDeclaration node, ReferenceCtx data) {
// since type headers are disambiguated early it doesn't matter
// if the context is inaccurate in type headers
return visitChildren(node, data.scopeDownToNested(node.getSymbol()));
}
@Override
public Void visit(ASTAmbiguousName name, ReferenceCtx processor) {
if (name.wasProcessed()) {
// don't redo analysis
return null;
}
JSymbolTable symbolTable = name.getSymbolTable();
assert symbolTable != null : "Symbol tables haven't been set yet??";
boolean isPackageOrTypeOnly;
if (name.getParent() instanceof ASTClassOrInterfaceType) {
isPackageOrTypeOnly = true;
} else if (name.getParent() instanceof ASTExpression) {
isPackageOrTypeOnly = false;
} else {
throw new AssertionError("Unrecognised context for ambiguous name: " + name.getParent());
}
// do resolve
JavaNode resolved = startResolve(name, processor, isPackageOrTypeOnly);
// finish
assert !isPackageOrTypeOnly
|| resolved instanceof ASTTypeExpression
|| resolved instanceof ASTAmbiguousName
: "Unexpected result " + resolved + " for PackageOrTypeName resolution";
if (isPackageOrTypeOnly && resolved instanceof ASTTypeExpression) {
// unambiguous, we just have to check that the parent is a member of the enclosing type
ASTClassOrInterfaceType resolvedType = (ASTClassOrInterfaceType) ((ASTTypeExpression) resolved).getTypeNode();
resolved = resolvedType;
ASTClassOrInterfaceType parent = (ASTClassOrInterfaceType) name.getParent();
checkParentIsMember(processor, resolvedType, parent);
}
if (resolved != name) { // NOPMD - intentional check for reference equality
((AbstractJavaNode) name.getParent()).setChild((AbstractJavaNode) resolved, name.getIndexInParent());
}
return null;
}
@Override
public Void visit(ASTClassOrInterfaceType type, ReferenceCtx ctx) {
if (type.getReferencedSym() != null) {
return null;
}
if (type.getFirstChild() instanceof ASTAmbiguousName) {
type.getFirstChild().acceptVisitor(this, ctx);
}
// revisit children, which may have changed
visitChildren(type, ctx);
if (type.getReferencedSym() != null) {
postProcess(type, ctx);
return null;
}
ASTClassOrInterfaceType lhsType = type.getQualifier();
if (lhsType != null) {
JTypeDeclSymbol lhsSym = lhsType.getReferencedSym();
assert lhsSym != null : "Unresolved LHS for " + type;
checkParentIsMember(ctx, lhsType, type);
} else {
if (type.getParent() instanceof ASTConstructorCall
&& ((ASTConstructorCall) type.getParent()).isQualifiedInstanceCreation()) {
// Leave the reference null, this is handled lazily,
// because the interaction it depends on the type of
// the qualifier
return null;
}
if (type.getReferencedSym() == null) {
setClassSymbolIfNoQualifier(type, ctx);
}
}
assert type.getReferencedSym() != null : "Null symbol for " + type;
postProcess(type, ctx);
return null;
}
private static void setClassSymbolIfNoQualifier(ASTClassOrInterfaceType type, ReferenceCtx ctx) {
final JTypeMirror resolved = ctx.resolveSingleTypeName(type.getSymbolTable(), type.getSimpleName(), type);
JTypeDeclSymbol sym;
if (resolved == null) {
ctx.reportCannotResolveSymbol(type, type.getSimpleName());
sym = setArity(type, ctx, type.getSimpleName());
} else {
sym = resolved.getSymbol();
if (sym.isUnresolved()) {
sym = setArity(type, ctx, ((JClassSymbol) sym).getCanonicalName());
}
}
type.setSymbol(sym);
type.setImplicitEnclosing(enclosingType(resolved));
}
private void postProcess(ASTClassOrInterfaceType type, ReferenceCtx ctx) {
JTypeDeclSymbol sym = type.getReferencedSym();
if (type.getParent() instanceof ASTAnnotation) {
if (!(sym instanceof JClassSymbol && (sym.isUnresolved() || ((JClassSymbol) sym).isAnnotation()))) {
ctx.getLogger().warning(type, JavaSemanticErrors.EXPECTED_ANNOTATION_TYPE);
}
return;
}
int actualArity = ASTList.sizeOrZero(type.getTypeArguments());
int expectedArity = sym instanceof JClassSymbol ? ((JClassSymbol) sym).getTypeParameterCount() : 0;
if (actualArity != 0 && actualArity != expectedArity) {
ctx.getLogger().warning(type, JavaSemanticErrors.MALFORMED_GENERIC_TYPE, expectedArity, actualArity);
}
}
private static @NonNull JTypeDeclSymbol setArity(ASTClassOrInterfaceType type, ReferenceCtx ctx, String canonicalName) {
int arity = ASTList.sizeOrZero(type.getTypeArguments());
return ctx.makeUnresolvedReference(canonicalName, arity);
}
/*
This is implemented as a set of mutually recursive methods
that act as a kind of automaton. State transitions:
+-----+ +--+ +--+
| | | | | |
+-----+ + v + v + v
|START+----> PACKAGE +---> TYPE +----> EXPR
+-----+ ^ ^
| | |
+-------------------------------------+
Not pictured are the error transitions.
Only Type & Expr are valid exit states.
*/
/**
* Resolve an ambiguous name occurring in an expression context.
* Returns the expression to which the name was resolved. If the
* name is a type, this is a {@link ASTTypeExpression}, otherwise
* it could be a {@link ASTFieldAccess} or {@link ASTVariableAccess},
* and in the worst case, the original {@link ASTAmbiguousName}.
*/
private static ASTExpression startResolve(ASTAmbiguousName name, ReferenceCtx ctx, boolean isPackageOrTypeOnly) {
Iterator<JavaccToken> tokens = name.tokens().iterator();
JavaccToken firstIdent = tokens.next();
TokenUtils.expectKind(firstIdent, JavaTokenKinds.IDENTIFIER);
JSymbolTable symTable = name.getSymbolTable();
if (!isPackageOrTypeOnly) {
// first test if the leftmost segment is an expression
JVariableSig varResult = symTable.variables().resolveFirst(firstIdent.getImage());
if (varResult != null) {
return resolveExpr(null, varResult, firstIdent, tokens, ctx);
}
}
// otherwise, test if it is a type name
JTypeMirror typeResult = ctx.resolveSingleTypeName(symTable, firstIdent.getImage(), name);
if (typeResult != null) {
JClassType enclosing = enclosingType(typeResult);
return resolveType(null, enclosing, typeResult.getSymbol(), false, firstIdent, tokens, name, isPackageOrTypeOnly, ctx);
}
// otherwise, first is reclassified as package name.
return resolvePackage(firstIdent, new StringBuilder(firstIdent.getImage()), tokens, name, isPackageOrTypeOnly, ctx);
}
/**
* Classify the given [identifier] as an expression name. This
* produces a FieldAccess/VariableAccess, depending on whether there is a qualifier.
* The remaining token chain is reclassified as a sequence of
* field accesses.
*
* TODO Check the field accesses are legal
* Also must filter by visibility
*/
private static ASTExpression resolveExpr(@Nullable ASTExpression qualifier, // lhs
@Nullable JVariableSig varSym, // signature, only set if this is the leftmost access
JavaccToken identifier, // identifier for the field/var name
Iterator<JavaccToken> remaining, // rest of tokens, starting with following '.'
ReferenceCtx ctx) {
TokenUtils.expectKind(identifier, JavaTokenKinds.IDENTIFIER);
ASTNamedReferenceExpr var;
if (qualifier == null) {
ASTVariableAccess varAccess = new ASTVariableAccess(identifier);
varAccess.setTypedSym(varSym);
var = varAccess;
} else {
ASTFieldAccess fieldAccess = new ASTFieldAccess(qualifier, identifier);
fieldAccess.setTypedSym((FieldSig) varSym);
var = fieldAccess;
}
if (!remaining.hasNext()) { // done
return var;
}
JavaccToken nextIdent = skipToNextIdent(remaining);
// following must also be expressions (field accesses)
// we can't assert that for now, as symbols lack type information
return resolveExpr(var, null, nextIdent, remaining, ctx);
}
/**
* Classify the given [identifier] as a reference to the [sym].
* This produces a ClassOrInterfaceType with the given [image] (which
* may be prepended by a package name, or otherwise is just a simple name).
* We then lookup the following identifier, and take a decision:
* <ul>
* <li>If there is a field with the given name in [classSym],
* then the remaining tokens are reclassified as expression names
* <li>Otherwise, if there is a member type with the given name
* in [classSym], then the remaining segment is classified as a
* type name (recursive call to this procedure)
* <li>Otherwise, normally a compile-time error occurs. We instead
* log a warning and treat it as a field access.
* </ul>
*
* @param isPackageOrTypeOnly If true, expressions are disallowed by the context, so we don't check fields
*/
private static ASTExpression resolveType(final @Nullable ASTClassOrInterfaceType qualifier, // lhs
final @Nullable JClassType implicitEnclosing, // enclosing type, if it is implicitly inherited
final JTypeDeclSymbol sym, // symbol for the type
final boolean isFqcn, // whether this is a fully-qualified name
final JavaccToken identifier, // ident of the simple name of the symbol
final Iterator<JavaccToken> remaining, // rest of tokens, starting with following '.'
final ASTAmbiguousName ambig, // original ambiguous name
final boolean isPackageOrTypeOnly,
final ReferenceCtx ctx) {
TokenUtils.expectKind(identifier, JavaTokenKinds.IDENTIFIER);
final ASTClassOrInterfaceType type = new ASTClassOrInterfaceType(qualifier, isFqcn, ambig.getFirstToken(), identifier);
type.setSymbol(sym);
type.setImplicitEnclosing(implicitEnclosing);
if (!remaining.hasNext()) { // done
return new ASTTypeExpression(type);
}
final JavaccToken nextIdent = skipToNextIdent(remaining);
final String nextSimpleName = nextIdent.getImage();
if (!isPackageOrTypeOnly) {
@Nullable FieldSig field = ctx.findStaticField(sym, nextSimpleName);
if (field != null) {
// todo check field is static
ASTTypeExpression typeExpr = new ASTTypeExpression(type);
return resolveExpr(typeExpr, field, nextIdent, remaining, ctx);
}
}
JClassSymbol inner = ctx.findTypeMember(sym, nextSimpleName, ambig);
if (inner == null && isPackageOrTypeOnly) {
// normally compile-time error, continue by considering it an unresolved inner type
ctx.reportUnresolvedMember(ambig, ReferenceCtx.Fallback.TYPE, nextSimpleName, sym);
inner = ctx.makeUnresolvedReference(sym, nextSimpleName, 0);
}
if (inner != null) {
return resolveType(type, null, inner, false, nextIdent, remaining, ambig, isPackageOrTypeOnly, ctx);
}
// no inner type, yet we have a lhs that is a type...
// this is normally a compile-time error
// treat as unresolved field accesses, this is the smoothest for later type res
// todo report on the specific token failing
ctx.reportUnresolvedMember(ambig, ReferenceCtx.Fallback.FIELD_ACCESS, nextSimpleName, sym);
ASTTypeExpression typeExpr = new ASTTypeExpression(type);
return resolveExpr(typeExpr, null, nextIdent, remaining, ctx); // this will chain for the rest of the name
}
/**
* Classify the given [identifier] as a package name. This means, that
* we look ahead into the [remaining] tokens, and try to find a class
* by that name in the given package. Then:
* <ul>
* <li>If such a class exists, continue the classification with resolveType
* <li>Otherwise, the looked ahead segment is itself reclassified as a package name
* </ul>
*
* <p>If we consumed the entire name without finding a suitable
* class, then we report it and return the original ambiguous name.
*/
private static ASTExpression resolvePackage(JavaccToken identifier,
StringBuilder packageImage,
Iterator<JavaccToken> remaining,
ASTAmbiguousName ambig,
boolean isPackageOrTypeOnly,
ReferenceCtx ctx) {
TokenUtils.expectKind(identifier, JavaTokenKinds.IDENTIFIER);
if (!remaining.hasNext()) {
if (isPackageOrTypeOnly) {
// There's one last segment to try, the parent of the ambiguous name
// This may only be because this ambiguous name is the package qualification of the parent type
forceResolveAsFullPackageNameOfParent(packageImage, ambig, ctx);
return ambig; // returning ambig makes the outer routine not replace
}
// then this name is unresolved, leave the ambiguous name in the tree
// this only happens inside expressions
ctx.getLogger().warning(ambig, CANNOT_RESOLVE_AMBIGUOUS_NAME, packageImage, ReferenceCtx.Fallback.AMBIGUOUS);
ambig.setProcessed(); // signal that we don't want to retry resolving this
return ambig;
}
JavaccToken nextIdent = skipToNextIdent(remaining);
packageImage.append('.').append(nextIdent.getImage());
String canonical = packageImage.toString();
// Don't interpret periods as nested class separators (this will be handled by resolveType).
// Otherwise lookup of a fully qualified name would be quadratic
JClassSymbol nextClass = ctx.resolveClassFromBinaryName(canonical);
if (nextClass != null) {
return resolveType(null, null, nextClass, true, nextIdent, remaining, ambig, isPackageOrTypeOnly, ctx);
} else {
return resolvePackage(nextIdent, packageImage, remaining, ambig, isPackageOrTypeOnly, ctx);
}
}
/**
* Force resolution of the ambiguous name as a package name.
* The parent type's image is set to a package name + simple name.
*/
private static void forceResolveAsFullPackageNameOfParent(StringBuilder packageImage, ASTAmbiguousName ambig, ReferenceCtx ctx) {
ASTClassOrInterfaceType parent = (ASTClassOrInterfaceType) ambig.getParent();
packageImage.append('.').append(parent.getSimpleName());
String fullName = packageImage.toString();
JClassSymbol parentClass = ctx.resolveClassFromBinaryName(fullName);
if (parentClass == null) {
ctx.getLogger().warning(parent, CANNOT_RESOLVE_AMBIGUOUS_NAME, fullName, ReferenceCtx.Fallback.TYPE);
parentClass = ctx.makeUnresolvedReference(fullName, ASTList.sizeOrZero(parent.getTypeArguments()));
}
parent.setSymbol(parentClass);
parent.setFullyQualified();
ambig.deleteInParent();
}
private static JavaccToken skipToNextIdent(Iterator<JavaccToken> remaining) {
JavaccToken dot = remaining.next();
TokenUtils.expectKind(dot, JavaTokenKinds.DOT);
assert remaining.hasNext() : "Ambiguous name must end with an identifier";
return remaining.next();
}
}
}
| 22,624 | 46.431866 | 148 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTSwitchLabel.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 either a {@code case} or {@code default} label inside
* a {@linkplain ASTSwitchStatement switch statement} or {@linkplain ASTSwitchExpression expression}.
* Since Java 14, labels may have several expressions.
*
* <pre class="grammar">
*
* SwitchLabel ::= "case" {@linkplain ASTExpression Expression} ("," {@linkplain ASTExpression Expression} )*
* | "case" "null [ "," "default" ]
* | "case" ( {@linkplain ASTTypePattern TypePattern} | {@linkplain ASTRecordPattern RecordPattern} )
* | "default"
*
* </pre>
*
* <p>Note: case null and the case patterns are a Java 19 Preview and Java 20 Preview language feature</p>
*
* @see <a href="https://openjdk.org/jeps/433">JEP 433: Pattern Matching for switch (Fourth Preview)</a>
* @see <a href="https://openjdk.org/jeps/432">JEP 432: Record Patterns (Second Preview)</a>
*/
public final class ASTSwitchLabel extends AbstractJavaNode implements Iterable<ASTExpression> {
private boolean isDefault;
ASTSwitchLabel(int id) {
super(id);
}
void setDefault() {
isDefault = true;
}
/** Returns true if this is the {@code default} label. */
// todo `case default`
public boolean isDefault() {
return isDefault;
}
/**
* Returns the expressions of this label, or an empty list if this
* is the default label. This may contain {@linkplain ASTPatternExpression pattern expressions}
* to represent patterns.
*/
public NodeStream<ASTExpression> getExprList() {
return children(ASTExpression.class);
}
@Override
protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
@Override
public Iterator<ASTExpression> iterator() {
return children(ASTExpression.class).iterator();
}
}
| 2,112 | 29.185714 | 116 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTBreakStatement.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.Function;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.ast.NodeStream;
/**
* A break statement, that jumps to a named label (or exits the current loop).
*
* <pre class="grammar">
*
* BreakStatement ::= "break" <IDENTIFIER>? ";"
*
* </pre>
*/
public final class ASTBreakStatement extends AbstractStatement {
private static final Function<Object, ASTStatement> BREAK_TARGET_MAPPER =
NodeStream.asInstanceOf(ASTLoopStatement.class, ASTSwitchStatement.class);
ASTBreakStatement(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 label, or null if there is none.
*/
public @Nullable String getLabel() {
return getImage();
}
/**
* Returns the statement that is the target of this break. This may be
* a loop, or a switch statement, or a labeled statement. This may
* return null if the code is invalid.
*/
public ASTStatement getTarget() {
String myLabel = this.getLabel();
if (myLabel == null) {
return ancestors().map(BREAK_TARGET_MAPPER).first();
}
return ancestors(ASTLabeledStatement.class)
.filter(it -> it.getLabel().equals(myLabel))
.first();
}
}
| 1,581 | 25.366667 | 91 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTNumericLiteral.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import java.math.BigInteger;
import java.util.Locale;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.java.types.JPrimitiveType;
/**
* A numeric literal of any type (double, int, long, float, etc).
*/
public final class ASTNumericLiteral extends AbstractLiteral implements ASTLiteral {
/**
* True if this is an integral literal, ie int OR long,
* false if this is a floating-point literal, ie float OR double.
*/
private boolean isIntegral;
ASTNumericLiteral(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 @NonNull Number getConstValue() {
// don't use ternaries, the compiler messes up autoboxing.
if (isIntegral()) {
if (isIntLiteral()) {
return getValueAsInt();
}
return getValueAsLong();
} else {
if (isFloatLiteral()) {
return getValueAsFloat();
}
return getValueAsDouble();
}
}
@Override
public @NonNull JPrimitiveType getTypeMirror() {
return (JPrimitiveType) super.getTypeMirror();
}
void setIntLiteral() {
this.isIntegral = true;
}
void setFloatLiteral() {
this.isIntegral = false;
}
@Override
public boolean isIntLiteral() {
return isIntegral && !isLongLiteral();
}
// TODO all of this can be done once in jjtCloseNodeScope
@Override
public boolean isLongLiteral() {
if (isIntegral) {
String image = getImage();
char lastChar = image.charAt(image.length() - 1);
return lastChar == 'l' || lastChar == 'L';
}
return false;
}
@Override
public boolean isFloatLiteral() {
if (!isIntegral) {
String image = getImage();
char lastChar = image.charAt(image.length() - 1);
return lastChar == 'f' || lastChar == 'F';
}
return false;
}
@Override
public boolean isDoubleLiteral() {
return !isIntegral && !isFloatLiteral();
}
private String stripIntValue() {
String image = getImage().toLowerCase(Locale.ROOT).replaceAll("_++", "");
// literals never have a sign.
char last = image.charAt(image.length() - 1);
// This method is only called if this is an int,
// in which case the 'd' and 'f' suffixes can only
// be hex digits, which we must not remove
if (last == 'l') {
image = image.substring(0, image.length() - 1);
}
// ignore base prefix if any
if (image.charAt(0) == '0' && image.length() > 1) {
if (image.charAt(1) == 'x' || image.charAt(1) == 'b') {
image = image.substring(2);
} else {
image = image.substring(1);
}
}
return image;
}
private String stripFloatValue() {
// This method is only called if this is a floating point literal.
// there can't be any 'l' suffix that the double parser doesn't support,
// so it's enough to just remove underscores
return getImage().replaceAll("_++", "");
}
/**
* Returns true if this is an integral literal, ie either a long or
* an integer literal. Otherwise, this is a floating point literal.
*/
public boolean isIntegral() {
return isIntegral;
}
/**
* Returns the base of the literal, eg 8 for an octal literal,
* 10 for a decimal literal, etc. By convention this returns 10
* for the literal {@code 0} (which can really be any base).
*/
public int getBase() {
final String image = getImage();
if (image.length() > 1 && image.charAt(0) == '0') {
switch (image.charAt(1)) {
case 'x':
case 'X':
return 16;
case 'b':
case 'B':
return 2;
case '.':
return 10;
default:
return 8;
}
}
return 10;
}
// From 7.0.x, these methods always return a meaningful number, the
// closest we can find.
// In 6.0.x, eg getValueAsInt was giving up when this was a double.
public int getValueAsInt() {
if (isIntegral) {
// the downcast allows to parse 0x80000000+ numbers as negative instead of a NumberFormatException
return (int) getValueAsLong();
} else {
return (int) getValueAsDouble();
}
}
public long getValueAsLong() {
if (isIntegral) {
// Using BigInteger to allow parsing 0x8000000000000000+ numbers as negative instead of a NumberFormatException
BigInteger bigInt = new BigInteger(stripIntValue(), getBase());
return bigInt.longValue();
} else {
return (long) getValueAsDouble();
}
}
public float getValueAsFloat() {
return isIntegral ? (float) getValueAsLong() : (float) getValueAsDouble();
}
public double getValueAsDouble() {
return isIntegral ? (double) getValueAsLong() : Double.parseDouble(stripFloatValue());
}
}
| 5,525 | 26.356436 | 123 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTMemberValue.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 the value of a member of an annotation.
* This can appear in a {@linkplain ASTMemberValuePair member-value pair},
* or in the {@linkplain ASTDefaultValue default clause} of an annotation
* method.
*
* <pre class="grammar">
*
* MemberValue ::= {@link ASTAnnotation Annotation}
* | {@link ASTMemberValueArrayInitializer MemberValueArrayInitializer}
* | {@link ASTExpression < any constant expression >}
*
* </pre>
*/
public interface ASTMemberValue extends JavaNode {
/**
* Returns the constant value of this node, if this is a constant
* expression. Otherwise, or if some references couldn't be resolved,
* returns null. Note that {@link ASTNullLiteral null} is not a constant
* value, so this method's returning null is not a problem. Note that
* annotations are not given a constant value by this implementation.
*/
default @Nullable Object getConstValue() {
return null;
}
}
| 1,186 | 31.972222 | 85 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTPattern.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 pattern (for pattern matching constructs like {@link ASTInfixExpression InstanceOfExpression}
* or within a {@link ASTSwitchLabel}). This is a JDK 16 feature.
*
* <p>This interface is implemented by all forms of patterns.
*
* <pre class="grammar">
*
* Pattern ::= {@linkplain ASTTypePattern TypePattern} | {@linkplain ASTRecordPattern RecordPattern}
*
* </pre>
*
* @see <a href="https://openjdk.org/jeps/394">JEP 394: Pattern Matching for instanceof</a>
* @see <a href="https://openjdk.org/jeps/405">JEP 405: Record Patterns (Preview)</a> (Java 19)
* @see <a href="https://openjdk.org/jeps/432">JEP 432: Record Patterns (Second Preview)</a> (Java 20)
*/
public interface ASTPattern extends JavaNode {
/**
* Returns the number of parenthesis levels around this pattern.
* If this method returns 0, then no parentheses are present.
*/
@Experimental
int getParenthesisDepth();
}
| 1,115 | 31.823529 | 102 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTComponentPatternList.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;
/**
* Contains a potentially empty list of nested Patterns for {@linkplain ASTRecordPattern RecordPattern}
* (Java 19 Preview and Java 20 Preview).
*
* <pre class="grammar">
*
* ComponentPatternList ::= "(" {@linkplain ASTPattern Pattern} ( "," {@linkplain ASTPattern pattern} ) ")"
*
* </pre>
*
* @see <a href="https://openjdk.org/jeps/432">JEP 432: Record Patterns (Second Preview)</a>
*/
@Experimental
public final class ASTComponentPatternList extends ASTList<ASTPattern> {
ASTComponentPatternList(int id) {
super(id, ASTPattern.class);
}
@Override
protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 913 | 26.69697 | 107 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/JavaTokenDocumentBehavior.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.JavaTokenKinds.GT;
import static net.sourceforge.pmd.lang.java.ast.JavaTokenKinds.RSIGNEDSHIFT;
import static net.sourceforge.pmd.lang.java.ast.JavaTokenKinds.RUNSIGNEDSHIFT;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.ast.impl.javacc.CharStream;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaEscapeTranslator;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccTokenDocument;
import net.sourceforge.pmd.lang.ast.impl.javacc.MalformedSourceException;
import net.sourceforge.pmd.lang.document.TextDocument;
/**
* {@link JavaccTokenDocument} for Java.
*/
final class JavaTokenDocumentBehavior extends JavaccTokenDocument.TokenDocumentBehavior {
static final JavaTokenDocumentBehavior INSTANCE = new JavaTokenDocumentBehavior();
private JavaTokenDocumentBehavior() {
super(JavaTokenKinds.TOKEN_NAMES);
}
@Override
public TextDocument translate(TextDocument text) throws MalformedSourceException {
return new JavaEscapeTranslator(text).translateDocument();
}
@Override
public JavaccToken createToken(JavaccTokenDocument self, int kind, CharStream jcs, @Nullable String image) {
switch (kind) {
case RUNSIGNEDSHIFT:
case RSIGNEDSHIFT:
case GT:
return new GTToken(
GT,
kind,
">",
jcs.getStartOffset(),
jcs.getEndOffset(),
jcs.getTokenDocument()
);
default:
return super.createToken(self, kind, jcs, image);
}
}
static int getRealKind(JavaccToken token) {
return token instanceof GTToken ? ((GTToken) token).realKind : token.kind;
}
private static final class GTToken extends JavaccToken {
final int realKind;
GTToken(int kind, int realKind, String image, int startOffset, int endOffset, JavaccTokenDocument doc) {
super(kind, image, startOffset, endOffset, doc);
this.realKind = realKind;
}
}
}
| 2,308 | 30.630137 | 112 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTYieldStatement.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 {@code yield} statement in a {@linkplain ASTSwitchExpression switch expression}.
*
* <pre class="grammar">
*
* YieldStatement ::= "yield" {@link ASTExpression} ";"
*
* </pre>
*/
public class ASTYieldStatement extends AbstractStatement {
ASTYieldStatement(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 yielded expression. */
public ASTExpression getExpr() {
return (ASTExpression) getChild(0);
}
/**
* Returns the switch expression to which this statement yields a
* value.
*/
@NonNull
public ASTSwitchExpression getYieldTarget() {
return Objects.requireNonNull(ancestors(ASTSwitchExpression.class).first(),
"Yield statements should only be parsable inside switch expressions");
}
}
| 1,188 | 21.865385 | 108 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTFinallyClause.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
/**
* The "finally" clause of a {@linkplain ASTTryStatement try statement}.
*
*
* <pre class="grammar">
*
* FinallyClause ::= "finally" {@link ASTBlock Block}
*
* </pre>
*/
public final class ASTFinallyClause extends AbstractJavaNode {
ASTFinallyClause(int id) {
super(id);
}
@Override
public <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
/**
* Returns the body of this finally clause.
*/
public ASTBlock getBody() {
return (ASTBlock) getChild(0);
}
}
| 733 | 18.837838 | 88 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTBodyDeclaration.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
/**
* Marker interface for declarations that can occur in a {@linkplain ASTTypeBody type body},
* such as field or method declarations. Some of those can also appear on the
* {@linkplain ASTTopLevelDeclaration top-level} of a file.
*
* <pre class="grammar">
*
* BodyDeclaration ::= {@link ASTAnyTypeDeclaration AnyTypeDeclaration}
* | {@link ASTMethodDeclaration MethodDeclaration}
* | {@link ASTConstructorDeclaration ConstructorDeclaration}
* | {@link ASTCompactConstructorDeclaration CompactConstructorDeclaration}
* | {@link ASTInitializer Initializer}
* | {@link ASTFieldDeclaration FieldDeclaration}
* | {@link ASTEnumConstant EnumConstant}
* | {@link ASTEmptyDeclaration EmptyDeclaration}
*
* </pre>
*
*/
public interface ASTBodyDeclaration extends JavaNode {
}
| 1,048 | 33.966667 | 93 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTTypeParameters.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;
/**
* Represents a list of type parameters.
*
* <pre class="grammar">
*
* TypeParameters ::= "<" {@linkplain ASTTypeParameter TypeParameter} ( "," {@linkplain ASTTypeParameter TypeParameter} )* ">"
*
* </pre>
*/
public final class ASTTypeParameters extends ASTNonEmptyList<ASTTypeParameter> {
ASTTypeParameters(int id) {
super(id, ASTTypeParameter.class);
}
@Override
protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 750 | 21.757576 | 132 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/AbstractMethodOrConstructorDeclaration.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.JExecutableSymbol;
import net.sourceforge.pmd.lang.java.types.JMethodSig;
abstract class AbstractMethodOrConstructorDeclaration<T extends JExecutableSymbol>
extends AbstractJavaNode
implements ASTMethodOrConstructorDeclaration,
LeftRecursiveNode {
private T symbol;
private JMethodSig sig;
AbstractMethodOrConstructorDeclaration(int i) {
super(i);
}
void setSymbol(T symbol) {
AbstractTypedSymbolDeclarator.assertSymbolNull(this.symbol, this);
this.symbol = symbol;
}
@Override
public T getSymbol() {
AbstractTypedSymbolDeclarator.assertSymbolNotNull(symbol, this);
return symbol;
}
@Override
public JMethodSig getGenericSignature() {
if (sig == null) {
sig = getTypeSystem().sigOf(getSymbol());
}
return sig;
}
}
| 1,047 | 23.372093 | 82 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTReturnStatement.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 return statement in a method or constructor body.
*
*
* <pre class="grammar">
*
* ReturnStatement ::= "return" {@link ASTExpression Expression}? ";"
*
* </pre>
*/
public final class ASTReturnStatement extends AbstractStatement {
ASTReturnStatement(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 returned expression, or null if this is a simple return.
*/
@Nullable
public ASTExpression getExpr() {
return AstImplUtil.getChildAs(this, 0, ASTExpression.class);
}
}
| 876 | 21.487179 | 91 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTArrayDimExpr.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 initialized with an expression in an
* {@linkplain ASTArrayAllocation array allocation expression}. This
* is always a child of {@link ASTArrayDimensions ArrayDimensions}.
*
* TODO not sure we need a separate node type here?
*
* <pre class="grammar">
*
* ArrayDimExpr ::= {@link ASTAnnotation TypeAnnotation}* "[" {@link ASTExpression Expression} "]"
*
* </pre>
*/
public final class ASTArrayDimExpr extends ASTArrayTypeDim implements Annotatable {
ASTArrayDimExpr(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 getLengthExpression() {
return (ASTExpression) getChild(getNumChildren() - 1);
}
}
| 964 | 25.081081 | 98 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.