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/rule/internal/TestFrameworksUtil.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.internal;
import static net.sourceforge.pmd.util.CollectionUtil.setOf;
import java.util.Set;
import net.sourceforge.pmd.lang.java.ast.ASTAnnotation;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTMethodCall;
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
import net.sourceforge.pmd.lang.java.ast.AccessNode.Visibility;
import net.sourceforge.pmd.lang.java.ast.JModifier;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.TypeTestUtil;
/**
* Utilities for rules related to test frameworks (Junit, TestNG, etc).
*/
public final class TestFrameworksUtil {
private static final String JUNIT3_CLASS_NAME = "junit.framework.TestCase";
private static final String JUNIT4_TEST_ANNOT = "org.junit.Test";
private static final String TESTNG_TEST_ANNOT = "org.testng.annotations.Test";
private static final Set<String> JUNIT5_ALL_TEST_ANNOTS =
setOf("org.junit.jupiter.api.Test",
"org.junit.jupiter.api.RepeatedTest",
"org.junit.jupiter.api.TestFactory",
"org.junit.jupiter.api.TestTemplate",
"org.junit.jupiter.params.ParameterizedTest"
);
private static final String JUNIT5_NESTED = "org.junit.jupiter.api.Nested";
private static final Set<String> ASSERT_CONTAINERS = setOf("org.junit.Assert",
"org.junit.jupiter.api.Assertions",
"org.hamcrest.MatcherAssert",
"org.testng.Assert",
"junit.framework.Assert",
"junit.framework.TestCase");
private static final Set<String> TEST_CONFIGURATION_ANNOTATIONS =
setOf("org.junit.Before",
"org.junit.BeforeClass",
"org.junit.After",
"org.junit.AfterClass",
"org.testng.annotations.AfterClass",
"org.testng.annotations.AfterGroups",
"org.testng.annotations.AfterMethod",
"org.testng.annotations.AfterSuite",
"org.testng.annotations.AfterTest",
"org.testng.annotations.BeforeClass",
"org.testng.annotations.BeforeGroups",
"org.testng.annotations.BeforeMethod",
"org.testng.annotations.BeforeSuite",
"org.testng.annotations.BeforeTest"
);
private TestFrameworksUtil() {
// utility class
}
/**
* True if this is a junit @Test method (or a junit 3 method).
*/
public static boolean isJUnitMethod(ASTMethodDeclaration method) {
if (method.hasModifiers(JModifier.STATIC) || method.getBody() == null) {
return false; // skip various inapplicable method variations
}
boolean result = isJUnit5Method(method);
result = result || isJUnit4Method(method);
result = result || isJUnit3Method(method);
return result;
}
/**
* Returns true if this is either a JUnit test or a TestNG test.
*/
public static boolean isTestMethod(ASTMethodDeclaration method) {
return isJUnitMethod(method) || isTestNgMethod(method);
}
/**
* Returns true if this is a Before/setUp method or After/tearDown.
*/
public static boolean isTestConfigurationMethod(ASTMethodDeclaration method) {
return TEST_CONFIGURATION_ANNOTATIONS.stream().anyMatch(method::isAnnotationPresent)
|| isJUnit3Class(method.getEnclosingType())
&& ("setUp".equals(method.getName())
|| "tearDown".equals(method.getName()));
}
private static boolean isTestNgMethod(ASTMethodDeclaration method) {
return method.isAnnotationPresent(TESTNG_TEST_ANNOT);
}
public static boolean isJUnit4Method(ASTMethodDeclaration method) {
return method.isAnnotationPresent(JUNIT4_TEST_ANNOT)
&& method.getVisibility() == Visibility.V_PUBLIC;
}
public static boolean isJUnit5Method(ASTMethodDeclaration method) {
return method.getDeclaredAnnotations().any(
it -> {
String canonicalName = it.getTypeMirror().getSymbol().getCanonicalName();
return JUNIT5_ALL_TEST_ANNOTS.contains(canonicalName);
}
);
}
public static boolean isJUnit3Method(ASTMethodDeclaration method) {
return isJUnit3Class(method.getEnclosingType())
&& isJunit3MethodSignature(method);
}
public static boolean isJunit4TestAnnotation(ASTAnnotation annot) {
return TypeTestUtil.isA(JUNIT4_TEST_ANNOT, annot);
}
/**
* Does not check the class (use {@link #isJUnit3Class(ASTAnyTypeDeclaration)}).
*/
public static boolean isJunit3MethodSignature(ASTMethodDeclaration method) {
return method.isVoid()
&& method.getVisibility() == Visibility.V_PUBLIC
&& method.getName().startsWith("test");
}
/**
* True if this is a {@code TestCase} class for Junit 3.
*/
public static boolean isJUnit3Class(ASTAnyTypeDeclaration node) {
return node.isRegularClass()
&& !node.isNested()
&& !node.isAbstract()
&& TypeTestUtil.isA(JUNIT3_CLASS_NAME, node);
}
public static boolean isTestClass(ASTAnyTypeDeclaration node) {
return node.isRegularClass() && !node.isAbstract() && !node.isNested()
&& (isJUnit3Class(node)
|| node.getDeclarations(ASTMethodDeclaration.class)
.any(TestFrameworksUtil::isTestMethod));
}
public static boolean isJUnit5NestedClass(ASTAnyTypeDeclaration innerClassDecl) {
return innerClassDecl.isAnnotationPresent(JUNIT5_NESTED);
}
public static boolean isExpectExceptionCall(ASTMethodCall call) {
return "expect".equals(call.getMethodName())
&& TypeTestUtil.isA("org.junit.rules.ExpectedException", call.getQualifier());
}
public static boolean isCallOnAssertionContainer(ASTMethodCall call) {
JTypeMirror declaring = call.getMethodType().getDeclaringType();
JTypeDeclSymbol sym = declaring.getSymbol();
return sym instanceof JClassSymbol
&& (ASSERT_CONTAINERS.contains(((JClassSymbol) sym).getBinaryName())
|| TypeTestUtil.isA("junit.framework.Assert", declaring));
}
public static boolean isProbableAssertCall(ASTMethodCall call) {
String name = call.getMethodName();
return name.startsWith("assert") && !isSoftAssert(call)
|| name.startsWith("check")
|| name.startsWith("verify")
|| "fail".equals(name)
|| "failWith".equals(name)
|| isExpectExceptionCall(call);
}
private static boolean isSoftAssert(ASTMethodCall call) {
return TypeTestUtil.isA("org.assertj.core.api.AbstractSoftAssertions", call.getMethodType().getDeclaringType())
&& !"assertAll".equals(call.getMethodName());
}
/**
* Tells if the node contains a @Test annotation with an expected exception.
*/
public static boolean isExpectAnnotated(ASTMethodDeclaration method) {
return method.getDeclaredAnnotations()
.filter(TestFrameworksUtil::isJunit4TestAnnotation)
.flatMap(ASTAnnotation::getMembers)
.any(it -> "expected".equals(it.getName()));
}
}
| 7,971 | 39.262626 | 119 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/internal/TypeResTestRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.internal;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.ast.TypeNode;
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
import net.sourceforge.pmd.util.StringUtil;
/**
* This is just a toy rule that counts the proportion of resolved types
* in a codebase, not meant as a real rule.
*/
@SuppressWarnings("PMD")
public class TypeResTestRule extends AbstractJavaRule {
private static class State {
public int fileId = 0;
public long numResolved = 0;
public long numerrors = 0;
public long numUnresolved = 0;
void print() {
System.out.println();
System.out.println(fileId);
System.out.println("Resolved: " + numResolved + ", unresolved " + numUnresolved);
double rate = numResolved / (double) (numUnresolved + numResolved);
System.out.println("Resolved " + Math.floor(1000000 * rate) / 10000 + "%");
System.out.println("Errors\t" + numerrors);
}
int absorb(State other) {
fileId += other.fileId;
numResolved += other.numResolved;
numUnresolved += other.numUnresolved;
numerrors += other.numerrors;
return fileId;
}
}
private static final State STATIC = new State();
private State state = new State();
private static final boolean PRINT_ALL_UNRESOLVED;
static {
PRINT_ALL_UNRESOLVED = Boolean.parseBoolean(System.getProperties().getOrDefault("PRINT_ALL_UNRESOLVED", "true").toString());
}
@Override
public Object visit(ASTCompilationUnit node, Object data) {
for (JavaNode descendant : node.descendants().crossFindBoundaries()) {
visitJavaNode(descendant, data);
}
return data;
}
@Override
public Object visitJavaNode(JavaNode node, Object data) {
if (node instanceof TypeNode) {
try {
JTypeMirror t = ((TypeNode) node).getTypeMirror();
TypeSystem ts = t.getTypeSystem();
if (t == ts.ERROR || t == ts.UNKNOWN) {
if (PRINT_ALL_UNRESOLVED) {
System.err.println("Unresolved at " + position(node) + "\t"
+ StringUtil.escapeJava(StringUtils.truncate(node.toString(), 100)));
}
state.numUnresolved++;
} else {
state.numResolved++;
}
} catch (Throwable e) {
System.err.println(position(node));
e.printStackTrace();
state.numerrors++;
if (e instanceof Error) {
// throw e;
}
}
}
return data;
}
public @NonNull String position(JavaNode node) {
return "In: " + node.getReportLocation().startPosToStringWithFile();
}
@Override
public void end(RuleContext ctx) {
super.end(ctx);
state.fileId++;
if (state.fileId % 200 == 0) {
int fid;
synchronized (STATIC) {
fid = STATIC.absorb(state);
}
state = new State();
if (fid % 400 == 0) {
synchronized (STATIC) {
if (STATIC.fileId % 400 == 0) {
STATIC.print();
}
}
}
}
}
}
| 3,951 | 29.875 | 132 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/internal/AbstractJavaCounterCheckRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.internal;
import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.metrics.JavaMetrics;
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule;
import net.sourceforge.pmd.lang.metrics.MetricOptions;
import net.sourceforge.pmd.lang.rule.internal.CommonPropertyDescriptors;
import net.sourceforge.pmd.properties.PropertyDescriptor;
/**
* Abstract class for rules counting the length of some node.
*
* @author Clément Fournier
* @since 7.0.0
*/
public abstract class AbstractJavaCounterCheckRule<T extends JavaNode> extends AbstractJavaRulechainRule {
private final PropertyDescriptor<Integer> reportLevel =
CommonPropertyDescriptors.reportLevelProperty()
.desc("Threshold above which a node is reported")
.require(positive())
.defaultValue(defaultReportLevel()).build();
public AbstractJavaCounterCheckRule(Class<T> nodeType) {
super(nodeType);
definePropertyDescriptor(reportLevel);
}
protected abstract int defaultReportLevel();
/** Return true if the node should be ignored. */
protected boolean isIgnored(T node) {
return false;
}
protected abstract boolean isViolation(T node, int reportLevel);
@Override
public Object visitJavaNode(JavaNode node, Object data) {
@SuppressWarnings("unchecked")
T t = (T) node;
// since we only visit this node, it's ok
if (!isIgnored(t)) {
if (isViolation(t, getProperty(reportLevel))) {
addViolation(data, node);
}
}
return data;
}
public abstract static class AbstractLineLengthCheckRule<T extends JavaNode> extends AbstractJavaCounterCheckRule<T> {
public AbstractLineLengthCheckRule(Class<T> nodeType) {
super(nodeType);
}
@Override
protected final boolean isViolation(T node, int reportLevel) {
return JavaMetrics.LINES_OF_CODE.computeFor(node, MetricOptions.emptyOptions()) > reportLevel;
}
}
}
| 2,360 | 28.886076 | 122 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/internal/DataflowPass.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.internal;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
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.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr;
import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.AccessType;
import net.sourceforge.pmd.lang.java.ast.ASTAssignmentExpression;
import net.sourceforge.pmd.lang.java.ast.ASTBlock;
import net.sourceforge.pmd.lang.java.ast.ASTBodyDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTBreakStatement;
import net.sourceforge.pmd.lang.java.ast.ASTCatchClause;
import net.sourceforge.pmd.lang.java.ast.ASTCatchParameter;
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.ASTConstructorDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTContinueStatement;
import net.sourceforge.pmd.lang.java.ast.ASTDoStatement;
import net.sourceforge.pmd.lang.java.ast.ASTEnumConstant;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTFieldAccess;
import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTFinallyClause;
import net.sourceforge.pmd.lang.java.ast.ASTForInit;
import net.sourceforge.pmd.lang.java.ast.ASTForStatement;
import net.sourceforge.pmd.lang.java.ast.ASTForUpdate;
import net.sourceforge.pmd.lang.java.ast.ASTForeachStatement;
import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter;
import net.sourceforge.pmd.lang.java.ast.ASTIfStatement;
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.ASTLocalVariableDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTLoopStatement;
import net.sourceforge.pmd.lang.java.ast.ASTMethodCall;
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTResourceList;
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.ASTSwitchBranch;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchExpression;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchFallthroughBranch;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchLike;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchStatement;
import net.sourceforge.pmd.lang.java.ast.ASTThisExpression;
import net.sourceforge.pmd.lang.java.ast.ASTThrowStatement;
import net.sourceforge.pmd.lang.java.ast.ASTTryStatement;
import net.sourceforge.pmd.lang.java.ast.ASTUnaryExpression;
import net.sourceforge.pmd.lang.java.ast.ASTVariableAccess;
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.ASTYieldStatement;
import net.sourceforge.pmd.lang.java.ast.BinaryOp;
import net.sourceforge.pmd.lang.java.ast.InvocationNode;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.ast.JavaVisitorBase;
import net.sourceforge.pmd.lang.java.ast.QualifiableExpression;
import net.sourceforge.pmd.lang.java.ast.TypeNode;
import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils;
import net.sourceforge.pmd.lang.java.rule.bestpractices.UnusedAssignmentRule;
import net.sourceforge.pmd.lang.java.rule.design.SingularFieldRule;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol;
import net.sourceforge.pmd.lang.java.symbols.JLocalVariableSymbol;
import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.util.CollectionUtil;
import net.sourceforge.pmd.util.DataMap;
import net.sourceforge.pmd.util.DataMap.SimpleDataKey;
import net.sourceforge.pmd.util.OptionalBool;
/**
* A reaching definition analysis. This may be used to check whether
* eg a value escapes, or is overwritten on all code paths.
*/
public final class DataflowPass {
// todo probably, make that non-optional. It would be useful to implement
// the flow-sensitive scopes of pattern variables
// todo things missing for full coverage of the JLS:
// - follow `this(...)` constructor calls
// - treat `while(true)` and `do while(true)` specially
// see also the todo comments in UnusedAssignmentRule
private static final SimpleDataKey<DataflowResult> DATAFLOW_RESULT_K = DataMap.simpleDataKey("java.dataflow.global");
private static final SimpleDataKey<ReachingDefinitionSet> REACHING_DEFS = DataMap.simpleDataKey("java.dataflow.reaching.backwards");
private static final SimpleDataKey<AssignmentEntry> VAR_DEFINITION = DataMap.simpleDataKey("java.dataflow.field.def");
private static final SimpleDataKey<OptionalBool> SWITCH_BRANCH_FALLS_THROUGH = DataMap.simpleDataKey("java.dataflow.switch.fallthrough");
private DataflowPass() {
// utility class
}
/**
* Returns the info computed by the dataflow pass for the given file.
* The computation is done at most once.
*/
public static DataflowResult getDataflowResult(ASTCompilationUnit acu) {
return acu.getUserMap().computeIfAbsent(DATAFLOW_RESULT_K, () -> process(acu));
}
/**
* If the var id is that of a field, returns the assignment entry that
* corresponds to its definition (either blank or its initializer). From
* there, using the kill record, we can draw the graph of all assignments.
* Returns null if not a field, or the compilation unit has not been processed.
*/
public static @Nullable AssignmentEntry getFieldDefinition(ASTVariableDeclaratorId varId) {
if (!varId.isField()) {
return null;
}
return varId.getUserMap().get(VAR_DEFINITION);
}
private static DataflowResult process(ASTCompilationUnit node) {
DataflowResult dataflowResult = new DataflowResult();
for (ASTAnyTypeDeclaration typeDecl : node.getTypeDeclarations()) {
GlobalAlgoState subResult = new GlobalAlgoState();
typeDecl.acceptVisitor(ReachingDefsVisitor.ONLY_LOCALS, new SpanInfo(subResult));
if (subResult.usedAssignments.size() < subResult.allAssignments.size()) {
Set<AssignmentEntry> unused = subResult.allAssignments;
unused.removeAll(subResult.usedAssignments);
unused.removeIf(AssignmentEntry::isUnbound);
unused.removeIf(AssignmentEntry::isFieldDefaultValue);
dataflowResult.unusedAssignments.addAll(unused);
}
CollectionUtil.mergeMaps(
dataflowResult.killRecord,
subResult.killRecord,
(s1, s2) -> {
s1.addAll(s2);
return s1;
});
}
return dataflowResult;
}
/**
* A set of reaching definitions, ie the assignments that are visible
* at some point. One can use {@link DataflowResult#getReachingDefinitions(ASTNamedReferenceExpr)}
* to get the data flow that reaches a variable usage (and go backwards with
* the {@linkplain DataflowResult#getKillers(AssignmentEntry) kill record}).
*/
public static final class ReachingDefinitionSet {
private Set<AssignmentEntry> reaching;
private boolean isNotFullyKnown;
private boolean containsInitialFieldValue;
private ReachingDefinitionSet() {
this.reaching = Collections.emptySet();
this.containsInitialFieldValue = false;
this.isNotFullyKnown = true;
}
ReachingDefinitionSet(/*Mutable*/Set<AssignmentEntry> reaching) {
this.reaching = reaching;
this.containsInitialFieldValue = reaching.removeIf(AssignmentEntry::isFieldAssignmentAtStartOfMethod);
// not || as we want the side effect
this.isNotFullyKnown = containsInitialFieldValue | reaching.removeIf(AssignmentEntry::isUnbound);
}
/** Returns the set of assignments that may reach the place. */
public Set<AssignmentEntry> getReaching() {
return Collections.unmodifiableSet(reaching);
}
/**
* Returns true if there were some {@linkplain AssignmentEntry#isUnbound() unbound}
* assignments in this set. They are not part of {@link #getReaching()}.
*/
public boolean isNotFullyKnown() {
return isNotFullyKnown;
}
/**
* Contains a {@link AssignmentEntry#isFieldAssignmentAtStartOfMethod()}.
* They are not part of {@link #getReaching()}.
*/
public boolean containsInitialFieldValue() {
return containsInitialFieldValue;
}
void absorb(ReachingDefinitionSet reaching) {
this.containsInitialFieldValue |= reaching.containsInitialFieldValue;
this.isNotFullyKnown |= reaching.isNotFullyKnown;
if (this.reaching.isEmpty()) { // unmodifiable
this.reaching = new LinkedHashSet<>(reaching.reaching);
} else {
this.reaching.addAll(reaching.reaching);
}
}
public static ReachingDefinitionSet unknown() {
return new ReachingDefinitionSet();
}
}
/**
* Global result of the dataflow analysis.
*/
// this is a façade class
public static final class DataflowResult {
final Set<AssignmentEntry> unusedAssignments;
final Map<AssignmentEntry, Set<AssignmentEntry>> killRecord;
DataflowResult() {
this.unusedAssignments = new LinkedHashSet<>();
this.killRecord = new LinkedHashMap<>();
}
/**
* To be interpreted by {@link UnusedAssignmentRule}.
*/
public Set<AssignmentEntry> getUnusedAssignments() {
return Collections.unmodifiableSet(unusedAssignments);
}
/**
* May be useful to check for reassignment.
*/
public @NonNull Set<AssignmentEntry> getKillers(AssignmentEntry assignment) {
return killRecord.getOrDefault(assignment, Collections.emptySet());
}
// These methods are only valid to be called if the dataflow pass has run.
// This is why they are instance methods here: by asking for the DataflowResult
// instance to get access to them, you ensure that the pass has been executed properly.
/**
* Returns whether the switch branch falls-through to the next one (or the end of the switch).
*/
public @NonNull OptionalBool switchBranchFallsThrough(ASTSwitchBranch b) {
if (b instanceof ASTSwitchFallthroughBranch) {
return Objects.requireNonNull(b.getUserMap().get(SWITCH_BRANCH_FALLS_THROUGH));
}
return OptionalBool.NO;
}
public @NonNull ReachingDefinitionSet getReachingDefinitions(ASTNamedReferenceExpr expr) {
return expr.getUserMap().computeIfAbsent(REACHING_DEFS, () -> reachingFallback(expr));
}
// Fallback, to compute reaching definitions for some fields
// that are not tracked by the tree exploration. Final fields
// indeed have a fully known set of reaching definitions.
// TODO maybe they should actually be tracked?
private @NonNull ReachingDefinitionSet reachingFallback(ASTNamedReferenceExpr expr) {
JVariableSymbol sym = expr.getReferencedSym();
if (sym == null || !sym.isField() || !sym.isFinal()) {
return ReachingDefinitionSet.unknown();
}
ASTVariableDeclaratorId node = sym.tryGetNode();
if (node == null) {
return ReachingDefinitionSet.unknown(); // we don't care about non-local declarations
}
Set<AssignmentEntry> assignments = node.getLocalUsages()
.stream()
.filter(it -> it.getAccessType() == AccessType.WRITE)
.map(usage -> {
JavaNode parent = usage.getParent();
if (parent instanceof ASTUnaryExpression
&& !((ASTUnaryExpression) parent).getOperator().isPure()) {
return parent;
} else if (usage.getIndexInParent() == 0
&& parent instanceof ASTAssignmentExpression) {
return ((ASTAssignmentExpression) parent).getRightOperand();
} else {
return null;
}
}).filter(Objects::nonNull)
.map(it -> new AssignmentEntry(sym, node, it))
.collect(CollectionUtil.toMutableSet());
ASTExpression init = node.getInitializer(); // this one is not in the usages
if (init != null) {
assignments.add(new AssignmentEntry(sym, node, init));
}
return new ReachingDefinitionSet(assignments);
}
}
private static final class ReachingDefsVisitor extends JavaVisitorBase<SpanInfo, SpanInfo> {
static final ReachingDefsVisitor ONLY_LOCALS = new ReachingDefsVisitor(null, false);
// The class scope for the "this" reference, used to find fields
// of this class
// null if we're not processing instance/static initializers,
// so in methods we don't care about fields
// If not null, fields are effectively treated as locals
private final JClassSymbol enclosingClassScope;
private final boolean inStaticCtx;
private ReachingDefsVisitor(JClassSymbol scope, boolean inStaticCtx) {
this.enclosingClassScope = scope;
this.inStaticCtx = inStaticCtx;
}
/**
* If true, we're also tracking fields of the {@code this} instance,
* because we're in a ctor or initializer, or instance method.
*/
private boolean trackThisInstance() {
return !inStaticCtx;
}
private boolean trackStaticFields() {
// only tracked in initializers
return enclosingClassScope != null && inStaticCtx;
}
// following deals with control flow structures
@Override
protected SpanInfo visitChildren(Node node, SpanInfo data) {
for (Node child : node.children()) {
// each output is passed as input to the next (most relevant for blocks)
data = child.acceptVisitor(this, data);
}
return data;
}
@Override
public SpanInfo visit(ASTBlock node, final SpanInfo data) {
// variables local to a loop iteration must be killed before the
// next iteration
SpanInfo state = data;
Set<ASTVariableDeclaratorId> localsToKill = new LinkedHashSet<>();
for (JavaNode child : node.children()) {
// each output is passed as input to the next (most relevant for blocks)
state = acceptOpt(child, state);
if (child instanceof ASTLocalVariableDeclaration) {
for (ASTVariableDeclaratorId id : (ASTLocalVariableDeclaration) child) {
localsToKill.add(id);
}
}
}
for (ASTVariableDeclaratorId var : localsToKill) {
state.deleteVar(var.getSymbol());
}
return state;
}
@Override
public SpanInfo visit(ASTSwitchStatement node, SpanInfo data) {
return processSwitch(node, data);
}
@Override
public SpanInfo visit(ASTSwitchExpression node, SpanInfo data) {
return processSwitch(node, data);
}
private SpanInfo processSwitch(ASTSwitchLike switchLike, SpanInfo data) {
GlobalAlgoState global = data.global;
SpanInfo before = acceptOpt(switchLike.getTestedExpression(), data);
global.breakTargets.push(before.fork());
SpanInfo current = before;
for (ASTSwitchBranch branch : switchLike.getBranches()) {
if (branch instanceof ASTSwitchArrowBranch) {
current = acceptOpt(((ASTSwitchArrowBranch) branch).getRightHandSide(), before.fork());
current = global.breakTargets.doBreak(current, null); // process this as if it was followed by a break
} else {
// fallthrough branch
current = acceptOpt(branch, before.fork().absorb(current));
branch.getUserMap().set(SWITCH_BRANCH_FALLS_THROUGH, current.hasCompletedAbruptly.complement());
}
}
before = global.breakTargets.pop();
// join with the last state, which is the exit point of the
// switch, if it's not closed by a break;
return before.absorb(current);
}
@Override
public SpanInfo visit(ASTIfStatement node, SpanInfo data) {
return makeConditional(data, node.getCondition(), node.getThenBranch(), node.getElseBranch());
}
@Override
public SpanInfo visit(ASTConditionalExpression node, SpanInfo data) {
return makeConditional(data, node.getCondition(), node.getThenBranch(), node.getElseBranch());
}
SpanInfo makeConditional(SpanInfo before, ASTExpression condition, JavaNode thenBranch, JavaNode elseBranch) {
SpanInfo thenState = before.fork();
SpanInfo elseState = elseBranch != null ? before.fork() : before;
linkConditional(before, condition, thenState, elseState, true);
thenState = acceptOpt(thenBranch, thenState);
elseState = acceptOpt(elseBranch, elseState);
return elseState.absorb(thenState);
}
/*
* This recursive procedure translates shortcut conditionals
* that occur in condition position in the following way:
*
* if (a || b) <then> if (a) <then>
* else <else> ~> else
* if (b) <then>
* else <else>
*
*
* if (a && b) <then> if (a)
* else <else> ~> if (b) <then>
* else <else>
* else <else>
*
* The new conditions are recursively processed to translate
* bigger conditions, like `a || b && c`
*
* This is how it works, but the <then> and <else> branch are
* visited only once, because it's not done in this method, but
* in makeConditional.
*
* @return the state in which all expressions have been evaluated
* Eg for `a || b`, this is the `else` state (all evaluated to false)
* Eg for `a && b`, this is the `then` state (all evaluated to true)
*
*/
private SpanInfo linkConditional(SpanInfo before, ASTExpression condition, SpanInfo thenState, SpanInfo elseState, boolean isTopLevel) {
if (condition == null) {
return before;
}
if (condition instanceof ASTInfixExpression) {
BinaryOp op = ((ASTInfixExpression) condition).getOperator();
if (op == BinaryOp.CONDITIONAL_OR) {
return visitShortcutOrExpr((ASTInfixExpression) condition, before, thenState, elseState);
} else if (op == BinaryOp.CONDITIONAL_AND) {
// To mimic a shortcut AND expr, swap the thenState and the elseState
// See explanations in method
return visitShortcutOrExpr((ASTInfixExpression) condition, before, elseState, thenState);
}
}
SpanInfo state = acceptOpt(condition, before);
if (isTopLevel) {
thenState.absorb(state);
elseState.absorb(state);
}
return state;
}
SpanInfo visitShortcutOrExpr(ASTInfixExpression orExpr,
SpanInfo before,
SpanInfo thenState,
SpanInfo elseState) {
// if (<a> || <b> || ... || <n>) <then>
// else <else>
//
// in <then>, we are sure that at least <a> was evaluated,
// but really any prefix of <a> ... <n> is possible so they're all merged
// in <else>, we are sure that all of <a> ... <n> were evaluated (to false)
// If you replace || with &&, then the above holds if you swap <then> and <else>
// So this method handles the OR expr, the caller can swap the arguments to make an AND
// ---
// This method side effects on thenState and elseState to
// set the variables.
SpanInfo cur = before;
cur = linkConditional(cur, orExpr.getLeftOperand(), thenState, elseState, false);
thenState.absorb(cur);
cur = linkConditional(cur, orExpr.getRightOperand(), thenState, elseState, false);
thenState.absorb(cur);
elseState.absorb(cur);
return cur;
}
@Override
public SpanInfo visit(ASTTryStatement node, final SpanInfo before) {
/*
<before>
try (<resources>) {
<body>
} catch (IOException e) {
<catch>
} finally {
<finally>
}
<end>
There is a path <before> -> <resources> -> <body> -> <finally> -> <end>
and for each catch, <before> -> <catch> -> <finally> -> <end>
Except that abrupt completion before the <finally> jumps
to the <finally> and completes abruptly for the same
reason (if the <finally> completes normally), which
means it doesn't go to <end>
*/
ASTFinallyClause finallyClause = node.getFinallyClause();
if (finallyClause != null) {
before.myFinally = before.forkEmpty();
}
final List<ASTCatchClause> catchClauses = node.getCatchClauses().toList();
final List<SpanInfo> catchSpans = catchClauses.isEmpty() ? Collections.emptyList()
: new ArrayList<>();
// pre-fill catch spans
for (int i = 0; i < catchClauses.size(); i++) {
catchSpans.add(before.forkEmpty());
}
@Nullable ASTResourceList resources = node.getResources();
SpanInfo bodyState = before.fork();
bodyState = bodyState.withCatchBlocks(catchSpans);
bodyState = acceptOpt(resources, bodyState);
bodyState = acceptOpt(node.getBody(), bodyState);
bodyState = bodyState.withCatchBlocks(Collections.emptyList());
SpanInfo exceptionalState = null;
int i = 0;
for (ASTCatchClause catchClause : node.getCatchClauses()) {
SpanInfo current = acceptOpt(catchClause, catchSpans.get(i));
exceptionalState = current.absorb(exceptionalState);
i++;
}
SpanInfo finalState;
finalState = bodyState.absorb(exceptionalState);
if (finallyClause != null) {
// this represents the finally clause when it was entered
// because of abrupt completion
// since we don't know when it terminated we must join it with before
SpanInfo abruptFinally = before.myFinally.absorb(before);
acceptOpt(finallyClause, abruptFinally);
before.myFinally = null;
abruptFinally.abruptCompletionByThrow(false); // propagate to enclosing catch/finallies
// this is the normal finally
finalState = acceptOpt(finallyClause, finalState);
}
// In the 7.0 grammar, the resources should be explicitly
// used here. For now they don't trigger anything as their
// node is not a VariableDeclaratorId. There's a test to
// check that.
return finalState;
}
@Override
public SpanInfo visit(ASTCatchClause node, SpanInfo data) {
SpanInfo result = visitJavaNode(node, data);
result.deleteVar(node.getParameter().getVarId().getSymbol());
return result;
}
@Override
public SpanInfo visit(ASTLambdaExpression node, SpanInfo data) {
// Lambda expression have control flow that is separate from the method
// So we fork the context, but don't join it
// Reaching definitions of the enclosing context still reach in the lambda
// Since those definitions are [effectively] final, they actually can't be
// killed, but they can be used in the lambda
SpanInfo before = data;
JavaNode lambdaBody = node.getChild(node.getNumChildren() - 1);
// if it's an expression, then no assignments may occur in it,
// but it can still use some variables of the context
acceptOpt(lambdaBody, before.forkCapturingNonLocal());
return before;
}
@Override
public SpanInfo visit(ASTWhileStatement node, SpanInfo data) {
return handleLoop(node, data, null, node.getCondition(), null, node.getBody(), true, null);
}
@Override
public SpanInfo visit(ASTDoStatement node, SpanInfo data) {
return handleLoop(node, data, null, node.getCondition(), null, node.getBody(), false, null);
}
@Override
public SpanInfo visit(ASTForeachStatement node, SpanInfo data) {
ASTStatement body = node.getBody();
ASTExpression init = node.getIterableExpr();
return handleLoop(node, data, init, null, null, body, true, node.getVarId());
}
@Override
public SpanInfo visit(ASTForStatement node, SpanInfo data) {
ASTStatement body = node.getBody();
ASTForInit init = node.firstChild(ASTForInit.class);
ASTExpression cond = node.getCondition();
ASTForUpdate update = node.firstChild(ASTForUpdate.class);
return handleLoop(node, data, init, cond, update, body, true, null);
}
private SpanInfo handleLoop(ASTLoopStatement loop,
SpanInfo before,
JavaNode init,
ASTExpression cond,
JavaNode update,
ASTStatement body,
boolean checkFirstIter,
ASTVariableDeclaratorId foreachVar) {
final GlobalAlgoState globalState = before.global;
//todo while(true) and do {}while(true); are special-cased
// by the compiler and there is no fork
SpanInfo breakTarget = before.forkEmpty();
SpanInfo continueTarget = before.forkEmpty();
pushTargets(loop, breakTarget, continueTarget);
// perform a few "iterations", to make sure that assignments in
// the body can affect themselves in the next iteration, and
// that they affect the condition, etc
before = acceptOpt(init, before);
if (checkFirstIter && cond != null) { // false for do-while
SpanInfo ifcondTrue = before.forkEmpty();
linkConditional(before, cond, ifcondTrue, breakTarget, true);
before = ifcondTrue;
}
if (foreachVar != null) {
// in foreach loops, the loop variable is assigned before the first iteration
before.assign(foreachVar.getSymbol(), foreachVar);
}
// make the defs of the body reach the other parts of the loop,
// including itself
SpanInfo iter = acceptOpt(body, before.fork());
if (foreachVar != null && iter.hasVar(foreachVar)) {
// in foreach loops, the loop variable is reassigned on each update
iter.assign(foreachVar.getSymbol(), foreachVar);
} else {
iter = acceptOpt(update, iter);
}
linkConditional(iter, cond, iter, breakTarget, true);
iter = acceptOpt(body, iter);
breakTarget = globalState.breakTargets.peek();
continueTarget = globalState.continueTargets.peek();
if (!continueTarget.symtable.isEmpty()) {
// make assignments before a continue reach the other parts of the loop
linkConditional(continueTarget, cond, continueTarget, breakTarget, true);
continueTarget = acceptOpt(body, continueTarget);
continueTarget = acceptOpt(update, continueTarget);
}
SpanInfo result = popTargets(loop, breakTarget, continueTarget);
result = result.absorb(iter);
if (checkFirstIter) {
// if the first iteration is checked,
// then it could be false on the first try, meaning
// the definitions before the loop reach after too
result = result.absorb(before);
}
if (foreachVar != null) {
result.deleteVar(foreachVar.getSymbol());
}
return result;
}
private void pushTargets(ASTLoopStatement loop, SpanInfo breakTarget, SpanInfo continueTarget) {
GlobalAlgoState globalState = breakTarget.global;
globalState.breakTargets.unnamedTargets.push(breakTarget);
globalState.continueTargets.unnamedTargets.push(continueTarget);
Node parent = loop.getParent();
while (parent instanceof ASTLabeledStatement) {
String label = ((ASTLabeledStatement) parent).getLabel();
globalState.breakTargets.namedTargets.put(label, breakTarget);
globalState.continueTargets.namedTargets.put(label, continueTarget);
parent = parent.getParent();
}
}
private SpanInfo popTargets(ASTLoopStatement loop, SpanInfo breakTarget, SpanInfo continueTarget) {
GlobalAlgoState globalState = breakTarget.global;
globalState.breakTargets.unnamedTargets.pop();
globalState.continueTargets.unnamedTargets.pop();
SpanInfo total = breakTarget.absorb(continueTarget);
Node parent = loop.getParent();
while (parent instanceof ASTLabeledStatement) {
String label = ((ASTLabeledStatement) parent).getLabel();
total = total.absorb(globalState.breakTargets.namedTargets.remove(label));
total = total.absorb(globalState.continueTargets.namedTargets.remove(label));
parent = parent.getParent();
}
return total;
}
private SpanInfo acceptOpt(JavaNode node, SpanInfo before) {
return node == null ? before : node.acceptVisitor(this, before);
}
@Override
public SpanInfo visit(ASTContinueStatement node, SpanInfo data) {
return data.global.continueTargets.doBreak(data, node.getImage());
}
@Override
public SpanInfo visit(ASTBreakStatement node, SpanInfo data) {
return data.global.breakTargets.doBreak(data, node.getImage());
}
@Override
public SpanInfo visit(ASTYieldStatement node, SpanInfo data) {
super.visit(node, data); // visit expression
// treat as break, ie abrupt completion + link reaching defs to outer context
return data.global.breakTargets.doBreak(data, null);
}
// both of those exit the scope of the method/ctor, so their assignments go dead
@Override
public SpanInfo visit(ASTThrowStatement node, SpanInfo data) {
super.visit(node, data);
return data.abruptCompletionByThrow(false);
}
@Override
public SpanInfo visit(ASTReturnStatement node, SpanInfo data) {
super.visit(node, data);
return data.abruptCompletion(null);
}
// following deals with assignment
@Override
public SpanInfo visit(ASTFormalParameter node, SpanInfo data) {
data.declareBlank(node.getVarId());
return data;
}
@Override
public SpanInfo visit(ASTCatchParameter node, SpanInfo data) {
data.declareBlank(node.getVarId());
return data;
}
@Override
public SpanInfo visit(ASTVariableDeclarator node, SpanInfo data) {
JVariableSymbol var = node.getVarId().getSymbol();
ASTExpression rhs = node.getInitializer();
if (rhs != null) {
rhs.acceptVisitor(this, data);
data.assign(var, rhs);
} else if (isAssignedImplicitly(node.getVarId())) {
data.declareBlank(node.getVarId());
}
return data;
}
/**
* Whether the variable has an implicit initializer, that is not
* an expression. For instance, formal parameters have a value
* within the method, same for exception parameters, foreach variables,
* fields (default value), etc. Only blank local variables have
* no initial value.
*/
private boolean isAssignedImplicitly(ASTVariableDeclaratorId var) {
return !var.isLocalVariable() || var.isForeachVariable();
}
@Override
public SpanInfo visit(ASTUnaryExpression node, SpanInfo data) {
data = acceptOpt(node.getOperand(), data);
if (node.getOperator().isPure()) {
return data;
} else {
return processAssignment(node.getOperand(), node, true, data);
}
}
@Override
public SpanInfo visit(ASTAssignmentExpression node, SpanInfo data) {
// visit operands in order
data = acceptOpt(node.getRightOperand(), data);
data = acceptOpt(node.getLeftOperand(), data);
return processAssignment(node.getLeftOperand(),
node.getRightOperand(),
node.getOperator().isCompound(),
data);
}
private SpanInfo processAssignment(ASTExpression lhs, // LHS or unary operand
ASTExpression rhs, // RHS or unary
boolean useBeforeAssigning,
SpanInfo result) {
if (lhs instanceof ASTNamedReferenceExpr) {
JVariableSymbol lhsVar = ((ASTNamedReferenceExpr) lhs).getReferencedSym();
if (lhsVar != null
&& (lhsVar instanceof JLocalVariableSymbol
|| isRelevantField(lhs))) {
if (useBeforeAssigning) {
// compound assignment, to use BEFORE assigning
result.use(lhsVar, (ASTNamedReferenceExpr) lhs);
}
result.assign(lhsVar, rhs);
}
}
return result;
}
private boolean isRelevantField(ASTExpression lhs) {
return lhs instanceof ASTNamedReferenceExpr
&& (trackThisInstance() && JavaAstUtils.isThisFieldAccess(lhs)
|| trackStaticFields() && isStaticFieldOfThisClass(((ASTNamedReferenceExpr) lhs).getReferencedSym()));
}
private boolean isStaticFieldOfThisClass(JVariableSymbol var) {
return var instanceof JFieldSymbol
&& ((JFieldSymbol) var).isStatic()
// must be non-null
&& enclosingClassScope.equals(((JFieldSymbol) var).getEnclosingClass());
}
private static JVariableSymbol getVarIfUnaryAssignment(ASTUnaryExpression node) { // NOPMD UnusedPrivateMethod
ASTExpression operand = node.getOperand();
if (!node.getOperator().isPure() && operand instanceof ASTNamedReferenceExpr) {
return ((ASTNamedReferenceExpr) operand).getReferencedSym();
}
return null;
}
// variable usage
@Override
public SpanInfo visit(ASTVariableAccess node, SpanInfo data) {
if (node.getAccessType() == AccessType.READ) {
data.use(node.getReferencedSym(), node);
}
return data;
}
@Override
public SpanInfo visit(ASTFieldAccess node, SpanInfo data) {
data = node.getQualifier().acceptVisitor(this, data);
if (isRelevantField(node) && node.getAccessType() == AccessType.READ) {
data.use(node.getReferencedSym(), node);
}
return data;
}
@Override
public SpanInfo visit(ASTThisExpression node, SpanInfo data) {
if (trackThisInstance() && !(node.getParent() instanceof ASTFieldAccess)) {
data.recordThisLeak(true, enclosingClassScope, node);
}
return data;
}
@Override
public SpanInfo visit(ASTMethodCall node, SpanInfo state) {
return visitInvocationExpr(node, state);
}
@Override
public SpanInfo visit(ASTConstructorCall node, SpanInfo state) {
state = visitInvocationExpr(node, state);
acceptOpt(node.getAnonymousClassDeclaration(), state);
return state;
}
private <T extends InvocationNode & QualifiableExpression> SpanInfo visitInvocationExpr(T node, SpanInfo state) {
state = acceptOpt(node.getQualifier(), state);
state = acceptOpt(node.getArguments(), state);
// todo In 7.0, with the precise type/overload resolution, we
// could only target methods that throw checked exceptions
// (unless some catch block catches an unchecked exceptions)
state.abruptCompletionByThrow(true); // this is a noop if we're outside a try block that has catch/finally
return state;
}
// ctor/initializer handling
@Override
public SpanInfo visitTypeDecl(ASTAnyTypeDeclaration node, SpanInfo data) {
// process initializers and ctors first
processInitializers(node.getDeclarations(), data, node.getSymbol());
for (ASTBodyDeclaration decl : node.getDeclarations()) {
if (decl instanceof ASTMethodDeclaration) {
ASTMethodDeclaration method = (ASTMethodDeclaration) decl;
if (method.getBody() != null) {
SpanInfo span = data.forkCapturingNonLocal();
if (!method.isStatic()) {
span.declareSpecialFieldValues(node.getSymbol());
}
ONLY_LOCALS.acceptOpt(decl, span);
}
} else if (decl instanceof ASTAnyTypeDeclaration) {
visitTypeDecl((ASTAnyTypeDeclaration) decl, data.forkEmptyNonLocal());
}
}
return data; // type doesn't contribute anything to the enclosing control flow
}
private static void processInitializers(NodeStream<ASTBodyDeclaration> declarations,
SpanInfo beforeLocal,
JClassSymbol classSymbol) {
ReachingDefsVisitor instanceVisitor = new ReachingDefsVisitor(classSymbol, false);
ReachingDefsVisitor staticVisitor = new ReachingDefsVisitor(classSymbol, true);
// All field initializers + instance initializers
SpanInfo ctorHeader = beforeLocal.forkCapturingNonLocal();
// All static field initializers + static initializers
SpanInfo staticInit = beforeLocal.forkEmptyNonLocal();
List<ASTBodyDeclaration> ctors = new ArrayList<>();
for (ASTBodyDeclaration declaration : declarations) {
final boolean isStatic;
if (declaration instanceof ASTEnumConstant) {
isStatic = true;
} else if (declaration instanceof ASTFieldDeclaration) {
isStatic = ((ASTFieldDeclaration) declaration).isStatic();
} else if (declaration instanceof ASTInitializer) {
isStatic = ((ASTInitializer) declaration).isStatic();
} else if (declaration instanceof ASTConstructorDeclaration
|| declaration instanceof ASTCompactConstructorDeclaration) {
ctors.add(declaration);
continue;
} else {
continue;
}
if (isStatic) {
staticInit = staticVisitor.acceptOpt(declaration, staticInit);
} else {
ctorHeader = instanceVisitor.acceptOpt(declaration, ctorHeader);
}
}
SpanInfo ctorEndState = ctors.isEmpty() ? ctorHeader : null;
for (ASTBodyDeclaration ctor : ctors) {
SpanInfo state = instanceVisitor.acceptOpt(ctor, ctorHeader.forkCapturingNonLocal());
ctorEndState = ctorEndState == null ? state : ctorEndState.absorb(state);
}
// assignments that reach the end of any constructor must be considered used
useAllSelfFields(staticInit, ctorEndState, classSymbol, classSymbol.tryGetNode());
}
static void useAllSelfFields(@Nullable SpanInfo staticState, SpanInfo instanceState, JClassSymbol enclosingSym, JavaNode escapingNode) {
for (JFieldSymbol field : enclosingSym.getDeclaredFields()) {
if (field.isStatic()) {
if (staticState != null) {
staticState.assignOutOfScope(field, escapingNode);
}
} else {
instanceState.assignOutOfScope(field, escapingNode);
}
}
}
}
/**
* The shared state for all {@link SpanInfo} instances in the same
* toplevel class.
*/
private static final class GlobalAlgoState {
final Set<AssignmentEntry> allAssignments;
final Set<AssignmentEntry> usedAssignments;
// track which assignments kill which
// assignment -> killers(assignment)
final Map<AssignmentEntry, Set<AssignmentEntry>> killRecord;
final TargetStack breakTargets = new TargetStack();
// continue jumps to the condition check, while break jumps to after the loop
final TargetStack continueTargets = new TargetStack();
private GlobalAlgoState(Set<AssignmentEntry> allAssignments,
Set<AssignmentEntry> usedAssignments,
Map<AssignmentEntry, Set<AssignmentEntry>> killRecord) {
this.allAssignments = allAssignments;
this.usedAssignments = usedAssignments;
this.killRecord = killRecord;
}
private GlobalAlgoState() {
this(new LinkedHashSet<>(),
new LinkedHashSet<>(),
new LinkedHashMap<>());
}
}
// Information about a variable in a code span.
static class VarLocalInfo {
// this is not modified so can be shared between different SpanInfos.
final Set<AssignmentEntry> reachingDefs;
VarLocalInfo(Set<AssignmentEntry> reachingDefs) {
this.reachingDefs = reachingDefs;
}
// and produce an independent instance
VarLocalInfo merge(VarLocalInfo other) {
if (other == this) { // NOPMD #3205
return this;
}
Set<AssignmentEntry> merged = new LinkedHashSet<>(reachingDefs.size() + other.reachingDefs.size());
merged.addAll(reachingDefs);
merged.addAll(other.reachingDefs);
return new VarLocalInfo(merged);
}
@Override
public String toString() {
return "VarLocalInfo{reachingDefs=" + reachingDefs + '}';
}
}
/**
* Information about a span of code.
*/
private static final class SpanInfo {
// spans are arranged in a tree, to look for enclosing finallies
// when abrupt completion occurs. Blocks that have non-local
// control-flow (lambda bodies, anonymous classes, etc) aren't
// linked to the outer parents.
final SpanInfo parent;
// If != null, then abrupt completion in this span of code (and any descendant)
// needs to go through the finally span (the finally must absorb it)
SpanInfo myFinally = null;
/**
* Inside a try block, we assume that any method/ctor call may
* throw, which means, any assignment reaching such a method call
* may reach the catch blocks if there are any.
*/
List<SpanInfo> myCatches;
final GlobalAlgoState global;
final Map<JVariableSymbol, VarLocalInfo> symtable;
private OptionalBool hasCompletedAbruptly = OptionalBool.NO;
private SpanInfo(GlobalAlgoState global) {
this(null, global, new LinkedHashMap<>());
}
private SpanInfo(SpanInfo parent,
GlobalAlgoState global,
Map<JVariableSymbol, VarLocalInfo> symtable) {
this.parent = parent;
this.global = global;
this.symtable = symtable;
this.myCatches = Collections.emptyList();
}
boolean hasVar(ASTVariableDeclaratorId var) {
return symtable.containsKey(var.getSymbol());
}
void declareBlank(ASTVariableDeclaratorId id) {
assign(id.getSymbol(), id);
}
void assign(JVariableSymbol var, JavaNode rhs) {
assign(var, rhs, false, false);
}
void assign(JVariableSymbol var, JavaNode rhs, boolean outOfScope, boolean isFieldBeforeMethod) {
ASTVariableDeclaratorId node = var.tryGetNode();
if (node == null) {
return; // we don't care about non-local declarations
}
AssignmentEntry entry = outOfScope || isFieldBeforeMethod
? new UnboundAssignment(var, node, rhs, isFieldBeforeMethod)
: new AssignmentEntry(var, node, rhs);
VarLocalInfo previous = symtable.put(var, new VarLocalInfo(Collections.singleton(entry)));
if (previous != null) {
// those assignments were overwritten ("killed")
for (AssignmentEntry killed : previous.reachingDefs) {
if (killed.isBlankLocal()) {
continue;
}
global.killRecord.computeIfAbsent(killed, k -> new LinkedHashSet<>(1))
.add(entry);
}
}
global.allAssignments.add(entry);
}
void declareSpecialFieldValues(JClassSymbol sym) {
List<JFieldSymbol> declaredFields = sym.getDeclaredFields();
for (JFieldSymbol field : declaredFields) {
ASTVariableDeclaratorId id = field.tryGetNode();
if (id == null || !SingularFieldRule.mayBeSingular(id)) {
// useless to track final fields
// static fields are out of scope of this impl for now
continue;
}
assign(field, id, true, true);
}
}
void assignOutOfScope(@Nullable JVariableSymbol var, JavaNode escapingNode) {
if (var == null) {
return;
}
use(var, null);
assign(var, escapingNode, true, false);
}
void use(@Nullable JVariableSymbol var, ASTNamedReferenceExpr reachingDefSink) {
if (var == null) {
return;
}
VarLocalInfo info = symtable.get(var);
// may be null for implicit assignments, like method parameter
if (info != null) {
global.usedAssignments.addAll(info.reachingDefs);
if (reachingDefSink != null) {
ReachingDefinitionSet reaching = new ReachingDefinitionSet(new LinkedHashSet<>(info.reachingDefs));
// need to merge into previous to account for cyclic control flow
reachingDefSink.getUserMap().compute(REACHING_DEFS, current -> {
if (current != null) {
current.absorb(reaching);
return current;
} else {
return reaching;
}
});
}
}
}
void deleteVar(JVariableSymbol var) {
symtable.remove(var);
}
/**
* Record a leak of the `this` reference in a ctor (including field initializers).
*
* <p>This means, all defs reaching this point, for all fields
* of `this`, may be used in the expression. We assume that the
* ctor finishes its execution atomically, that is, following
* definitions are not observable at an arbitrary point (that
* would be too conservative).
*
* <p>Constructs that are considered to leak the `this` reference
* (only processed if they occur in a ctor):
* - using `this` as a method/ctor argument
* - using `this` as the receiver of a method/ctor invocation
*
* <p>Because `this` may be aliased (eg in a field, a local var,
* inside an anon class or capturing lambda, etc), any method
* call, on any receiver, may actually observe field definitions
* of `this`. So the analysis may show some false positives, which
* hopefully should be rare enough.
*/
public void recordThisLeak(boolean thisIsLeaking, JClassSymbol enclosingClassSym, JavaNode escapingNode) {
if (thisIsLeaking && enclosingClassSym != null) {
// all reaching defs to fields until now may be observed
ReachingDefsVisitor.useAllSelfFields(null, this, enclosingClassSym, escapingNode);
}
}
// Forks duplicate this context, to preserve the reaching defs
// of the current context while analysing a sub-block
// Forks must be merged later if control flow merges again, see ::absorb
SpanInfo fork() {
return doFork(this, copyTable());
}
SpanInfo forkEmpty() {
return doFork(this, new LinkedHashMap<>());
}
SpanInfo forkEmptyNonLocal() {
return doFork(null, new LinkedHashMap<>());
}
SpanInfo forkCapturingNonLocal() {
return doFork(null, copyTable());
}
private Map<JVariableSymbol, VarLocalInfo> copyTable() {
return new LinkedHashMap<>(this.symtable);
}
private SpanInfo doFork(/*nullable*/ SpanInfo parent, Map<JVariableSymbol, VarLocalInfo> reaching) {
return new SpanInfo(parent, this.global, reaching);
}
/** Abrupt completion for return, continue, break. */
SpanInfo abruptCompletion(SpanInfo target) {
// if target == null then this will unwind all the parents
hasCompletedAbruptly = OptionalBool.YES;
SpanInfo parent = this;
while (parent != target && parent != null) { // NOPMD CompareObjectsWithEqual this is what we want
if (parent.myFinally != null) {
parent.myFinally.absorb(this);
// stop on the first finally, its own end state will
// be merged into the nearest enclosing finally
return this;
}
parent = parent.parent;
}
this.symtable.clear();
return this;
}
/**
* Record an abrupt completion occurring because of a thrown
* exception.
*
* @param byMethodCall If true, a method/ctor call threw the exception
* (we conservatively consider they do inside try blocks).
* Otherwise, a throw statement threw.
*/
SpanInfo abruptCompletionByThrow(boolean byMethodCall) {
// Find the first block that has a finally
// Be absorbed into every catch block on the way.
// In 7.0, with the precise type/overload resolution, we
// can target the specific catch block that would catch the
// exception.
if (!byMethodCall) {
hasCompletedAbruptly = OptionalBool.YES;
}
SpanInfo parent = this;
while (parent != null) {
if (!parent.myCatches.isEmpty()) {
for (SpanInfo c : parent.myCatches) {
c.absorb(this);
}
}
if (parent.myFinally != null) {
// stop on the first finally, its own end state will
// be merged into the nearest enclosing finally
parent.myFinally.absorb(this);
return this;
}
parent = parent.parent;
}
if (!byMethodCall) {
this.symtable.clear(); // following is dead code
}
return this;
}
SpanInfo withCatchBlocks(List<SpanInfo> catchStmts) {
assert myCatches.isEmpty() || catchStmts.isEmpty() : "Cannot set catch blocks twice";
myCatches = Collections.unmodifiableList(catchStmts); // we own the list now, to avoid copying
return this;
}
SpanInfo absorb(SpanInfo other) {
// Merge reaching defs of the other scope into this
// This is used to join paths after the control flow has forked
// a spanInfo may be absorbed several times so this method should not
// destroy the parameter
if (other == this || other == null || other.symtable.isEmpty()) { // NOPMD #3205
return this;
}
CollectionUtil.mergeMaps(this.symtable, other.symtable, VarLocalInfo::merge);
this.hasCompletedAbruptly = mergeCertitude(this.hasCompletedAbruptly, other.hasCompletedAbruptly);
return this;
}
private OptionalBool mergeCertitude(OptionalBool first, OptionalBool other) {
if (first.isKnown() && other.isKnown()) {
return first == other ? first : OptionalBool.UNKNOWN;
}
return OptionalBool.UNKNOWN;
}
@Override
public String toString() {
return symtable.toString();
}
}
static class TargetStack {
final Deque<SpanInfo> unnamedTargets = new ArrayDeque<>();
final Map<String, SpanInfo> namedTargets = new LinkedHashMap<>();
void push(SpanInfo state) {
unnamedTargets.push(state);
}
SpanInfo pop() {
return unnamedTargets.pop();
}
SpanInfo peek() {
return unnamedTargets.getFirst();
}
SpanInfo doBreak(SpanInfo data, /* nullable */ String label) {
// basically, reaching defs at the point of the break
// also reach after the break (wherever it lands)
SpanInfo target;
if (label == null) {
target = unnamedTargets.getFirst();
} else {
target = namedTargets.get(label);
}
if (target != null) { // otherwise CT error
target.absorb(data);
}
return data.abruptCompletion(target);
}
}
public static class AssignmentEntry implements Comparable<AssignmentEntry> {
final JVariableSymbol var;
final ASTVariableDeclaratorId node;
// this is not necessarily an expression, it may be also the
// variable declarator of a foreach loop
final JavaNode rhs;
AssignmentEntry(JVariableSymbol var, ASTVariableDeclaratorId node, JavaNode rhs) {
this.var = var;
this.node = node;
this.rhs = rhs;
// This may be overwritten repeatedly in loops, we probably don't care,
// as normally they're created equal
// Also for now we don't support getting a field.
if ((isInitializer() || isBlankDeclaration()) && !isUnbound()) {
node.getUserMap().set(VAR_DEFINITION, this);
}
}
public boolean isInitializer() {
return rhs.getParent() instanceof ASTVariableDeclarator
&& rhs.getIndexInParent() > 0;
}
public boolean isBlankDeclaration() {
return rhs instanceof ASTVariableDeclaratorId;
}
public boolean isFieldDefaultValue() {
return isBlankDeclaration() && isField();
}
/**
* A blank local that has no value (ie not a catch param or formal).
*/
public boolean isBlankLocal() {
return isBlankDeclaration() && node.isLocalVariable();
}
public boolean isUnaryReassign() {
return rhs instanceof ASTUnaryExpression
&& ReachingDefsVisitor.getVarIfUnaryAssignment((ASTUnaryExpression) rhs) == var; // NOPMD #3205
}
@Override
public int compareTo(AssignmentEntry o) {
return this.rhs.compareLocation(o.rhs);
}
public int getLine() {
return getLocation().getBeginLine();
}
public boolean isField() {
return var instanceof JFieldSymbol;
}
public boolean isForeachVar() {
return node.isForeachVariable();
}
public ASTVariableDeclaratorId getVarId() {
return node;
}
public JavaNode getLocation() {
return rhs;
}
// todo i'm probably missing some
/**
* <p>Returns non-null for an assignment expression, eg for (a = b), returns b.
* For (i++), returns (i++) and not (i), same for (i--).
* Returns null if the assignment is, eg, the default value
* of a field; the "blank" definition of a local variable,
* exception parameter, formal parameter, foreach variable, etc.
*/
public @Nullable ASTExpression getRhsAsExpression() {
if (isUnbound() || isBlankDeclaration()) {
return null;
}
if (rhs instanceof ASTExpression) {
return (ASTExpression) rhs;
}
return null;
}
/**
* Returns the type of the right-hand side if it is an explicit
* expression, null if it cannot be determined or there is no
* right-hand side to this expression. TODO test
*/
public @Nullable JTypeMirror getRhsType() {
/* test case
List<A> as;
for (Object o : as) {
// the rhs type of o should be A
}
*/
if (isUnbound() || isBlankDeclaration()) {
return null;
} else if (rhs instanceof ASTExpression) {
return ((TypeNode) rhs).getTypeMirror();
}
return null;
}
/**
* If true, then this "assignment" is not real. We conservatively
* assume that the variable may have been set to another value by
* a call to some external code.
*/
public boolean isUnbound() {
return false;
}
/**
* If true, then this "assignment" is the placeholder value given
* to an instance field before a method starts. This is a subset of
* {@link #isUnbound()}.
*/
public boolean isFieldAssignmentAtStartOfMethod() {
return false;
}
/**
* If true, then this "assignment" is the placeholder value given
* to a non-final instance field after a ctor ends. This is a subset of
* {@link #isUnbound()}.
*/
public boolean isFieldAssignmentAtEndOfCtor() {
return false;
}
@Override
public String toString() {
return var.getSimpleName() + " := " + rhs;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AssignmentEntry that = (AssignmentEntry) o;
return Objects.equals(var, that.var)
&& Objects.equals(rhs, that.rhs);
}
@Override
public int hashCode() {
return 31 * var.hashCode() + rhs.hashCode();
}
}
static class UnboundAssignment extends AssignmentEntry {
/**
* If true, then this is the unknown value of a field
* before an instance method call.
*/
private final boolean isFieldStartValue;
UnboundAssignment(JVariableSymbol var, ASTVariableDeclaratorId node, JavaNode rhs, boolean isFieldStartValue) {
super(var, node, rhs);
this.isFieldStartValue = isFieldStartValue;
}
@Override
public boolean isUnbound() {
return true;
}
@Override
public boolean isFieldAssignmentAtStartOfMethod() {
return isFieldStartValue;
}
@Override
public boolean isFieldAssignmentAtEndOfCtor() {
return rhs instanceof ASTAnyTypeDeclaration;
}
}
}
| 64,935 | 39.509046 | 144 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/internal/StablePathMatcher.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.internal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTFieldAccess;
import net.sourceforge.pmd.lang.java.ast.ASTMethodCall;
import net.sourceforge.pmd.lang.java.ast.ASTSuperExpression;
import net.sourceforge.pmd.lang.java.ast.ASTThisExpression;
import net.sourceforge.pmd.lang.java.ast.ASTVariableAccess;
import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils;
import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol;
/**
* A matcher for an expression like {@code a}, {@code a.b}, {@code a.getFoo()}.
* Those are expressions we assume to be pure, and to be referring to
* the same reference when they're called repeatedly if no side effect
* occurs between calls.
*
* <p>Note that this is not relocatable: you must use a matcher in the
* same scope it has been created in, to avoid bugs with accessibility/shadowing/etc.
* You must take care yourself that no side-effect occurs.
*/
public final class StablePathMatcher {
// if owner == null, then the owner is `this`.
private final @Nullable JVariableSymbol owner;
private final List<Segment> path;
private StablePathMatcher(@Nullable JVariableSymbol owner, List<Segment> path) {
this.owner = owner;
this.path = path;
}
/**
* Returns true if the expression matches the path.
*/
public boolean matches(@Nullable ASTExpression e) {
if (e == null) {
return false;
}
for (Segment segment : path) {
boolean isField = segment.isField;
String name = segment.name;
if (isField) {
if (!(e instanceof ASTFieldAccess)) {
return false;
}
ASTFieldAccess access = (ASTFieldAccess) e;
if (!access.getName().equals(name)) {
return false;
}
e = access.getQualifier();
} else {
if (!(e instanceof ASTMethodCall)) {
return false;
}
ASTMethodCall call = (ASTMethodCall) e;
if (!call.getMethodName().equals(name) || call.getArguments().size() != 0) {
return false;
}
e = call.getQualifier();
}
}
if (e instanceof ASTVariableAccess) {
return Objects.equals(((ASTVariableAccess) e).getReferencedSym(), owner);
} else if (e instanceof ASTFieldAccess) {
ASTFieldAccess fieldAccess = (ASTFieldAccess) e;
return JavaAstUtils.isUnqualifiedThis(fieldAccess.getQualifier())
&& Objects.equals(fieldAccess.getReferencedSym(), owner);
}
return false;
}
/**
* Returns a matcher matching the given expression if it is stable.
* Otherwise returns null.
*/
public static @Nullable StablePathMatcher matching(ASTExpression e) {
if (e == null) {
return null;
}
JVariableSymbol owner = null;
List<Segment> segments = new ArrayList<>();
while (e != null) {
if (e instanceof ASTFieldAccess) {
ASTFieldAccess access = (ASTFieldAccess) e;
segments.add(new Segment(access.getName(), true));
e = access.getQualifier();
} else if (e instanceof ASTMethodCall) {
ASTMethodCall call = (ASTMethodCall) e;
if (JavaRuleUtil.isGetterCall(call)) {
segments.add(new Segment(call.getMethodName(), false));
e = call.getQualifier();
} else {
return null;
}
} else if (e instanceof ASTVariableAccess) {
owner = ((ASTVariableAccess) e).getReferencedSym();
if (owner == null) {
return null; // unresolved
}
break;
} else if (e instanceof ASTThisExpression) {
if (((ASTThisExpression) e).getQualifier() != null) {
return null;
}
break;
} else if (e instanceof ASTSuperExpression) {
if (((ASTSuperExpression) e).getQualifier() != null) {
return null;
}
break;
} else {
return null;
}
}
return new StablePathMatcher(owner, segments);
}
public static StablePathMatcher matching(JVariableSymbol e) {
return new StablePathMatcher(e, Collections.emptyList());
}
private static final class Segment {
final String name;
final boolean isField;
Segment(String name, boolean isField) {
this.name = name;
this.isField = isField;
}
@Override
public String toString() {
return isField ? "." + name
: "." + name + "()";
}
}
}
| 5,343 | 33.25641 | 92 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/javadoc/JavadocTag.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.javadoc;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public final class JavadocTag {
public final String label;
public final String description;
private static final Map<String, JavadocTag> TAGS_BY_ID = new HashMap<>();
public static final JavadocTag AUTHOR = new JavadocTag("author",
"Authors of the source code, in chronological order");
public static final JavadocTag SINCE = new JavadocTag("since",
"Version of the source code that this item was introduced, can be a number or a date");
public static final JavadocTag VERSION = new JavadocTag("version", "Current version number of the source code");
public static final JavadocTag DEPRECATED = new JavadocTag("deprecated",
"Indicates that an item is a member of the deprecated API");
public static final JavadocTag PARAM = new JavadocTag("param", " ");
public static final JavadocTag THROWS = new JavadocTag("throws", " ");
public static final JavadocTag RETURN = new JavadocTag("return", " ");
public static final JavadocTag SEE = new JavadocTag("see", " ");
/* public static final JavadocTag POST = new JavadocTag("post", " ");
public static final JavadocTag PRE = new JavadocTag("pre", " ");
public static final JavadocTag RETURN = new JavadocTag("return", " ");
public static final JavadocTag INV = new JavadocTag("inv", " ");
public static final JavadocTag INVARIANT = new JavadocTag("invariant", " ");
public static final JavadocTag PATTERN = new JavadocTag("pattern", " ");
public static final JavadocTag SERIAL = new JavadocTag("serial", " ");
public static final JavadocTag SERIAL_DATA = new JavadocTag("serialData", " ");
public static final JavadocTag SERIAL_FIELD = new JavadocTag("serialField"," ");
public static final JavadocTag GENERATED = new JavadocTag("generated", " ");
public static final JavadocTag GENERATED_BY = new JavadocTag("generatedBy"," "); */
private JavadocTag(String theLabel, String theDescription) {
label = theLabel;
description = theDescription;
if (TAGS_BY_ID.containsKey(theLabel)) {
throw new IllegalArgumentException("pre-existing tag!");
}
TAGS_BY_ID.put(theLabel, this);
}
public static JavadocTag tagFor(String id) {
return TAGS_BY_ID.get(id);
}
public static Set<String> allTagIds() {
return TAGS_BY_ID.keySet();
}
}
| 2,721 | 43.622951 | 116 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/package-info.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
/**
* Support for compile-time type resolution on the AST.
*/
package net.sourceforge.pmd.lang.java.types;
/*
TODO: inference of `throws` clause
-> pretty hard, see throws constraint formulas in JLS 18
import java.io.IOException;
@FunctionalInterface
interface ThrowingRunnable<E extends Throwable> {
void run() throws E;
}
class Scratch {
static <E extends Throwable> void wrap(ThrowingRunnable<? extends E> runnable) throws E {
runnable.run();
}
static void runThrowing() throws IOException {
throw new IOException();
}
{
try {
wrap(Scratch::runThrowing); // throws IOException
} catch (IOException e) {
}
}
}
*/
/* TODO possibly, the type node for a diamond should have the parameterized
type, for now it's the generic type declaration, which has out-of-scope
type params
See TypesFromAst
import java.util.ArrayList;
class O {
{
List<String> l = new ArrayList<>();
// -----------
// maybe this node should have type ArrayList<String>
// Note that the whole expression already has type ArrayList<String> after inference
}
}
*/
/* TODO test bridge method execution filtering
In AsmLoaderTest
*/
/* TODO finish NamedReferenceExpr by patching LazyTypeResolver
this needs tests, will be done in fwd branch
*/
/* TODO test explicitly typed lambda (in ExplicitTypesTest)
wildcard parameterization inference is not implemented yet.
*/
| 1,639 | 19 | 93 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/JPrimitiveType.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
/**
* Mirror a primitive types. Even though {@code void.class.isPrimitive()}
* returns true, we don't treat it as such and represent it with
* {@link TypeSystem#NO_TYPE} instead.
*/
public final class JPrimitiveType implements JTypeMirror {
Set<JTypeMirror> superTypes; // set by the constructor of TypeSystem
private final TypeSystem ts;
private final PrimitiveTypeKind kind;
/** Primitive class. */
private final JClassSymbol type;
/** Boxed representation. */
private final JClassType box;
private final PSet<SymAnnot> typeAnnots;
JPrimitiveType(TypeSystem ts, PrimitiveTypeKind kind, JClassSymbol type, JClassSymbol boxType, PSet<SymAnnot> typeAnnots) {
this.ts = ts;
this.kind = kind;
this.type = type;
this.typeAnnots = typeAnnots;
this.box = new BoxedPrimitive(ts, boxType, this, typeAnnots); // not erased
}
private JPrimitiveType(JPrimitiveType pType, PSet<SymAnnot> typeAnnots) {
this(pType.ts, pType.kind, pType.type, pType.box.getSymbol(), typeAnnots);
this.superTypes = pType.superTypes; // Shared instance
}
@Override
public PSet<SymAnnot> getTypeAnnotations() {
return typeAnnots;
}
@Override
public JTypeMirror withAnnotations(PSet<SymAnnot> newTypeAnnots) {
if (newTypeAnnots.isEmpty() && this.typeAnnots.isEmpty()) {
return this;
}
return new JPrimitiveType(this, newTypeAnnots);
}
@Override
public TypeSystem getTypeSystem() {
return ts;
}
@Override
public JClassType box() {
return box;
}
@Override
public JPrimitiveType unbox() {
return this;
}
@Override
public JTypeMirror getErasure() {
return this;
}
/**
* Returns the type of the primitive class, eg {@link Integer#TYPE}.
* The returned type {@link Class#isPrimitive()} is true.
*/
@Override
public @NonNull JClassSymbol getSymbol() {
return type;
}
@Override
public boolean isNumeric() {
return kind != PrimitiveTypeKind.BOOLEAN;
}
@Override
public boolean isPrimitive(PrimitiveTypeKind kind) {
return this.kind == Objects.requireNonNull(kind, "null kind");
}
@Override
public boolean isFloatingPoint() {
return kind == PrimitiveTypeKind.DOUBLE || kind == PrimitiveTypeKind.FLOAT;
}
@Override
public boolean isIntegral() {
return kind != PrimitiveTypeKind.BOOLEAN && !isFloatingPoint();
}
@Override
public boolean isPrimitive() {
return true;
}
@Override
public Set<JTypeMirror> getSuperTypeSet() {
return superTypes;
}
@Override
public String toString() {
return TypePrettyPrint.prettyPrint(this);
}
@Override
public boolean equals(Object obj) {
return obj instanceof JPrimitiveType && ((JPrimitiveType) obj).kind == this.kind;
}
@Override
public int hashCode() {
return kind.hashCode();
}
/**
* Returns the token used to represent the type in source,
* e.g. "int" or "double".
*/
public @NonNull String getSimpleName() {
return kind.name;
}
public PrimitiveTypeKind getKind() {
return kind;
}
@Override
public <T, P> T acceptVisitor(JTypeVisitor<T, P> visitor, P p) {
return visitor.visitPrimitive(this, p);
}
@Override
public JTypeMirror subst(Function<? super SubstVar, ? extends @NonNull JTypeMirror> subst) {
return this;
}
public enum PrimitiveTypeKind {
BOOLEAN(boolean.class),
CHAR(char.class),
BYTE(byte.class),
SHORT(short.class),
INT(int.class),
LONG(long.class),
FLOAT(float.class),
DOUBLE(double.class);
final String name = name().toLowerCase(Locale.ROOT);
private final Class<?> jvm;
PrimitiveTypeKind(Class<?> jvm) {
this.jvm = jvm;
}
public String getSimpleName() {
return name;
}
@Override
public String toString() {
return name;
}
public Class<?> jvmRepr() {
return jvm;
}
/**
* Gets an enum constant from the token used to represent it in source,
* e.g. "int" or "double". Note that "void" is not a valid primitive name
* in this API, and this would return null in this case.
*
* @param token String token
*
* @return A constant, or null if the string doesn't correspond
* to a primitive type
*/
public static @Nullable PrimitiveTypeKind fromName(String token) {
switch (token) {
case "boolean": return BOOLEAN;
case "char": return CHAR;
case "byte": return BYTE;
case "short": return SHORT;
case "int": return INT;
case "long": return LONG;
case "float": return FLOAT;
case "double": return DOUBLE;
default:
return null;
}
}
}
}
| 5,714 | 25.336406 | 127 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/JTypeVisitable.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.util.function.Function;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* Common supertype for {@link JMethodSig} and {@link JTypeMirror}.
* Those are the kinds of objects that a {@link JTypeVisitor} can
* explore.
*/
public interface JTypeVisitable {
/**
* Replace the type variables occurring in the given type by their
* image by the given function. Substitutions are not applied
* recursively (ie, is not applied on the result of a substitution).
*
* @param subst Substitution function, eg a {@link Substitution}
*/
JTypeVisitable subst(Function<? super SubstVar, ? extends @NonNull JTypeMirror> subst);
/**
* Accept a type visitor, dispatching on this object's runtime type
* to the correct method of the visitor.
*
* @param <P> Type of data of the visitor
* @param <T> Type of result of the visitor
*/
<T, P> T acceptVisitor(JTypeVisitor<T, P> visitor, P p);
}
| 1,114 | 28.342105 | 91 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/JVariableSig.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.util.Objects;
import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol;
import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol;
import net.sourceforge.pmd.lang.java.symbols.table.JSymbolTable;
/**
* Represents a {@link JVariableSymbol value symbol} viewed in the context
* of a particular program point (ie under a particular {@link Substitution}).
*
* <p>The type given to a symbol is context-dependent. For example,
* when looking in the supertypes of the current class for a field, we
* have:
* <pre>{@code
*
* abstract class Sup<K> {
* K field;
*
* // In this scope the type of `field` is `K`, an abstract type variable
*
* }
*
*
* class Foo extends Sup<Integer> {
*
* {
* // in this scope, the type of `super.field` is `Integer`, not `K`,
* // because we inherit `Sup` where `K` is substituted with `Integer`.
* // `K` is not even in scope.
*
* super.field = 2;
* }
*
* }
*
* }</pre>
*
* <p>This interface plays a similar role to {@link JMethodSig}. It is
* the type of search results of a {@link JSymbolTable}, see
* {@link JSymbolTable#variables()}.
*/
public class JVariableSig {
private final JVariableSymbol sym;
private final JTypeMirror declarator;
private JVariableSig(JTypeMirror declarator, JVariableSymbol sym) {
assert sym != null;
assert declarator != null;
this.sym = sym;
this.declarator = declarator;
}
/**
* This is the substituted type. Eg in the example of the class javadoc,
* for {@code super.field}, this would be {@code Sup<Integer>}. For local
* variables, this is always the generic type declaration of the enclosing
* type.
*/
// mm so this thing is useless except for FieldSig
// Looks weird to me. Also getTypeMirror is captured by LazyTypeResolver
// but not this one.
public JTypeMirror getDeclaringType() {
return declarator;
}
/**
* Returns the symbol for this variable.
*/
public JVariableSymbol getSymbol() {
return sym;
}
/**
* Returns the type given to the symbol in the particular scope this
* signature is valid in.
*/
public JTypeMirror getTypeMirror() {
Substitution subst = declarator instanceof JClassType
? ((JClassType) declarator).getTypeParamSubst()
: Substitution.EMPTY; // array
return declarator.isRaw() ? ClassTypeImpl.eraseToRaw(sym.getTypeMirror(Substitution.EMPTY), subst)
: sym.getTypeMirror(subst);
}
static JVariableSig.FieldSig forField(JTypeMirror declarator, JFieldSymbol sym) {
return new JVariableSig.FieldSig(declarator, sym);
}
static JVariableSig forLocal(JClassType declarator, JVariableSymbol sym) {
return new JVariableSig(declarator, sym);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof JVariableSig) || o.getClass() != this.getClass()) {
return false;
}
JVariableSig that = (JVariableSig) o;
return Objects.equals(sym, that.sym)
&& Objects.equals(declarator, that.declarator);
}
@Override
public int hashCode() {
return Objects.hash(sym, declarator);
}
@Override
public String toString() {
return "Signature of " + sym + " in " + declarator;
}
/**
* A field signature.
*/
public static final class FieldSig extends JVariableSig {
FieldSig(JTypeMirror declarator, JFieldSymbol sym) {
super(declarator, sym);
}
@Override
public JFieldSymbol getSymbol() {
return (JFieldSymbol) super.sym;
}
}
}
| 4,002 | 27.190141 | 106 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/SentinelType.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.util.Collections;
import java.util.Set;
import java.util.function.Function;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.pcollections.HashTreePSet;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
/**
* A "type" that exists outside the main type hierarchy. This is only
* used to have some sentinel values, to e.g. represent failure or errors.
*/
final class SentinelType implements JTypeMirror {
private final TypeSystem ts;
private final String name;
private final JTypeDeclSymbol symbol;
SentinelType(TypeSystem ts, String name, @NonNull JTypeDeclSymbol symbol) {
this.ts = ts;
this.name = name;
this.symbol = symbol;
}
@Override
public JTypeMirror withAnnotations(PSet<SymAnnot> newTypeAnnots) {
return this;
}
@Override
public PSet<SymAnnot> getTypeAnnotations() {
return HashTreePSet.empty();
}
@Override
public @NonNull JTypeDeclSymbol getSymbol() {
return symbol;
}
@Override
public JTypeMirror subst(Function<? super SubstVar, ? extends @NonNull JTypeMirror> subst) {
return this;
}
@Override
public TypeSystem getTypeSystem() {
return ts;
}
@Override
public Set<JTypeMirror> getSuperTypeSet() {
return Collections.singleton(this);
}
@Override
public <T, P> T acceptVisitor(JTypeVisitor<T, P> visitor, P p) {
return visitor.visitSentinel(this, p);
}
@Override
public String toString() {
return name;
}
}
| 1,816 | 23.554054 | 96 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/ArraySymbolImpl.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import java.lang.reflect.Modifier;
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.objectweb.asm.Opcodes;
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.symbols.SymbolVisitor;
import net.sourceforge.pmd.lang.java.symbols.internal.ImplicitMemberSymbols;
import net.sourceforge.pmd.lang.java.symbols.internal.SymbolEquality;
import net.sourceforge.pmd.lang.java.symbols.internal.SymbolToStrings;
/**
* Generic implementation for array symbols, which does not rely on
* reflection.
*/
class ArraySymbolImpl implements JClassSymbol {
// Like Class::getModifiers, we preserve the public/private/protected flag
private static final int COMPONENT_MOD_MASK =
Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED | Opcodes.ACC_PUBLIC;
private final TypeSystem ts;
private final JTypeDeclSymbol component;
ArraySymbolImpl(TypeSystem ts, JTypeDeclSymbol component) {
this.component = Objects.requireNonNull(component, "Array symbol requires component");
this.ts = Objects.requireNonNull(ts, "Array symbol requires symbol factory");
if (component instanceof JClassSymbol && ((JClassSymbol) component).isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous classes cannot be array components: " + component);
}
}
@Override
public TypeSystem getTypeSystem() {
return ts;
}
@Override
public @NonNull String getBinaryName() {
if (component instanceof JClassSymbol) {
return ((JClassSymbol) component).getBinaryName() + "[]";
}
return component.getSimpleName() + "[]";
}
@Override
public String getCanonicalName() {
if (component instanceof JClassSymbol) {
String compName = ((JClassSymbol) component).getCanonicalName();
return compName == null ? null : compName + "[]";
}
return component.getSimpleName() + "[]";
}
@Override
public boolean isUnresolved() {
return false;
}
@Override
public @Nullable JExecutableSymbol getEnclosingMethod() {
return null;
}
@Override
public List<JMethodSymbol> getDeclaredMethods() {
return Collections.singletonList(ImplicitMemberSymbols.arrayClone(this));
}
@Override
public List<JFieldSymbol> getDeclaredFields() {
return Collections.singletonList(ImplicitMemberSymbols.arrayLengthField(this));
}
@Override
public @Nullable JClassSymbol getSuperclass() {
return getTypeSystem().OBJECT.getSymbol();
}
@Override
public List<JClassSymbol> getSuperInterfaces() {
return listOf(getTypeSystem().CLONEABLE.getSymbol(), getTypeSystem().SERIALIZABLE.getSymbol());
}
@Override
public List<JClassType> getSuperInterfaceTypes(Substitution substitution) {
return listOf(getTypeSystem().CLONEABLE, getTypeSystem().SERIALIZABLE);
}
@Override
public @Nullable JClassType getSuperclassType(Substitution substitution) {
return getTypeSystem().OBJECT;
}
@Override
public @NonNull JTypeDeclSymbol getArrayComponent() {
return component;
}
@Override
public <R, P> R acceptVisitor(SymbolVisitor<R, P> visitor, P param) {
return visitor.visitArray(this, component, param);
}
@Override
public boolean equals(Object o) {
return SymbolEquality.equals(this, o);
}
@Override
public int hashCode() {
return SymbolEquality.hash(this);
}
@Override
public boolean isAnnotation() {
return false;
}
@Override
public List<JClassSymbol> getDeclaredClasses() {
return Collections.emptyList();
}
@Override
public List<JConstructorSymbol> getConstructors() {
return Collections.singletonList(ImplicitMemberSymbols.arrayConstructor(this));
}
@Override
@NonNull
public String getPackageName() {
return getArrayComponent().getPackageName();
}
@Override
@NonNull
public String getSimpleName() {
return getArrayComponent().getSimpleName() + "[]";
}
@Override
public int getModifiers() {
int comp = getArrayComponent().getModifiers() & COMPONENT_MOD_MASK;
return Modifier.FINAL | Modifier.ABSTRACT | comp;
}
@Override
public List<JTypeVar> getTypeParameters() {
return Collections.emptyList();
}
@Override
@Nullable
public JClassSymbol getEnclosingClass() {
return null;
}
@Override
public boolean isArray() {
return true;
}
@Override
public boolean isPrimitive() {
return false;
}
@Override
public boolean isInterface() {
return false;
}
@Override
public boolean isEnum() {
return false;
}
@Override
public boolean isRecord() {
return false;
}
@Override
public boolean isLocalClass() {
return false;
}
@Override
public boolean isAnonymousClass() {
return false;
}
@Override
public String toString() {
return SymbolToStrings.SHARED.toString(this);
}
}
| 5,873 | 26.069124 | 109 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/LexicalScope.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import static net.sourceforge.pmd.util.CollectionUtil.associateByTo;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An index of type variables by name.
*/
public final class LexicalScope extends MapFunction<String, @Nullable JTypeVar> {
/** The empty scope contains no vars. */
public static final LexicalScope EMPTY = new LexicalScope(Collections.emptyMap());
private LexicalScope(Map<String, ? extends JTypeVar> map) {
super(Collections.unmodifiableMap(map));
}
/**
* Returns the type var with the given name, or null.
*/
@Override
public @Nullable JTypeVar apply(@NonNull String var) {
return getMap().get(var);
}
/**
* Return a new scope which contains the given tvars. They shadow
* tvars that were in this scope.
*/
public LexicalScope andThen(List<? extends JTypeVar> vars) {
if (this == EMPTY && vars.isEmpty()) { // NOPMD CompareObjectsWithEquals
return EMPTY;
}
return new LexicalScope(associateByTo(new HashMap<>(getMap()), vars, JTypeVar::getName));
}
}
| 1,411 | 27.24 | 97 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/ErasedClassType.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.util.Collections;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
final class ErasedClassType extends ClassTypeImpl {
ErasedClassType(TypeSystem typeSystem, JClassSymbol symbol, PSet<SymAnnot> typeAnnots) {
super(typeSystem, symbol, Collections.emptyList(), true, typeAnnots);
}
@Override
public boolean hasErasedSuperTypes() {
return true;
}
@Override
public JClassType getErasure() {
return this;
}
}
| 721 | 23.066667 | 92 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/JTypeVar.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.util.Collection;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeParameterSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
/**
* The type of a type variable. There are two sorts of those:
*
* <ul>
* <li>Types of type parameters, which have a user-defined name, and an origin.
* Those may only have an {@linkplain #getUpperBound() upper bound}.
* <li>Types of {@linkplain #isCaptured() captured variables}, which arise
* from {@linkplain TypeConversion#capture(JTypeMirror) capture-conversion}. Those can
* have a non-trivial lower bound.
* </ul>
*
* <p>Type variables may appear in their own bound (F-bound), and we
* have to make sure all those occurrences are represented by the same instance.
* We have to pay attention to cycles in our algos too.
*
* <p>Type variables do not, in general, use reference identity. Use
* equals to compare them.
*/
public interface JTypeVar extends JTypeMirror, SubstVar {
/**
* Returns the reflected type variable this instance represents,
* or null if this is a capture variable.
*/
@Override
@Nullable JTypeParameterSymbol getSymbol();
/**
* Returns the name of this variable, which may something
* autogenerated if this is a captured variable. This is not necessarily
* an identifier.
*/
@NonNull String getName();
/**
* Gets the upper bound. This defaults to Object, and may be an
* {@linkplain JIntersectionType intersection type}.
*
* <p>Note that the upper bound of a capture variable is not necessarily
* the upper bound of the {@linkplain #getCapturedOrigin() captured wildcard}.
* The declared bound of each variable is {@link TypeSystem#glb(Collection) glb}ed with the declared
* bound of the wildcard. For example, given {@code class Foo<T extends List<T>>},
* then {@code Foo<?>} will have {@link TypeSystem#UNBOUNDED_WILD} as a type
* argument. But the capture of {@code Foo<?>} will look like {@code Foo<capture#.. of ?>},
* where the capture var's upper bound is actually {@code List<?>}.
*/
@NonNull JTypeMirror getUpperBound();
/**
* Gets the lower bound. {@link TypeSystem#NULL_TYPE} conventionally represents
* the bottom type (a trivial lower bound).
*/
@NonNull
JTypeMirror getLowerBound();
/**
* Returns true if this is a capture variable, ie this variable
* originates from the {@linkplain TypeConversion#capture(JTypeMirror) capture} of a wildcard
* type argument. Capture variables use reference identity.
*/
boolean isCaptured();
/**
* Returns true if this is a capture variable for the given wildcard.
*/
boolean isCaptureOf(JWildcardType wildcard);
/**
* Returns the original wildcard, if this is a capture variable.
* Otherwise returns null.
*/
@Nullable JWildcardType getCapturedOrigin();
@Override
default <T, P> T acceptVisitor(JTypeVisitor<T, P> visitor, P p) {
return visitor.visitTypeVar(this, p);
}
/**
* Like {@link #subst(Function)}, except this typevar is not the
* subject of the substitution, only its bounds. May return a new
* tvar, must return this is the bound is unchanged.
*/
JTypeVar substInBounds(Function<? super SubstVar, ? extends @NonNull JTypeMirror> substitution);
/**
* @throws UnsupportedOperationException If this is not a capture var
*/
JTypeVar cloneWithBounds(JTypeMirror lower, JTypeMirror upper);
/**
* Return a new type variable with the same underlying symbol or
* capture variable, but the upper bound is now the given type.
*
* @param newUB New upper bound
*
* @return a new tvar
*/
JTypeVar withUpperBound(@NonNull JTypeMirror newUB);
@Override // refine return type
JTypeVar withAnnotations(PSet<SymAnnot> newTypeAnnots);
@Override
default JTypeVar addAnnotation(@NonNull SymAnnot newAnnot) {
return withAnnotations(getTypeAnnotations().plus(Objects.requireNonNull(newAnnot)));
}
@Override
default Stream<JMethodSig> streamMethods(Predicate<? super JMethodSymbol> prefilter) {
// recursively bound type vars will throw this into an infinite cycle
// eg <T extends X, X extends T>
// this is a compile-time error though
return getUpperBound().streamMethods(prefilter);
}
}
| 4,934 | 32.80137 | 104 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/Substitution.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import static net.sourceforge.pmd.util.CollectionUtil.associateWith;
import static net.sourceforge.pmd.util.CollectionUtil.zip;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Function;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.util.AssertionUtil;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* A function from {@link SubstVar}s to types. Applying it to a type
* replaces the occurrences of some variables with other types. This
* can be done with {@link TypeOps#subst(JTypeMirror, Function)}.
*/
public final class Substitution extends MapFunction<@NonNull SubstVar, @NonNull JTypeMirror> {
/** The empty substitution maps every type variable to itself. */
public static final Substitution EMPTY = new Substitution(Collections.emptyMap());
Substitution(Map<@NonNull SubstVar, @NonNull JTypeMirror> map) {
super(map);
}
public static boolean isEmptySubst(Function<?, ?> m) {
return m == EMPTY || m instanceof MapFunction && ((MapFunction<?, ?>) m).isEmpty();
}
/** Returns the type with which the given variable should be replaced. */
@Override
public @NonNull JTypeMirror apply(@NonNull SubstVar var) {
return getMap().getOrDefault(var, var);
}
/**
* Returns a composed substitution that first applies this substitution
* to its input, and then applies the {@code after} substitution to the
* result.
*
* <p>Given two substitutions S1, S2 and a type t:
* <br>
* {@code subst(subst(t, S1), S2) == subst(t, S1.andThen(S2)) }
*
* <p>For example:
* <pre>{@code
* S1 = [ T -> A<U> ]
* S2 = [ U -> B<V> ]
*
* subst(List<T>, S1) = List<A<U>>
* subst(List<A<U>>, S2) = List<A<B<V>>>
*
* S1.andThen(S2) = [ T -> A<B<V>>, U -> B<V> ]
* }</pre>
*
* @param other the function to apply after this function is applied
*
* @return a composed substitution
*
* @throws NullPointerException if other is null
*/
public Substitution andThen(Substitution other) {
AssertionUtil.requireParamNotNull("subst", other);
if (other.isEmpty()) {
return this;
}
Map<SubstVar, JTypeMirror> newSubst = new HashMap<>(other.getMap());
for (Entry<SubstVar, JTypeMirror> entry : getMap().entrySet()) {
JTypeMirror substed = entry.getValue().subst(other);
newSubst.put(entry.getKey(), substed);
}
return new Substitution(newSubst);
}
/**
* Maps the given variable to the given type. This does not apply
* this substitution to the type mirror.
*/
public Substitution plus(SubstVar from, JTypeMirror to) {
return new Substitution(CollectionUtil.plus(getMap(), from, to));
}
/**
* Builds a substitution where the mapping from vars to types is
* defined by the correspondence between the two lists.
* <p>
* If there are no vars to be mapped, then no substitution is returned
* even though some types might have been supplied.
*
* @throws IllegalArgumentException If the two lists are of different lengths
* @throws NullPointerException If any of the two lists is null
*/
public static Substitution mapping(List<? extends SubstVar> from, List<? extends JTypeMirror> to) {
AssertionUtil.requireParamNotNull("from", from);
AssertionUtil.requireParamNotNull("to", to);
if (from.isEmpty()) {
return EMPTY;
}
// zip throws IllegalArgumentException if the lists are of different lengths
return new Substitution(zip(from, to));
}
/**
* Returns a substitution that replaces the given type variables
* with their erasure.
*
* @param tparams Type variables to erase
*/
public static Substitution erasing(List<? extends JTypeVar> tparams) {
if (tparams.isEmpty()) {
return EMPTY;
}
return new Substitution(associateWith(tparams, JTypeMirror::getErasure));
}
}
| 4,357 | 30.810219 | 103 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/TypeConversion.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import static java.util.Arrays.asList;
import static net.sourceforge.pmd.lang.java.types.JPrimitiveType.PrimitiveTypeKind.BYTE;
import static net.sourceforge.pmd.lang.java.types.JPrimitiveType.PrimitiveTypeKind.CHAR;
import static net.sourceforge.pmd.lang.java.types.JPrimitiveType.PrimitiveTypeKind.DOUBLE;
import static net.sourceforge.pmd.lang.java.types.JPrimitiveType.PrimitiveTypeKind.FLOAT;
import static net.sourceforge.pmd.lang.java.types.JPrimitiveType.PrimitiveTypeKind.LONG;
import static net.sourceforge.pmd.lang.java.types.JPrimitiveType.PrimitiveTypeKind.SHORT;
import java.util.ArrayList;
import java.util.List;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* Utility class for type conversions, as defined in <a href="https://docs.oracle.com/javase/specs/jls/se10/html/jls-5.html">JLS§5</a>.
*/
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public final class TypeConversion {
private TypeConversion() {
}
/**
* Performs <a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-5.html#jls-5.6.1">Unary numeric promotion
* (JLS§5.6.1)</a>.
* <p>This occurs in the following situations:
* <ul>
* <li>Each dimension expression in an array creation expression (§15.10.1)
* <li>The index expression in an array access expression (§15.10.3)
* <li>The operand of a unary plus operator + (§15.15.3)
* <li>The operand of a unary minus operator - (§15.15.4)
* <li>The operand of a bitwise complement operator ~ (§15.15.5)
* <li>Each operand, separately, of a shift operator <<, >>, or >>> (§15.19).
* </ul>
*
* <p>Returns {@link TypeSystem#ERROR} if the given type is
* not a numeric type, {@link TypeSystem#UNKNOWN} if the type
* is unresolved.
*/
public static JTypeMirror unaryNumericPromotion(JTypeMirror t) {
t = t.unbox();
TypeSystem ts = t.getTypeSystem();
if (t.isPrimitive(BYTE) || t.isPrimitive(SHORT) || t.isPrimitive(CHAR)) {
return ts.INT;
}
return t.isNumeric() || t == ts.UNKNOWN ? t : ts.ERROR;
}
/**
* JLS§5.6.2
* https://docs.oracle.com/javase/specs/jls/se9/html/jls-5.html#jls-5.6.2
*
* Binary numeric promotion is performed on the operands of certain operators:
* <ul>
* <li>The multiplicative operators *, /, and % (§15.17)
* <li>The addition and subtraction operators for numeric types + and - (§15.18.2)
* <li>The numerical comparison operators <, <=, >, and >= (§15.20.1)
* <li>The numerical equality operators == and != (§15.21.1)
* <li>The integer bitwise operators &, ^, and | (§15.22.1)
* <li>In certain cases, the conditional operator ? : (§15.25)
* </ul>
* <p>Returns {@link TypeSystem#ERROR} if either of the parameters
* is not numeric. This DOES NOT care for unresolved types.
*/
public static JTypeMirror binaryNumericPromotion(JTypeMirror t, JTypeMirror s) {
JTypeMirror t1 = t.unbox();
JTypeMirror s1 = s.unbox();
TypeSystem ts = t.getTypeSystem();
if (t1.isPrimitive(DOUBLE) || s1.isPrimitive(DOUBLE)) {
return ts.DOUBLE;
} else if (t1.isPrimitive(FLOAT) || s1.isPrimitive(FLOAT)) {
return ts.FLOAT;
} else if (t1.isPrimitive(LONG) || s1.isPrimitive(LONG)) {
return ts.LONG;
} else if (t1.isNumeric() && s1.isNumeric()) {
return ts.INT;
} else {
// this is a typing error, both types should be referring to a numeric type
return ts.ERROR;
}
}
/**
* Is t convertible to s by boxing/unboxing/widening conversion?
* Only t can undergo conversion.
*/
public static boolean isConvertibleUsingBoxing(JTypeMirror t, JTypeMirror s) {
return isConvertibleCommon(t, s, false);
}
/**
* Is t convertible to s by boxing/unboxing conversion?
* Only t can undergo conversion.
*/
public static boolean isConvertibleInCastContext(JTypeMirror t, JTypeMirror s) {
return isConvertibleCommon(t, s, true);
}
private static boolean isConvertibleCommon(JTypeMirror t, JTypeMirror s, boolean isCastContext) {
TypeSystem ts = t.getTypeSystem();
if (t == ts.UNKNOWN || t == ts.ERROR) {
return true;
}
if (t instanceof InferenceVar || s instanceof InferenceVar) {
return t.box().isSubtypeOf(s.box());
}
if (t.isPrimitive() == s.isPrimitive()) {
return t.isConvertibleTo(s).bySubtyping();
}
if (isCastContext) {
return t.isPrimitive() ? t.box().isConvertibleTo(s).bySubtyping()
: t.isConvertibleTo(s.box()).bySubtyping();
} else {
return t.isPrimitive() ? t.box().isConvertibleTo(s).somehow()
: t.unbox().isConvertibleTo(s).somehow();
}
}
/**
* Perform capture conversion on the type t. This replaces wildcards
* with fresh type variables. Capture conversion is not applied recursively.
* Capture conversion on any type other than a parameterized type (§4.5) acts
* as an identity conversion (§5.1.1).
*
* @return The capture conversion of t
*/
public static JTypeMirror capture(JTypeMirror t) {
return t instanceof JClassType ? capture((JClassType) t) : t;
}
/**
* Perform capture conversion on the type t. This replaces wildcards
* with fresh type variables. Capture conversion is not applied recursively.
* Capture conversion on any type other than a parameterized type (§4.5) acts
* as an identity conversion (§5.1.1).
*
* @return The capture conversion of t
*/
public static JClassType capture(JClassType type) {
if (type == null) {
return null;
}
final @Nullable JClassType enclosing = capture(type.getEnclosingType());
if (enclosing == type.getEnclosingType() && !isWilcardParameterized(type)) {
return type; // 99% take this path
}
TypeSystem ts = type.getTypeSystem();
List<JTypeMirror> typeArgs = type.getTypeArgs();
List<JTypeVar> typeParams = type.getFormalTypeParams();
// This is the algorithm described at https://docs.oracle.com/javase/specs/jls/se10/html/jls-5.html#jls-5.1.10
// Let G name a generic type declaration (§8.1.2, §9.1.2)
// with n type parameters A1,...,An with corresponding bounds U1,...,Un.
// There exists a capture conversion from a parameterized type G<T1,...,Tn> (§4.5)
// to a parameterized type G<S1,...,Sn>, where, for 1 ≤ i ≤ n :
// -> see the loop
// typeParams is A1..An
// typeArgs is T1..Tn
// freshVars is S1..Sn
List<JTypeMirror> freshVars = makeFreshVars(type);
// types may be non-well formed if the symbol is unresolved
// in this case the typeParams list is most likely empty
boolean wellFormed = typeParams.size() == freshVars.size();
// Map of Ai to Si, for the substitution
Substitution subst = wellFormed ? Substitution.mapping(typeParams, freshVars) : Substitution.EMPTY;
for (int i = 0; i < typeArgs.size(); i++) {
JTypeMirror fresh = freshVars.get(i); // Si
JTypeMirror arg = typeArgs.get(i); // Ti
// we mutate the bounds to preserve the correct instance in
// the substitutions
if (arg instanceof JWildcardType) {
JWildcardType w = (JWildcardType) arg; // Ti alias
TypeVarImpl.CapturedTypeVar freshVar = (TypeVarImpl.CapturedTypeVar) fresh; // Si alias
JTypeMirror prevUpper = wellFormed ? typeParams.get(i).getUpperBound() : ts.OBJECT; // Ui
JTypeMirror substituted = TypeOps.subst(prevUpper, subst);
if (w.isUnbounded()) {
// If Ti is a wildcard type argument (§4.5.1) of the form ?,
// then Si is a fresh type variable whose upper bound is Ui[A1:=S1,...,An:=Sn]
// and whose lower bound is the null type (§4.1).
freshVar.setUpperBound(substituted);
freshVar.setLowerBound(ts.NULL_TYPE);
} else if (w.isUpperBound()) {
// If Ti is a wildcard type argument of the form ? extends Bi,
// then Si is a fresh type variable whose upper bound is glb(Bi, Ui[A1:=S1,...,An:=Sn])
// and whose lower bound is the null type.
freshVar.setUpperBound(ts.glb(asList(substituted, w.getBound())));
freshVar.setLowerBound(ts.NULL_TYPE);
} else {
// If Ti is a wildcard type argument of the form ? super Bi,
// then Si is a fresh type variable whose upper bound is Ui[A1:=S1,...,An:=Sn]
// and whose lower bound is Bi.
freshVar.setUpperBound(substituted);
freshVar.setLowerBound(w.getBound());
}
}
}
if (enclosing != null) {
return enclosing.selectInner(type.getSymbol(), freshVars);
} else {
return type.withTypeArguments(freshVars);
}
}
/**
* Returns true if the type is a parameterized class type, which has
* wildcards as type arguments. Capture variables don't count.
*/
public static boolean isWilcardParameterized(JTypeMirror t) {
return t instanceof JClassType
&& CollectionUtil.any(((JClassType) t).getTypeArgs(), it -> it instanceof JWildcardType);
}
private static List<JTypeMirror> makeFreshVars(JClassType type) {
List<JTypeMirror> freshVars = new ArrayList<>(type.getTypeArgs().size());
for (JTypeMirror typeArg : type.getTypeArgs()) {
if (typeArg instanceof JWildcardType) {
freshVars.add(TypeVarImpl.freshCapture((JWildcardType) typeArg));
} else {
freshVars.add(typeArg);
}
}
return freshVars;
}
}
| 10,565 | 39.174905 | 135 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/TypeSystem.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import static net.sourceforge.pmd.util.CollectionUtil.emptyList;
import static net.sourceforge.pmd.util.CollectionUtil.immutableSetOf;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
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.JavaNode;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
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.JLocalVariableSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeParameterSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolResolver;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.lang.java.symbols.internal.UnresolvedClassStore;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.AsmSymbolResolver;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.Classpath;
import net.sourceforge.pmd.lang.java.types.BasePrimitiveSymbol.RealPrimitiveSymbol;
import net.sourceforge.pmd.lang.java.types.BasePrimitiveSymbol.VoidSymbol;
import net.sourceforge.pmd.lang.java.types.JPrimitiveType.PrimitiveTypeKind;
import net.sourceforge.pmd.util.AssertionUtil;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* Root context object for type analysis. Type systems own a global
* {@link SymbolResolver}, which creates and caches external symbols.
* Methods of this class promote symbols to types, and compose types together.
* {@link TypeOps} and {@link TypeConversion} have some more operations on types.
*
* <p>Some special types are presented as constant fields, eg {@link #OBJECT}
* or {@link #NULL_TYPE}. These are always comparable by reference.
* Note that the primitive wrapper types are not exposed as constants
* here, but can be accessed by using the {@link JTypeMirror#box() box}
* method on some primitive constant.
*
* <p>The lifetime of a type system is the analysis: it is shared by
* all compilation units.
* TODO this is hacked together by comparing the ClassLoader, but this
* should be in the language instance
*
* <p>Nodes have a reference to the type system they were created for:
* {@link JavaNode#getTypeSystem()}.
*/
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public final class TypeSystem {
/**
* Top type of the reference type system. This is the type for the
* {@link Object} class. Note that even interfaces have this type
* as a supertype ({@link JTypeMirror#getSuperTypeSet()}).
*/
public final JClassType OBJECT;
/**
* The bottom type of the reference type system. This is named
* the <i>null type</i> in the JLS and is not denotable in Java
* programs.
*
* <p>This implementation uses this as the type of the 'null' literal.
*
* <p>The null type has no symbol.
*/
public final JTypeMirror NULL_TYPE = new NullType(this);
/** Primitive type {@code boolean}. */
public final JPrimitiveType BOOLEAN;
/** Primitive type {@code char}. */
public final JPrimitiveType CHAR;
/** Primitive type {@code byte}. */
public final JPrimitiveType BYTE;
/** Primitive type {@code short}. */
public final JPrimitiveType SHORT;
/** Primitive type {@code int}. */
public final JPrimitiveType INT;
/** Primitive type {@code long}. */
public final JPrimitiveType LONG;
/** Primitive type {@code float}. */
public final JPrimitiveType FLOAT;
/** Primitive type {@code double}. */
public final JPrimitiveType DOUBLE;
/**
* The set of all primitive types. See {@link #getPrimitive(PrimitiveTypeKind)}.
*/
public final Set<JPrimitiveType> allPrimitives;
private final Map<PrimitiveTypeKind, JPrimitiveType> primitivesByKind;
/**
* A constant to represent the normal absence of a type. The
* primitive {@code void.class} represents that type, and this
* is the return type of a void method.
*
* <p>Note that the type of the class literal {@code void.class}
* is {@code Class<java.lang.Void>}, not NO_TYPE.
*
* <p>{@code java.lang.Void} is represented by {@link #BOXED_VOID}.
* Note that {@code BOXED_VOID.unbox() != NO_TYPE}, {@code NO_TYPE.box() != BOXED_VOID}.
*
* <p>{@code NO_TYPE.isPrimitive()} returns false, even though
* {@code void.class.isPrimitive()} returns true.
*/
public final JTypeMirror NO_TYPE;
/**
* A constant to represent an unresolved type. This means, that resolution
* was attempted but failed and shouldn't be tried again. The symbol
* is a {@link JClassSymbol}.
*
* <p>Note that {@link TypeOps#isConvertible(JTypeMirror, JTypeMirror)}
* considers this type a subtype of anything, even primitive types.
*/
public final JTypeMirror UNKNOWN;
/**
* A constant to represent a typing error. This would have been
* reported by a compiler, and is used to propagate errors.
*
* <p>Note that {@link TypeOps#isConvertible(JTypeMirror, JTypeMirror)}
* considers this type a subtype of anything, even primitive types.
*/
public final JTypeMirror ERROR;
/**
* Sentinel value for an unresolved method. This type corresponds to
* a method declaration in the type {@link #UNKNOWN}, returning {@link #UNKNOWN}.
*/
public final JMethodSig UNRESOLVED_METHOD = new UnresolvedMethodSig(this);
/*
* Common, non-special types.
*/
/** The unbounded wildcard, "?". */
public final JWildcardType UNBOUNDED_WILD;
/** The interface Cloneable. This is included because it is a supertype of array types. */
public final JClassType CLONEABLE;
/** The interface Serializable. This is included because it is a supertype of array types. */
public final JClassType SERIALIZABLE;
/**
* This is the boxed type of {@code Void.class}, not to be confused with
* {@code void.class}, which in this framework is represented by
* {@link #NO_TYPE}.
*
* <p>Note that {@code BOXED_VOID.unbox() != NO_TYPE}, {@code NO_TYPE.box() != BOXED_VOID}.
*/
public final JClassType BOXED_VOID;
/** Contains special types, that must be shared to be comparable by reference. */
private final Map<JTypeDeclSymbol, JTypeMirror> sharedTypes;
// test only
final SymbolResolver resolver;
/**
* Builds a new type system. Its public fields will be initialized
* with fresh types, unrelated to other types.
*
* @param bootstrapResourceLoader Classloader used to resolve class files
* to populate the fields of the new type
* system
*/
public static TypeSystem usingClassLoaderClasspath(ClassLoader bootstrapResourceLoader) {
return usingClasspath(Classpath.forClassLoader(bootstrapResourceLoader));
}
/**
* Builds a new type system. Its public fields will be initialized
* with fresh types, unrelated to other types.
*
* @param bootstrapResourceLoader Classpath used to resolve class files
* to populate the fields of the new type
* system
*/
public static TypeSystem usingClasspath(Classpath bootstrapResourceLoader) {
return new TypeSystem(ts -> new AsmSymbolResolver(ts, bootstrapResourceLoader));
}
/**
* Builds a new type system. Its public fields will be initialized
* with fresh types, unrelated to other types.
*
* @param symResolverMaker A function that creates a new symbol
* resolver, which will be owned by the
* new type system. Because of cyclic
* dependencies, the new type system
* is leaked before its initialization
* completes, so fields of the type system
* are unusable at that time.
* The resolver is used to create some shared
* types: {@link #OBJECT}, {@link #CLONEABLE},
* {@link #SERIALIZABLE}, {@link #BOXED_VOID}.
*/
public TypeSystem(Function<TypeSystem, ? extends SymbolResolver> symResolverMaker) {
this.resolver = symResolverMaker.apply(this); // leak the this
// initialize primitives. their constructor also initializes their box + box erasure
BOOLEAN = createPrimitive(PrimitiveTypeKind.BOOLEAN, Boolean.class);
CHAR = createPrimitive(PrimitiveTypeKind.CHAR, Character.class);
BYTE = createPrimitive(PrimitiveTypeKind.BYTE, Byte.class);
SHORT = createPrimitive(PrimitiveTypeKind.SHORT, Short.class);
INT = createPrimitive(PrimitiveTypeKind.INT, Integer.class);
LONG = createPrimitive(PrimitiveTypeKind.LONG, Long.class);
FLOAT = createPrimitive(PrimitiveTypeKind.FLOAT, Float.class);
DOUBLE = createPrimitive(PrimitiveTypeKind.DOUBLE, Double.class);
BOOLEAN.superTypes = immutableSetOf(BOOLEAN);
CHAR.superTypes = immutableSetOf(CHAR, INT, LONG, FLOAT, DOUBLE);
BYTE.superTypes = immutableSetOf(BYTE, SHORT, INT, LONG, FLOAT, DOUBLE);
SHORT.superTypes = immutableSetOf(SHORT, INT, LONG, FLOAT, DOUBLE);
INT.superTypes = immutableSetOf(INT, LONG, FLOAT, DOUBLE);
LONG.superTypes = immutableSetOf(LONG, FLOAT, DOUBLE);
FLOAT.superTypes = immutableSetOf(FLOAT, DOUBLE);
DOUBLE.superTypes = immutableSetOf(DOUBLE);
this.allPrimitives = immutableSetOf(BOOLEAN, CHAR, BYTE, SHORT, INT, LONG, FLOAT, DOUBLE);
this.primitivesByKind = new EnumMap<>(PrimitiveTypeKind.class);
primitivesByKind.put(PrimitiveTypeKind.BOOLEAN, BOOLEAN);
primitivesByKind.put(PrimitiveTypeKind.CHAR, CHAR);
primitivesByKind.put(PrimitiveTypeKind.BYTE, BYTE);
primitivesByKind.put(PrimitiveTypeKind.SHORT, SHORT);
primitivesByKind.put(PrimitiveTypeKind.INT, INT);
primitivesByKind.put(PrimitiveTypeKind.LONG, LONG);
primitivesByKind.put(PrimitiveTypeKind.FLOAT, FLOAT);
primitivesByKind.put(PrimitiveTypeKind.DOUBLE, DOUBLE);
// note that those intentionally have names that are invalid as java identifiers
// todo those special types should probably have a special implementation here,
// so as not to depend on UnresolvedClassStore
UnresolvedClassStore unresolvedSyms = new UnresolvedClassStore(this);
JClassSymbol unresolvedTypeSym = unresolvedSyms.makeUnresolvedReference("(*unknown*)", 0);
UNKNOWN = new SentinelType(this, "(*unknown*)", unresolvedTypeSym);
JClassSymbol errorTypeSym = unresolvedSyms.makeUnresolvedReference("(*error*)", 0);
ERROR = new SentinelType(this, "(*error*)", errorTypeSym);
JClassSymbol primitiveVoidSym = new VoidSymbol(this);
NO_TYPE = new SentinelType(this, "void", primitiveVoidSym);
// reuse instances for common types
// this map is vital to preserve some of the invariants of
// the framework, e.g., that primitive types are never represented
// by a ClassType, or that OBJECT is unique
// this is only appropriate for non-generic types
Map<JClassSymbol, JTypeMirror> shared = new HashMap<>();
OBJECT = addSpecial(Object.class, shared);
SERIALIZABLE = addSpecial(Serializable.class, shared);
CLONEABLE = addSpecial(Cloneable.class, shared);
BOXED_VOID = addSpecial(Void.class, shared);
shared.put(primitiveVoidSym, NO_TYPE);
shared.put(unresolvedTypeSym, UNKNOWN);
shared.put(errorTypeSym, ERROR);
for (JPrimitiveType prim : allPrimitives) {
// primitives have a special implementation for their box
shared.put(prim.getSymbol(), prim);
shared.put(prim.box().getSymbol(), prim.box());
}
// make it really untouchable
this.sharedTypes = Collections.unmodifiableMap(new HashMap<>(shared));
UNBOUNDED_WILD = new WildcardTypeImpl(this, true, OBJECT, HashTreePSet.empty());
}
/**
* Returns the bootstrap symbol resolver. Concrete analysis passes
* may decorate this with different resolvers.
*/
public SymbolResolver bootstrapResolver() {
return resolver;
}
// helpers for the constructor, cannot use typeOf, only for trusted types
private JClassType addSpecial(Class<?> klass, Map<JClassSymbol, JTypeMirror> shared) {
JClassSymbol sym = getBootStrapSymbol(klass);
JClassType nonErased = new ClassTypeImpl(this, sym, HashTreePSet.empty());
shared.put(sym, nonErased);
return nonErased;
}
private JClassSymbol getBootStrapSymbol(Class<?> clazz) {
AssertionUtil.requireParamNotNull("clazz", clazz);
JClassSymbol sym = resolver.resolveClassFromBinaryName(clazz.getName());
return Objects.requireNonNull(sym, "sym");
}
private @NonNull JPrimitiveType createPrimitive(PrimitiveTypeKind kind, Class<?> box) {
return new JPrimitiveType(this, kind, new RealPrimitiveSymbol(this, kind), getBootStrapSymbol(box), HashTreePSet.empty());
}
// type creation routines
/**
* Returns the class symbol for the given reflected class. This asks
* the classloader of this type system. Returns null if the parameter
* is null, or the class is not available in the analysis classpath.
*
* @param clazz Class
*/
public @Nullable JClassSymbol getClassSymbol(@Nullable Class<?> clazz) {
if (clazz == null) {
return null;
} else if (clazz.isPrimitive()) {
PrimitiveTypeKind kind = PrimitiveTypeKind.fromName(clazz.getName());
if (kind == null) { // void
return (JClassSymbol) NO_TYPE.getSymbol();
}
return getPrimitive(kind).getSymbol();
} else if (clazz.isArray()) {
return new ArraySymbolImpl(this, getClassSymbol(clazz.getComponentType()));
}
return resolver.resolveClassFromBinaryName(clazz.getName());
}
/**
* Returns a symbol for the binary name. Returns null if the name is
* null or the symbol is not found on the classpath. The class must
* not be an array.
*
* @param binaryName Binary name
*
* @return A symbol, or null
*
* @throws IllegalArgumentException if the argument is not a binary name
*/
public @Nullable JClassSymbol getClassSymbol(String binaryName) {
return getClassSymbolImpl(binaryName, false);
}
/**
* Returns a symbol for the canonical name. Returns null if the name is
* null or the symbol is not found on the classpath. The class must
* not be an array.
*
* <p>Canonical names separate nested classes with {@code .}
* (periods) instead of {@code $} (dollars) as the JVM does. Users
* usually use canonical names, but lookup is much more costly.
*
* @param canonicalName Canonical name
*
* @return A symbol, or null
*
* @throws IllegalArgumentException if the argument is not a binary name
*/
public @Nullable JClassSymbol getClassSymbolFromCanonicalName(String canonicalName) {
return getClassSymbolImpl(canonicalName, true);
}
private @Nullable JClassSymbol getClassSymbolImpl(String name, boolean isCanonical) {
if (name == null) {
return null;
}
if ("void".equals(name)) {
return (JClassSymbol) NO_TYPE.getSymbol();
}
PrimitiveTypeKind kind = PrimitiveTypeKind.fromName(name);
if (kind != null) { // void
return getPrimitive(kind).getSymbol();
}
AssertionUtil.assertValidJavaBinaryNameNoArray(name);
return isCanonical ? resolver.resolveClassFromCanonicalName(name)
: resolver.resolveClassFromBinaryName(name);
}
/**
* Returns a type mirror for the given symbol. If the symbol declares
* type parameters, then the resulting type is raw (differs from the
* behaviour of {@link #declaration(JClassSymbol)}), meaning all its
* supertypes are erased.
*
* <p>If the symbol is a {@link JTypeParameterSymbol type parameter},
* returns a {@link JTypeVar}.
*
* <p>If the symbol is a {@link JClassSymbol}, then:
* <ul>
* <li>If it represents a primitive type, the corresponding {@link JPrimitiveType}
* is returned (one of {@link #INT}, {@link #CHAR}, etc.).
* <li>If it represents an array type, a new {@link JArrayType} is
* returned. The component type will be built with a recursive call.
* <li>If it represents a class or interface type, a {@link JClassType}
* is returned.
* <ul>
* <li>If the parameter {@code isErased} is true, and if the
* symbol declares type parameters, then it will be a
* {@linkplain JClassType#isRaw() raw type}. This means,
* which means all its generic supertypes are {@linkplain JClassType#hasErasedSuperTypes() erased}.
* <li>Otherwise, the generic supertypes are preserved. In particular,
* if the symbol declares type parameters itself, then it will
* be a {@linkplain JClassType#isGenericTypeDeclaration() generic type declaration}.
* </ul>
* If the symbol is a non-static member of another class, then the given
* type's {@linkplain JClassType#getEnclosingType() enclosing type} is
* created, applying the above rules about erasure recursively. A type
* is either completely erased, or completely parameterized.
* </li>
* </ul>
*
* @param symbol Symbol for the type declaration
* @param isErased Whether the type should be consider erased, if it
* represents a class or interface type. This does not
* erase type variables, or array types for that matter.
*
* @return A type, or null if the symbol is null
*/
public JTypeMirror typeOf(@Nullable JTypeDeclSymbol symbol, boolean isErased) {
if (symbol == null) {
return null;
}
// takes care of primitives, and constants like OBJECT or UNRESOLVED_TYPE
JTypeMirror common = specialCache(symbol);
if (common != null) {
return common;
}
if (symbol instanceof JClassSymbol) {
JClassSymbol classSym = (JClassSymbol) symbol;
if (classSym.isArray()) {
JTypeMirror component = typeOf(classSym.getArrayComponent(), isErased);
assert component != null : "the symbol necessarily has an array component symbol";
return arrayType(component, classSym);
} else {
return new ClassTypeImpl(this, classSym, emptyList(), isErased, HashTreePSet.empty());
}
} else if (symbol instanceof JTypeParameterSymbol) {
return ((JTypeParameterSymbol) symbol).getTypeMirror();
}
throw AssertionUtil.shouldNotReachHere("Uncategorized type symbol " + symbol.getClass() + ": " + symbol);
}
// test only for now
JClassType forceErase(JClassType t) {
JClassType erasure = t.getErasure();
if (erasure == t) {
return new ErasedClassType(this, t.getSymbol(), t.getTypeAnnotations());
}
return erasure;
}
/**
* Like {@link #typeOf(JTypeDeclSymbol, boolean)}, defaulting the
* erased parameter to true. If the symbol is not generic,
* the returned symbol is not actually raw.
*
* @param klass Symbol
*
* @return An erased class type
*/
public JTypeMirror rawType(@Nullable JTypeDeclSymbol klass) {
return typeOf(klass, true);
}
/**
* Like {@link #typeOf(JTypeDeclSymbol, boolean)}, defaulting the
* erased parameter to false. If the symbol is not generic,
* the returned symbol is not actually a generic type declaration.
*
* @param klass Symbol
*
* @return An erased class type
*/
public JTypeMirror declaration(@Nullable JClassSymbol klass) {
return typeOf(klass, false);
}
/**
* Produce a parameterized type with the given symbol and type arguments.
* The type argument list must match the declared formal type parameters in
* length. Non-generic symbols are accepted by this method, provided the
* argument list is empty. If the symbol is unresolved, any type argument
* list is accepted.
*
* <p>This method is equivalent to {@code rawType(klass).withTypeArguments(typeArgs)},
* but that code would require a cast.
*
* @param klass A symbol
* @param typeArgs List of type arguments
*
* @throws IllegalArgumentException see {@link JClassType#withTypeArguments(List)}
*/
// todo how does this behave with nested generic types
public @NonNull JTypeMirror parameterise(@NonNull JClassSymbol klass, @NonNull List<? extends JTypeMirror> typeArgs) {
if (typeArgs.isEmpty()) {
return rawType(klass); // note this ensures that OBJECT and such is preserved
}
// if the type arguments are mismatched, the constructor will throw
return new ClassTypeImpl(this, klass, CollectionUtil.defensiveUnmodifiableCopy(typeArgs), true, HashTreePSet.empty());
}
/**
* Creates a new array type from an arbitrary element type.
*
* <pre>{@code
* arrayType(T, 0) = T
* arrayType(T, 1) = T[]
* arrayType(T, 3) = T[][][]
* arrayType(T[], 2) = T[][][]
* }</pre>
*
* @param element Element type
* @param numDimensions Number of dimensions
*
* @return A new array type
*
* @throws IllegalArgumentException If numDimensions is negative
* @throws IllegalArgumentException If the element type is a {@link JWildcardType},
* the null type, or {@link #NO_TYPE void}.
* @throws NullPointerException If the element type is null
*/
public JTypeMirror arrayType(@NonNull JTypeMirror element, int numDimensions) {
AssertionUtil.requireNonNegative("numDimensions", numDimensions);
checkArrayElement(element); // note we throw even if numDimensions == 0
if (numDimensions == 0) {
return element;
}
JArrayType res = new JArrayType(this, element);
while (--numDimensions > 0) {
res = new JArrayType(this, res);
}
return res;
}
/**
* Like {@link #arrayType(JTypeMirror, int)}, with one dimension.
*
* @param component Component type
*
* @return An array type
*
* @throws IllegalArgumentException If the element type is a {@link JWildcardType},
* the null type, or {@link #NO_TYPE void}.
* @throws NullPointerException If the element type is null
*/
public JArrayType arrayType(@NonNull JTypeMirror component) {
return arrayType(component, null);
}
/** Trusted constructor. */
private JArrayType arrayType(@NonNull JTypeMirror component, @Nullable JClassSymbol symbol) {
checkArrayElement(component);
return new JArrayType(this, component, symbol, HashTreePSet.empty());
}
private void checkArrayElement(@NonNull JTypeMirror element) {
AssertionUtil.requireParamNotNull("elementType", element);
if (element instanceof JWildcardType
|| element == NULL_TYPE
|| element == NO_TYPE) {
throw new IllegalArgumentException("The type < " + element + " > is not a valid array element type");
}
}
public JMethodSig sigOf(JExecutableSymbol methodSym) {
return sigOf(methodSym, Substitution.EMPTY);
}
public JMethodSig sigOf(JExecutableSymbol methodSym, Substitution subst) {
JClassType klass = (JClassType) declaration(methodSym.getEnclosingClass());
return new ClassMethodSigImpl(klass.subst(subst), methodSym);
}
public JVariableSig.FieldSig sigOf(JTypeMirror decl, JFieldSymbol fieldSym) {
return JVariableSig.forField(decl, fieldSym);
}
public JVariableSig sigOf(JClassType decl, JLocalVariableSymbol fieldSym) {
return JVariableSig.forLocal(decl, fieldSym);
}
public JVariableSig sigOf(JClassType decl, JFormalParamSymbol fieldSym) {
return JVariableSig.forLocal(decl, fieldSym);
}
/**
* Builds a wildcard type with a single bound.
*
* <pre>{@code
*
* wildcard(true, T) = ? extends T
* wildcard(false, T) = ? super T
* wildcard(true, OBJECT) = ?
*
* }</pre>
*
* @param isUpperBound If true, this is an "extends" wildcard, otherwise a "super"
* @param bound Bound of the wildcard
*
* @return A wildcard
*
* @throws NullPointerException If the bound is null
* @throws IllegalArgumentException If the bound is a primitive type,
* or a wildcard type
* @throws IllegalArgumentException If the bound is OBJECT and this
* is a lower-bounded wildcard (? super Object)
*/
public JWildcardType wildcard(boolean isUpperBound, @NonNull JTypeMirror bound) {
Objects.requireNonNull(bound, "Argument shouldn't be null");
if (bound.isPrimitive() || bound instanceof JWildcardType) {
throw new IllegalArgumentException("<" + bound + "> cannot be a wildcard bound");
}
return isUpperBound && bound == OBJECT ? UNBOUNDED_WILD
: new WildcardTypeImpl(this, isUpperBound, bound, HashTreePSet.empty());
}
/**
* Maps a type decl symbol to its shared representation. Eg this
* maps the symbol for {@code int.class} to {@link #INT}. Only
* non-generic types are cached.
*/
private @Nullable JTypeMirror specialCache(JTypeDeclSymbol raw) {
return sharedTypes.get(raw);
}
/**
* Gets the primitive type identified by the given kind.
*
* @param kind Kind of primitive type
*
* @return A primitive type
*
* @throws NullPointerException if kind is null
*/
public @NonNull JPrimitiveType getPrimitive(@NonNull PrimitiveTypeKind kind) {
AssertionUtil.requireParamNotNull("kind", kind);
return primitivesByKind.get(kind);
}
/**
* The least upper bound, or "lub", of a set of reference types is
* a shared supertype that is more specific than any other shared
* supertype (that is, no other shared supertype is a subtype of the
* least upper bound).
*
* @throws IllegalArgumentException If types is empty
* @throws NullPointerException If types is null
*/
public JTypeMirror lub(Collection<? extends JTypeMirror> types) {
return Lub.lub(this, types);
}
/**
* Returns the greatest lower bound of the given set of types.
* This is defined in JLS§5.1.10 (Capture Conversion):
*
* <pre>
* glb(V1,...,Vm) = V1 & ... & Vm
* glb(V) = V
* </pre>
*
* <p>This may alter the components, so that:
* <ul>
* <li>No intersection type is a component: {@code ((A & B) & C) = (A & (B & C)) = (A & B & C)}
* <li>No two types in the intersection are subtypes of one another
* (the intersection is minimal): {@code A <: B => (A & B) = A}, in particular, {@code (A & A) = A}
* <li>The intersection has a single component that is a
* class, array, or type variable. If all components are interfaces,
* then that component is {@link #OBJECT}.
* </ul>
*
* <p>If after these transformations, only a single component remains,
* then that is the returned type. Otherwise a {@link JIntersectionType}
* is created. Note that the intersection may be unsatisfiable (eg {@code A[] & Runnable}),
* but we don't attempt to minimize this to {@link #NULL_TYPE}.
*
* <p>See also JLS§4.9 (Intersection types).
*
* @throws IllegalArgumentException If some component is not a class, interface, array, or type variable
* @throws IllegalArgumentException If there is more than one minimal class or array type
* @throws IllegalArgumentException If types is empty
* @throws NullPointerException If types is null
*/
public JTypeMirror glb(Collection<? extends JTypeMirror> types) {
return Lub.glb(this, types);
}
// package-private
JClassType erasedType(@NonNull JClassSymbol symbol) {
JTypeMirror t = specialCache(symbol);
if (t != null) {
return (JClassType) t.getErasure();
} else {
return new ErasedClassType(this, symbol, HashTreePSet.empty());
}
}
/**
* Returns a new type variable for the given symbol. This is only
* intended to be used by the implementor of {@link JTypeParameterSymbol}.
*/
public JTypeVar newTypeVar(JTypeParameterSymbol symbol) {
// note: here we don't pass the symbol's annotations. These stay on
// the symbol as they can be visually noisy since they would be
// repeated at each use-site
return new TypeVarImpl.RegularTypeVar(this, symbol, HashTreePSet.empty());
}
private static final class NullType implements JTypeMirror {
private final TypeSystem ts;
NullType(TypeSystem ts) {
this.ts = ts;
}
@Override
public JTypeMirror withAnnotations(PSet<SymAnnot> newTypeAnnots) {
return this;
}
@Override
public PSet<SymAnnot> getTypeAnnotations() {
return HashTreePSet.empty();
}
@Override
public JTypeMirror subst(Function<? super SubstVar, ? extends @NonNull JTypeMirror> subst) {
return this;
}
@Override
public TypeSystem getTypeSystem() {
return ts;
}
@Override
public boolean isBottom() {
return true;
}
@Override
public @Nullable JClassSymbol getSymbol() {
return null;
}
@Override
public <T, P> T acceptVisitor(JTypeVisitor<T, P> visitor, P p) {
return visitor.visitNullType(this, p);
}
@Override
public String toString() {
return "null";
}
}
}
| 31,428 | 38.833967 | 130 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/TypeOps.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import static net.sourceforge.pmd.lang.java.types.Substitution.EMPTY;
import static net.sourceforge.pmd.lang.java.types.Substitution.mapping;
import static net.sourceforge.pmd.lang.java.types.TypeConversion.capture;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.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.JMethodSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.CoreResolvers;
import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.NameResolver;
import net.sourceforge.pmd.lang.java.symbols.table.internal.JavaResolvers;
import net.sourceforge.pmd.lang.java.types.JVariableSig.FieldSig;
import net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar;
import net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar.BoundKind;
import net.sourceforge.pmd.lang.java.types.internal.infer.OverloadSet;
import net.sourceforge.pmd.util.CollectionUtil;
import net.sourceforge.pmd.util.IteratorUtil;
/**
* Common operations on types.
*/
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public final class TypeOps {
private TypeOps() {
// utility class
}
// <editor-fold defaultstate="collapsed" desc="Type equality">
/**
* Return true if t and s are the same method type. This compares
* their declaring type, and then their signature.
*
* @see #haveSameSignature(JMethodSig, JMethodSig)
*/
public static boolean isSameType(JMethodSig t, JMethodSig s) {
return t.getDeclaringType().equals(s.getDeclaringType()) && haveSameSignature(t, s);
}
/*
* Note that type mirror implementations use this method as their
* Object#equals, which means it can't be used here unless it's on
* the smaller parts of a type.
*/
/**
* Return true if t and s are the same type, ignoring any type annotations
* appearing within them. This is the implementation of the equals method
* of {@link JTypeMirror}.
*/
public static boolean isSameType(JTypeMirror t, JTypeMirror s) {
return isSameType(t, s, false, false);
}
/**
* Return true if t and s are the same type, considering any type annotations
* appearing within them.
*/
public static boolean isSameTypeWithSameAnnotations(JTypeMirror t, JTypeMirror s) {
return isSameType(t, s, false, true);
}
/**
* Return true if t and s are the same type. This may perform side effects
* on inference variables. Annotations are ignored.
*/
@InternalApi
public static boolean isSameTypeInInference(JTypeMirror t, JTypeMirror s) {
return isSameType(t, s, true, false);
}
/**
* Returns true if t and s are the same type. If 'inInference' is
* true, then encountering inference variables produces side effects
* on them, adding bounds.
*/
private static boolean isSameType(JTypeMirror t, JTypeMirror s, boolean inInference, boolean considerAnnotations) {
if (t == s) {
// also returns true if both t and s are null
return true;
}
if (t == null || s == null) {
return false;
}
if (!inInference) {
if (considerAnnotations) {
if (t instanceof CaptureMatcher || s instanceof CaptureMatcher) {
return t.equals(s); // skip check for type annotations
}
return t.getTypeAnnotations().equals(s.getTypeAnnotations())
&& t.acceptVisitor(SameTypeVisitor.PURE_WITH_ANNOTATIONS, s);
} else {
return t.acceptVisitor(SameTypeVisitor.PURE, s);
}
}
// reorder
if (t instanceof InferenceVar) {
return t.acceptVisitor(SameTypeVisitor.INFERENCE, s);
} else {
return s.acceptVisitor(SameTypeVisitor.INFERENCE, t);
}
}
public static boolean areSameTypes(List<JTypeMirror> ts, List<JTypeMirror> ss) {
return areSameTypes(ts, ss, EMPTY, false, false);
}
public static boolean areSameTypesInInference(List<JTypeMirror> ts, List<JTypeMirror> ss) {
return areSameTypes(ts, ss, EMPTY, true, false);
}
private static boolean areSameTypes(List<JTypeMirror> ts, List<JTypeMirror> ss, boolean inInference, boolean considerAnnotations) {
return areSameTypes(ts, ss, EMPTY, inInference, considerAnnotations);
}
private static boolean areSameTypes(List<JTypeMirror> ts, List<JTypeMirror> ss, Substitution subst) {
return areSameTypes(ts, ss, subst, false, false);
}
private static boolean areSameTypes(List<JTypeMirror> ts, List<JTypeMirror> ss, Substitution subst, boolean inInference, boolean considerAnnotations) {
if (ts.size() != ss.size()) {
return false;
}
for (int i = 0; i < ts.size(); i++) {
if (!isSameType(ts.get(i), ss.get(i).subst(subst), inInference, considerAnnotations)) {
return false;
}
}
return true;
}
// note that this does not take type annotations into account
private static final class SameTypeVisitor implements JTypeVisitor<Boolean, JTypeMirror> {
static final SameTypeVisitor INFERENCE = new SameTypeVisitor(true, false);
static final SameTypeVisitor PURE = new SameTypeVisitor(false, false);
static final SameTypeVisitor PURE_WITH_ANNOTATIONS = new SameTypeVisitor(false, true);
private final boolean inInference;
private final boolean considerAnnotations;
private SameTypeVisitor(boolean inInference, boolean considerAnnotations) {
this.inInference = inInference;
this.considerAnnotations = considerAnnotations;
}
@Override
public Boolean visit(JTypeMirror t, JTypeMirror s) {
// for sentinel types
return t == s;
}
@Override
public Boolean visitPrimitive(JPrimitiveType t, JTypeMirror s) {
return s.isPrimitive(t.getKind());
}
@Override
public Boolean visitClass(JClassType t, JTypeMirror s) {
if (s instanceof JClassType) {
JClassType s2 = (JClassType) s;
return t.getSymbol().equals(s2.getSymbol()) // maybe compare the type system as well.
&& t.hasErasedSuperTypes() == s2.hasErasedSuperTypes()
&& isSameType(t.getEnclosingType(), s2.getEnclosingType(), inInference, considerAnnotations)
&& areSameTypes(t.getTypeArgs(), s2.getTypeArgs(), inInference, considerAnnotations);
}
return false;
}
@Override
public Boolean visitTypeVar(JTypeVar t, JTypeMirror s) {
return t.equals(s);
}
@Override
public Boolean visitWildcard(JWildcardType t, JTypeMirror s) {
if (!(s instanceof JWildcardType)) {
return false;
}
JWildcardType s2 = (JWildcardType) s;
return s2.isUpperBound() == t.isUpperBound() && isSameType(t.getBound(), s2.getBound(), inInference, considerAnnotations);
}
@Override
public Boolean visitInferenceVar(InferenceVar t, JTypeMirror s) {
if (!inInference) {
return t == s;
}
if (s instanceof JPrimitiveType) {
return false;
}
if (s instanceof JWildcardType) {
JWildcardType s2 = (JWildcardType) s;
if (s2.isUpperBound()) {
t.addBound(BoundKind.UPPER, s2.asUpperBound());
} else {
t.addBound(BoundKind.LOWER, s2.asLowerBound());
}
return true;
}
// add an equality bound
t.addBound(BoundKind.EQ, s);
return true;
}
@Override
public Boolean visitIntersection(JIntersectionType t, JTypeMirror s) {
if (!(s instanceof JIntersectionType)) {
return false;
}
JIntersectionType s2 = (JIntersectionType) s;
// order is irrelevant
if (s2.getComponents().size() != t.getComponents().size()) {
return false;
}
if (!isSameType(t.getPrimaryBound(), s2.getPrimaryBound(), inInference, considerAnnotations)) {
return false;
}
List<JTypeMirror> sComps = ((JIntersectionType) s).getComponents();
for (JTypeMirror ti : t.getComponents()) {
boolean found = false;
for (JTypeMirror si : sComps) {
// todo won't this behaves weirdly during inference? test it
if (isSameType(ti, si, inInference, considerAnnotations)) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
@Override
public Boolean visitArray(JArrayType t, JTypeMirror s) {
return s instanceof JArrayType
&& isSameType(t.getComponentType(), ((JArrayType) s).getComponentType(), inInference, considerAnnotations);
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Supertype enumeration">
/**
* Returns the set of all supertypes of the given type.
*
* @see JTypeMirror#getSuperTypeSet()
*/
public static Set<JTypeMirror> getSuperTypeSet(@NonNull JTypeMirror t) {
Set<JTypeMirror> result = new LinkedHashSet<>();
t.acceptVisitor(SuperTypesVisitor.INSTANCE, result);
assert !result.isEmpty() : "Empty supertype set for " + t;
return result;
}
private static final class SuperTypesVisitor implements JTypeVisitor<Void, Set<JTypeMirror>> {
static final SuperTypesVisitor INSTANCE = new SuperTypesVisitor();
@Override
public Void visit(JTypeMirror t, Set<JTypeMirror> result) {
throw new IllegalStateException("Should not be called");
}
@Override
public Void visitTypeVar(JTypeVar t, Set<JTypeMirror> result) {
if (result.add(t)) {
// prevent infinite loop
t.getUpperBound().acceptVisitor(this, result);
}
return null;
}
@Override
public Void visitNullType(JTypeMirror t, Set<JTypeMirror> result) {
// too many types
throw new UnsupportedOperationException("The null type has all reference types as supertype");
}
@Override
public Void visitSentinel(JTypeMirror t, Set<JTypeMirror> result) {
result.add(t);
return null;
}
@Override
public Void visitInferenceVar(InferenceVar t, Set<JTypeMirror> result) {
result.add(t);
return null;
}
@Override
public Void visitWildcard(JWildcardType t, Set<JTypeMirror> result) {
t.asUpperBound().acceptVisitor(this, result);
// wildcards should be captured and so we should not end up here
return null;
}
@Override
public Void visitClass(JClassType t, Set<JTypeMirror> result) {
result.add(t);
// prefer digging up the superclass first
JClassType sup = t.getSuperClass();
if (sup != null) {
sup.acceptVisitor(this, result);
}
for (JClassType i : t.getSuperInterfaces()) {
visitClass(i, result);
}
if (t.isInterface() && t.getSuperInterfaces().isEmpty()) {
result.add(t.getTypeSystem().OBJECT);
}
return null;
}
@Override
public Void visitIntersection(JIntersectionType t, Set<JTypeMirror> result) {
for (JTypeMirror it : t.getComponents()) {
it.acceptVisitor(this, result);
}
return null;
}
@Override
public Void visitArray(JArrayType t, Set<JTypeMirror> result) {
result.add(t);
TypeSystem ts = t.getTypeSystem();
for (JTypeMirror componentSuper : t.getComponentType().getSuperTypeSet()) {
result.add(ts.arrayType(componentSuper));
}
result.add(ts.CLONEABLE);
result.add(ts.SERIALIZABLE);
result.add(ts.OBJECT);
return null;
}
@Override
public Void visitPrimitive(JPrimitiveType t, Set<JTypeMirror> result) {
result.addAll(t.getSuperTypeSet()); // special implementation in JPrimitiveType
return null;
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Subtyping">
public static Convertibility isConvertible(@NonNull JTypeMirror t, @NonNull JTypeMirror s) {
return isConvertible(t, s, true);
}
public static Convertibility isConvertibleNoCapture(@NonNull JTypeMirror t, @NonNull JTypeMirror s) {
return isConvertible(t, s, false);
}
/**
* Returns whether if {@code T <: S}, ie T is a subtype of S.
*
* <p>Note that {@link TypeSystem#ERROR} and {@link TypeSystem#UNKNOWN}
* are considered subtypes of anything.
*
* @param t A type T
* @param s A type S
*/
public static Convertibility isConvertible(@NonNull JTypeMirror t, @NonNull JTypeMirror s, boolean capture) {
// This is commented out as it makes JTypeMirror#isSubtypeOf partial,
// which is not nice for the API... But this assert caught a bug and
// should probably be enabled.
// assert !(t instanceof JWildcardType || s instanceof JWildcardType) : "Wildcards do not support subtyping";
if (t == s) {
Objects.requireNonNull(t);
return Convertibility.SUBTYPING;
} else if (s.isTop()) {
return Convertibility.subtypeIf(!t.isPrimitive());
} else if (s.isVoid() || t.isVoid()) { // t != s
return Convertibility.NEVER;
} else if (s instanceof InferenceVar) {
// it's possible to add a bound to UNKNOWN or ERROR
((InferenceVar) s).addBound(BoundKind.LOWER, t);
return Convertibility.SUBTYPING;
} else if (isTypeRange(s)) {
// If s is a type range L..U,
// then showing t <: s is the same thing as t <: L
JTypeMirror lower = lowerBoundRec(s);
if (!lower.isBottom()) {
return isConvertible(t, lower, capture);
}
// otherwise fallthrough
} else if (isSpecialUnresolved(t)) {
// error type or unresolved type
return Convertibility.SUBTYPING;
} else if (hasUnresolvedSymbol(t) && t instanceof JClassType) {
// This also considers types with an unresolved symbol
// subtypes of (nearly) anything. This allows them to
// pass bound checks on type variables.
if (Objects.equals(t.getSymbol(), s.getSymbol())) {
return typeArgsAreContained((JClassType) t, (JClassType) s);
} else {
return Convertibility.subtypeIf(s instanceof JClassType); // excludes array or so
}
} else if (s instanceof JIntersectionType) { // TODO test intersection with tvars & arrays
// If S is an intersection, then T must conform to *all* bounds of S
// Symmetrically, if T is an intersection, T <: S requires only that
// at least one bound of T is a subtype of S.
return Convertibility.subtypesAll(t, asList(s));
}
if (capture) {
t = capture(t);
}
return t.acceptVisitor(SubtypeVisitor.INSTANCE, s);
}
// does not perform side effects on inference vars
private static Convertibility isSubtypePure(JTypeMirror t, JTypeMirror s) {
if (t instanceof InferenceVar) {
return Convertibility.subtypeIf(((InferenceVar) t).isSubtypeNoSideEffect(s));
} else if (s instanceof InferenceVar) {
return Convertibility.subtypeIf(((InferenceVar) s).isSupertypeNoSideEffect(t));
}
return isConvertible(t, s);
}
public static boolean allArgsAreUnboundedWildcards(List<JTypeMirror> sargs) {
for (JTypeMirror sarg : sargs) {
if (!(sarg instanceof JWildcardType) || !((JWildcardType) sarg).isUnbounded()) {
return false;
}
}
return true;
}
/**
* A result for a convertibility check. This is a tiny generalization of
* a subtyping check.
*
* <p>Primitive types are implicitly convertible to each other by
* widening primitive conversion. For reference types, subtyping
* implies convertibility (the conversion is technically called
* "widening reference conversion"). You can check those cases using:
*
* {@link #bySubtyping() t.isConvertibleTo(s).bySubtyping()}
*
* <p>Unchecked conversion may go backwards from subtyping. For example,
* {@code List<String>} is a subtype of the raw type {@code List}, and
* as such is convertible to it by reference widening. But {@code List}
* may be "coerced" to {@code List<String>} with an unchecked warning:
*
* {@link #withUncheckedWarning() t.isConvertibleTo(s).withUncheckedWarning()}
*
* <p>If the parameterized type only has wildcard type arguments,
* then the conversion produces no warning.
*
* {@link #UNCHECKED_NO_WARNING t.isConvertibleTo(s) == UNCHECKED_NO_WARNING}
*
* <p>Two types may be unconvertible:
*
* {@link #never() t.isConvertibleTo(s).never()}
*
* <p>the negation of which being
*
* {@link #somehow() t.isConvertibleTo(s).somehow()}
*
* <p>Note that this does not check for boxing or unboxing conversions,
* nor for narrowing conversions, which may happen through casts.
*/
public enum Convertibility {
/** T is never implicitly convertible to S. */
NEVER,
/**
* T is not a subtype of S, but every time T is used in a context
* where an S is expected, unchecked conversion converts the T to
* an S with a mandated warning. For example the raw type {@code Class}
* is convertible to {@code Class<String>} with an unchecked warning.
*/
UNCHECKED_WARNING,
/**
* {@code T <: |S|} and {@code T </: S}, but S is
* parameterized with only unbounded wildcards. This is a special
* case of unchecked conversion that produces no warning. We keep
* it distinct from subtyping to help some algorithms that require
* subtyping to be a partial order.
*
* <p>For example, {@code List<String>} is a subtype of the raw
* {@code Collection}, not a subtype of {@code Collection<?>},
* but it is still convertible without warning.
*/
UNCHECKED_NO_WARNING,
/**
* T is a subtype of S ({@code T <: S}). In particular, any type
* is a subtype of itself ({@code T <: T}).
*
* <p>For example, {@code int} can be widened to {@code long},
* so we consider {@code int <: long}.
*/
SUBTYPING;
// public:
/** Returns true if this is {@link #NEVER}. */
public boolean never() {
return this == NEVER;
}
/**
* Returns true if this is anything but {@link #NEVER}.
*/
public boolean somehow() {
return this != NEVER;
}
/**
* True if this is {@link #SUBTYPING}.
*/
public boolean bySubtyping() {
return this == SUBTYPING;
}
/**
* True if this is {@link #UNCHECKED_WARNING}.
*/
public boolean withUncheckedWarning() {
return this == UNCHECKED_WARNING;
}
// package:
/** Preserves an unchecked warning. */
Convertibility and(Convertibility b) {
return min(this, b);
}
static Convertibility min(Convertibility c1, Convertibility c2) {
return c1.ordinal() < c2.ordinal() ? c1 : c2;
}
static Convertibility subtypeIf(boolean b) {
return b ? SUBTYPING : NEVER;
}
static Convertibility subtypesAll(JTypeMirror t, Iterable<? extends JTypeMirror> supers) {
Convertibility result = SUBTYPING;
for (JTypeMirror ui : supers) {
Convertibility sub = isConvertible(t, ui);
if (sub == NEVER) {
return NEVER;
}
result = result.and(sub);
}
return result;
}
static Convertibility anySubTypesAny(Iterable<? extends JTypeMirror> us, Iterable<? extends JTypeMirror> vs) {
for (JTypeMirror ui : us) {
for (JTypeMirror vi : vs) {
Convertibility sub = isConvertible(ui, vi);
if (sub != NEVER) {
return sub.and(SUBTYPING); // never return identity here
}
}
}
return NEVER;
}
}
private static JTypeMirror wildUpperBound(JTypeMirror type) {
if (type instanceof JWildcardType) {
JWildcardType wild = (JWildcardType) type;
if (wild.isUpperBound()) {
return wildUpperBound(wild.asUpperBound());
} else if (wild.asLowerBound() instanceof JTypeVar) {
return ((JTypeVar) wild.asLowerBound()).getUpperBound();
}
} else if (type instanceof JTypeVar && ((JTypeVar) type).isCaptured()) {
// note: tvar.getUpperBound() != tvar.getCapturedOrigin().asUpperBound()
return wildUpperBound(((JTypeVar) type).getUpperBound());
}
return type;
}
private static JTypeMirror wildLowerBound(JTypeMirror type) {
if (type instanceof JWildcardType) {
return wildLowerBound(((JWildcardType) type).asLowerBound());
}
return type;
}
private static JTypeMirror lowerBoundRec(JTypeMirror type) {
if (type instanceof JWildcardType) {
return lowerBoundRec(((JWildcardType) type).asLowerBound());
} else if (type instanceof JTypeVar && ((JTypeVar) type).isCaptured()) {
return lowerBoundRec(((JTypeVar) type).getLowerBound());
}
return type;
}
private static boolean isTypeRange(JTypeMirror s) {
return s instanceof JWildcardType || isCvar(s);
}
private static boolean isCvar(JTypeMirror s) {
return s instanceof JTypeVar && ((JTypeVar) s).isCaptured();
}
/**
* Returns true if {@code T <= S}, ie "S contains T".
*
* <p>S contains T if:
*
* <p>{@code L(S) <: L(T) && U(T) <: U(S)}
*
* <p>This only makes sense for type arguments, it's a component of
* subtype checks for parameterized types:
*
* <p>{@code C<S> <: C<T> if S <= T}
*
* <p>Defined in JLS§4.5.1 (Type Arguments of Parameterized Types)
*/
static Convertibility typeArgContains(JTypeMirror s, JTypeMirror t) {
// the contains relation can be understood intuitively if we
// represent types as ranges on a line:
// ⊥ ---------L(S)---L(T)------U(T)-----U(S)---> Object
// range of S [-------------------------]
// range of T [---------]
// here S contains T because its range is greater
// since a wildcard is either "super" or "extends", in reality
// either L(S) = ⊥, or U(S) = Object.
// meaning when S != T, we only have two scenarios where T <= S:
// ⊥ -------U(T)-----U(S)------> Object (L(T) = L(S) = ⊥)
// ⊥ -------L(S)-----L(T)------> Object (U(T) = U(S) = Object)
if (isSameTypeInInference(s, t)) {
// S <= S
return Convertibility.SUBTYPING;
}
if (s instanceof JWildcardType) {
JWildcardType sw = (JWildcardType) s;
// capt(? extends T) <= ? extends T
// capt(? super T) <= ? super T
if (t instanceof JTypeVar && ((JTypeVar) t).isCaptureOf(sw)) {
return Convertibility.SUBTYPING;
}
if (sw.isUpperBound()) {
// Test U(T) <: U(S), we already know L(S) <: L(T), because L(S) is bottom
return isConvertible(wildUpperBound(t), sw.asUpperBound());
} else {
// Test L(S) <: L(T), we already know U(T) <: U(S), because U(S) is top
return isConvertible(sw.asLowerBound(), wildLowerBound(t));
}
}
return Convertibility.NEVER;
}
/**
* Generalises containment to check if for each i, {@code Ti <= Si}.
*/
static Convertibility typeArgsAreContained(JClassType t, JClassType s) {
List<JTypeMirror> targs = t.getTypeArgs();
List<JTypeMirror> sargs = s.getTypeArgs();
if (targs.isEmpty()) {
if (sargs.isEmpty()) {
// Some "erased" non-generic types may appear as the supertypes
// of raw types, and they're different from the regular flavor
// as their own supertypes are erased, yet they're not considered
// raw. To fix the subtyping relation, we say that `C <: (erased) C`
// but `(erased) C` converts to `C` by unchecked conversion, without
// warning.
boolean tRaw = t.hasErasedSuperTypes();
boolean sRaw = s.hasErasedSuperTypes();
if (tRaw && !sRaw) {
return Convertibility.UNCHECKED_NO_WARNING;
} else {
return Convertibility.SUBTYPING;
}
}
// for some C, S = C<...> and T = C, ie T is raw
// T is convertible to S, by unchecked conversion.
// If S = D<?, .., ?>, then the conversion produces
// no unchecked warning.
return allArgsAreUnboundedWildcards(sargs) ? Convertibility.UNCHECKED_NO_WARNING
: Convertibility.UNCHECKED_WARNING;
}
if (targs.size() != sargs.size()) {
// types are not well-formed
return Convertibility.NEVER;
}
Convertibility result = Convertibility.SUBTYPING;
for (int i = 0; i < targs.size(); i++) {
Convertibility sub = typeArgContains(sargs.get(i), targs.get(i));
if (sub == Convertibility.NEVER) {
return Convertibility.NEVER;
}
result = result.and(sub);
}
return result;
}
private static final class SubtypeVisitor implements JTypeVisitor<Convertibility, JTypeMirror> {
static final SubtypeVisitor INSTANCE = new SubtypeVisitor();
@Override
public Convertibility visit(JTypeMirror t, JTypeMirror s) {
throw new IllegalStateException("Should not be called");
}
@Override
public Convertibility visitTypeVar(JTypeVar t, JTypeMirror s) {
if (s instanceof JTypeVar && t.getSymbol() != null && Objects.equals(t.getSymbol(), s.getSymbol())) {
return Convertibility.SUBTYPING;
}
if (isTypeRange(s)) {
return isConvertible(t, lowerBoundRec(s));
}
return isConvertible(t.getUpperBound(), s);
}
@Override
public Convertibility visitNullType(JTypeMirror t, JTypeMirror s) {
return Convertibility.subtypeIf(!s.isPrimitive());
}
@Override
public Convertibility visitSentinel(JTypeMirror t, JTypeMirror s) {
// we know t != s
return t.isVoid() ? Convertibility.NEVER
: Convertibility.SUBTYPING;
}
@Override
public Convertibility visitInferenceVar(InferenceVar t, JTypeMirror s) {
if (s == t.getTypeSystem().NULL_TYPE || s instanceof JPrimitiveType) {
return Convertibility.NEVER;
}
// here we add a constraint on the variable
t.addBound(BoundKind.UPPER, s);
return Convertibility.SUBTYPING;
}
@Override
public Convertibility visitWildcard(JWildcardType t, JTypeMirror s) {
// wildcards should be captured and so we should not end up here
return Convertibility.NEVER;
}
@Override
public Convertibility visitClass(JClassType t, JTypeMirror s) {
if (!(s instanceof JClassType)) {
// note, that this ignores wildcard types,
// because they're only compared through
// type argument containment.
return Convertibility.NEVER;
}
JClassType cs = (JClassType) s;
JClassType superDecl = t.getAsSuper(cs.getSymbol());
if (superDecl == null) {
return Convertibility.NEVER;
} else if (cs.isRaw()) {
// a raw type C is a supertype for all the family of parameterized type generated by C<F1, .., Fn>
return Convertibility.SUBTYPING;
} else {
return typeArgsAreContained(superDecl, cs);
}
}
@Override
public Convertibility visitIntersection(JIntersectionType t, JTypeMirror s) {
// A & B <: A
// A & B <: B
// But for a class C, `C <: A & B` if `C <: A` and `C <: B`
// So we can't just say, "any component of t must subtype s",
// because if s is itself an intersection we have a problem:
// Eg let T = S = A & B
// T <: S -> A & B <: S
// -> A <: S OR B <: S
// -> A <: A & B OR B <: A & B
// -> A <: A AND A <: B OR B <: A AND B <: B
// -> true AND false OR false AND true
// -> false
// what we mean is, if S is an intersection, then
// "any component of T subtypes any component of S"
return Convertibility.anySubTypesAny(t.getComponents(), asList(s));
}
@Override
public Convertibility visitArray(JArrayType t, JTypeMirror s) {
TypeSystem ts = t.getTypeSystem();
if (s == ts.OBJECT || s.equals(ts.CLONEABLE) || s.equals(ts.SERIALIZABLE)) {
return Convertibility.SUBTYPING;
}
if (!(s instanceof JArrayType)) {
// not comparable to any other type
return Convertibility.NEVER;
}
JArrayType cs = (JArrayType) s;
if (t.getComponentType().isPrimitive() || cs.getComponentType().isPrimitive()) {
// arrays of primitive types have no sub-/ supertype
return Convertibility.subtypeIf(cs.getComponentType() == t.getComponentType());
} else {
return isConvertible(t.getComponentType(), cs.getComponentType());
}
}
@Override
public Convertibility visitPrimitive(JPrimitiveType t, JTypeMirror s) {
if (s instanceof JPrimitiveType) {
return t.superTypes.contains(s) ? Convertibility.SUBTYPING
: Convertibility.NEVER;
}
return Convertibility.NEVER;
}
}
public static boolean isStrictSubtype(@NonNull JTypeMirror t, @NonNull JTypeMirror s) {
return !t.equals(s) && t.isSubtypeOf(s);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Substitution">
/**
* Replace the type variables occurring in the given type to their
* image by the given function. Substitutions are not applied
* recursively.
*
* @param type Type to substitute
* @param subst Substitution function, eg a {@link Substitution}
*/
public static JTypeMirror subst(@Nullable JTypeMirror type, Function<? super SubstVar, ? extends @NonNull JTypeMirror> subst) {
if (type == null || Substitution.isEmptySubst(subst)) {
return type;
}
return type.subst(subst);
}
/** Substitute on a list of types. */
public static List<JTypeMirror> subst(List<? extends JTypeMirror> ts, Function<? super SubstVar, ? extends @NonNull JTypeMirror> subst) {
if (Substitution.isEmptySubst(subst)) {
return CollectionUtil.makeUnmodifiableAndNonNull(ts);
}
return mapPreservingSelf(ts, t -> t.subst(subst));
}
public static List<JClassType> substClasses(List<JClassType> ts, Function<? super SubstVar, ? extends @NonNull JTypeMirror> subst) {
if (Substitution.isEmptySubst(subst)) {
return ts;
}
return mapPreservingSelf(ts, t -> t.subst(subst));
}
public static List<JTypeVar> substInBoundsOnly(List<JTypeVar> ts, Function<? super SubstVar, ? extends @NonNull JTypeMirror> subst) {
if (Substitution.isEmptySubst(subst)) {
return ts;
}
return mapPreservingSelf(ts, t -> t.substInBounds(subst));
}
// relies on the fact the original list is unmodifiable or won't be
// modified
@SuppressWarnings("unchecked")
private static @NonNull <T> List<T> mapPreservingSelf(List<? extends T> ts, Function<? super T, ? extends @NonNull T> subst) {
// Profiling shows, only 10% of calls to this method need to
// create a new list. Substitution in general is a hot spot
// of the framework, so optimizing this out is nice
List<T> list = null;
for (int i = 0, size = ts.size(); i < size; i++) {
T it = ts.get(i);
T substed = subst.apply(it);
if (substed != it) {
if (list == null) {
list = Arrays.asList((T[]) ts.toArray()); // NOPMD ClassCastExceptionWithToArray
}
list.set(i, substed);
}
}
// subst relies on the fact that the original list is returned
// to avoid new type creation. Thus one cannot use
// Collections::unmodifiableList here
return list != null ? list : (List<T>) ts;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Projection">
/**
* Returns the upwards projection of the given type, with respect
* to the set of capture variables that are found in it. This is
* some supertype of T which does not mention those capture variables.
* This is used for local variable type inference.
*
* https://docs.oracle.com/javase/specs/jls/se11/html/jls-4.html#jls-4.10.5
*/
public static JTypeMirror projectUpwards(JTypeMirror t) {
return t.acceptVisitor(UPWARDS_PROJECTOR, new RecursionStop());
}
private static final JTypeMirror NO_DOWN_PROJECTION = null;
private static final ProjectionVisitor UPWARDS_PROJECTOR = new ProjectionVisitor(true) {
@Override
public JTypeMirror visitTypeVar(JTypeVar t, RecursionStop recursionStop) {
if (t.isCaptured()) {
return t.getUpperBound().acceptVisitor(UPWARDS_PROJECTOR, recursionStop);
}
return t;
}
@Override
public JTypeMirror visitWildcard(JWildcardType t, RecursionStop recursionStop) {
JTypeMirror u = t.getBound().acceptVisitor(UPWARDS_PROJECTOR, recursionStop);
TypeSystem ts = t.getTypeSystem();
if (u == t.getBound()) {
return t;
}
if (t.isUpperBound()) {
return ts.wildcard(true, u);
} else {
JTypeMirror down = t.getBound().acceptVisitor(DOWNWARDS_PROJECTOR, recursionStop);
return down == NO_DOWN_PROJECTION ? ts.UNBOUNDED_WILD : ts.wildcard(false, down);
}
}
@Override
public JTypeMirror visitNullType(JTypeMirror t, RecursionStop recursionStop) {
return t;
}
};
private static final ProjectionVisitor DOWNWARDS_PROJECTOR = new ProjectionVisitor(false) {
@Override
public JTypeMirror visitWildcard(JWildcardType t, RecursionStop recursionStop) {
JTypeMirror u = t.getBound().acceptVisitor(UPWARDS_PROJECTOR, recursionStop);
if (u == t.getBound()) {
return t;
}
TypeSystem ts = t.getTypeSystem();
if (t.isUpperBound()) {
JTypeMirror down = t.getBound().acceptVisitor(DOWNWARDS_PROJECTOR, recursionStop);
return down == NO_DOWN_PROJECTION ? NO_DOWN_PROJECTION
: ts.wildcard(true, down);
} else {
return ts.wildcard(false, u);
}
}
@Override
public JTypeMirror visitTypeVar(JTypeVar t, RecursionStop recursionStop) {
if (t.isCaptured()) {
return t.getLowerBound().acceptVisitor(DOWNWARDS_PROJECTOR, recursionStop);
}
return t;
}
@Override
public JTypeMirror visitNullType(JTypeMirror t, RecursionStop recursionStop) {
return NO_DOWN_PROJECTION;
}
};
static final class RecursionStop {
private Set<JTypeVar> set;
boolean isAbsent(JTypeVar tvar) {
if (set == null) {
set = new LinkedHashSet<>(1);
}
return set.add(tvar);
}
<T extends JTypeMirror> JTypeMirror recurseIfNotDone(T t, BiFunction<T, RecursionStop, JTypeMirror> body) {
if (t instanceof JTypeVar) {
JTypeVar var = (JTypeVar) t;
try {
if (isAbsent(var)) {
return body.apply(t, this);
} else {
return t;
}
} finally {
set.remove(var);
}
} else {
return body.apply(t, this);
}
}
}
/**
* Restricted type variables are:
* - Inference vars
* - Capture vars
*
* See
*
* https://docs.oracle.com/javase/specs/jls/se11/html/jls-4.html#jls-4.10.5
*
*
* <p>Here we use {@link #NO_DOWN_PROJECTION} as a sentinel
* (downwards projection is a partial function). If a type does not mention
* restricted type variables, then the visitor should return the original
* type (same reference). This allows testing predicates like
* <blockquote>
* "If Ai does not mention any restricted type variable, then Ai' = Ai."
* </blockquote>
*/
private abstract static class ProjectionVisitor implements JTypeVisitor<JTypeMirror, RecursionStop> {
private final boolean upwards;
private ProjectionVisitor(boolean upwards) {
this.upwards = upwards;
}
@Override
public abstract JTypeMirror visitNullType(JTypeMirror t, RecursionStop recursionStop);
@Override
public abstract JTypeMirror visitWildcard(JWildcardType t, RecursionStop recursionStop);
@Override
public abstract JTypeMirror visitTypeVar(JTypeVar t, RecursionStop recursionStop);
@Override
public JTypeMirror visit(JTypeMirror t, RecursionStop recursionStop) {
return t;
}
@Override
public JTypeMirror visitClass(JClassType t, RecursionStop recursionStop) {
if (t.isParameterizedType()) {
TypeSystem ts = t.getTypeSystem();
List<JTypeMirror> targs = t.getTypeArgs();
List<JTypeMirror> newTargs = new ArrayList<>(targs.size());
List<JTypeVar> formals = t.getFormalTypeParams();
boolean change = false;
for (int i = 0; i < targs.size(); i++) {
JTypeMirror ai = targs.get(i);
JTypeMirror u = recursionStop.recurseIfNotDone(ai, (s, stop) -> s.acceptVisitor(this, stop));
if (u == ai) {
if (isCvar(ai)) { // cvar hit recursion stop
u = ts.UNBOUNDED_WILD;
change = true;
}
// no change, or handled by the visitWildcard
newTargs.add(u);
continue;
} else if (!upwards) {
// If Ai is a type that mentions a restricted type variable, then Ai' is undefined.
return NO_DOWN_PROJECTION;
}
change = true;
/*
If Ai is a type that mentions a restricted type variable...
*/
JTypeMirror bi = formals.get(i).getUpperBound();
if (u != ts.OBJECT && (mentionsAny(bi, formals) || !bi.isSubtypeOf(u))) {
newTargs.add(ts.wildcard(true, u));
} else {
JTypeMirror down = ai.acceptVisitor(DOWNWARDS_PROJECTOR, recursionStop);
if (down == NO_DOWN_PROJECTION) {
newTargs.add(ts.UNBOUNDED_WILD);
} else {
newTargs.add(ts.wildcard(false, down));
}
}
}
return change ? t.withTypeArguments(newTargs) : t;
} else {
return t;
}
}
@Override
public JTypeMirror visitIntersection(JIntersectionType t, RecursionStop recursionStop) {
List<JTypeMirror> comps = new ArrayList<>(t.getComponents());
boolean change = false;
for (int i = 0; i < comps.size(); i++) {
JTypeMirror ci = comps.get(i);
JTypeMirror proj = ci.acceptVisitor(this, recursionStop);
if (proj == NO_DOWN_PROJECTION) {
return NO_DOWN_PROJECTION;
} else {
comps.set(i, proj);
if (ci != proj) {
change = true;
}
}
}
return change ? t.getTypeSystem().glb(comps) : t;
}
@Override
public JTypeMirror visitArray(JArrayType t, RecursionStop recursionStop) {
JTypeMirror comp2 = t.getComponentType().acceptVisitor(this, recursionStop);
return comp2 == NO_DOWN_PROJECTION
? NO_DOWN_PROJECTION
: comp2 == t.getComponentType()
? t : t.getTypeSystem().arrayType(comp2);
}
@Override
public JTypeMirror visitSentinel(JTypeMirror t, RecursionStop recursionStop) {
return t;
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Overriding">
/**
* Returns true if m1 is return-type substitutable with m2. The notion of return-type-substitutability
* supports covariant returns, that is, the specialization of the return type to a subtype.
*
* https://docs.oracle.com/javase/specs/jls/se9/html/jls-8.html#jls-8.4.5
*/
public static boolean isReturnTypeSubstitutable(JMethodSig m1, JMethodSig m2) {
JTypeMirror r1 = m1.getReturnType();
JTypeMirror r2 = m2.getReturnType();
if (r1 == r1.getTypeSystem().NO_TYPE) {
return r1 == r2;
}
if (r1.isPrimitive()) {
return r1 == r2;
}
JMethodSig m1Prime = adaptForTypeParameters(m1, m2);
return m1Prime != null && isConvertible(m1Prime.getReturnType(), r2) != Convertibility.NEVER
|| !haveSameSignature(m1, m2) && isSameType(r1, r2.getErasure());
}
/**
* Adapt m1 to the type parameters of m2. Returns null if that's not possible.
*
* https://docs.oracle.com/javase/specs/jls/se9/html/jls-8.html#jls-8.4.4
*
* <p>Note that the type parameters of m1 are not replaced, only
* their occurrences in the rest of the signature.
*/
static @Nullable JMethodSig adaptForTypeParameters(JMethodSig m1, JMethodSig m2) {
if (haveSameTypeParams(m1, m2)) {
return m1.subst(mapping(m1.getTypeParameters(), m2.getTypeParameters()));
}
return null;
}
public static boolean haveSameTypeParams(JMethodSig m1, JMethodSig m2) {
List<JTypeVar> tp1 = m1.getTypeParameters();
List<JTypeVar> tp2 = m2.getTypeParameters();
if (tp1.size() != tp2.size()) {
return false;
}
if (tp1.isEmpty()) {
return true;
}
Substitution mapping = mapping(tp2, tp1);
for (int i = 0; i < tp1.size(); i++) {
JTypeVar p1 = tp1.get(i);
JTypeVar p2 = tp2.get(i);
if (!isSameType(p1.getUpperBound(), subst(p2.getUpperBound(), mapping))) {
return false;
}
}
return true;
}
/**
* Two method signatures m1 and m2 are override-equivalent iff either
* m1 is a subsignature of m2 or m2 is a subsignature of m1. This does
* not look at the origin of the methods (their declaring class).
*
* <p>This is a prerequisite for one method to override the other,
* but not the only condition. See {@link #overrides(JMethodSig, JMethodSig, JTypeMirror)}.
*
* See <a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-8.html#jls-8.4.2">JLS§8</a>
*/
public static boolean areOverrideEquivalent(JMethodSig m1, JMethodSig m2) {
// This method is a very hot spot as it is used to prune shadowed/overridden/hidden
// methods from overload candidates before overload resolution.
// Any optimization makes a big impact.
if (m1.getArity() != m2.getArity()) {
return false; // easy case
} else if (m1 == m2) {
return true;
} else if (!m1.getName().equals(m2.getName())) {
// note: most call sites statically know this is true
// profile to figure out whether this matters
return false;
}
List<JTypeMirror> formals1 = m1.getFormalParameters();
List<JTypeMirror> formals2 = m2.getFormalParameters();
for (int i = 0; i < formals1.size(); i++) {
JTypeMirror fi1 = formals1.get(i);
JTypeMirror fi2 = formals2.get(i);
if (!isSameType(fi1.getErasure(), fi2.getErasure())) {
return false;
}
}
// a non-generic method may override a generic one
return !m1.isGeneric() || !m2.isGeneric()
// if both are generic, they must have the same type params
|| haveSameTypeParams(m1, m2);
}
/**
* The signature of a method m1 is a subsignature of the signature of a method m2 if either:
* - m2 has the same signature as m1, or
* - the signature of m1 is the same as the erasure (§4.6) of the signature of m2.
*/
public static boolean isSubSignature(JMethodSig m1, JMethodSig m2) {
// prune easy cases
if (m1.getArity() != m2.getArity() || !m1.getName().equals(m2.getName())) {
return false;
}
boolean m1Gen = m1.isGeneric();
boolean m2Gen = m2.isGeneric();
if (m1Gen ^ m2Gen) {
if (m1Gen) {
return false; // this test is assymetric
} else {
m2 = m2.getErasure();
}
}
return haveSameSignature(m1, m2);
}
/**
* Two methods or constructors, M and N, have the same signature if
* they have the same name, the same type parameters (if any) (§8.4.4),
* and, after adapting the formal parameter types of N to the the type
* parameters of M, the same formal parameter types.
*
* Thrown exceptions are not part of the signature of a method.
*/
private static boolean haveSameSignature(JMethodSig m1, JMethodSig m2) {
return m1.getName().equals(m2.getName())
&& m1.getArity() == m2.getArity()
&& haveSameTypeParams(m1, m2)
&& areSameTypes(m1.getFormalParameters(),
m2.getFormalParameters(),
Substitution.mapping(m2.getTypeParameters(), m1.getTypeParameters()));
}
/**
* Returns true if m1 overrides m2, when both are view as members of
* class origin. m1 and m2 may be declared in supertypes of origin,
* possibly unrelated (default methods), which is why we need that
* third parameter. By convention a method overrides itself.
*
* <p>This method ignores the static modifier. If both methods are
* static, then this method tests for <i>hiding</i>. Otherwise, this
* method properly tests for overriding. Note that it is an error for
* a static method to override an instance method, or the reverse.
*/
public static boolean overrides(JMethodSig m1, JMethodSig m2, JTypeMirror origin) {
if (m1.isConstructor() || m2.isConstructor()) {
return m1.equals(m2); // "by convention a method overrides itself"
}
JTypeMirror m1Owner = m1.getDeclaringType();
JClassType m2Owner = (JClassType) m2.getDeclaringType();
if (isOverridableIn(m2, m1Owner.getSymbol())) {
JClassType m2AsM1Supertype = (JClassType) m1Owner.getAsSuper(m2Owner.getSymbol());
if (m2AsM1Supertype != null) {
JMethodSig m2Prime = m2AsM1Supertype.getDeclaredMethod(m2.getSymbol());
assert m2Prime != null;
if (isSubSignature(m1, m2Prime)) {
return true;
}
}
}
// todo that is very weird
if (m1.isAbstract()
|| !m2.isAbstract() && !m2.getSymbol().isDefaultMethod()
|| !isOverridableIn(m2, origin.getSymbol())
|| !(m1Owner instanceof JClassType)) {
return false;
}
JTypeMirror m1AsSuper = origin.getAsSuper(((JClassType) m1Owner).getSymbol());
JTypeMirror m2AsSuper = origin.getAsSuper(m2Owner.getSymbol());
if (m1AsSuper instanceof JClassType && m2AsSuper instanceof JClassType) {
m1 = ((JClassType) m1AsSuper).getDeclaredMethod(m1.getSymbol());
m2 = ((JClassType) m2AsSuper).getDeclaredMethod(m2.getSymbol());
assert m1 != null && m2 != null;
return isSubSignature(m1, m2);
}
return false;
}
private static boolean isOverridableIn(JMethodSig m, JTypeDeclSymbol origin) {
return isOverridableIn(m.getSymbol(), origin);
}
/**
* Returns true if the given method can be overridden in the origin
* class. This only checks access modifiers and not eg whether the
* method is final or static. Regardless of whether the method is
* final it is overridden - whether this is a compile error or not
* is another matter.
*
* <p>Like {@link #overrides(JMethodSig, JMethodSig, JTypeMirror)},
* this does not check the static modifier, and tests for hiding
* if the method is static.
*
* @param m Method to test
* @param origin Site of the potential override
*/
public static boolean isOverridableIn(JExecutableSymbol m, JTypeDeclSymbol origin) {
if (m instanceof JConstructorSymbol) {
return false;
}
final int accessFlags = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE;
// JLS 8.4.6.1
switch (m.getModifiers() & accessFlags) {
case Modifier.PUBLIC:
return true;
case Modifier.PROTECTED:
return !origin.isInterface();
case 0:
// package private
return
m.getPackageName().equals(origin.getPackageName())
&& !origin.isInterface();
default:
// private
return false;
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="SAM types">
/*
* Function types of SAM (single-abstract-method) types.
*
* See https://docs.oracle.com/javase/specs/jls/se11/html/jls-9.html#jls-9.9
*/
/**
* Returns the non-wildcard parameterization of the given functional
* interface type. Returns null if such a parameterization does not
* exist.
*
* <p>This is used to remove wildcards from the type of a functional
* interface.
*
* https://docs.oracle.com/javase/specs/jls/se9/html/jls-9.html#jls-9.9
*
* @param type A parameterized functional interface type
*/
public static @Nullable JClassType nonWildcardParameterization(@NonNull JClassType type) {
TypeSystem ts = type.getTypeSystem();
List<JTypeMirror> targs = type.getTypeArgs();
if (targs.stream().noneMatch(it -> it instanceof JWildcardType)) {
return type;
}
List<JTypeVar> tparams = type.getFormalTypeParams();
List<JTypeMirror> newArgs = new ArrayList<>();
for (int i = 0; i < tparams.size(); i++) {
JTypeMirror ai = targs.get(i);
if (ai instanceof JWildcardType) {
JTypeVar pi = tparams.get(i);
JTypeMirror bi = pi.getUpperBound();
if (mentionsAny(bi, new HashSet<>(tparams))) {
return null;
}
JWildcardType ai2 = (JWildcardType) ai;
if (ai2.isUnbounded()) {
newArgs.add(bi);
} else if (ai2.isUpperBound()) {
newArgs.add(ts.glb(Arrays.asList(ai2.asUpperBound(), bi)));
} else { // lower bound
newArgs.add(ai2.asLowerBound());
}
} else {
newArgs.add(ai);
}
}
return type.withTypeArguments(newArgs);
}
/**
* Finds the method of the given type that can be overridden as a lambda
* expression. That is more complicated than "the unique abstract method",
* it's actually a function type which can override all abstract methods
* of the SAM at once.
*
* https://docs.oracle.com/javase/specs/jls/se9/html/jls-9.html#jls-9.9
*
* <p>If the parameter is not mappable to a class type with {@link #asClassType(JTypeMirror)},
* or if the functional method does not exist, returns null.
*/
public static @Nullable JMethodSig findFunctionalInterfaceMethod(@Nullable JTypeMirror type) {
JClassType candidateSam = asClassType(type);
if (candidateSam == null) {
return null;
}
if (candidateSam.isParameterizedType()) {
return findFunctionTypeImpl(nonWildcardParameterization(candidateSam));
} else if (candidateSam.isRaw()) {
// The function type of the raw type of a generic functional
// interface I<...> is the erasure of the function type of the generic functional interface I<...>.
JMethodSig fun = findFunctionTypeImpl(candidateSam.getGenericTypeDeclaration());
return fun == null ? null : fun.getErasure();
} else {
return findFunctionTypeImpl(candidateSam);
}
}
/**
* Returns t if it is a class or interface type. If it is an intersection type,
* returns the induced class or interface type. Returns null otherwise, including
* if the parameter is null.
*/
public static @Nullable JClassType asClassType(@Nullable JTypeMirror t) {
if (t instanceof JClassType) {
return (JClassType) t;
} else if (t instanceof JIntersectionType) {
return ((JIntersectionType) t).getInducedClassType();
}
return null;
}
private static @Nullable JMethodSig findFunctionTypeImpl(@Nullable JClassType candidateSam) {
if (candidateSam == null || !candidateSam.isInterface() || candidateSam.getSymbol().isAnnotation()) {
return null;
}
Map<String, List<JMethodSig>> relevantMethods = candidateSam.streamMethods(it -> !Modifier.isStatic(it.getModifiers()))
.filter(TypeOps::isNotDeclaredInClassObject)
.collect(Collectors.groupingBy(JMethodSig::getName, OverloadSet.collectMostSpecific(candidateSam)));
List<JMethodSig> candidates = new ArrayList<>();
for (Entry<String, List<JMethodSig>> entry : relevantMethods.entrySet()) {
for (JMethodSig sig : entry.getValue()) {
if (sig.isAbstract()) {
candidates.add(sig);
}
}
}
if (candidates.isEmpty()) {
return null;
} else if (candidates.size() == 1) {
return candidates.get(0);
}
JMethodSig currentBest = null;
nextCandidate:
for (int i = 0; i < candidates.size(); i++) {
JMethodSig cand = candidates.get(i);
for (JMethodSig other : candidates) {
if (!isSubSignature(cand, other)
|| !isReturnTypeSubstitutable(cand, other)) {
continue nextCandidate;
}
}
if (currentBest == null) {
currentBest = cand;
} else if (cand.getReturnType().isSubtypeOf(currentBest.getReturnType())) {
// select the most specific return type
currentBest = cand;
}
}
return currentBest;
}
private static boolean isNotDeclaredInClassObject(JMethodSig it) {
TypeSystem ts = it.getDeclaringType().getTypeSystem();
return ts.OBJECT.streamDeclaredMethods(om -> Modifier.isPublic(om.getModifiers())
&& om.nameEquals(it.getName()))
.noneMatch(om -> haveSameSignature(it, om));
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="As super">
/**
* @see JTypeMirror#getAsSuper(JClassSymbol)
*/
public static @Nullable JTypeMirror asSuper(@NonNull JTypeMirror t, @NonNull JClassSymbol s) {
if (!t.isPrimitive() && s.equals(t.getTypeSystem().OBJECT.getSymbol())) {
// interface types need to have OBJECT somewhere up their hierarchy
return t.getTypeSystem().OBJECT;
}
return t.acceptVisitor(AsSuperVisitor.INSTANCE, s);
}
/**
* Return the base type of t or any of its outer types that starts
* with the given type. If none exists, return null.
*/
public static JClassType asOuterSuper(JTypeMirror t, JClassSymbol sym) {
if (t instanceof JClassType) {
JClassType ct = (JClassType) t;
do {
JClassType sup = ct.getAsSuper(sym);
if (sup != null) {
return sup;
}
ct = ct.getEnclosingType();
} while (ct != null);
} else if (t instanceof JTypeVar || t instanceof JArrayType) {
return (JClassType) t.getAsSuper(sym);
}
return null;
}
private static final class AsSuperVisitor implements JTypeVisitor<@Nullable JTypeMirror, JClassSymbol> {
static final AsSuperVisitor INSTANCE = new AsSuperVisitor();
/** Parameter is the erasure of the target. */
@Override
public JTypeMirror visit(JTypeMirror t, JClassSymbol target) {
return null;
}
@Override
public JTypeMirror visitClass(JClassType t, JClassSymbol target) {
if (target.equals(t.getSymbol())) {
return t;
}
// prefer digging up the superclass first
JClassType sup = t.getSuperClass();
JClassType res = sup == null ? null : (JClassType) sup.acceptVisitor(this, target);
if (res != null) {
return res;
} else {
// then look in interfaces if possible
if (target.isInterface() || target.isUnresolved()) {
return firstResult(target, t.getSuperInterfaces());
}
}
return null;
}
@Override
public JTypeMirror visitIntersection(JIntersectionType t, JClassSymbol target) {
return firstResult(target, t.getComponents());
}
public @Nullable JTypeMirror firstResult(JClassSymbol target, Iterable<? extends JTypeMirror> components) {
for (JTypeMirror ci : components) {
@Nullable JTypeMirror sup = ci.acceptVisitor(this, target);
if (sup != null) {
return sup;
}
}
return null;
}
@Override
public JTypeMirror visitTypeVar(JTypeVar t, JClassSymbol target) {
// caution, infinite recursion
return t.getUpperBound().acceptVisitor(this, target);
}
@Override
public JTypeMirror visitArray(JArrayType t, JClassSymbol target) {
// Cloneable, Serializable, Object
JTypeMirror decl = t.getTypeSystem().declaration(target);
return t.isSubtypeOf(decl) ? decl : null;
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="LUB/GLB">
/**
* Returns a subset S of the parameter, whose components have no
* strict supertype in S.
*
* <pre>{@code
* S = { V | V in set, and for all W ≠ V in set, it is not the case that W <: V }
* }</pre>
*/
public static Set<JTypeMirror> mostSpecific(Collection<? extends JTypeMirror> set) {
Set<JTypeMirror> result = new LinkedHashSet<>(set.size());
// Notice that this loop needs a well-behaved subtyping relation,
// i.e. antisymmetric: A <: B && A != B implies not(B <: A)
// This is not the case if we include unchecked conversion in there,
// or special provisions for unresolved types.
vLoop:
for (JTypeMirror v : set) {
for (JTypeMirror w : set) {
if (!w.equals(v) && !hasUnresolvedSymbol(w) && isSubtypePure(w, v).bySubtyping()) {
continue vLoop;
}
}
result.add(v);
}
return result;
}
// </editor-fold>
/**
* Returns the components of t if it is an intersection type,
* otherwise returns t.
*/
public static List<JTypeMirror> asList(JTypeMirror t) {
if (t instanceof JIntersectionType) {
return ((JIntersectionType) t).getComponents();
} else {
return Collections.singletonList(t);
}
}
/** Returns a list with the erasures of the given types, may be unmodifiable. */
public static List<JTypeMirror> erase(Collection<? extends JTypeMirror> ts) {
return CollectionUtil.map(ts, JTypeMirror::getErasure);
}
// <editor-fold defaultstate="collapsed" desc="Mentions">
public static boolean mentions(@NonNull JTypeVisitable type, @NonNull InferenceVar parent) {
return type.acceptVisitor(MentionsVisitor.INSTANCE, Collections.singleton(parent));
}
public static boolean mentionsAny(JTypeVisitable t, Collection<? extends SubstVar> vars) {
return !vars.isEmpty() && t.acceptVisitor(MentionsVisitor.INSTANCE, vars);
}
private static final class MentionsVisitor implements JTypeVisitor<Boolean, Collection<? extends JTypeMirror>> {
static final MentionsVisitor INSTANCE = new MentionsVisitor();
@Override
public Boolean visit(JTypeMirror t, Collection<? extends JTypeMirror> targets) {
return false;
}
@Override
public Boolean visitTypeVar(JTypeVar t, Collection<? extends JTypeMirror> targets) {
return targets.contains(t);
}
@Override
public Boolean visitInferenceVar(InferenceVar t, Collection<? extends JTypeMirror> targets) {
return targets.contains(t);
}
@Override
public Boolean visitWildcard(JWildcardType t, Collection<? extends JTypeMirror> targets) {
return t.getBound().acceptVisitor(this, targets);
}
@Override
public Boolean visitMethodType(JMethodSig t, Collection<? extends JTypeMirror> targets) {
if (t.getReturnType().acceptVisitor(this, targets)) {
return true;
}
for (JTypeMirror fi : t.getFormalParameters()) {
if (fi.acceptVisitor(this, targets)) {
return true;
}
}
for (JTypeMirror ti : t.getThrownExceptions()) {
if (ti.acceptVisitor(this, targets)) {
return true;
}
}
return false;
}
@Override
public Boolean visitClass(JClassType t, Collection<? extends JTypeMirror> targets) {
JClassType encl = t.getEnclosingType();
if (encl != null && encl.acceptVisitor(this, targets)) {
return true;
}
for (JTypeMirror typeArg : t.getTypeArgs()) {
if (typeArg.acceptVisitor(this, targets)) {
return true;
}
}
return false;
}
@Override
public Boolean visitIntersection(JIntersectionType t, Collection<? extends JTypeMirror> targets) {
for (JTypeMirror comp : t.getComponents()) {
if (comp.acceptVisitor(this, targets)) {
return true;
}
}
return false;
}
@Override
public Boolean visitArray(JArrayType t, Collection<? extends JTypeMirror> targets) {
return t.getComponentType().acceptVisitor(this, targets);
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Accessibility utils">
public static Predicate<JMethodSymbol> accessibleMethodFilter(String name, @NonNull JClassSymbol symbol) {
return it -> it.nameEquals(name) && isAccessible(it, symbol);
}
public static Iterable<JMethodSig> lazyFilterAccessible(List<JMethodSig> visible, @NonNull JClassSymbol accessSite) {
return () -> IteratorUtil.filter(visible.iterator(), it -> isAccessible(it.getSymbol(), accessSite));
}
public static List<JMethodSig> filterAccessible(List<JMethodSig> visible, @NonNull JClassSymbol accessSite) {
return CollectionUtil.mapNotNull(visible, m -> isAccessible(m.getSymbol(), accessSite) ? m : null);
}
public static List<JMethodSig> getMethodsOf(JTypeMirror type, String name, boolean staticOnly, @NonNull JClassSymbol enclosing) {
if (staticOnly && type.isInterface()) {
// static methods, start on interface
// static interface methods are not inherited
return type.streamDeclaredMethods(staticMethodFilter(name, true, enclosing)).collect(Collectors.toList());
} else if (staticOnly) {
// static methods, doesn't start on interface
// -> ignore non-static, ignore any that are interfaces
return type.streamMethods(staticMethodFilter(name, false, enclosing)).collect(OverloadSet.collectMostSpecific(type));
} else {
return type.streamMethods(methodFilter(name, enclosing))
.collect(OverloadSet.collectMostSpecific(type));
}
}
private static @NonNull Predicate<JMethodSymbol> methodFilter(String name, @NonNull JClassSymbol enclosing) {
return it -> isAccessibleWithName(name, enclosing, it);
}
private static @NonNull Predicate<JMethodSymbol> staticMethodFilter(String name, boolean acceptItfs, @NonNull JClassSymbol enclosing) {
return it -> Modifier.isStatic(it.getModifiers())
&& (acceptItfs || !it.getEnclosingClass().isInterface())
&& isAccessibleWithName(name, enclosing, it);
}
private static boolean isAccessibleWithName(String name, @NonNull JClassSymbol enclosing, JMethodSymbol m) {
return m.nameEquals(name) && isAccessible(m, enclosing);
}
private static boolean isAccessible(JExecutableSymbol method, JClassSymbol ctx) {
Objects.requireNonNull(ctx, "Cannot check a null symbol");
int mods = method.getModifiers();
if (Modifier.isPublic(mods)) {
return true;
}
JClassSymbol owner = method.getEnclosingClass();
if (Modifier.isPrivate(mods)) {
return ctx.getNestRoot().equals(owner.getNestRoot());
}
return ctx.getPackageName().equals(owner.getPackageName())
// we can exclude interfaces because their members are all public
|| Modifier.isProtected(mods) && isSubClassOfNoInterface(ctx, owner);
}
private static boolean isSubClassOfNoInterface(JClassSymbol sub, JClassSymbol symbol) {
if (symbol.equals(sub)) {
return true;
}
JClassSymbol superclass = sub.getSuperclass();
return superclass != null && isSubClassOfNoInterface(superclass, symbol);
}
public static NameResolver<FieldSig> getMemberFieldResolver(JTypeMirror c, @NonNull String accessPackageName, @Nullable JClassSymbol access, String name) {
if (c instanceof JClassType) {
// fast path
return JavaResolvers.getMemberFieldResolver((JClassType) c, accessPackageName, access, name);
}
return c.acceptVisitor(GetFieldVisitor.INSTANCE, new FieldSearchParams(accessPackageName, access, name));
}
private static final class FieldSearchParams {
private final @NonNull String accessPackageName;
private final @Nullable JClassSymbol access;
private final String name;
FieldSearchParams(@NonNull String accessPackageName, @Nullable JClassSymbol access, String name) {
this.accessPackageName = accessPackageName;
this.access = access;
this.name = name;
}
}
private static final class GetFieldVisitor implements JTypeVisitor<NameResolver<FieldSig>, FieldSearchParams> {
static final GetFieldVisitor INSTANCE = new GetFieldVisitor();
@Override
public NameResolver<FieldSig> visit(JTypeMirror t, FieldSearchParams fieldSearchParams) {
return CoreResolvers.emptyResolver();
}
@Override
public NameResolver<FieldSig> visitClass(JClassType t, FieldSearchParams fieldSearchParams) {
return JavaResolvers.getMemberFieldResolver(t, fieldSearchParams.accessPackageName, fieldSearchParams.access, fieldSearchParams.name);
}
@Override
public NameResolver<FieldSig> visitTypeVar(JTypeVar t, FieldSearchParams fieldSearchParams) {
return t.getUpperBound().acceptVisitor(this, fieldSearchParams);
}
@Override
public NameResolver<FieldSig> visitIntersection(JIntersectionType t, FieldSearchParams fieldSearchParams) {
return NameResolver.composite(
CollectionUtil.map(t.getComponents(), c -> c.acceptVisitor(this, fieldSearchParams))
);
}
@Override
public NameResolver<FieldSig> visitArray(JArrayType t, FieldSearchParams fieldSearchParams) {
if ("length".equals(fieldSearchParams.name)) {
return CoreResolvers.singleton("length", t.getTypeSystem().sigOf(t, t.getSymbol().getDeclaredField("length")));
}
return CoreResolvers.emptyResolver();
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Miscellaneous">
/**
* Returns true if both types have a common supertype that is not Object.
* Primitive types are only related to themselves.
*
* @param t Non-null type
* @param s Non-null type
*
* @throws NullPointerException if a parameter is null
*/
public static boolean areRelated(@NonNull JTypeMirror t, JTypeMirror s) {
if (t.isPrimitive() || s.isPrimitive()) {
return s.equals(t);
}
if (t.equals(s)) {
return true;
}
// maybe they have a common supertype
Set<JTypeMirror> tSupertypes = new HashSet<>(t.getSuperTypeSet());
tSupertypes.retainAll(s.getSuperTypeSet());
return !tSupertypes.equals(Collections.singleton(t.getTypeSystem().OBJECT));
}
/**
* Returns true if the type is {@link TypeSystem#UNKNOWN},
* {@link TypeSystem#ERROR}, or its symbol is unresolved.
*
* @param t Non-null type
*
* @throws NullPointerException if the parameter is null
*/
public static boolean isUnresolved(@NonNull JTypeMirror t) {
return isSpecialUnresolved(t) || hasUnresolvedSymbol(t);
}
public static boolean isSpecialUnresolved(@NonNull JTypeMirror t) {
TypeSystem ts = t.getTypeSystem();
return t == ts.UNKNOWN || t == ts.ERROR;
}
/**
* Return true if the argument is a {@link JClassType} with
* {@linkplain JClassSymbol#isUnresolved() an unresolved symbol} or
* a {@link JArrayType} whose element type matches the first criterion.
*/
public static boolean hasUnresolvedSymbol(@Nullable JTypeMirror t) {
if (!(t instanceof JClassType)) {
return t instanceof JArrayType && hasUnresolvedSymbol(((JArrayType) t).getElementType());
}
return t.getSymbol() != null && t.getSymbol().isUnresolved();
}
public static boolean isUnresolvedOrNull(@Nullable JTypeMirror t) {
return t == null || isUnresolved(t);
}
public static @Nullable JTypeMirror getArrayComponent(@Nullable JTypeMirror t) {
return t instanceof JArrayType ? ((JArrayType) t).getComponentType() : null;
}
// </editor-fold>
}
| 76,045 | 36.113714 | 168 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/JWildcardType.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
/**
* Represents a wildcard type. Such types are converted to {@link JTypeVar}
* by {@linkplain TypeConversion#capture(JTypeMirror) capture conversion}.
*
* <p>This implements JTypeMirror for convenience, however, it may only
* occur as a type argument, and as such some of the behaviour of JTypeMirror
* is undefined: {@link #isSubtypeOf(JTypeMirror) subtyping} and {@link #getErasure() erasure}.
*/
public interface JWildcardType extends JTypeMirror {
/** Returns the bound. Interpretation is given by {@link #isUpperBound()}. */
@NonNull
JTypeMirror getBound();
/** Returns true if this is an "extends" wildcard, with no bound ("?"). */
default boolean isUnbounded() {
return isUpperBound() && getBound().isTop();
}
/** Returns true if this is an "extends" wildcard, the bound is then an upper bound. */
boolean isUpperBound();
/** Returns true if this is a "super" wildcard, the bound is then a lower bound. */
default boolean isLowerBound() {
return !isUpperBound();
}
/** Returns the lower bound, or the bottom type if this is an "extends" wildcard. */
default @NonNull JTypeMirror asLowerBound() {
return isUpperBound() ? getTypeSystem().NULL_TYPE : getBound();
}
/** Returns the upper bound, or Object if this is a "super" wildcard. */
default @NonNull JTypeMirror asUpperBound() {
return isUpperBound() ? getBound() : getTypeSystem().OBJECT;
}
/**
* This is implemented for convenience. However, the erasure of a
* wildcard type is undefined and useless. This is because they can
* only occur in type arguments, which are erased themselves.
*/
@Override
default JTypeMirror getErasure() {
return this;
}
@Override
default Stream<JMethodSig> streamMethods(Predicate<? super JMethodSymbol> prefilter) {
return asUpperBound().streamMethods(prefilter);
}
@Override
JWildcardType subst(Function<? super SubstVar, ? extends @NonNull JTypeMirror> subst);
@Override
JWildcardType withAnnotations(PSet<SymAnnot> newTypeAnnots);
@Override
default <T, P> T acceptVisitor(JTypeVisitor<T, P> visitor, P p) {
return visitor.visitWildcard(this, p);
}
}
| 2,734 | 29.730337 | 95 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/JTypeVisitor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar;
/**
* Visits a type. This allows implementing many algorithms simply.
*
* @param <R> Return type
* @param <P> Parameter type
*/
public interface JTypeVisitor<R, P> {
R visit(JTypeMirror t, P p);
default R visitClass(JClassType t, P p) {
return visit(t, p);
}
default R visitWildcard(JWildcardType t, P p) {
return visit(t, p);
}
default R visitPrimitive(JPrimitiveType t, P p) {
return visit(t, p);
}
default R visitTypeVar(JTypeVar t, P p) {
return visit(t, p);
}
default R visitInferenceVar(InferenceVar t, P p) {
return visit(t, p);
}
default R visitMethodType(JMethodSig t, P p) {
throw new UnsupportedOperationException("You can't do this by accident");
}
default R visitIntersection(JIntersectionType t, P p) {
return visit(t, p);
}
default R visitArray(JArrayType t, P p) {
return visit(t, p);
}
default R visitNullType(JTypeMirror t, P p) {
return visit(t, p);
}
/**
* Visit a sentinel type. The argument may be one of
* {@link TypeSystem#UNKNOWN}, {@link TypeSystem#NO_TYPE},
* and {@link TypeSystem#NULL_TYPE}.
*/
default R visitSentinel(JTypeMirror t, P p) {
return visit(t, p);
}
}
| 1,516 | 19.226667 | 81 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/ClassTypeImpl.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import static net.sourceforge.pmd.util.CollectionUtil.emptyList;
import static net.sourceforge.pmd.util.CollectionUtil.map;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Stream;
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.symbols.JClassSymbol;
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.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.lang.java.symbols.table.internal.SuperTypesEnumerator;
import net.sourceforge.pmd.lang.java.types.JVariableSig.FieldSig;
import net.sourceforge.pmd.util.CollectionUtil;
class ClassTypeImpl implements JClassType {
private final @Nullable JClassType enclosingType;
private final JClassSymbol symbol;
private final TypeSystem ts;
private final List<JTypeMirror> typeArgs;
private final PSet<SymAnnot> typeAnnotations;
private final TypeGenericity genericity;
private JClassType superClass;
private List<JClassType> interfaces;
private Substitution subst;
// Cache the hash. Instances are super often put in sets or used as
// map keys and hash computation is expensive since we recurse in the
// type arguments. This was confirmed through profiling
private int hash = 0;
/**
* @param symbol Erased type
* @param typeArgs Type arguments of this parameterization. If empty
* and isDecl is false, this will represent a raw type.
* If empty and isDecl is true, this will represent a
* generic type declaration.
* @param isRaw Choose a bias towards generic type declaration or raw
* type. If the [rawType] param has no type parameters,
* then this parameter makes *no difference*.
*
* @throws IllegalArgumentException if the typeArgs don't have the same length
* as the type's type parameters
* @throws IllegalArgumentException if any type argument is of a primitive type.
*/
ClassTypeImpl(TypeSystem ts, JClassSymbol symbol, List<JTypeMirror> typeArgs, boolean isRaw, PSet<SymAnnot> typeAnnotations) {
this(ts, null, symbol, typeArgs, typeAnnotations, isRaw);
}
private ClassTypeImpl(TypeSystem ts, JClassType enclosing, JClassSymbol symbol, List<JTypeMirror> typeArgs, PSet<SymAnnot> typeAnnotations, boolean isRaw) {
this.typeAnnotations = typeAnnotations;
validateParams(enclosing, symbol, typeArgs);
this.ts = ts;
this.symbol = symbol;
this.typeArgs = typeArgs;
this.enclosingType = enclosing != null
? enclosing
: makeEnclosingOf(symbol);
this.genericity = computeGenericity(isRaw);
}
// Special ctor for boxed primitives and other specials that are built
// during initialization of TypeSystem. This cannot call JClassSymbol#isGeneric,
// because that would trigger parsing of the class file while the type system is not ready
protected ClassTypeImpl(TypeSystem ts, JClassSymbol symbol, PSet<SymAnnot> typeAnnotations) {
this.typeAnnotations = typeAnnotations;
this.ts = ts;
this.symbol = symbol;
this.typeArgs = emptyList();
this.enclosingType = null;
this.genericity = TypeGenericity.NON_GENERIC;
}
private @NonNull TypeGenericity computeGenericity(boolean isRaw) {
boolean isGeneric = symbol.isGeneric();
if (enclosingType != null && enclosingType.isRaw()) {
return TypeGenericity.RAW;
} else if (typeArgs.isEmpty()) {
if (isGeneric && isRaw) {
return TypeGenericity.RAW;
} else if (isGeneric) {
return TypeGenericity.GENERIC_TYPEDECL;
} else {
return TypeGenericity.NON_GENERIC;
}
} else {
return TypeGenericity.GENERIC_PARAMETERIZED;
}
}
private JClassType makeEnclosingOf(JClassSymbol sym) {
if (Modifier.isStatic(sym.getModifiers())) {
return null;
}
JClassSymbol enclosing = sym.getEnclosingClass();
if (enclosing == null) {
return null;
}
// this means, that all enclosing types of a raw type are erased.
if (this.hasErasedSuperTypes()) {
return ts.erasedType(enclosing);
}
return (JClassType) ts.typeOf(enclosing, false);
}
@Override
public TypeSystem getTypeSystem() {
return ts;
}
@Override
public PSet<SymAnnot> getTypeAnnotations() {
return typeAnnotations;
}
@Override
public JClassType withAnnotations(PSet<SymAnnot> newTypeAnnots) {
if (newTypeAnnots.isEmpty() && this.typeAnnotations.isEmpty()) {
return this;
}
return new ClassTypeImpl(ts, enclosingType, symbol, typeArgs, newTypeAnnots, isRaw());
}
@Override
public List<JTypeVar> getFormalTypeParams() {
return symbol.getTypeParameters();
}
@Override
public Substitution getTypeParamSubst() {
if (subst == null) {
Substitution enclSubst = getEnclosingType() == null
? Substitution.EMPTY
: getEnclosingType().getTypeParamSubst();
subst = enclSubst.andThen(localSubst());
}
return subst;
}
private Substitution localSubst() {
if (hasErasedSuperTypes()) {
return Substitution.erasing(getFormalTypeParams());
} else if (isGenericTypeDeclaration() || !isGeneric()) {
return Substitution.EMPTY;
} else {
return Substitution.mapping(getFormalTypeParams(), getTypeArgs());
}
}
/**
* Given a type appearing in a member, and the given substitution
*/
static JTypeMirror eraseToRaw(JTypeMirror t, Substitution typeSubst) {
if (TypeOps.mentionsAny(t, typeSubst.getMap().keySet())) {
return t.getErasure();
} else {
// This type does not depend on any of the type variables to erase.
return t;
}
}
/**
* Given a type appearing in a member of the given owner, erase
* the member type if the owner is raw. The type needs not be erased
* if it is generic but does not mention any of the type variables
* to erase.
*/
static JTypeMirror maybeEraseMemberType(JClassType owner, JTypeMirror t) {
if (owner.isRaw() && TypeOps.mentionsAny(t, owner.getTypeParamSubst().getMap().keySet())) {
return t.getErasure();
} else {
// This type does not depend on any of the type variables to erase.
return t;
}
}
static List<JTypeMirror> maybeEraseMemberType(JClassType owner, List<JTypeMirror> ts) {
if (owner.isRaw()) {
return map(ts, t -> maybeEraseMemberType(owner, t));
} else {
// This type does not depend on any of the type variables to erase.
return ts;
}
}
@Override
public final JClassType selectInner(JClassSymbol symbol, List<? extends JTypeMirror> targs, PSet<SymAnnot> typeAnnotations) {
return new ClassTypeImpl(ts,
this,
symbol,
CollectionUtil.defensiveUnmodifiableCopy(targs),
typeAnnotations,
isRaw());
}
@Override
public final boolean isRaw() {
return genericity == TypeGenericity.RAW;
}
@Override
public final boolean isGenericTypeDeclaration() {
return genericity == TypeGenericity.GENERIC_TYPEDECL;
}
@Override
public final boolean isParameterizedType() {
return genericity == TypeGenericity.GENERIC_PARAMETERIZED;
}
@Override
public final boolean isGeneric() {
return genericity != TypeGenericity.NON_GENERIC;
}
@Override
public JClassType getGenericTypeDeclaration() {
if (isGenericTypeDeclaration() || !isGeneric()) {
return this;
}
return new ClassTypeImpl(ts, symbol, emptyList(), false, typeAnnotations);
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<JTypeMirror> getTypeArgs() {
return isGenericTypeDeclaration() ? (List) getFormalTypeParams() : typeArgs;
}
@Override
public @Nullable JClassType getEnclosingType() {
return enclosingType;
}
@Override
public boolean hasErasedSuperTypes() {
return isRaw();
}
@Override
public JClassType getErasure() {
if ((!isGeneric() || isRaw()) && enclosingType == null) {
return this;
}
return new ErasedClassType(ts, symbol, typeAnnotations);
}
@Override
public JClassType withTypeArguments(List<? extends JTypeMirror> typeArgs) {
if (enclosingType != null) {
return enclosingType.selectInner(this.symbol, typeArgs, this.typeAnnotations);
}
int expected = symbol.getTypeParameterCount();
if (expected == 0 && typeArgs.isEmpty() && this.typeArgs.isEmpty()) {
return this; // non-generic
}
return new ClassTypeImpl(ts, symbol, CollectionUtil.defensiveUnmodifiableCopy(typeArgs), true, typeAnnotations);
}
@Override
public @Nullable JClassType getSuperClass() {
if (superClass == null && !isTop()) {
if (hasErasedSuperTypes()) {
superClass = ts.erasedType(symbol.getSuperclass());
} else {
superClass = symbol.getSuperclassType(getTypeParamSubst());
}
}
return superClass;
}
@Override
public List<JClassType> getSuperInterfaces() {
if (interfaces == null) {
if (hasErasedSuperTypes()) {
interfaces = map(symbol.getSuperInterfaces(), ts::erasedType);
} else {
interfaces = symbol.getSuperInterfaceTypes(getTypeParamSubst());
}
}
return interfaces;
}
@Override
public List<FieldSig> getDeclaredFields() {
return CollectionUtil.map(symbol.getDeclaredFields(), it -> JVariableSig.forField(this, it));
}
@Override
public List<JClassType> getDeclaredClasses() {
return CollectionUtil.map(symbol.getDeclaredClasses(), this::getDeclaredClass);
}
private JClassType getDeclaredClass(JClassSymbol inner) {
if (Modifier.isStatic(inner.getModifiers())) {
return new ClassTypeImpl(ts, null, inner, emptyList(), typeAnnotations, isRaw());
} else {
return selectInner(inner, emptyList());
}
}
@Override
public @Nullable FieldSig getDeclaredField(String simpleName) {
@Nullable JFieldSymbol declaredField = symbol.getDeclaredField(simpleName);
if (declaredField != null) {
return JVariableSig.forField(this, declaredField);
}
return null;
}
@Override
public @Nullable JClassType getDeclaredClass(String simpleName) {
JClassSymbol declaredClass = symbol.getDeclaredClass(simpleName);
if (declaredClass != null) {
if (Modifier.isStatic(declaredClass.getModifiers())) {
return new ClassTypeImpl(ts, null, declaredClass, emptyList(), HashTreePSet.empty(), isRaw());
} else {
return selectInner(declaredClass, emptyList());
}
}
return null;
}
@Override
public List<JMethodSig> getConstructors() {
return map(
symbol.getConstructors(),
it -> new ClassMethodSigImpl(this, it)
);
}
@Override
public Stream<JMethodSig> streamMethods(Predicate<? super JMethodSymbol> prefilter) {
return SuperTypesEnumerator.ALL_SUPERTYPES_INCLUDING_SELF.stream(this)
.flatMap(sup -> sup.streamDeclaredMethods(prefilter));
}
@Override
public Stream<JMethodSig> streamDeclaredMethods(Predicate<? super JMethodSymbol> prefilter) {
return getSymbol().getDeclaredMethods().stream()
.filter(prefilter)
.map(m -> new ClassMethodSigImpl(this, m));
}
@Override
public @Nullable JMethodSig getDeclaredMethod(JExecutableSymbol sym) {
if (sym.getEnclosingClass().equals(getSymbol())) {
return new ClassMethodSigImpl(this, sym);
}
return null;
}
@Override
public final @NonNull JClassSymbol getSymbol() {
return symbol;
}
@Override
public final boolean isTop() {
return this.getSymbol().equals(ts.OBJECT.getSymbol()); // NOPMD CompareObjectsWithEquals
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof JClassType)) {
return false;
}
JClassType that = (JClassType) o;
return TypeOps.isSameType(this, that);
}
@Override
public int hashCode() {
if (hash == 0) { // hash collision is harmless
hash = typeArgs.hashCode() * 31 + symbol.hashCode();
}
return hash;
}
@Override
public String toString() {
return TypePrettyPrint.prettyPrint(this);
}
private static void validateParams(JClassType enclosing, JClassSymbol symbol, List<JTypeMirror> typeArgs) {
Objects.requireNonNull(symbol, "Symbol shouldn't be null");
checkUserEnclosingTypeIsOk(enclosing, symbol);
if (!typeArgsAreOk(symbol, typeArgs)) {
throw invalidTypeArgs(symbol, typeArgs);
}
for (JTypeMirror arg : typeArgs) {
checkTypeArg(symbol, typeArgs, arg);
}
}
protected static @NonNull IllegalArgumentException invalidTypeArgs(JClassSymbol symbol, List<? extends JTypeMirror> typeArgs) {
return new IllegalArgumentException("Cannot parameterize " + symbol + " with " + typeArgs
+ ", expecting " + symbol.getTypeParameterCount()
+ " type arguments");
}
private static void checkTypeArg(JClassSymbol symbol, List<JTypeMirror> typeArgs, JTypeMirror arg) {
if (arg == null) {
throw new IllegalArgumentException("Null type argument for " + symbol + " in " + typeArgs);
} else if (arg.isPrimitive()) {
throw new IllegalArgumentException("Primitive type argument for " + symbol + " in " + typeArgs);
}
}
private static boolean typeArgsAreOk(JClassSymbol symbol, List<? extends JTypeMirror> typeArgs) {
return typeArgs.isEmpty() // always ok (raw/ decl/ non-generic)
|| symbol.isUnresolved()
|| symbol.getTypeParameterCount() == typeArgs.size();
}
private static void checkUserEnclosingTypeIsOk(@Nullable JClassType enclosing, JClassSymbol symbol) {
// TODO all enclosing types should be raw, or all should be parameterized
if (symbol.isUnresolved() || enclosing != null && enclosing.getSymbol().isUnresolved()) {
return;
}
if (enclosing != null) {
if (Modifier.isStatic(symbol.getModifiers())) {
throw new IllegalArgumentException("Cannot select *static* type " + symbol + " inside " + enclosing);
} else if (!enclosing.getSymbol().equals(symbol.getEnclosingClass())) {
throw new IllegalArgumentException("Cannot select type " + symbol + " inside " + enclosing);
}
}
}
private enum TypeGenericity {
RAW,
GENERIC_TYPEDECL,
GENERIC_PARAMETERIZED,
NON_GENERIC
}
}
| 16,516 | 33.993644 | 160 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/ArrayMethodSigImpl.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import static java.util.Collections.emptyList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
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.symbols.JConstructorSymbol;
import net.sourceforge.pmd.lang.java.symbols.JExecutableSymbol;
import net.sourceforge.pmd.lang.java.types.internal.InternalMethodTypeItf;
// for array clone or array constructor
class ArrayMethodSigImpl implements JMethodSig, InternalMethodTypeItf {
private final JArrayType owner;
// either method or constructor
private final JExecutableSymbol symbol;
ArrayMethodSigImpl(JArrayType owner,
@NonNull JExecutableSymbol symbol) {
this.owner = owner;
this.symbol = symbol;
}
@Override
public TypeSystem getTypeSystem() {
return owner.getTypeSystem();
}
@Override
public JExecutableSymbol getSymbol() {
return symbol;
}
@Override
public JArrayType getDeclaringType() {
return owner;
}
@Override
public JMethodSig getErasure() {
JArrayType erasedOwner = owner.getErasure();
return erasedOwner == owner ? this : new ArrayMethodSigImpl(erasedOwner, symbol); // NOPMD CompareObjectsWithEquals
}
@Override
public JTypeMirror getAnnotatedReceiverType() {
return owner;
}
@Override
public JTypeMirror getReturnType() {
return owner; // clone or cons
}
@Override
public List<JTypeMirror> getFormalParameters() {
if (getSymbol() instanceof JConstructorSymbol) {
return Collections.singletonList(owner.getTypeSystem().INT);
}
return emptyList();
}
@Override
public List<JTypeVar> getTypeParameters() {
return emptyList();
}
@Override
public List<JTypeMirror> getThrownExceptions() {
return emptyList();
}
@Override
public InternalMethodTypeItf internalApi() {
return this;
}
@Override
public JMethodSig withReturnType(JTypeMirror returnType) {
if (!returnType.equals(owner)) {
throw new UnsupportedOperationException("Something went wrong");
}
return this;
}
@Override
public JMethodSig withTypeParams(@Nullable List<JTypeVar> tparams) {
if (tparams != null && !tparams.isEmpty()) {
throw new UnsupportedOperationException("Something went wrong");
}
return this;
}
@Override
public JMethodSig subst(Function<? super SubstVar, ? extends JTypeMirror> fun) {
JArrayType subbed = (JArrayType) TypeOps.subst(owner, fun);
return new ArrayMethodSigImpl(subbed, getSymbol());
}
@Override
public JMethodSig withOwner(JTypeMirror newOwner) {
if (newOwner instanceof JArrayType) {
return new ArrayMethodSigImpl((JArrayType) newOwner, symbol);
} else {
throw new IllegalArgumentException(newOwner + " cannot be the owner of " + this);
}
}
@Override
public JMethodSig markAsAdapted() {
return this;
}
@Override
public JMethodSig originalMethod() {
return new ArrayMethodSigImpl(owner, symbol);
}
@Override
public JMethodSig adaptedMethod() {
return originalMethod();
}
@Override
public String toString() {
return TypePrettyPrint.prettyPrint(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof JMethodSig)) {
return false;
}
JMethodSig that = (JMethodSig) o;
return TypeOps.isSameType(this, that);
}
@Override
public int hashCode() {
return Objects.hash(getName(), getFormalParameters(), getReturnType());
}
}
| 4,107 | 24.836478 | 123 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/JMethodSig.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.function.Function;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.java.symbols.JConstructorSymbol;
import net.sourceforge.pmd.lang.java.symbols.JExecutableSymbol;
import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol;
import net.sourceforge.pmd.lang.java.types.internal.InternalMethodTypeItf;
/**
* Represents the signature of methods and constructors. An instance of
* this interface is a {@link JMethodSymbol} viewed under a particular
* substitution.
*
* <p>All the types returned by {@link #getFormalParameters()},
* {@link #getReturnType()}, {@link #getTypeParameters()} and
* {@link #getThrownExceptions()} can mention type parameters of the method,
* of its {@linkplain #getDeclaringType() declaring type} and all its enclosing
* types.
*
* <p>Typically the output of type inference is a method symbol whose
* type parameters have been given a specific instantiation. But If a signature
* is produced by type inference, it may not match
* its symbol exactly (ie, not just be a substitution applied to the
* symbol's type parameters), to account for special cases depending
* on context information. For example, the actual return type of a method
* whose applicability required an unchecked conversion is the erasure of the
* return type of the declaration.
*/
public interface JMethodSig extends JTypeVisitable {
/** Return the type system with which this method was created. */
TypeSystem getTypeSystem();
/** Return the symbol of the method or constructor. */
JExecutableSymbol getSymbol();
/**
* Return the name of the method. If this is a constructor,
* returns {@link JConstructorSymbol#CTOR_NAME}.
*/
default String getName() {
return getSymbol().getSimpleName();
}
/** Return whether this is a constructor. */
default boolean isConstructor() {
return JConstructorSymbol.CTOR_NAME.equals(getName());
}
/** Return method modifiers as decodable by {@link java.lang.reflect.Modifier}. */
default int getModifiers() {
return getSymbol().getModifiers();
}
/**
* Return the type that declares this method. May be an array type,
* a class type. If this is a constructor for a generic class, returns
* the generic type declaration of the constructor.
*/
JTypeMirror getDeclaringType();
/**
* Return the type of {@code this} in the body of the method. This
* is the declaring type with
*/
JTypeMirror getAnnotatedReceiverType();
/**
* Return the result type of the method. If this is a constructor,
* returns the type of the instance produced by the constructor. In
* particular, for a diamond constructor call, returns the inferred
* type. For example for {@code List<String> l = new ArrayList<>()},
* returns {@code ArrayList<String>}.
*/
JTypeMirror getReturnType();
/**
* The erasure of a method is a new, non-generic method, whose
* parameters, owner, and return type, are erased. For example:
* <pre>{@code
* <N extends Number, U> U fun(N, Supplier<U>, U);
* }</pre>
* erases to
* <pre>
* Object fun(Number, Supplier, Object);
* </pre>
*/
JMethodSig getErasure();
/**
* Return the types of the formal parameters. If this is a varargs
* method, the last parameter should have an array type. For generic
* methods that have been inferred, these are substituted with the
* inferred type parameters. For example for {@code Arrays.asList("a", "b")},
* returns a singleton list containing {@code String[]}.
*/
List<JTypeMirror> getFormalParameters();
/**
* Number of formal parameters. A varargs parameter counts as one.
*/
default int getArity() {
return getSymbol().getArity();
}
/**
* Return the type parameters of the method. After type inference,
* occurrences of these type parameters are replaced by their instantiation
* in formals, return type and thrown exceptions (but not type parameter bounds).
* If instantiation failed, some variables might have been substituted
* with {@link TypeSystem#ERROR}.
*/
List<JTypeVar> getTypeParameters();
/**
* Return the list of thrown exception types. Exception types may
* be type variables of the method or of an enclosing context, that
* extend Throwable.
*/
List<JTypeMirror> getThrownExceptions();
/** Return true if this method is abstract. */
default boolean isAbstract() {
return Modifier.isAbstract(getModifiers());
}
/** Return true if this method is static. */
default boolean isStatic() {
return Modifier.isStatic(getModifiers());
}
/** Return true if this method has a varargs parameter. */
default boolean isVarargs() {
return getSymbol().isVarargs();
}
/**
* Return true if this method signature declares type parameters.
*/
default boolean isGeneric() {
// do not override
// the type parameters may be adapted and we
// can't compare to the symbol
return !getTypeParameters().isEmpty();
}
@Override
JMethodSig subst(Function<? super SubstVar, ? extends @NonNull JTypeMirror> subst);
@Override
default <T, P> T acceptVisitor(JTypeVisitor<T, P> visitor, P p) {
return visitor.visitMethodType(this, p);
}
/**
* Internal API, should not be used outside of the type inference
* implementation.
*/
@InternalApi
InternalMethodTypeItf internalApi();
}
| 5,926 | 31.037838 | 87 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/TypesFromReflection.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.reflect.TypeLiteral;
import org.apache.commons.lang3.reflect.Typed;
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.UnresolvedClassStore;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* Builds type mirrors from {@link Type} instances.
*
* <p>This is intended as a public API to help rules build types.
*/
public final class TypesFromReflection {
private TypesFromReflection() {
// util class
}
/**
* Builds a type from reflection. This overload expects a ground type,
* ie it will fail if the given type mentions type variables. This can
* be used to get a type quickly, eg:
* <pre>{@code
*
* // note the anonymous class body
* JTypeMirror streamOfInt = fromReflect(new TypeLiteral<Stream<Integer>>() {}, node.getTypeSystem());
*
* if (node.getTypeMirror().equals(streamOfInt))
* addViolation(node, "Use IntStream instead of Stream<Integer>");
*
* // going the long way:
* TypeSystem ts = node.getTypeSystem();
* JTypeMirror streamOfInt = ts.typeOf(ts.getClassSymbol(Stream.class), false)
* .withTypeParameters(listOf(ts.INT.box()));
*
* }</pre>
*
* @param ts Type system that will build the type
* @param reflected A {@link Typed} instance, eg a {@link TypeLiteral}.
*
* @throws IllegalArgumentException If the given type mentions type variables
* @throws NullPointerException If the type, or the type system, are null
*/
public static JTypeMirror fromReflect(Typed<?> reflected, TypeSystem ts) {
return fromReflect(ts, reflected.getType(), LexicalScope.EMPTY, Substitution.EMPTY);
}
public static JTypeMirror fromReflect(Type reflected, TypeSystem ts) {
return fromReflect(ts, reflected, LexicalScope.EMPTY, Substitution.EMPTY);
}
/**
* Builds a type from reflection. This takes care of preserving the
* identity of type variables.
*
* @param ts Type system
* @param reflected A type instance obtained from reflection
* @param lexicalScope An index for the in-scope type variables. All
* type variables occurring in the type must be
* referenced.
* @param subst Substitution to apply to tvars
*
* @return A type, or null if the type system's symbol resolver cannot map
* the types to its own representation
*
* @throws IllegalArgumentException If there are free type variables in the type.
* Any type variable should be accessible in the
* lexical scope parameter.
* @throws NullPointerException If any parameter is null
*/
public static @Nullable JTypeMirror fromReflect(TypeSystem ts, @NonNull Type reflected, LexicalScope lexicalScope, Substitution subst) {
Objects.requireNonNull(reflected, "Null type");
Objects.requireNonNull(ts, "Null type system");
Objects.requireNonNull(lexicalScope, "Null lexical scope, use the empty scope");
Objects.requireNonNull(subst, "Null substitution, use the empty subst");
if (reflected instanceof Class) {
return ts.rawType(ts.getClassSymbol((Class<?>) reflected));
} else if (reflected instanceof ParameterizedType) {
ParameterizedType parameterized = (ParameterizedType) reflected;
Class<?> raw = (Class<?>) parameterized.getRawType();
JClassSymbol sym = ts.getClassSymbol(raw);
if (sym == null) {
return null;
}
Type[] typeArguments = parameterized.getActualTypeArguments();
List<JTypeMirror> mapped = CollectionUtil.map(
typeArguments,
a -> fromReflect(ts, a, lexicalScope, subst)
);
if (CollectionUtil.any(mapped, Objects::isNull)) {
return null;
}
Type ownerType = parameterized.getOwnerType();
if (ownerType != null && !Modifier.isStatic(raw.getModifiers())) {
JClassType owner = (JClassType) fromReflect(ts, ownerType, lexicalScope, subst);
if (owner == null) {
return null;
}
return owner.selectInner(sym, mapped);
}
return ts.parameterise(sym, mapped);
} else if (reflected instanceof TypeVariable<?>) {
TypeVariable<?> typeVariable = (TypeVariable<?>) reflected;
@Nullable SubstVar mapped = lexicalScope.apply(typeVariable.getName());
if (mapped == null) {
throw new IllegalArgumentException(
"The lexical scope " + lexicalScope + " does not contain an entry for type variable "
+ typeVariable.getName() + " (declared on " + typeVariable.getGenericDeclaration() + ")"
);
}
return subst.apply(mapped);
} else if (reflected instanceof WildcardType) {
Type[] lowerBounds = ((WildcardType) reflected).getLowerBounds();
if (lowerBounds.length == 0) {
// no explicit lower bound, ie an upper bound
return makeWildcard(ts, true, ((WildcardType) reflected).getUpperBounds(), lexicalScope, subst);
} else {
return makeWildcard(ts, false, lowerBounds, lexicalScope, subst);
}
} else if (reflected instanceof GenericArrayType) {
JTypeMirror comp = fromReflect(ts, ((GenericArrayType) reflected).getGenericComponentType(), lexicalScope, subst);
if (comp == null) {
return null;
}
return ts.arrayType(comp);
}
throw new IllegalStateException("Illegal type " + reflected.getClass() + " " + reflected.getTypeName());
}
private static JTypeMirror makeWildcard(TypeSystem ts,
boolean isUpper,
Type[] bounds,
LexicalScope lexicalScope,
Substitution subst) {
List<JTypeMirror> boundsMapped = new ArrayList<>(bounds.length);
for (Type a : bounds) {
JTypeMirror jTypeMirror = fromReflect(ts, a, lexicalScope, subst);
if (jTypeMirror == null) {
return null;
}
boundsMapped.add(jTypeMirror);
}
// we intersect
return ts.wildcard(isUpper, ts.glb(boundsMapped));
}
/**
* Load a class. Supports loading array types like 'java.lang.String[]' and
* converting a canonical name to a binary name (eg 'java.util.Map.Entry' ->
* 'java.util.Map$Entry').
*/
public static @Nullable JTypeMirror loadType(TypeSystem ctr, String className) {
return loadType(ctr, className, null);
}
/**
* Load a class. Supports loading array types like 'java.lang.String[]' and
* converting a canonical name to a binary name (eg 'java.util.Map.Entry' ->
* 'java.util.Map$Entry'). Types that are not on the classpath may
* be replaced by placeholder types if the {@link UnresolvedClassStore}
* parameter is non-null.
*/
public static @Nullable JTypeMirror loadType(TypeSystem ctr, String className, UnresolvedClassStore unresolvedStore) {
return loadClassMaybeArray(ctr, StringUtils.deleteWhitespace(className), unresolvedStore);
}
public static @Nullable JClassSymbol loadSymbol(TypeSystem ctr, String className) {
JTypeMirror type = loadType(ctr, className);
return type == null ? null : (JClassSymbol) type.getSymbol();
}
private static @Nullable JTypeMirror loadClassMaybeArray(TypeSystem ts,
String className,
@Nullable UnresolvedClassStore unresolvedClassStore) {
Validate.notNull(className, "className must not be null.");
if (className.endsWith("[]")) {
int dimension = 0;
int i = className.length();
while (i >= 2 && className.startsWith("[]", i - 2)) {
dimension++;
i -= 2;
}
checkJavaIdent(className, i);
String elementName = className.substring(0, i);
JClassSymbol elementType = getClassOrDefault(ts, unresolvedClassStore, elementName);
if (elementType == null) {
return null;
}
return ts.arrayType(ts.rawType(elementType), dimension);
} else {
checkJavaIdent(className, className.length());
return ts.rawType(getClassOrDefault(ts, unresolvedClassStore, className));
}
}
private static JClassSymbol getClassOrDefault(TypeSystem ts, @Nullable UnresolvedClassStore unresolvedClassStore, String canonicalName) {
JClassSymbol loaded = ts.getClassSymbolFromCanonicalName(canonicalName);
if (loaded == null && unresolvedClassStore != null) {
loaded = unresolvedClassStore.makeUnresolvedReference(canonicalName, 0);
}
return loaded;
}
private static IllegalArgumentException invalidClassName(String className) {
return new IllegalArgumentException("Not a valid class name \"" + className + "\"");
}
private static void checkJavaIdent(String className, int endOffsetExclusive) {
if (endOffsetExclusive <= 0 || !Character.isJavaIdentifierStart(className.charAt(0))) {
throw invalidClassName(className);
}
for (int i = 1; i < endOffsetExclusive; i++) {
char c = className.charAt(i);
if (!(Character.isJavaIdentifierPart(c) || c == '.')) {
throw invalidClassName(className);
}
}
}
}
| 10,764 | 39.318352 | 141 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/InvocationMatcher.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTList;
import net.sourceforge.pmd.lang.java.ast.InvocationNode;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.ast.QualifiableExpression;
import net.sourceforge.pmd.util.AssertionUtil;
import net.sourceforge.pmd.util.CollectionUtil;
import net.sourceforge.pmd.util.OptionalBool;
import net.sourceforge.pmd.util.StringUtil;
/**
* Matches a method or constructor call against a particular overload.
* Use {@link #parse(String)} to create one. For example,
*
* <pre>
* java.lang.String#toString() // match calls to toString on String instances
* _#toString() // match calls to toString on any receiver
* _#_() // match all calls to a method with no parameters
* _#toString(_*) // match calls to a "toString" method with any number of parameters
* _#eq(_, _) // match calls to an "eq" method that has 2 parameters of unspecified type
* _#eq(java.lang.String, _) // like the previous, but the first parameter must be String
* java.util.ArrayList#new(int) // match constructor calls of this overload of the ArrayList constructor
* </pre>
*
* <p>The receiver matcher (first half) is matched against the
* static type of the <i>receiver</i> of the call, and not the
* declaration site of the method, unless the called method is
* static, or a constructor.
*
* <p>The parameters are matched against the declared parameters
* types of the called overload, and not the actual argument types.
* In particular, for vararg methods, the signature should mention
* a single parameter, with an array type.
*
* <p>For example {@code Integer.valueOf('0')} will be matched by
* {@code _#valueOf(int)} but not {@code _#valueOf(char)}, which is
* an overload that does not exist (the char is widened to an int,
* so the int overload is selected).
*
* <h5 id='ebnf'>Full EBNF grammar</h5>
*
* <p>(no whitespace is tolerated anywhere):
* <pre>{@code
* sig ::= type '#' method_name param_list
* type ::= qname ( '[]' )* | '_'
* method_name ::= '_' | ident | 'new'
* param_list ::= '(_*)' | '(' type (',' type )* ')'
* qname ::= java binary name
* }</pre>
*/
public final class InvocationMatcher {
final @Nullable String expectedName;
final @Nullable List<TypeMatcher> argMatchers;
final TypeMatcher qualifierMatcher;
InvocationMatcher(TypeMatcher qualifierMatcher, String expectedName, @Nullable List<TypeMatcher> argMatchers) {
this.expectedName = "_".equals(expectedName) ? null : expectedName;
this.argMatchers = argMatchers;
this.qualifierMatcher = qualifierMatcher;
}
/**
* See {@link #matchesCall(InvocationNode)}.
*/
public boolean matchesCall(@Nullable JavaNode node) {
return node instanceof InvocationNode && matchesCall((InvocationNode) node);
}
/**
* Returns true if the call matches this matcher. This means,
* the called overload is the one identified by the argument
* matchers, and the actual qualifier type is a subtype of the
* one mentioned by the qualifier matcher.
*/
public boolean matchesCall(@Nullable InvocationNode node) {
if (node == null) {
return false;
}
if (expectedName != null && !node.getMethodName().equals(expectedName)
|| argMatchers != null && ASTList.sizeOrZero(node.getArguments()) != argMatchers.size()) {
return false;
}
OverloadSelectionResult info = node.getOverloadSelectionInfo();
return !info.isFailed() && matchQualifier(node)
&& argsMatchOverload(info.getMethodType());
}
private boolean matchQualifier(InvocationNode node) {
if (qualifierMatcher == TypeMatcher.ANY) { // NOPMD CompareObjectsWithEquals
return true;
}
if (node instanceof ASTConstructorCall) {
JTypeMirror newType = ((ASTConstructorCall) node).getTypeNode().getTypeMirror();
return qualifierMatcher.matches(newType, true);
}
JMethodSig m = node.getMethodType();
JTypeMirror qualType;
if (node instanceof QualifiableExpression) {
ASTExpression qualifier = ((QualifiableExpression) node).getQualifier();
if (qualifier != null) {
qualType = qualifier.getTypeMirror();
} else {
// todo: if qualifier == null, then we should take the type of the
// implicit receiver, ie `this` or `SomeOuter.this`
qualType = m.getDeclaringType();
}
} else {
qualType = m.getDeclaringType();
}
return qualifierMatcher.matches(qualType, m.isStatic());
}
private boolean argsMatchOverload(JMethodSig invoc) {
if (argMatchers == null) {
return true;
}
List<JTypeMirror> formals = invoc.getFormalParameters();
if (invoc.getArity() != argMatchers.size()) {
return false;
}
for (int i = 0; i < formals.size(); i++) {
if (!argMatchers.get(i).matches(formals.get(i), true)) {
return false;
}
}
return true;
}
/**
* Parses a {@link CompoundInvocationMatcher} which matches any of
* the provided matchers.
*
* @param first First signature, in the format described on this class
* @param rest Other signatures, in the format described on this class
*
* @return A sig matcher
*
* @throws IllegalArgumentException If any signature is malformed (see <a href='#ebnf'>EBNF</a>)
* @throws NullPointerException If any signature is null
* @see #parse(String)
*/
public static CompoundInvocationMatcher parseAll(String first, String... rest) {
List<InvocationMatcher> matchers = CollectionUtil.map(listOf(first, rest), InvocationMatcher::parse);
return new CompoundInvocationMatcher(matchers);
}
/**
* Parses an {@link InvocationMatcher}.
*
* @param sig A signature in the format described on this class
*
* @return A sig matcher
*
* @throws IllegalArgumentException If the signature is malformed (see <a href='#ebnf'>EBNF</a>)
* @throws NullPointerException If the signature is null
* @see #parseAll(String, String...)
*/
public static InvocationMatcher parse(String sig) {
int i = parseType(sig, 0);
final TypeMatcher qualifierMatcher = newMatcher(sig.substring(0, i));
i = consumeChar(sig, i, '#');
final int nameStart = i;
i = parseSimpleName(sig, i);
final String methodName = sig.substring(nameStart, i);
i = consumeChar(sig, i, '(');
if (isChar(sig, i, ')')) {
return new InvocationMatcher(qualifierMatcher, methodName, Collections.emptyList());
}
// (_*) matches any argument list
List<TypeMatcher> argMatchers;
if (isChar(sig, i, '_')
&& isChar(sig, i + 1, '*')
&& isChar(sig, i + 2, ')')) {
argMatchers = null;
i = i + 3;
} else {
argMatchers = new ArrayList<>();
i = parseArgList(sig, i, argMatchers);
}
if (i != sig.length()) {
throw new IllegalArgumentException("Not a valid signature " + sig);
}
return new InvocationMatcher(qualifierMatcher, methodName, argMatchers);
}
private static int parseSimpleName(String sig, final int start) {
int i = start;
while (i < sig.length() && Character.isJavaIdentifierPart(sig.charAt(i))) {
i++;
}
if (i == start) {
throw new IllegalArgumentException("Not a valid signature " + sig);
}
return i;
}
private static int parseArgList(String sig, int i, List<TypeMatcher> argMatchers) {
while (i < sig.length()) {
i = parseType(sig, i, argMatchers);
if (isChar(sig, i, ')')) {
return i + 1;
}
i = consumeChar(sig, i, ',');
}
throw new IllegalArgumentException("Not a valid signature " + sig);
}
private static int consumeChar(String source, int i, char c) {
if (isChar(source, i, c)) {
return i + 1;
}
throw newParseException(source, i, "character '" + c + "'");
}
private static RuntimeException newParseException(String source, int i, String expectedWhat) {
final String indent = " ";
String message = "Expected " + expectedWhat + " at index " + i + ":\n";
message += indent + "\"" + StringUtil.escapeJava(source) + "\"\n";
message += indent + StringUtils.repeat(' ', i + 1) + '^' + "\n";
return new IllegalArgumentException(message);
}
private static boolean isChar(String source, int i, char c) {
return i < source.length() && source.charAt(i) == c;
}
private static int parseType(String source, int i, List<TypeMatcher> result) {
final int start = i;
i = parseType(source, i);
result.add(newMatcher(source.substring(start, i)));
return i;
}
private static int parseType(String source, int i) {
final int start = i;
while (i < source.length() && (Character.isJavaIdentifierPart(source.charAt(i))
|| source.charAt(i) == '.')) {
i++;
}
if (i == start) {
throw newParseException(source, i, "type");
}
AssertionUtil.assertValidJavaBinaryName(source.substring(start, i));
// array dimensions
while (isChar(source, i, '[')) {
i = consumeChar(source, i + 1, ']');
}
return i;
}
private static TypeMatcher newMatcher(String name) {
return "_".equals(name) ? TypeMatcher.ANY : new TypeMatcher(name);
}
private static final class TypeMatcher {
/** Matches any type. */
public static final TypeMatcher ANY = new TypeMatcher(null);
final @Nullable String name;
private TypeMatcher(@Nullable String name) {
this.name = name;
}
boolean matches(JTypeMirror type, boolean exact) {
return name == null
|| (exact ? TypeTestUtil.isExactlyAOrAnon(name, type) == OptionalBool.YES
: TypeTestUtil.isA(name, type));
}
}
/**
* A compound of several matchers (logical OR). Get one from
* {@link InvocationMatcher#parseAll(String, String...)};
*/
public static final class CompoundInvocationMatcher {
private final List<InvocationMatcher> matchers;
private CompoundInvocationMatcher(List<InvocationMatcher> matchers) {
this.matchers = matchers;
}
// todo make this smarter. Like collecting all possible names
// into a set to do a quick pre-screening before we test
// everything linearly
/**
* Returns true if any of the matchers match the node.
*
* @see #matchesCall(JavaNode)
*/
public boolean anyMatch(InvocationNode node) {
return CollectionUtil.any(matchers, it -> it.matchesCall(node));
}
/**
* Returns true if any of the matchers match the node.
*
* @see #matchesCall(JavaNode)
*/
public boolean anyMatch(JavaNode node) {
return CollectionUtil.any(matchers, it -> it.matchesCall(node));
}
}
}
| 12,190 | 36.167683 | 115 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/JArrayType.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.pcollections.HashTreePSet;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* An array type (1 dimension). Multi-level arrays have an array type
* as component themselves.
*/
public final class JArrayType implements JTypeMirror {
private final JTypeMirror component;
private final TypeSystem ts;
private final PSet<SymAnnot> typeAnnots;
private JClassSymbol symbol;
JArrayType(TypeSystem ts, JTypeMirror component) {
this(ts, component, null, HashTreePSet.empty());
}
JArrayType(TypeSystem ts, JTypeMirror component, JClassSymbol arraySymbol, PSet<SymAnnot> typeAnnots) {
assert component != null : "Expected non-null component";
assert typeAnnots != null : "Expected non-null annotations";
this.component = component;
this.ts = ts;
this.symbol = arraySymbol;
this.typeAnnots = typeAnnots;
}
@Override
public TypeSystem getTypeSystem() {
return ts;
}
@Override
public @NonNull JClassSymbol getSymbol() {
if (symbol == null) {
JTypeDeclSymbol comp = getComponentType().getSymbol();
if (comp == null) {
comp = getComponentType().getErasure().getSymbol();
}
symbol = new ArraySymbolImpl(ts, comp); // will nullcheck
}
return symbol;
}
@Override
public PSet<SymAnnot> getTypeAnnotations() {
return typeAnnots;
}
@Override
public JArrayType withAnnotations(PSet<SymAnnot> newTypeAnnots) {
if (newTypeAnnots.isEmpty() && this.typeAnnots.isEmpty()) {
return this;
}
return new JArrayType(ts, component, symbol, newTypeAnnots);
}
@Override
public boolean isInterface() {
return false;
}
@Override
public JArrayType getErasure() {
JTypeMirror erasedComp = component.getErasure();
return erasedComp == component ? this // NOPMD CompareObjectsWithEquals
: new JArrayType(ts, erasedComp, symbol, typeAnnots);
}
/**
* Gets the component type of this array. This is the same type as
* the array, stripped of a single array dimensions, e.g. the component
* type of {@code int[][][]} is {@code int[][]}.
*
* @return The component type of this array type
*
* @see #getElementType()
*/
public JTypeMirror getComponentType() {
return component;
}
/**
* Gets the element type of this array. This is the same type as
* the array, stripped of all array dimensions, e.g. the element
* type of {@code int[][][]} is {@code int}.
*
* @return The element type of this array type
*
* @see #getComponentType()
*/
public JTypeMirror getElementType() {
JTypeMirror c = this;
while (c instanceof JArrayType) {
c = ((JArrayType) c).getComponentType();
}
return c;
}
@Override
public Stream<JMethodSig> streamMethods(Predicate<? super JMethodSymbol> prefilter) {
return Stream.concat(
streamDeclaredMethods(prefilter),
// inherited object methods
ts.OBJECT.streamMethods(prefilter)
);
}
@Override
public Stream<JMethodSig> streamDeclaredMethods(Predicate<? super JMethodSymbol> prefilter) {
return getSymbol().getDeclaredMethods().stream()
.filter(prefilter)
.map(it -> new ArrayMethodSigImpl(this, it));
}
@Override
public List<JMethodSig> getConstructors() {
return CollectionUtil.map(getSymbol().getConstructors(), it -> new ArrayMethodSigImpl(this, it));
}
@Override
public boolean isRaw() {
return getElementType().isRaw();
}
@Override
public <T, P> T acceptVisitor(JTypeVisitor<T, P> visitor, P p) {
return visitor.visitArray(this, p);
}
@Override
public JArrayType subst(Function<? super SubstVar, ? extends @NonNull JTypeMirror> subst) {
JTypeMirror newComp = getComponentType().subst(subst);
return newComp == component ? this // NOPMD UseEqualsToCompareObjectReferences
: getTypeSystem().arrayType(newComp).withAnnotations(getTypeAnnotations());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof JArrayType)) {
return false;
}
JArrayType that = (JArrayType) o;
return TypeOps.isSameType(this, that);
}
@Override
public int hashCode() {
return component.hashCode() * 3;
}
@Override
public String toString() {
return TypePrettyPrint.prettyPrint(this);
}
}
| 5,427 | 28.661202 | 111 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/BoxedPrimitive.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
/**
* Special primitive wrappers, these are the only ones for which
* {@link #unbox()} is not the identity conversion.
*
* <p>Order of initialization is tricky since there is a circular
* dependency between JPrimitiveType constants and their PrimitiveWrapper.
* The current solution is to leak the 'this' instance in the enum
* constructor.
*/
final class BoxedPrimitive extends ClassTypeImpl {
private final JPrimitiveType unboxed;
// constructor called by JPrimitiveType, exactly once per type system and per primitive
BoxedPrimitive(TypeSystem factory, JClassSymbol boxType, JPrimitiveType unboxed, PSet<SymAnnot> typeAnnots) {
super(factory, boxType, typeAnnots);
this.unboxed = unboxed;
}
@Override
public JClassType withAnnotations(PSet<SymAnnot> newTypeAnnots) {
if (newTypeAnnots.isEmpty() && this.getTypeAnnotations().isEmpty()) {
return this;
}
return new BoxedPrimitive(
getTypeSystem(),
this.getSymbol(),
this.unboxed,
newTypeAnnots
);
}
@Override
public JTypeMirror unbox() {
return unboxed.withAnnotations(this.getTypeAnnotations());
}
@Override
public JClassType getErasure() {
return this;
}
}
| 1,593 | 28.518519 | 113 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/FakeIntersectionSymbol.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.lang.reflect.Modifier;
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 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.util.CollectionUtil;
class FakeIntersectionSymbol implements JClassSymbol {
private final String name;
private final JClassType superClass;
private final List<JClassType> superItfs;
FakeIntersectionSymbol(String name, @NonNull JClassType superClass, List<JClassType> superItfs) {
this.name = name;
this.superClass = Objects.requireNonNull(superClass, "null superclass");
this.superItfs = superItfs;
}
@Override
public boolean isInterface() {
return superClass.isTop();
}
@Override
public @NonNull String getBinaryName() {
return name;
}
@Override
public @Nullable String getCanonicalName() {
return null;
}
@Override
public @Nullable JExecutableSymbol getEnclosingMethod() {
return null;
}
@Override
public List<JClassSymbol> getDeclaredClasses() {
return Collections.emptyList();
}
@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 @NonNull List<JFieldSymbol> getEnumConstants() {
return superClass.getSymbol().getEnumConstants();
}
@Override
public List<JClassType> getSuperInterfaceTypes(Substitution substitution) {
return TypeOps.substClasses(superItfs, substitution);
}
@Override
public @Nullable JClassType getSuperclassType(Substitution substitution) {
return superClass.subst(substitution);
}
@Override
public @Nullable JClassSymbol getSuperclass() {
return superClass.getSymbol();
}
@Override
public List<JClassSymbol> getSuperInterfaces() {
return CollectionUtil.map(superItfs, JClassType::getSymbol);
}
@Override
public @Nullable JTypeDeclSymbol getArrayComponent() {
return null;
}
@Override
public boolean isArray() {
return false;
}
@Override
public boolean isPrimitive() {
return false;
}
@Override
public boolean isEnum() {
return false;
}
@Override
public boolean isAnnotation() {
return false;
}
@Override
public boolean isLocalClass() {
return false;
}
@Override
public boolean isRecord() {
return false;
}
@Override
public boolean isAnonymousClass() {
return false;
}
@Override
public @NonNull String getSimpleName() {
return "";
}
@Override
public TypeSystem getTypeSystem() {
return superClass.getTypeSystem();
}
@Override
public List<JTypeVar> getTypeParameters() {
return Collections.emptyList();
}
@Override
public int getModifiers() {
return Modifier.PUBLIC;
}
@Override
public @Nullable JClassSymbol getEnclosingClass() {
return null;
}
@Override
public @NonNull String getPackageName() {
return "";
}
}
| 3,960 | 22.3 | 101 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/OverloadSelectionResult.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall;
import net.sourceforge.pmd.lang.java.ast.ASTEnumConstant;
import net.sourceforge.pmd.lang.java.ast.InvocationNode;
import net.sourceforge.pmd.lang.java.ast.TypeNode;
/**
* Information about the overload-resolution for a specific
* {@linkplain InvocationNode expression}.
*/
// implnote: this is implemented privately in the infer package
public interface OverloadSelectionResult {
/**
* Returns the type of the method or constructor that is called by
* the {@link InvocationNode}. This is a method type whose type
* parameters have been instantiated by their actual inferred values.
*
* <p>For constructors the return type of this signature may be
* different from the type of this node. For an anonymous class
* constructor (in {@link ASTEnumConstant} or {@link ASTConstructorCall}),
* the selected constructor is the *superclass* constructor. In
* particular, if the anonymous class implements an interface,
* the constructor is the constructor of class {@link Object}.
* In that case though, the {@link TypeNode#getTypeMirror()} of the {@link InvocationNode}
* will be the type of the anonymous class (hence the difference).
*
* <p></p>
*/
JMethodSig getMethodType();
/**
* Whether the declaration needed unchecked conversion to be
* applicable. In this case, the return type of the method is
* erased.
*/
boolean needsUncheckedConversion();
/**
* Returns true if this is a varargs call. This means, that the
* called method is varargs, and was overload-selected in the varargs
* phase. For example:
* <pre>{@code
* Arrays.asList("a", "b"); // this is a varargs call
* Arrays.asList(new String[] { "a", "b" }); // this is not a varargs call
* }</pre>
*
* In this case, the last formal parameter of the method type should
* be interpreted specially with-respect-to the argument expressions
* (see {@link #ithFormalParam(int)}).
*/
boolean isVarargsCall();
/**
* Returns the type of the i-th formal parameter of the method.
* This is relevant when the call is varargs: {@code i} can in
* that case be greater that the number of formal parameters.
*
* @param i Index for a formal
*
* @throws AssertionError If the parameter is negative, or
* greater than the number of argument
* expressions to the method
*/
JTypeMirror ithFormalParam(int i);
/**
* Returns true if the invocation of this method failed. This
* means, the presented method type is a fallback, whose type
* parameters might not have been fully instantiated. This may
* also mean several methods were ambiguous, and an arbitrary
* one was chosen.
*/
boolean isFailed();
}
| 3,085 | 36.634146 | 94 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/JClassType.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import static net.sourceforge.pmd.lang.java.types.JVariableSig.FieldSig;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
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.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JExecutableSymbol;
import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
/**
* Represents class and interface types, including functional interface
* types. This interface can be thought of as a {@link JClassSymbol}
* viewed under a given parameterization. Methods like {@link #streamMethods(Predicate)},
* return signatures that are already partially substituted. Eg the
* method {@code get(int)} for type {@code List<String>} has return
* type {@code String}, not the type var {@code T} or the erasure
* {@code Object}.
*
* <p>A class type may present its symbol under several views:
* <ul>
* <li>If the symbol is not generic, then it may be either
* <i>{@linkplain #hasErasedSuperTypes() erased}</i> (where all supertypes are erased),
* or not. Note that a non-erased type may have some erased supertypes,
* see {@link #getErasure()}.
* <li>If the symbol is generic, then the type could be in one of the
* following configurations:
* <ul>
* <li><i>{@linkplain #isGenericTypeDeclaration() Generic declaration}</i>:
* the type arguments are the formal type parameters. All enclosing types are
* either non-generic or also generic type declarations. Eg {@code interface List<T> { .. } }.
* <li><i>{@linkplain #isParameterizedType() Parameterized}</i>: the type
* has type arguments. All enclosing types are either non-generic or
* also parameterised. Eg {@code List<String>}.
* <li><i>{@linkplain #isRaw() Raw}</i>: the type doesn't have type arguments,
* it's considered {@linkplain #hasErasedSuperTypes() erased}, so all its supertypes are
* also erased. All enclosing types are also erased. Eg {@code List}.
* </ul>
*/
public interface JClassType extends JTypeMirror {
@Override
@NonNull
JClassSymbol getSymbol();
@Override
JClassType withAnnotations(PSet<SymAnnot> newTypeAnnots);
@Override
default JClassType subst(Function<? super SubstVar, ? extends @NonNull JTypeMirror> fun) {
if (Substitution.isEmptySubst(fun)) {
return this;
}
JClassType encl = getEnclosingType();
if (encl != null) {
encl = encl.subst(fun);
}
List<JTypeMirror> targs = getTypeArgs();
if (targs.isEmpty() && encl == getEnclosingType()) { // NOPMD CompareObjectsWithEquals
return this;
}
List<JTypeMirror> newArgs = TypeOps.subst(targs, fun);
if (newArgs == targs && encl == getEnclosingType()) { // NOPMD CompareObjectsWithEquals
return this;
}
return encl != null ? encl.selectInner(getSymbol(), newArgs, getTypeAnnotations())
: withTypeArguments(newArgs);
}
/**
* Returns true if this type is erased. In that case, all the generic
* supertypes of this type are erased, type parameters are erased in
* its field and method types. In particular, if this type declares
* type parameters, then it is a {@linkplain #isRaw() raw type}.
*/
boolean hasErasedSuperTypes();
/**
* Returns true if this type represents a raw type, ie a type whose
* declaration is {@linkplain #isGeneric() generic}, but for which
* no type arguments were provided. In that case the type arguments
* are an empty list, and all supertypes are erased.
*
* <p>Raw types are convertible to any parameterized type of the
* same family via unchecked conversion.
*/
@Override
boolean isRaw();
@Override
boolean isGenericTypeDeclaration();
/**
* If this type is generic, returns the type that represents its
* generic type declaration. Otherwise, returns this type.
*
* @see #isGenericTypeDeclaration()
*/
JClassType getGenericTypeDeclaration();
/**
* Returns true if the symbol of this type declares some type
* parameters. This is true also for erased types.
*
* <p>For example, {@code List}, {@code List<T>}, and {@code List<String>}
* are generic, but {@code String} is not.
*/
@Override
boolean isGeneric();
/**
* Returns the type immediately enclosing this type. This may be null
* if this is a top-level type.
*/
@Nullable
JClassType getEnclosingType();
/**
* A specific instantiation of the type variables in {@link #getFormalTypeParams()}.
* Note that the type arguments and formal type parameters may be mismatched in size,
* (only if the symbol is unresolved). In any case, no attempt is made to check that
* the type arguments conform to the bound on type parameters in methods like
* {@link #withTypeArguments(List)}, although this is taken into account during type
* inference.
*
* <p>If this type is not generic, or a raw type, returns an empty list.
* <p>If this is a {@linkplain #isGenericTypeDeclaration() generic type declaration},
* returns exactly the same list as {@link #getFormalTypeParams()}.
*
* @see #getFormalTypeParams()
*/
List<JTypeMirror> getTypeArgs();
/**
* Returns the list of type variables declared by the generic type declaration.
*
* <p>If this type is not generic, returns an empty list. Note that if the symbol
* is unresolved, it is considered non-generic. But it still may have type arguments.
*
* @see #getTypeArgs()
*/
List<JTypeVar> getFormalTypeParams();
/**
* Returns the substitution mapping the formal type parameters of all
* enclosing types to their type arguments. If a type is raw, then its type
* parameters are not part of the returned mapping. Note, that this
* does not include type parameters of the supertypes.
*
* <p>If this type is erased, returns a substitution erasing all type
* parameters.
*
* <p>For instance, in the type {@code List<String>}, this is the substitution mapping
* the type parameter {@code T} of {@code interface List<T>} to {@code String}.
* It is suitable for use in e.g. {@link JMethodSymbol#getReturnType(Substitution)}.
*/
Substitution getTypeParamSubst();
/**
* Select an inner type. This can only be called if the given
* symbol represents a non-static member type of this type declaration.
*
* @param symbol Symbol for the inner type
* @param targs Type arguments of the inner type. If that is an empty
* list, and the given symbol is generic, then the inner
* type will be raw, or a generic type declaration,
* depending on whether this type is erased or not.
*
* @return A type for the inner type
*
* @throws NullPointerException If one of the parameter is null
* @throws IllegalArgumentException If the given symbol is static
* @throws IllegalArgumentException If the symbol is not a member type
* of this type (local/anon classes don't work)
* @throws IllegalArgumentException If the type arguments don't match the
* type parameters of the symbol (see {@link #withTypeArguments(List)})
* @throws IllegalArgumentException If this type is raw and the inner type is not,
* or this type is parameterized and the inner type is not
*/
default JClassType selectInner(JClassSymbol symbol, List<? extends JTypeMirror> targs) {
return selectInner(symbol, targs, HashTreePSet.empty());
}
/**
* Select an inner type, with new type annotations. This can only be called if the given
* symbol represents a non-static member type of this type declaration.
*
* @param symbol Symbol for the inner type
* @param targs Type arguments of the inner type. If that is an empty
* list, and the given symbol is generic, then the inner
* type will be raw, or a generic type declaration,
* depending on whether this type is erased or not.
* @param typeAnnotations Type annotations on the inner type
*
* @return A type for the inner type
*
* @throws NullPointerException If one of the parameter is null
* @throws IllegalArgumentException If the given symbol is static
* @throws IllegalArgumentException If the symbol is not a member type
* of this type (local/anon classes don't work)
* @throws IllegalArgumentException If the type arguments don't match the
* type parameters of the symbol (see {@link #withTypeArguments(List)})
* @throws IllegalArgumentException If this type is raw and the inner type is not,
* or this type is parameterized and the inner type is not
*/
JClassType selectInner(JClassSymbol symbol, List<? extends JTypeMirror> targs, PSet<SymAnnot> typeAnnotations);
/**
* Returns the generic superclass type. Returns null if this is
* {@link TypeSystem#OBJECT Object}. Returns {@link TypeSystem#OBJECT}
* if this is an interface type.
*/
@Nullable JClassType getSuperClass();
@Override
default @Nullable JClassType getAsSuper(@NonNull JClassSymbol symbol) {
return (JClassType) JTypeMirror.super.getAsSuper(symbol);
}
/**
* Returns the typed signature for the symbol, if it is declared
* directly in this type, and not a supertype.
*
* @param sym Method or constructor symbol
*/
@Nullable JMethodSig getDeclaredMethod(JExecutableSymbol sym);
/**
* Return the list of declared nested classes. They are substituted
* with the actual type arguments of this type, if it is parameterized.
* They are raw if this type is raw.
* Does not look into supertypes.
*/
List<JClassType> getDeclaredClasses();
/**
* Return the list of declared fields. They are substituted
* with the actual type arguments of this type, if it is parameterized.
* Does not look into supertypes.
*/
List<FieldSig> getDeclaredFields();
/**
* Return the field with the given name, or null if there
* is none. Does not look into supertypes.
*/
@Nullable FieldSig getDeclaredField(String simpleName);
/**
* Return the nested class with the given name, or null if there
* is none. Does not look into supertypes.
*/
@Nullable JClassType getDeclaredClass(String simpleName);
@Override
JClassType getErasure();
/** Return the list of interface types directly implemented by this type. */
List<JClassType> getSuperInterfaces();
/**
* Returns another class type which has the same erasure, but new
* type arguments.
*
* @param args Type arguments of the returned type. If empty, and
* this type is generic, returns a raw type.
*
* @throws IllegalArgumentException If the type argument list doesn't
* match the type parameters of this
* type in length. If the symbol is unresolved,
* any number of type arguments is accepted.
* @throws IllegalArgumentException If any type of the list is null, or
* a primitive type
*/
JClassType withTypeArguments(List<? extends JTypeMirror> args);
@Override
default <T, P> T acceptVisitor(JTypeVisitor<T, P> visitor, P p) {
return visitor.visitClass(this, p);
}
}
| 12,321 | 38.11746 | 115 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/TypingContext.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol;
import net.sourceforge.pmd.util.AssertionUtil;
/**
* A mapping of variables to types.
*/
public final class TypingContext extends MapFunction<JVariableSymbol, @Nullable JTypeMirror> {
/**
* Empty context. Corresponds to defaulting all lambda param types
* to their value in the AST.
*/
public static final TypingContext DEFAULT = new TypingContext(null, Collections.emptyMap());
private final @Nullable TypingContext parent;
private TypingContext(@Nullable TypingContext parent, Map<JVariableSymbol, @Nullable JTypeMirror> map) {
super(map);
this.parent = parent;
}
@Override
public @Nullable JTypeMirror apply(JVariableSymbol var) {
JTypeMirror t = getMap().get(var);
if (t == null && parent != null) {
// try with parent
return parent.apply(var);
}
return t;
}
/**
* Return a new typing context which uses this one as a parent.
*/
public TypingContext andThen(Map<JVariableSymbol, @Nullable JTypeMirror> map) {
return new TypingContext(this, map);
}
public TypingContext andThenZip(List<JVariableSymbol> symbols, List<JTypeMirror> types) {
AssertionUtil.requireParamNotNull("symbols", symbols);
AssertionUtil.requireParamNotNull("types", types);
if (symbols.size() != types.size()) {
throw new IllegalArgumentException("Wrong size");
} else if (symbols.isEmpty()) {
return this;
}
Map<JVariableSymbol, JTypeMirror> newMap = new HashMap<>(symbols.size() + this.getMap().size());
newMap.putAll(getMap());
for (int i = 0; i < symbols.size(); i++) {
newMap.put(symbols.get(i), types.get(i));
}
return this.andThen(newMap);
}
public static TypingContext zip(List<JVariableSymbol> symbols, List<JTypeMirror> types) {
return DEFAULT.andThenZip(symbols, types);
}
}
| 2,320 | 30.364865 | 108 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/CaptureMatcher.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.util.Objects;
import java.util.function.Function;
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.symbols.JTypeParameterSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
/**
* Test only. This binds to the first capture variable it tests equal
* with, and keeps the same binding forever.
*/
final class CaptureMatcher implements JTypeVar {
private final JWildcardType wild;
private @Nullable JTypeVar captured = null;
CaptureMatcher(JWildcardType wild) {
this.wild = wild;
}
@Override
public TypeSystem getTypeSystem() {
return wild.getTypeSystem();
}
@Override
public boolean isCaptured() {
return true;
}
@Override
public JTypeVar withAnnotations(PSet<SymAnnot> newTypeAnnots) {
throw new UnsupportedOperationException("this is a test only object which should only be used for equals");
}
@Override
public JTypeVar withUpperBound(@NonNull JTypeMirror newUB) {
throw new UnsupportedOperationException("this is a test only object which should only be used for equals");
}
@Override
public PSet<SymAnnot> getTypeAnnotations() {
if (captured != null) {
return captured.getTypeAnnotations();
}
return HashTreePSet.empty();
}
@Override
public @Nullable JTypeParameterSymbol getSymbol() {
return null; // captured
}
@Override
public @NonNull String getName() {
if (captured != null) {
return captured.getName();
}
throw new UnsupportedOperationException("this is a test only object which should only be used for equals");
}
@Override
public @NonNull JTypeMirror getUpperBound() {
return captured != null ? captured.getUpperBound() : getTypeSystem().OBJECT;
}
@Override
public @NonNull JTypeMirror getLowerBound() {
return captured != null ? captured.getLowerBound() : getTypeSystem().NULL_TYPE;
}
@Override
public boolean isCaptureOf(JWildcardType wildcard) {
return this.wild.equals(wildcard);
}
@Override
public @Nullable JWildcardType getCapturedOrigin() {
return wild;
}
@Override
public JTypeVar cloneWithBounds(JTypeMirror lower, JTypeMirror upper) {
throw new UnsupportedOperationException("this is a test only object which should only be used for equals");
}
@Override
public JTypeVar substInBounds(Function<? super SubstVar, ? extends @NonNull JTypeMirror> substitution) {
throw new UnsupportedOperationException("this is a test only object which should only be used for equals");
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof JTypeVar)) {
return false;
}
if (captured != null) {
return captured.equals(o);
}
JTypeVar that = (JTypeVar) o;
if (!Objects.equals(that.getCapturedOrigin(), this.getCapturedOrigin())) {
return false;
}
this.captured = that;
return true;
}
@Override
public int hashCode() {
throw new UnsupportedOperationException("this is a test only object which should only be used for equals");
}
@Override
public String toString() {
return captured == null ? "unbound capture matcher"
: "bound(" + captured.toString() + ")";
}
}
| 3,832 | 27.819549 | 115 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/TypeVarImpl.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.util.Objects;
import java.util.function.Function;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.java.symbols.JTypeParameterSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.util.AssertionUtil;
@SuppressWarnings("PMD.CompareObjectsWithEquals")
abstract class TypeVarImpl implements JTypeVar {
final TypeSystem ts;
JTypeMirror upperBound;
/**
* These are only the type annotations on a usage of the variable.
* Annotations on the declaration of the tparam are not considered.
*/
final PSet<SymAnnot> typeAnnots;
// constructor only for the captured version.
private TypeVarImpl(TypeSystem ts, PSet<SymAnnot> typeAnnots) {
this.ts = ts;
this.typeAnnots = Objects.requireNonNull(typeAnnots);
}
@Override
public PSet<SymAnnot> getTypeAnnotations() {
return typeAnnots;
}
@Override
public TypeSystem getTypeSystem() {
return ts;
}
@Override
public JTypeMirror getErasure() {
return getUpperBound().getErasure();
}
@Override
public String toString() {
return TypePrettyPrint.prettyPrint(this);
}
/**
* Returns a fresh type variable, whose bounds will be initialised by
* the capture conversion algo in {@link TypeConversion#capture(JTypeMirror)}.
* Captured variables use reference identity as equality relation.
*/
static TypeVarImpl.CapturedTypeVar freshCapture(JWildcardType wildcard) {
return new CapturedTypeVar(wildcard, wildcard.getTypeAnnotations());
}
static final class RegularTypeVar extends TypeVarImpl {
private final @NonNull JTypeParameterSymbol symbol;
RegularTypeVar(TypeSystem ts, @NonNull JTypeParameterSymbol symbol, PSet<SymAnnot> typeAnnots) {
super(ts, typeAnnots);
this.symbol = symbol;
}
private RegularTypeVar(RegularTypeVar base, PSet<SymAnnot> typeAnnots) {
this(base.ts, base.symbol, typeAnnots);
this.upperBound = base.upperBound;
}
@Override
public boolean isCaptured() {
return false;
}
@Override
public @NonNull JTypeMirror getLowerBound() {
return ts.NULL_TYPE;
}
@Override
public @NonNull JTypeParameterSymbol getSymbol() {
return symbol;
}
@Override
public @NonNull String getName() {
return symbol.getSimpleName();
}
@Override
public @NonNull JTypeMirror getUpperBound() {
if (upperBound == null) {
upperBound = symbol.computeUpperBound();
}
return upperBound;
}
@Override
public JTypeVar withUpperBound(@NonNull JTypeMirror newUB) {
RegularTypeVar tv = new RegularTypeVar(this, this.typeAnnots);
tv.upperBound = newUB;
return tv;
}
@Override
public JTypeVar withAnnotations(PSet<SymAnnot> newTypeAnnots) {
if (newTypeAnnots.isEmpty() && this.typeAnnots.isEmpty()) {
return this;
}
return new RegularTypeVar(this, newTypeAnnots);
}
@Override
public JTypeVar substInBounds(Function<? super SubstVar, ? extends @NonNull JTypeMirror> substitution) {
if (Substitution.isEmptySubst(substitution)) {
return this;
}
JTypeMirror newBound = getUpperBound().subst(substitution);
if (newBound == upperBound) {
return this;
}
RegularTypeVar newTVar = new RegularTypeVar(this.ts, this.symbol, this.getTypeAnnotations());
newTVar.upperBound = newBound;
return newTVar;
}
@Override
public JTypeVar cloneWithBounds(JTypeMirror lower, JTypeMirror upper) {
throw new UnsupportedOperationException("Not a capture variable");
}
@Override
public boolean isCaptureOf(JWildcardType wildcard) {
return false;
}
@Override
public @Nullable JWildcardType getCapturedOrigin() {
return null;
}
// we only compare the symbol
// the point is to make tvars whose bound was substed equal to the original
// tvar, for substs to work repeatedly. Maybe improving how JMethodSig works
// would remove the need for that
// Eg it would be nice to conceptualize JMethodSig as just a method symbol +
// a substitution mapping type params in scope at that point to actual types
// The problem is that we may want to subst it with type vars, and then use
// those
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RegularTypeVar that = (RegularTypeVar) o;
return symbol.equals(that.symbol);
}
@Override
public int hashCode() {
return Objects.hash(symbol);
}
}
static final class CapturedTypeVar extends TypeVarImpl {
private static final int PRIME = 997; // largest prime less than 1000
private final @NonNull JWildcardType wildcard;
private JTypeMirror upperBound;
private JTypeMirror lowerBound;
private CapturedTypeVar(JWildcardType wild, PSet<SymAnnot> typeAnnots) {
this(wild, wild.asLowerBound(), wild.asUpperBound(), typeAnnots);
}
private CapturedTypeVar(JWildcardType wild, @NonNull JTypeMirror lower, @NonNull JTypeMirror upper, PSet<SymAnnot> typeAnnots) {
super(wild.getTypeSystem(), typeAnnots);
this.upperBound = upper;
this.lowerBound = lower;
this.wildcard = wild;
}
void setUpperBound(@NonNull JTypeMirror upperBound) {
this.upperBound = upperBound;
}
void setLowerBound(@NonNull JTypeMirror lowerBound) {
this.lowerBound = lowerBound;
}
@Override
public boolean equals(Object o) {
return this == o || o instanceof CaptureMatcher && o.equals(this);
}
@Override
public int hashCode() { // NOPMD UselessOverridingMethod
return super.hashCode();
}
@Override
public boolean isCaptured() {
return true;
}
@Override
public boolean isCaptureOf(JWildcardType wildcard) {
return this.wildcard.equals(wildcard);
}
@Override
public JWildcardType getCapturedOrigin() {
return wildcard;
}
@Override
public JTypeVar substInBounds(Function<? super SubstVar, ? extends @NonNull JTypeMirror> substitution) {
JWildcardType wild = this.wildcard.subst(substitution);
JTypeMirror lower = getLowerBound().subst(substitution);
JTypeMirror upper = getUpperBound().subst(substitution);
if (wild == this.wildcard && lower == this.lowerBound && upper == this.lowerBound) {
return this;
}
return new CapturedTypeVar(wild, lower, upper, getTypeAnnotations());
}
@Override
public JTypeVar cloneWithBounds(JTypeMirror lower, JTypeMirror upper) {
return new CapturedTypeVar(wildcard, lower, upper, getTypeAnnotations());
}
@Override
public JTypeVar withAnnotations(PSet<SymAnnot> newTypeAnnots) {
if (newTypeAnnots.isEmpty() && typeAnnots.isEmpty()) {
return this;
}
return new CapturedTypeVar(wildcard, lowerBound, upperBound, newTypeAnnots);
}
@Override
public JTypeVar withUpperBound(@NonNull JTypeMirror newUB) {
AssertionUtil.requireParamNotNull("upper bound", newUB);
return new CapturedTypeVar(wildcard, lowerBound, newUB, getTypeAnnotations());
}
@Override
public @NonNull JTypeMirror getUpperBound() {
return upperBound;
}
@Override
public @NonNull JTypeMirror getLowerBound() {
return lowerBound;
}
@Override
public @Nullable JTypeParameterSymbol getSymbol() {
return null;
}
@Override
public @NonNull String getName() {
return "capture#" + hashCode() % PRIME + " of " + wildcard;
}
}
}
| 8,951 | 30.300699 | 136 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/TypePrettyPrint.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import static net.sourceforge.pmd.util.OptionalBool.NO;
import static net.sourceforge.pmd.util.OptionalBool.UNKNOWN;
import static net.sourceforge.pmd.util.OptionalBool.YES;
import java.util.Arrays;
import java.util.List;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.java.symbols.JTypeParameterSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar;
import net.sourceforge.pmd.util.OptionalBool;
/**
* Pretty-printing methods to display types. The current API is only
* offered for debugging, not for displaying types to users.
*/
public final class TypePrettyPrint {
private TypePrettyPrint() {
}
public static @NonNull String prettyPrint(@NonNull JTypeVisitable t) {
return prettyPrint(t, new TypePrettyPrinter());
}
public static @NonNull String prettyPrintWithSimpleNames(@NonNull JTypeVisitable t) {
return prettyPrint(t, new TypePrettyPrinter().qualifyNames(false));
}
public static String prettyPrint(@NonNull JTypeVisitable t, TypePrettyPrinter prettyPrinter) {
t.acceptVisitor(PrettyPrintVisitor.INSTANCE, prettyPrinter);
return prettyPrinter.consumeResult();
}
/**
* Options to pretty print a type. Cannot be used concurrently.
*/
public static class TypePrettyPrinter {
private final StringBuilder sb = new StringBuilder();
private boolean printMethodHeader = true;
private boolean printMethodReturnType = true;
private OptionalBool printTypeVarBounds = UNKNOWN;
private boolean qualifyTvars = false;
private boolean qualifyNames = true;
private boolean isVarargs = false;
private boolean printTypeAnnotations = true;
private boolean qualifyAnnotations = false;
/** Create a new pretty printer with the default configuration. */
public TypePrettyPrinter() { // NOPMD
// default
}
StringBuilder append(char o) {
return sb.append(o);
}
StringBuilder append(String o) {
return sb.append(o);
}
/**
* Print the declaring type of the method and its type parameters.
* Default: true.
*/
public TypePrettyPrinter printMethodHeader(boolean printMethodHeader) {
this.printMethodHeader = printMethodHeader;
return this;
}
/**
* Print the return type of methods (as postfix).
* Default: true.
*/
public TypePrettyPrinter printMethodResult(boolean printMethodResult) {
this.printMethodReturnType = printMethodResult;
return this;
}
/**
* Print the bounds of type variables.
* Default: false.
*/
public void printTypeVarBounds(OptionalBool printTypeVarBounds) {
this.printTypeVarBounds = printTypeVarBounds;
}
/**
* Qualify type variables with the name of the declaring symbol.
* Eg {@code Foo#T} for {@code class Foo<T>}}.
* Default: false.
*/
public TypePrettyPrinter qualifyTvars(boolean qualifyTvars) {
this.qualifyTvars = qualifyTvars;
return this;
}
/**
* Whether to print the binary name of a type annotation or
* just the simple name if false.
* Default: false.
*/
public TypePrettyPrinter qualifyAnnotations(boolean qualifyAnnotations) {
this.qualifyAnnotations = qualifyAnnotations;
return this;
}
/**
* Whether to print the type annotations.
* Default: true.
*/
public TypePrettyPrinter printAnnotations(boolean printAnnotations) {
this.printTypeAnnotations = printAnnotations;
return this;
}
/**
* Use qualified names for class types instead of simple names.
* Default: true.
*/
public TypePrettyPrinter qualifyNames(boolean qualifyNames) {
this.qualifyNames = qualifyNames;
return this;
}
String consumeResult() {
// The pretty printer might be reused by another call,
// delete the buffer.
String result = sb.toString();
this.sb.setLength(0);
return result;
}
private void printTypeAnnotations(PSet<SymAnnot> annots) {
if (this.printTypeAnnotations) {
for (SymAnnot annot : annots) {
String name = this.qualifyAnnotations ? annot.getBinaryName()
: annot.getSimpleName();
append('@').append(name).append(' ');
}
}
}
}
private static final class PrettyPrintVisitor implements JTypeVisitor<Void, TypePrettyPrinter> {
static final PrettyPrintVisitor INSTANCE = new PrettyPrintVisitor();
@Override
public Void visit(JTypeMirror t, TypePrettyPrinter sb) {
sb.printTypeAnnotations(t.getTypeAnnotations());
sb.append(t.toString());
return null;
}
@Override
public Void visitClass(JClassType t, TypePrettyPrinter sb) {
JClassType enclosing = t.getEnclosingType();
boolean isAnon = t.getSymbol().isAnonymousClass();
if (enclosing != null && !isAnon) {
visitClass(enclosing, sb);
sb.append('#');
} else if (t.hasErasedSuperTypes() && !t.isRaw()) {
sb.append("(erased) ");
}
sb.printTypeAnnotations(t.getTypeAnnotations());
if (t.getSymbol().isUnresolved()) {
sb.append('*'); // a small marker to spot them
}
if (enclosing != null && !isAnon || !sb.qualifyNames) {
sb.append(t.getSymbol().getSimpleName());
} else {
sb.append(t.getSymbol().getBinaryName());
}
List<JTypeMirror> targs = t.getTypeArgs();
if (t.isRaw() || targs.isEmpty()) {
return null;
}
if (t.isGenericTypeDeclaration() && sb.printTypeVarBounds != NO) {
sb.printTypeVarBounds = YES;
}
join(sb, targs, ", ", "<", ">");
return null;
}
@Override
public Void visitWildcard(JWildcardType t, TypePrettyPrinter sb) {
sb.printTypeAnnotations(t.getTypeAnnotations());
sb.append("?");
if (t.isUnbounded()) {
return null;
}
sb.append(t.isUpperBound() ? " extends " : " super ");
t.getBound().acceptVisitor(this, sb);
return null;
}
@Override
public Void visitPrimitive(JPrimitiveType t, TypePrettyPrinter sb) {
sb.printTypeAnnotations(t.getTypeAnnotations());
sb.append(t.getSimpleName());
return null;
}
@Override
public Void visitTypeVar(JTypeVar t, TypePrettyPrinter sb) {
if (t instanceof CaptureMatcher) {
sb.append(t.toString());
return null;
}
if (!t.isCaptured() && sb.qualifyTvars) {
JTypeParameterSymbol sym = t.getSymbol();
if (sym != null) {
sb.append(sym.getDeclaringSymbol().getSimpleName());
sb.append('#');
}
}
sb.printTypeAnnotations(t.getTypeAnnotations());
sb.append(t.getName());
if (sb.printTypeVarBounds == YES) {
sb.printTypeVarBounds = NO;
if (!t.getUpperBound().isTop()) {
sb.append(" extends ");
t.getUpperBound().acceptVisitor(this, sb);
}
if (!t.getLowerBound().isBottom()) {
sb.append(" super ");
t.getLowerBound().acceptVisitor(this, sb);
}
sb.printTypeVarBounds = YES;
}
return null;
}
/**
* Formats {@link Arrays#asList(Object[])} as {@code <T> asList(T...) -> List<T>}
*/
@Override
public Void visitMethodType(JMethodSig t, TypePrettyPrinter sb) {
if (sb.printMethodHeader) {
t.getDeclaringType().acceptVisitor(this, sb);
sb.append(".");
if (t.isGeneric()) {
final OptionalBool printBounds = sb.printTypeVarBounds;
if (printBounds != NO) {
sb.printTypeVarBounds = YES;
}
join(sb, t.getTypeParameters(), ", ", "<", "> ", false);
sb.printTypeVarBounds = printBounds;
}
}
sb.append(t.getName());
join(sb, t.getFormalParameters(), ", ", "(", ")", t.isVarargs());
if (sb.printMethodReturnType) {
sb.append(" -> ");
t.getReturnType().acceptVisitor(this, sb);
}
return null;
}
@Override
public Void visitIntersection(JIntersectionType t, TypePrettyPrinter sb) {
return join(sb, t.getComponents(), " & ", "", "");
}
@Override
public Void visitArray(JArrayType t, TypePrettyPrinter sb) {
JTypeMirror component = t.getComponentType();
if (component instanceof JIntersectionType) {
sb.append("(");
}
boolean isVarargs = sb.isVarargs;
sb.isVarargs = false;
component.acceptVisitor(this, sb);
if (component instanceof JIntersectionType) {
sb.append(")");
}
// todo I think the annotation placement might be wrong, add tests
sb.printTypeAnnotations(t.getTypeAnnotations());
sb.append(isVarargs ? "..." : "[]");
return null;
}
@Override
public Void visitNullType(JTypeMirror t, TypePrettyPrinter sb) {
sb.append("null");
return null;
}
@Override
public Void visitInferenceVar(InferenceVar t, TypePrettyPrinter sb) {
sb.append(t.getName());
return null;
}
private Void join(TypePrettyPrinter sb, List<? extends JTypeMirror> ts, String delim, String prefix, String suffix) {
return join(sb, ts, delim, prefix, suffix, false);
}
private Void join(TypePrettyPrinter sb, List<? extends JTypeMirror> types, String delim, String prefix, String suffix, boolean isVarargs) {
sb.isVarargs = false;
boolean empty = types.isEmpty();
sb.append(prefix);
if (!empty) {
for (int i = 0; i < types.size() - 1; i++) {
types.get(i).acceptVisitor(this, sb);
sb.append(delim);
}
if (isVarargs) {
sb.isVarargs = true;
}
types.get(types.size() - 1).acceptVisitor(this, sb);
}
sb.append(suffix);
return null;
}
}
}
| 11,662 | 32.418338 | 147 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/SubstVar.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.util.function.Function;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar;
/**
* Common supertype for {@link JTypeVar} and {@link InferenceVar},
* the two kinds of types that can be substituted in types.
*
* @see TypeOps#subst(JTypeMirror, Function)
*/
public interface SubstVar extends JTypeMirror {
@Override
default JTypeMirror subst(Function<? super SubstVar, ? extends @NonNull JTypeMirror> subst) {
return subst.apply(this);
}
}
| 692 | 23.75 | 97 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/MapFunction.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.util.Comparator;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* A partial function built on a map.
*/
abstract class MapFunction<T, R> implements Function<T, R> {
private final Map<T, R> map;
MapFunction(Map<T, R> map) {
this.map = map;
}
protected Map<T, R> getMap() {
return map;
}
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public String toString() {
return map.entrySet().stream()
.sorted(Comparator.comparing(e -> e.getKey().toString()))
.map(it -> it.getKey() + " => " + it.getValue())
.collect(Collectors.joining("; ", getClass().getSimpleName() + "[", "]"));
}
}
| 924 | 21.560976 | 92 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/JIntersectionType.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
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.annotation.Experimental;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* An intersection type. Intersections type act as the
* {@linkplain TypeSystem#glb(Collection) greatest lower bound}
* for a set of types.
*
* <p>https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.9
*/
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public final class JIntersectionType implements JTypeMirror {
private final TypeSystem ts;
private final JTypeMirror primaryBound;
private final List<JTypeMirror> components;
private JClassType induced;
/**
* @param primaryBound may be Object if every bound is an interface
* @param allBounds including the superclass, unless Object
*/
JIntersectionType(TypeSystem ts,
JTypeMirror primaryBound,
List<? extends JTypeMirror> allBounds) {
this.primaryBound = primaryBound;
this.components = Collections.unmodifiableList(allBounds);
this.ts = ts;
assert Lub.isExclusiveIntersectionBound(primaryBound)
: "Wrong primary intersection bound: " + toString(primaryBound, allBounds);
assert primaryBound != ts.OBJECT || allBounds.size() > 1
: "Intersection of a single bound: " + toString(primaryBound, allBounds); // should be caught by GLB
checkWellFormed(primaryBound, allBounds);
}
@Override
public PSet<SymAnnot> getTypeAnnotations() {
return HashTreePSet.empty();
}
@Override
public JTypeMirror withAnnotations(PSet<SymAnnot> newTypeAnnots) {
return new JIntersectionType(
ts,
primaryBound.withAnnotations(newTypeAnnots),
CollectionUtil.map(components, c -> c.withAnnotations(newTypeAnnots))
);
}
/**
* Returns the list of components. Their erasure must be pairwise disjoint.
* If the intersection's superclass is {@link TypeSystem#OBJECT},
* then it is excluded from this set.
*/
public List<JTypeMirror> getComponents() {
return components;
}
/**
* The primary bound of this intersection, which may be a type variable,
* array type, or class type (not an interface). If all bounds are interfaces,
* then this returns {@link TypeSystem#OBJECT}.
*/
public @NonNull JTypeMirror getPrimaryBound() {
return primaryBound;
}
/**
* Returns all additional bounds on the primary bound, which are
* necessarily interface types.
*/
@SuppressWarnings({"unchecked", "rawtypes"}) // safe because of checkWellFormed
public @NonNull List<JClassType> getInterfaces() {
return (List) (primaryBound == ts.OBJECT ? components
: components.subList(1, components.size()));
}
/**
* Every intersection type induces a notional class or interface
* for the purpose of identifying its members. This may be a functional
* interface. This returns null for the non-implemented cases.
*
* @experimental this is only relevant to check for functional
* interface parameterization, eg {@code Runnable & Serializable}. Do
* not use this to find out the members of this type, rather, use {@link #streamMethods(Predicate)}
* or so.
*/
@Experimental
public @Nullable JClassType getInducedClassType() {
JTypeMirror primary = getPrimaryBound();
if (primary instanceof JTypeVar || primary instanceof JArrayType) {
// Normally, should generate an interface which has all the members of Ti
// But as per the experimental notice, this case may be ignored until needed
return null;
}
if (induced == null) {
JClassSymbol sym = new FakeIntersectionSymbol("", (JClassType) primary, getInterfaces());
this.induced = (JClassType) ts.declaration(sym);
}
return induced;
}
@Override
public <T, P> T acceptVisitor(JTypeVisitor<T, P> visitor, P p) {
return visitor.visitIntersection(this, p);
}
@Override
public Stream<JMethodSig> streamMethods(Predicate<? super JMethodSymbol> prefilter) {
return getComponents().stream().flatMap(it -> it.streamMethods(prefilter));
}
@Override
public JIntersectionType subst(Function<? super SubstVar, ? extends @NonNull JTypeMirror> subst) {
JTypeMirror newPrimary = primaryBound.subst(subst);
List<JClassType> myItfs = getInterfaces();
List<JClassType> newBounds = TypeOps.substClasses(myItfs, subst);
return newPrimary == getPrimaryBound() && newBounds == myItfs // NOPMD UseEqualsToCompareObjectReferences
? this
: new JIntersectionType(ts, newPrimary, newBounds);
}
@Override
public @Nullable JTypeDeclSymbol getSymbol() {
return null; // the induced type may have a symbol though
}
@Override
public TypeSystem getTypeSystem() {
return ts;
}
@Override
public JTypeMirror getErasure() {
return getPrimaryBound().getErasure();
}
@Override
public String toString() {
return TypePrettyPrint.prettyPrint(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof JIntersectionType)) {
return false;
}
JIntersectionType that = (JIntersectionType) o;
return TypeOps.isSameType(this, that);
}
@Override
public int hashCode() {
return Objects.hash(components);
}
private static void checkWellFormed(JTypeMirror primary, List<? extends JTypeMirror> flattened) {
assert flattened.get(0) == primary || primary == primary.getTypeSystem().OBJECT
: "Not a well-formed intersection " + flattened;
for (int i = 0; i < flattened.size(); i++) {
JTypeMirror ci = flattened.get(i);
Objects.requireNonNull(ci, "Null intersection component");
if (Lub.isExclusiveIntersectionBound(ci)) {
if (i != 0) {
throw malformedIntersection(primary, flattened);
}
} else if (ci instanceof JClassType) {
// must be an interface, as per isExclusiveBlabla
assert ci.isInterface() || TypeOps.hasUnresolvedSymbol(ci);
} else {
throw malformedIntersection(primary, flattened);
}
}
}
private static RuntimeException malformedIntersection(JTypeMirror primary, List<? extends JTypeMirror> flattened) {
return new IllegalArgumentException(
"Malformed intersection: " + toString(primary, flattened)
);
}
private static String toString(JTypeMirror primary, List<? extends JTypeMirror> flattened) {
return flattened.stream().map(JTypeMirror::toString).collect(Collectors.joining(" & ",
primary.toString() + " & ",
""));
}
}
| 8,072 | 34.721239 | 119 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/TypeTestUtil.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.lang.reflect.Modifier;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.InternalApiBridge;
import net.sourceforge.pmd.lang.java.ast.TypeNode;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeParameterSymbol;
import net.sourceforge.pmd.lang.java.symbols.internal.UnresolvedClassStore;
import net.sourceforge.pmd.util.AssertionUtil;
import net.sourceforge.pmd.util.OptionalBool;
/**
* Public utilities to test the type of nodes.
*
* @see InvocationMatcher
*/
public final class TypeTestUtil {
private TypeTestUtil() {
// utility class
}
/**
* Checks whether the static type of the node is a subtype of the
* class identified by the given name. This ignores type arguments,
* if the type of the node is parameterized. Examples:
*
* <pre>{@code
* isA(List.class, <new ArrayList<String>()>) = true
* isA(ArrayList.class, <new ArrayList<String>()>) = true
* isA(int[].class, <new int[0]>) = true
* isA(Object[].class, <new String[0]>) = true
* isA(_, null) = false
* isA(null, _) = NullPointerException
* }</pre>
*
* <p>If either type is unresolved, the types are tested for equality,
* thus giving more useful results than {@link JTypeMirror#isSubtypeOf(JTypeMirror)}.
*
* <p>Note that primitives are NOT considered subtypes of one another
* by this method, even though {@link JTypeMirror#isSubtypeOf(JTypeMirror)} does.
*
* @param clazz a class (non-null)
* @param node the type node to check
*
* @return true if the type test matches
*
* @throws NullPointerException if the class parameter is null
*/
public static boolean isA(final @NonNull Class<?> clazz, final @Nullable TypeNode node) {
AssertionUtil.requireParamNotNull("class", clazz);
return node != null && (hasNoSubtypes(clazz) ? isExactlyA(clazz, node)
: isA(clazz, node.getTypeMirror()));
}
/**
* Checks whether the given type of the node is a subtype of the
* first argument. See {@link #isA(Class, TypeNode)} for examples
* and more info.
*
* @param clazz a class or array type (without whitespace)
* @param type the type node to check
*
* @return true if the second argument is not null and the type test matches
*
* @throws NullPointerException if the class parameter is null
* @see #isA(Class, TypeNode)
*/
public static boolean isA(@NonNull Class<?> clazz, @Nullable JTypeMirror type) {
AssertionUtil.requireParamNotNull("klass", clazz);
if (type == null) {
return false;
}
JTypeMirror otherType = TypesFromReflection.fromReflect(clazz, type.getTypeSystem());
if (otherType == null || TypeOps.isUnresolved(type) || hasNoSubtypes(clazz)) {
// We'll return true if the types have equal symbols (same binary name),
// but we ignore subtyping.
return otherType != null && Objects.equals(otherType.getSymbol(), type.getSymbol());
}
return isA(otherType, type);
}
/**
* Checks whether the static type of the node is a subtype of the
* class identified by the given name. See {@link #isA(Class, TypeNode)}
* for examples and more info.
*
* @param canonicalName the canonical name of a class or array type (without whitespace)
* @param node the type node to check
*
* @return true if the type test matches
*
* @throws NullPointerException if the class name parameter is null
* @throws IllegalArgumentException if the class name parameter is not a valid java binary name,
* eg it has type arguments
* @see #isA(Class, TypeNode)
*/
public static boolean isA(final @NonNull String canonicalName, final @Nullable TypeNode node) {
AssertionUtil.requireParamNotNull("canonicalName", (Object) canonicalName);
AssertionUtil.assertValidJavaBinaryName(canonicalName);
if (node == null) {
return false;
}
UnresolvedClassStore unresolvedStore = InternalApiBridge.getProcessor(node).getUnresolvedStore();
return isA(canonicalName, node.getTypeMirror(), unresolvedStore);
}
public static boolean isA(@NonNull String canonicalName, @Nullable JTypeMirror thisType) {
AssertionUtil.requireParamNotNull("canonicalName", (Object) canonicalName);
return thisType != null && isA(canonicalName, thisType, null);
}
public static boolean isA(@NonNull JTypeMirror t1, @Nullable TypeNode t2) {
return t2 != null && isA(t1, t2.getTypeMirror());
}
/**
* Checks whether the second type is a subtype of the first. This
* removes some behavior of isSubtypeOf that we don't want (eg, that
* unresolved types are subtypes of everything).
*
* @param t1 A supertype
* @param t2 A type
*
* @return Whether t1 is a subtype of t2
*/
public static boolean isA(@Nullable JTypeMirror t1, @NonNull JTypeMirror t2) {
if (t1 == null) {
return false;
} else if (t2.isPrimitive() || t1.isPrimitive()) {
return t2.equals(t1); // isSubtypeOf considers primitive widening like subtyping
} else if (TypeOps.isUnresolved(t2)) {
// we can't get any useful info from this, isSubtypeOf would return true
return false;
} else if (t1.isClassOrInterface() && ((JClassType) t1).getSymbol().isAnonymousClass()) {
return false; // conventionally
} else if (t2 instanceof JTypeVar) {
return t1.isTop() || isA(t1, ((JTypeVar) t2).getUpperBound());
}
return t2.isSubtypeOf(t1);
}
private static boolean isA(@NonNull String canonicalName, @NonNull JTypeMirror thisType, @Nullable UnresolvedClassStore unresolvedStore) {
OptionalBool exactMatch = isExactlyAOrAnon(canonicalName, thisType);
if (exactMatch != OptionalBool.NO) {
return exactMatch == OptionalBool.YES; // otherwise anon, and we return false
}
JTypeDeclSymbol thisClass = thisType.getSymbol();
if (thisClass != null && thisClass.isUnresolved()) {
// we can't get any useful info from this, isSubtypeOf would return true
// do not test for equality, we already checked isExactlyA, which has its fallback
return false;
}
TypeSystem ts = thisType.getTypeSystem();
@Nullable JTypeMirror otherType = TypesFromReflection.loadType(ts, canonicalName, unresolvedStore);
return isA(otherType, thisType);
}
/**
* Checks whether the static type of the node is exactly the type
* of the class. This ignores strict supertypes, and type arguments,
* if the type of the node is parameterized.
*
* <pre>{@code
* isExactlyA(List.class, <new ArrayList<String>()>) = false
* isExactlyA(ArrayList.class, <new ArrayList<String>()>) = true
* isExactlyA(int[].class, <new int[0]>) = true
* isExactlyA(Object[].class, <new String[0]>) = false
* isExactlyA(_, null) = false
* isExactlyA(null, _) = NullPointerException
* }</pre>
*
* @param clazz a class (non-null)
* @param node the type node to check
*
* @return true if the node is non-null and has the given type
*
* @throws NullPointerException if the class parameter is null
*/
public static boolean isExactlyA(final @NonNull Class<?> clazz, final @Nullable TypeNode node) {
AssertionUtil.requireParamNotNull("class", clazz);
return node != null && isExactlyA(clazz, node.getTypeMirror().getSymbol());
}
public static boolean isExactlyA(@NonNull Class<?> klass, @Nullable JTypeMirror type) {
AssertionUtil.requireParamNotNull("class", klass);
return type != null && isExactlyA(klass, type.getSymbol());
}
public static boolean isExactlyA(@NonNull Class<?> klass, @Nullable JTypeDeclSymbol type) {
AssertionUtil.requireParamNotNull("klass", klass);
if (!(type instanceof JClassSymbol)) {
// Class cannot reference a type parameter
return false;
}
JClassSymbol symClass = (JClassSymbol) type;
if (klass.isArray()) {
return symClass.isArray() && isExactlyA(klass.getComponentType(), symClass.getArrayComponent());
}
// Note: klass.getName returns a type descriptor for arrays,
// which is why we have to destructure the array above
return symClass.getBinaryName().equals(klass.getName());
}
/**
* Returns true if the signature is that of a method declared in the
* given class.
*
* @param klass Class
* @param sig Method signature to test
*
* @throws NullPointerException If any argument is null
*/
public static boolean isDeclaredInClass(@NonNull Class<?> klass, @NonNull JMethodSig sig) {
return isExactlyA(klass, sig.getDeclaringType().getSymbol());
}
/**
* Checks whether the static type of the node is exactly the type
* given by the name. See {@link #isExactlyA(Class, TypeNode)} for
* examples and more info.
*
* @param canonicalName a canonical name of a class or array type
* @param node the type node to check
*
* @return true if the node is non-null and has the given type
*
* @throws NullPointerException if the class name parameter is null
* @throws IllegalArgumentException if the class name parameter is not a valid java binary name,
* eg it has type arguments
* @see #isExactlyA(Class, TypeNode)
*/
public static boolean isExactlyA(@NonNull String canonicalName, final @Nullable TypeNode node) {
AssertionUtil.assertValidJavaBinaryName(canonicalName);
return node != null && isExactlyAOrAnon(canonicalName, node.getTypeMirror()) == OptionalBool.YES;
}
static OptionalBool isExactlyAOrAnon(@NonNull String canonicalName, final @NonNull JTypeMirror node) {
AssertionUtil.requireParamNotNull("canonicalName", canonicalName);
JTypeDeclSymbol sym = node.getSymbol();
if (sym == null || sym instanceof JTypeParameterSymbol) {
return OptionalBool.NO;
}
canonicalName = StringUtils.deleteWhitespace(canonicalName);
JClassSymbol klass = (JClassSymbol) sym;
String canonical = klass.getCanonicalName();
if (canonical == null) {
return OptionalBool.UNKNOWN; // anonymous
}
return OptionalBool.definitely(canonical.equals(canonicalName));
}
private static boolean hasNoSubtypes(Class<?> clazz) {
// Neither final nor an annotation. Enums & records have ACC_FINAL
// Note: arrays have ACC_FINAL, but have subtypes by covariance
// Note: annotations may be implemented by classes
return Modifier.isFinal(clazz.getModifiers()) && !clazz.isArray() || clazz.isPrimitive();
}
}
| 11,673 | 39.255172 | 142 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/ClassMethodSigImpl.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import static net.sourceforge.pmd.lang.java.types.Substitution.EMPTY;
import static net.sourceforge.pmd.lang.java.types.Substitution.isEmptySubst;
import static net.sourceforge.pmd.util.CollectionUtil.map;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
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.symbols.JExecutableSymbol;
import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol;
import net.sourceforge.pmd.lang.java.types.internal.InternalMethodTypeItf;
class ClassMethodSigImpl implements JMethodSig, InternalMethodTypeItf {
private final JMethodSig adaptedMethod;
private final JClassType owner;
// either method or constructor
private final JExecutableSymbol symbol;
private @Nullable List<JTypeVar> tparams;
private JTypeMirror resultType;
private List<JTypeMirror> formals;
private List<JTypeMirror> thrown;
ClassMethodSigImpl(@NonNull JClassType owner, @NonNull JExecutableSymbol symbol) {
this(owner, symbol, null, null, null, null, null);
}
private ClassMethodSigImpl(@NonNull JClassType owner,
@NonNull JExecutableSymbol symbol,
JMethodSig adapted,
@Nullable List<JTypeVar> tparams,
@Nullable JTypeMirror resultType,
@Nullable List<JTypeMirror> formals,
@Nullable List<JTypeMirror> thrown) {
this.adaptedMethod = adapted == null ? this : adapted;
this.owner = owner;
this.symbol = symbol;
this.resultType = resultType;
this.formals = formals;
this.thrown = thrown;
this.tparams = tparams;
}
@Override
public TypeSystem getTypeSystem() {
return owner.getTypeSystem();
}
@Override
public JExecutableSymbol getSymbol() {
return symbol;
}
@Override
public JClassType getDeclaringType() {
return owner;
}
@Override
public JTypeMirror getAnnotatedReceiverType() {
return symbol.getAnnotatedReceiverType(getTypeParamSubst());
}
@Override
public JMethodSig getErasure() {
return new ClassMethodSigImpl(
owner.getErasure(),
symbol,
null,
Collections.emptyList(),
getReturnType().getErasure(),
TypeOps.erase(getFormalParameters()),
TypeOps.erase(getThrownExceptions())
);
}
@Override
public JTypeMirror getReturnType() {
if (resultType == null) {
if (symbol instanceof JMethodSymbol) {
if (owner.isRaw()) {
resultType = ClassTypeImpl.eraseToRaw(((JMethodSymbol) symbol).getReturnType(EMPTY), getTypeParamSubst());
} else {
resultType = ((JMethodSymbol) symbol).getReturnType(getTypeParamSubst());
}
} else {
// constructor
resultType = owner;
}
}
return resultType;
}
@Override
public List<JTypeMirror> getFormalParameters() {
if (formals == null) {
if (owner.isRaw()) {
formals = map(symbol.getFormalParameterTypes(EMPTY), m -> ClassTypeImpl.eraseToRaw(m, getTypeParamSubst()));
} else {
formals = symbol.getFormalParameterTypes(getTypeParamSubst());
}
}
return formals;
}
@Override
public List<JTypeVar> getTypeParameters() {
if (tparams == null) {
// bounds of the type params of a method need to be substituted
// with the lexical subst of the owner
tparams = TypeOps.substInBoundsOnly(symbol.getTypeParameters(), owner.getTypeParamSubst());
}
return tparams;
}
@Override
public List<JTypeMirror> getThrownExceptions() {
if (thrown == null) {
if (owner.isRaw()) {
thrown = map(symbol.getThrownExceptionTypes(EMPTY), m -> ClassTypeImpl.eraseToRaw(m, getTypeParamSubst()));
} else {
thrown = symbol.getThrownExceptionTypes(getTypeParamSubst());
}
}
return thrown;
}
@Override
public InternalMethodTypeItf internalApi() {
return this;
}
@Override
public JMethodSig withReturnType(JTypeMirror returnType) {
// share formals & thrown to avoid recomputing
return new ClassMethodSigImpl(owner, symbol, adaptedMethod, tparams, returnType, formals, thrown);
}
@Override
public JMethodSig withTypeParams(@Nullable List<JTypeVar> tparams) {
return new ClassMethodSigImpl(owner, symbol, adaptedMethod, tparams, resultType, formals, thrown);
}
@Override
public JMethodSig subst(Function<? super SubstVar, ? extends JTypeMirror> fun) {
if (isEmptySubst(fun)) {
return this;
}
return new ClassMethodSigImpl(
owner,
symbol,
adaptedMethod,
tparams, // don't substitute type parameters
TypeOps.subst(getReturnType(), fun),
TypeOps.subst(getFormalParameters(), fun),
TypeOps.subst(getThrownExceptions(), fun)
);
}
@Override
public JMethodSig markAsAdapted() {
return new ClassMethodSigImpl(owner, symbol, null, tparams, resultType, formals, thrown);
}
@Override
public JMethodSig withOwner(JTypeMirror newOwner) {
if (newOwner instanceof JClassType && Objects.equals(newOwner.getSymbol(), this.owner.getSymbol())) {
return new ClassMethodSigImpl((JClassType) newOwner, symbol, adaptedMethod, tparams, resultType, formals, thrown);
} else {
throw new IllegalArgumentException(newOwner + " cannot be the owner of " + this);
}
}
@Override
public JMethodSig originalMethod() {
return new ClassMethodSigImpl(owner, symbol);
}
@Override
public JMethodSig adaptedMethod() {
return adaptedMethod == null ? originalMethod() : adaptedMethod;
}
private Substitution getTypeParamSubst() {
return owner.getTypeParamSubst();
}
@Override
public String toString() {
return TypePrettyPrint.prettyPrint(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof JMethodSig)) {
return false;
}
JMethodSig that = (JMethodSig) o;
return TypeOps.isSameType(this, that);
}
@Override
public int hashCode() {
return Objects.hash(getName(), getFormalParameters(), getReturnType());
}
}
| 7,073 | 30.162996 | 126 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/UnresolvedMethodSig.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.List;
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.symbols.JClassSymbol;
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.types.internal.InternalMethodTypeItf;
final class UnresolvedMethodSig implements JMethodSig, InternalMethodTypeItf {
private final TypeSystem ts;
private final JExecutableSymbol sym;
UnresolvedMethodSig(TypeSystem ts) {
this.ts = ts;
sym = new UnresolvedMethodSym(ts);
}
@Override
public TypeSystem getTypeSystem() {
return ts;
}
@Override
public JExecutableSymbol getSymbol() {
return sym;
}
@Override
public JMethodSig getErasure() {
return this;
}
@Override
public JTypeMirror getDeclaringType() {
return ts.UNKNOWN;
}
@Override
public JTypeMirror getReturnType() {
return ts.UNKNOWN;
}
@Override
public JTypeMirror getAnnotatedReceiverType() {
return ts.UNKNOWN;
}
@Override
public List<JTypeMirror> getFormalParameters() {
return Collections.emptyList();
}
@Override
public List<JTypeVar> getTypeParameters() {
return Collections.emptyList();
}
@Override
public List<JTypeMirror> getThrownExceptions() {
return Collections.emptyList();
}
@Override
public JMethodSig withReturnType(JTypeMirror returnType) {
return this;
}
@Override
public JMethodSig markAsAdapted() {
return this;
}
@Override
public JMethodSig adaptedMethod() {
return this;
}
@Override
public JMethodSig withTypeParams(@Nullable List<JTypeVar> tparams) {
return this;
}
@Override
public JMethodSig subst(Function<? super SubstVar, ? extends @NonNull JTypeMirror> subst) {
return this;
}
@Override
public JMethodSig withOwner(JTypeMirror newOwner) {
return this;
}
@Override
public JMethodSig originalMethod() {
return this;
}
@Override
public InternalMethodTypeItf internalApi() {
return this;
}
@Override
public String toString() {
return getName();
}
private static class UnresolvedMethodSym implements JMethodSymbol {
private final TypeSystem ts;
UnresolvedMethodSym(TypeSystem ts) {
this.ts = ts;
}
@Override
public boolean isUnresolved() {
return true;
}
@Override
public TypeSystem getTypeSystem() {
return ts;
}
@Override
public boolean isBridge() {
return false;
}
@Override
public JTypeMirror getReturnType(Substitution subst) {
return ts.NO_TYPE;
}
@Override
public List<JFormalParamSymbol> getFormalParameters() {
return Collections.emptyList();
}
@Override
public boolean isVarargs() {
return false;
}
@Override
public int getArity() {
return 0;
}
@Override
public @Nullable JTypeMirror getAnnotatedReceiverType(Substitution subst) {
return ts.UNKNOWN;
}
@Override
public @NonNull JClassSymbol getEnclosingClass() {
return (JClassSymbol) ts.UNKNOWN.getSymbol();
}
@Override
public List<JTypeMirror> getFormalParameterTypes(Substitution subst) {
return Collections.emptyList();
}
@Override
public List<JTypeMirror> getThrownExceptionTypes(Substitution subst) {
return Collections.emptyList();
}
@Override
public List<JTypeVar> getTypeParameters() {
return Collections.emptyList();
}
@Override
public int getModifiers() {
return Modifier.PUBLIC;
}
@Override
public String getSimpleName() {
return "(*unknown method*)";
}
@Override
public String toString() {
return getSimpleName();
}
}
}
| 4,650 | 21.687805 | 95 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/Lub.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* Helper class for {@link TypeSystem#lub(Collection)} and {@link TypeSystem#glb(Collection)}.
*
* <p>Lub: Least Upper Bound, Glb: Greatest Lower Bound.
*/
final class Lub {
private Lub() {
}
static JTypeMirror lub(TypeSystem ts, Collection<? extends JTypeMirror> us) {
return new LubJudge(ts).lub(us);
}
private static JTypeMirror upperBound(JTypeMirror type) {
if (type instanceof JWildcardType) {
return ((JWildcardType) type).asUpperBound();
}
return type;
}
private static JTypeMirror lowerBound(JTypeMirror type) {
if (type instanceof JWildcardType) {
return ((JWildcardType) type).asLowerBound();
}
return type;
}
private static boolean isUpperBound(JTypeMirror type) {
return type instanceof JWildcardType && ((JWildcardType) type).isUpperBound();
}
private static boolean isLowerBound(JTypeMirror type) {
return type instanceof JWildcardType && ((JWildcardType) type).isLowerBound();
}
/**
* The "relevant" parameterizations of G, Relevant(G), is:
*
* <pre>{@code
* Relevant(G) = { V | 1 ≤ i ≤ k: V in ST(Ui) and V = G<...> }
* = { V ∈ stunion | V = G<...> }
* }</pre>
*
* <p>G must be erased (raw).
*
* @return null if G is not a generic type, otherwise Relevant(G)
*/
@SuppressWarnings("PMD.ReturnEmptyCollectionRatherThanNull") // null is explicit mentioned as a possible return value
static @Nullable List<JClassType> relevant(JClassType g, Set<JTypeMirror> stunion) {
if (!g.isRaw()) {
return null;
}
// else generic type:
List<JClassType> list = new ArrayList<>();
for (JTypeMirror it : stunion) {
if (it instanceof JClassType
&& it.getErasure().equals(g) && !it.isRaw()) {
list.add((JClassType) it);
}
}
return list;
}
private static Set<JTypeMirror> erasedSuperTypes(Set<JTypeMirror> stui) {
Set<JTypeMirror> erased = new LinkedHashSet<>();
for (JTypeMirror it : stui) {
JTypeMirror t = it instanceof JTypeVar ? it : it.getErasure();
erased.add(t);
}
return erased;
}
private static class LubJudge {
// this is what this class is about: caching lubs, so that we
// don't get an infinitely recursive type.
private final Set<TypePair> lubCache = new HashSet<>();
private final TypeSystem ts;
LubJudge(TypeSystem ts) {
this.ts = ts;
}
JTypeMirror lub(JTypeMirror... in) {
return lub(Arrays.asList(in));
}
JTypeMirror glb(JTypeMirror... in) {
return ts.glb(Arrays.asList(in));
}
JTypeMirror lub(Collection<? extends JTypeMirror> in) {
if (in.isEmpty()) {
throw new IllegalArgumentException("Empty set for lub?");
}
Set<JTypeMirror> us = new LinkedHashSet<>(in);
us.remove(ts.NULL_TYPE);
Iterator<JTypeMirror> uIterator = us.iterator();
if (us.size() == 1) {
return uIterator.next();
} else if (us.isEmpty()) {
// we removed the null type previously
return ts.NULL_TYPE;
}
// This is the union of all generic supertypes of the Uis
Set<JTypeMirror> stunion = new LinkedHashSet<>(uIterator.next().box().getSuperTypeSet());
// Let EC, the erased candidate set for U1 ... Uk, be the intersection of all the sets EST(Ui)
Set<JTypeMirror> ec = erasedSuperTypes(stunion);
while (uIterator.hasNext()) {
// Let ST(Ui), the set of supertypes of Ui
Set<JTypeMirror> stui = uIterator.next().box().getSuperTypeSet();
// Let EST(Ui), the set of erased supertypes of Ui
Set<JTypeMirror> estui = erasedSuperTypes(stui);
ec.retainAll(estui);
stunion.addAll(stui);
}
// Let MEC, the minimal erased candidate set for U1 ... Uk, be:
// MEC = { V | V in EC, and for all W ≠ V in EC, it is not the case that W <: V }
Set<JTypeMirror> mec = TypeOps.mostSpecific(ec);
List<JTypeMirror> best = CollectionUtil.map(mec, g -> {
if (g instanceof JClassType) {
List<JClassType> relevant = relevant((JClassType) g, stunion);
return relevant != null ? lcp(relevant) : g;
} else {
return g;
}
});
return best.isEmpty() ? ts.OBJECT : ts.glb(best);
}
/**
* LCP is the "least containing parameterization" of a set of
* parameterizations of the same generic type G.
*
* <p>It is a parameterization of G such that all elements of
* the set are subtypes of that parameterization.
*/
private JClassType lcp(List<JClassType> relevant) {
if (relevant.isEmpty()) {
throw new IllegalArgumentException("Empty set");
}
if (relevant.size() == 1) {
// single parameter
return relevant.get(0);
}
JClassType acc = lcp(relevant.get(0), relevant.get(1));
for (int i = 2; i < relevant.size(); i++) {
acc = lcp(acc, relevant.get(i));
}
return acc;
}
private JClassType lcp(JClassType t, JClassType s) {
int n = t.getFormalTypeParams().size();
List<JTypeMirror> leastArgs = new ArrayList<>(n);
List<JTypeMirror> targs = t.getTypeArgs();
List<JTypeMirror> sargs = s.getTypeArgs();
for (int i = 0; i < n; i++) {
leastArgs.add(lcta(targs.get(i), sargs.get(i)));
}
return t.withTypeArguments(leastArgs);
}
/**
* lcta(T, S), the least containing type argument, finds the most specific
* type argument that contains both T and S, in the sense of
* {@link TypeOps#typeArgContains(JTypeMirror, JTypeMirror)}.
*/
private JTypeMirror lcta(JTypeMirror t, JTypeMirror s) {
TypePair pair = new TypePair(t, s);
if (lubCache.add(pair)) {
JTypeMirror res = computeLcta(t, s);
lubCache.remove(pair);
return res;
} else {
// We're recursing on lcta(T,S) with the same arguments.
// We have to break the recursion.
return ts.UNBOUNDED_WILD;
}
}
private @NonNull JTypeMirror computeLcta(JTypeMirror t, JTypeMirror s) {
// lcta(U, V) = U if U = V
if (t.equals(s)) {
return t;
}
if (isUpperBound(t) && isLowerBound(s)) {
// lcta(? extends U, ? super V) = ?
return ts.UNBOUNDED_WILD;
}
if (isUpperBound(s)) {
// lcta(U, ? extends V) = ? extends lub(U, V)
// lcta(? extends U, ? extends V) = ? extends lub(U, V)
return ts.wildcard(true, this.lub(upperBound(t), upperBound(s)));
}
if (isLowerBound(s)) {
// lcta(U, ? super V) = ? super glb(U, V)
// lcta(? super U, ? super V) = ? super glb(U, V)
return ts.wildcard(false, this.glb(lowerBound(t), lowerBound(s)));
}
// otherwise ? extends lub(U, V)
return ts.wildcard(true, this.lub(t, s));
}
}
/** Simple record type for a pair of types. */
private static final class TypePair {
public final JTypeMirror left;
public final JTypeMirror right;
TypePair(JTypeMirror left, JTypeMirror right) {
this.left = left;
this.right = right;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TypePair pair = (TypePair) o;
return Objects.equals(left, pair.left)
&& Objects.equals(right, pair.right);
}
@Override
public int hashCode() {
return Objects.hash(left, right);
}
@Override
public String toString() {
return "Pair(" + left + " - " + right + ")";
}
}
static JTypeMirror glb(TypeSystem ts, Collection<? extends JTypeMirror> types) {
if (types.isEmpty()) {
throw new IllegalArgumentException("Cannot compute GLB of empty set");
} else if (types.size() == 1) {
return types.iterator().next();
}
List<JTypeMirror> flat = flattenRemoveTrivialBound(types);
if (flat.size() == 1) {
return flat.get(0);
} else if (flat.isEmpty()) {
return ts.OBJECT;
}
Set<JTypeMirror> mostSpecific = TypeOps.mostSpecific(flat);
assert !mostSpecific.isEmpty() : "Empty most specific for bounds " + flat;
if (mostSpecific.size() == 1) {
return mostSpecific.iterator().next();
}
List<JTypeMirror> bounds = new ArrayList<>(mostSpecific);
JTypeMirror primaryBound = null;
for (int i = 0; i < bounds.size(); i++) {
JTypeMirror ci = bounds.get(i);
if (isExclusiveIntersectionBound(ci)) {
// either Ci is an array, or Ci is a class, or Ci is a type var (possibly captured)
// Ci is not unresolved
if (primaryBound == null) {
primaryBound = ci;
// move primary bound first
Collections.swap(bounds, 0, i);
} else {
throw new IllegalArgumentException(
"Bad intersection, unrelated class types " + ci + " and " + primaryBound + " in " + types
);
}
}
}
if (primaryBound == null) {
if (bounds.size() == 1) {
return bounds.get(0);
}
primaryBound = ts.OBJECT;
}
return new JIntersectionType(ts, primaryBound, bounds);
}
private static void checkGlbComponent(Collection<? extends JTypeMirror> types, JTypeMirror ci) {
if (ci.isPrimitive() || ci instanceof JWildcardType || ci instanceof JIntersectionType) {
throw new IllegalArgumentException("Bad intersection type component: " + ci + " in " + types);
}
}
private static @NonNull List<JTypeMirror> flattenRemoveTrivialBound(Collection<? extends JTypeMirror> types) {
List<JTypeMirror> bounds = new ArrayList<>(types.size());
for (JTypeMirror type : types) {
// flatten intersections: (A & (B & C)) => (A & B & C)
if (type instanceof JIntersectionType) {
bounds.addAll(((JIntersectionType) type).getComponents());
} else {
checkGlbComponent(types, type);
if (!type.isTop()) {
bounds.add(type);
}
}
}
return bounds;
}
static boolean isExclusiveIntersectionBound(JTypeMirror ci) {
return !ci.isInterface()
&& !(ci instanceof InferenceVar)
&& (ci.getSymbol() == null || !ci.getSymbol().isUnresolved());
}
}
| 12,478 | 31.245478 | 121 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/JTypeMirror.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.pcollections.PSet;
import net.sourceforge.pmd.annotation.Experimental;
import net.sourceforge.pmd.lang.java.ast.TypeNode;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JExecutableSymbol;
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.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.lang.java.types.JPrimitiveType.PrimitiveTypeKind;
import net.sourceforge.pmd.lang.java.types.TypeOps.Convertibility;
import net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar;
import net.sourceforge.pmd.util.AssertionUtil;
/**
* Type mirrors represent Java types. They are created by a {@link TypeSystem}
* from {@linkplain JTypeDeclSymbol symbols}, a layer of abstraction above reflection
* classes.
*
* <p>Type mirrors can be obtained {@linkplain TypesFromReflection from reflected types},
* directly {@linkplain TypeNode#getTypeMirror() from nodes}, or from
* arbitrary symbols (see {@link TypeSystem}).
*
* <p>Type mirrors are primarily divided between {@linkplain JPrimitiveType primitive types}
* and reference types. Reference types can be of one of those kinds:
* <ul>
* <li>{@linkplain JClassType class or interface types}
* <li>{@linkplain JArrayType array types}
* <li>{@linkplain JIntersectionType intersection types}
* <li>{@linkplain JTypeVar type variables}
* </ul>
*
* <p>{@linkplain JWildcardType Wildcard types} implement this interface,
* but are not really types, they can only occur as type arguments of a
* class type.
*
* <p>A few other special types do not implement one of these public interfaces:
* <ul>
* <li>{@linkplain TypeSystem#NULL_TYPE The null type}
* <li>{@linkplain TypeSystem#ERROR The error type}
* <li>{@linkplain TypeSystem#UNKNOWN The unresolved type}
* </ul>
*
* <p>Lastly, types may be {@linkplain InferenceVar inference variables},
* which <i>should not ever occur</i> outside of a type inference
* run and should be ignored when querying the AST. If you find an ivar,
* report a bug.
*
* <p>Note that implementing this type hierarchy outside of this package
* is not a supported usage of this API. The API is built to work with any
* symbol implementation, and that is its extension point.
*/
public interface JTypeMirror extends JTypeVisitable {
// TODO: unstable stuff (@Experimental)
// - Member access:
// - #getDeclaredField
// - #getDeclaredClass
// - In JWildcardType, the specification of some methods is unstable:
// - #isSubtypeOf/#isConvertibleTo
// - #getErasure
// TODO figure out what parts of TypeOps/TypeConversion are internal
// - problem is that parts of those access package-private API, eg
// to implement capture.
/**
* Returns the type system that built this type.
*/
TypeSystem getTypeSystem();
/**
* Return a list of annotations on this type. Annotations can be written
* on nearly any type (eg {@code @A Out.@B In<@C T>}, {@code @A ? extends @B Up}).
*
* <p>For {@link JTypeVar}, this includes both the annotations defined
* on the type var and those defined at use site. For instance
* <pre>{@code
* <@A T> void accept(@B T t);
* }</pre>
* The T type var will have annotation {@code @A} in the symbol
* ({@link JTypeParameterSymbol#getDeclaredAnnotations()})
* and in the type var that is in the {@link JMethodSig#getTypeParameters()}.
* In the formal parameter, the type var will have annotations {@code @B @A}.
*/
// todo annotations do not participate in equality of types.
PSet<SymAnnot> getTypeAnnotations();
/**
* Returns true if this type is the same type or a subtype of the
* given type. Note that for convenience, this returns true if both
* types are primitive, and this type is convertible to the other
* through primitive widening. See {@link Convertibility#bySubtyping()}.
*
* @throws NullPointerException If the argument is null
*/
default boolean isSubtypeOf(@NonNull JTypeMirror other) {
return isConvertibleTo(other).bySubtyping();
}
/**
* Tests this type's convertibility to the other type. See
* {@link Convertibility} for a description of the results.
*
* <p>Note that this does not check for boxing/unboxing conversions.
*
* @throws NullPointerException If the argument is null
*/
default Convertibility isConvertibleTo(@NonNull JTypeMirror other) {
return TypeOps.isConvertible(this, other);
}
/**
* Returns the set of (nominal) supertypes of this type.
* If this is a primitive type, returns the set of other
* primitives to which this type is convertible by widening
* conversion (eg for {@code long} returns {@code {long, float, double}}).
*
* <p>The returned set always contains this type, so is
* never empty. Ordering is stable, though unspecified.
*
* <p>Note that this set contains {@link TypeSystem#OBJECT}
* for interfaces too.
*
* <p>Note that for types having type annotations, the supertypes
* do not bear the same annotations. Eg the supertypes of {@code @A String}
* contain {@code Object} but not {@code @A Object}. The supertypes
* may be annotated though, eg if a class declares {@code extends @A Foo},
* the supertypes contain {@code @A Foo}.
*
* @throws UnsupportedOperationException If this is the null type
*/
default Set<JTypeMirror> getSuperTypeSet() {
return TypeOps.getSuperTypeSet(this);
}
/**
* Returns the erasure of this type. Erasure is defined by JLS§4.6,
* an adapted definition follows:
*
* <blockquote>
* <ol>
* <li>The erasure of a parameterized type (§4.5) {@literal G<T1,...,Tn>} is |G|.
* <li>The erasure of a nested type T.C is |T|.C.
* <li>The erasure of an array type T[] is |T|[].
* <li>The erasure of a type variable (§4.4) is the erasure of its upper bound.
* <li>The erasure of an intersection type is the erasure of its leftmost component.
* <li>The erasure of every other type is the type itself.
* </ol>
* </blockquote>
*
* <p>The JVM representation of a type is in general the symbol
* of its erasure. So to get a {@link Class} instance for the runtime
* representation of a type, you should do {@code t.getErasure().getSymbol()}.
* The erasure procedure gets rid of types that have no symbol (except
* if {@code t} is a wildcard type, or the {@link TypeSystem#NULL_TYPE})
*/
default JTypeMirror getErasure() {
return this;
}
/**
* Returns the symbol declaring this type. {@linkplain #isReifiable() Reifiable}
* types present a symbol, and some other types too. This method's
* return value depends on this type:
* <ul>
* <li>{@link JClassType}: a {@link JClassSymbol}, always (even if not reifiable)
* <li>{@link JPrimitiveType}: a {@link JClassSymbol}, always
* <li>{@link JArrayType}: a {@link JClassSymbol}, if the element type does present a symbol.
* <li>{@link JTypeVar}: a {@link JTypeParameterSymbol}, or null if this is a capture variable.
* Note that the erasure yields a different symbol (eg Object for unbounded tvars).
* <li>{@link JIntersectionType}: null, though their erasure always
* presents a symbol.
* <li>{@link JWildcardType}, {@link TypeSystem#NULL_TYPE the null type}: null, always
* </ul>
*
* <p>Note that type annotations are not reflected on the
* symbol, but only on the type.
*/
default @Nullable JTypeDeclSymbol getSymbol() {
return null;
}
/**
* Returns the primitive wrapper type of this type, if this is a
* primitive type. Otherwise returns this type unchanged.
*/
default JTypeMirror box() {
return this;
}
/**
* Returns the unboxed version of this type. Returns this type unchanged
* if this is not a primitive wrapper type.
*/
default JTypeMirror unbox() {
return this;
}
/**
* Returns the most specific declared supertype of this type whose erasure
* is the same as that of the parameter. E.g. for {@code Enum<E>, Comparable},
* returns {@code Comparable<E>}.
*
* <p>Returns null if that can't be found, meaning that the given type
* is not a supertype of this type.
*/
default @Nullable JTypeMirror getAsSuper(@NonNull JClassSymbol symbol) {
return TypeOps.asSuper(this, symbol);
}
/**
* Returns true if this type is reifiable. If so, its {@link #getSymbol() symbol}
* will not be null (the reverse is not necessarily true).
*
* <p>Reifiable types are those types that are completely available
* at run time. See also <a href="https://docs.oracle.com/javase/specs/jls/se13/html/jls-4.html#jls-4.7">JLS§4.7</a>
*/
default boolean isReifiable() {
if (this instanceof JPrimitiveType) {
return true;
} else if (this instanceof JArrayType) {
return ((JArrayType) this).getElementType().isReifiable();
}
return this instanceof JClassType && TypeOps.allArgsAreUnboundedWildcards(((JClassType) this).getTypeArgs());
}
/** Returns true if this type is a {@linkplain JPrimitiveType primitive type}. */
default boolean isPrimitive() {
return false; // overridden in JPrimitiveType
}
/** Returns true if this type is the primitive type of the given kind in its type system. */
default boolean isPrimitive(PrimitiveTypeKind kind) {
return false; // overridden in JPrimitiveType
}
/**
* Returns true if this type is a {@linkplain JPrimitiveType primitive type}
* of a floating point type.
*/
default boolean isFloatingPoint() {
return false; // overridden in JPrimitiveType
}
/**
* Returns true if this type is a {@linkplain JPrimitiveType primitive type}
* of an integral type.
*/
default boolean isIntegral() {
return false; // overridden in JPrimitiveType
}
/** Returns true if this type is a {@linkplain JTypeVar type variable}. */
default boolean isTypeVariable() {
return this instanceof JTypeVar;
}
/**
* Returns true if this type is a boxed primitive type. This is a {@link JClassType},
* whose {@link #unbox()} method returns a {@link JPrimitiveType}.
*/
default boolean isBoxedPrimitive() {
return unbox() != this; // NOPMD CompareObjectsWithEquals
}
/**
* Returns true if this is a primitive numeric type. The only
* non-numeric primitive type is {@link TypeSystem#BOOLEAN}.
*/
default boolean isNumeric() {
return false;
}
/** Returns true if this is a {@linkplain JClassType class or interface type}. */
default boolean isClassOrInterface() {
return this instanceof JClassType;
}
/**
* Returns true if this is {@link TypeSystem#OBJECT}.
*/
default boolean isTop() {
return false; // overridden
}
/**
* Returns true if this is {@link TypeSystem#NULL_TYPE}.
*/
default boolean isBottom() {
return false; // overridden
}
/**
* Returns true if this is {@link TypeSystem#NO_TYPE}, ie {@code void}.
*/
default boolean isVoid() {
return this == getTypeSystem().NO_TYPE; // NOPMD CompareObjectsWithEquals
}
/** Returns true if this is an {@linkplain JArrayType array type}. */
default boolean isArray() {
return this instanceof JArrayType;
}
/**
* Returns true if this represents the *declaration* of a generic
* class or interface and not some parameterization. This is the
* "canonical" form of a parameterized type.
*
* <p>In that case, the {@link JClassType#getTypeArgs()} is the same
* as {@link JClassType#getFormalTypeParams()}.
*
* <p>The generic type declaration of a generic type may be obtained
* with {@link JClassType#getGenericTypeDeclaration()}.
*/
default boolean isGenericTypeDeclaration() {
return false;
}
/**
* Returns true if this type is a generic class type.
* This means, the symbol declares some type parameters,
* which is also true for erased types, including raw types.
*
* <p>For example, {@code List}, {@code List<T>}, and {@code List<String>}
* are generic, but {@code String} is not.
*
* @see JClassType#isGeneric().
*/
default boolean isGeneric() {
return false;
}
/**
* Returns true if this type is generic, and it it neither {@linkplain #isRaw() raw},
* nor a {@linkplain JClassType#isGenericTypeDeclaration() generic type declaration}.
*
* <p>E.g. returns true for {@code List<String>} or {@code Enum<KeyCode>},
* but not for {@code List} (raw type), {@code List<T>} (generic type declaration),
* or {@code KeyCode} (not a generic type).
*/
default boolean isParameterizedType() {
return false;
}
/**
* Returns true if this is a raw type. This may be
* <ul>
* <li>A generic class or interface type for which no type arguments
* were provided
* <li>An array type whose element type is raw
* <li>A non-static member type of a raw type
* </ul>
*
* <p>https://docs.oracle.com/javase/specs/jls/se11/html/jls-4.html#jls-4.8
*
* @see JClassType#isRaw()
*/
default boolean isRaw() {
return false;
}
/**
* Returns true if this is an interface type. Annotations are also
* interface types.
*/
default boolean isInterface() {
JTypeDeclSymbol sym = getSymbol();
return sym != null && sym.isInterface();
}
/**
* Returns a stream of method signatures declared in and inherited
* by this type. Method signatures are created on-demand by this
* method, they're not reused between calls. This stream does not
* include constructors.
*
* @param prefilter Filter selecting symbols for which a signature
* should be created and yielded by the stream
*
* @experimental streams are a bit impractical when it comes to
* configuring the filter. Possibly a specialized API should be introduced.
* We need to support the use cases of the symbol table, ie filter by name + accessibility + staticity,
* and also possibly use cases for rules, like getting a method from
* a known signature. See also {@link JClassType#getDeclaredMethod(JExecutableSymbol)},
* which looks like this. Unifying this API would be nice.
*/
@Experimental
default Stream<JMethodSig> streamMethods(Predicate<? super JMethodSymbol> prefilter) {
return Stream.empty();
}
/**
* Like {@link #streamMethods(Predicate) streamMethods}, but does
* not recurse into supertypes. Note that only class and array types
* declare methods themselves.
*
* @experimental See {@link #streamMethods(Predicate)}
*
* @see #streamMethods(Predicate)
*/
@Experimental
default Stream<JMethodSig> streamDeclaredMethods(Predicate<? super JMethodSymbol> prefilter) {
return Stream.empty();
}
/**
* Returns a list of all the declared constructors for this type.
* Abstract types like type variables and interfaces have no constructors.
*/
@Experimental
default List<JMethodSig> getConstructors() {
return Collections.emptyList();
}
@Override
JTypeMirror subst(Function<? super SubstVar, ? extends @NonNull JTypeMirror> subst);
/**
* Returns a type mirror that is equal to this instance but has different
* type annotations. Note that some types ignore this method and return
* themselves without changing. Eg the null type cannot be annotated.
*
* @param newTypeAnnots New type annotations (not null)
*
* @return A new type, maybe this one
*/
JTypeMirror withAnnotations(PSet<SymAnnot> newTypeAnnots);
/**
* Returns a type mirror that is equal to this instance but has one
* more type annotation.
*
* @see #withAnnotations(PSet)
*/
default JTypeMirror addAnnotation(@NonNull SymAnnot newAnnot) {
AssertionUtil.requireParamNotNull("annot", newAnnot);
return withAnnotations(getTypeAnnotations().plus(newAnnot));
}
/**
* Returns true if the object is a type equivalent to this one. A
* few kinds of types use reference identity, like captured type
* variables, or the null type. A few special types are represented
* by constants (see {@link TypeSystem}). Apart from those, types
* should always be compared using this method. or {@link TypeOps#isSameType(JTypeMirror, JTypeMirror)}
* (which is null-safe).
*
* <p>Note that types belonging to different type systems do <i>not</i>
* test equal. The type system object is global to the analysis though,
* so this should not ever happen in rules.
*
* @param o {@inheritDoc}
*
* @return {@inheritDoc}
*
* @implSpec This method should be implemented with
* {@link TypeOps#isSameType(JTypeMirror, JTypeMirror)},
* and perform no side-effects on inference variables.
*/
@Override
boolean equals(Object o);
/**
* The toString of type mirrors prints useful debug information,
* but shouldn't be relied on anywhere, as it may change anytime.
* Use {@link TypePrettyPrint} to display types.
*/
@Override
String toString();
}
| 18,448 | 34.753876 | 120 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/WildcardTypeImpl.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.util.Objects;
import java.util.function.Function;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
final class WildcardTypeImpl implements JWildcardType {
private final JTypeMirror bound;
private final boolean isUpperBound;
private final TypeSystem ts;
private final PSet<SymAnnot> typeAnnots;
WildcardTypeImpl(TypeSystem ts, boolean isUpperBound, @Nullable JTypeMirror bound, PSet<SymAnnot> typeAnnots) {
this.ts = ts;
this.typeAnnots = typeAnnots;
this.bound = bound != null ? bound
: isUpperBound ? ts.OBJECT : ts.NULL_TYPE;
this.isUpperBound = isUpperBound;
}
@Override
public JWildcardType subst(Function<? super SubstVar, ? extends @NonNull JTypeMirror> subst) {
JTypeMirror newBound = getBound().subst(subst);
return newBound == getBound() ? this : ts.wildcard(isUpperBound(), newBound).withAnnotations(typeAnnots); // NOPMD CompareObjectsWithEquals
}
@Override
public PSet<SymAnnot> getTypeAnnotations() {
return typeAnnots;
}
@Override
public JWildcardType withAnnotations(PSet<SymAnnot> newTypeAnnots) {
if (newTypeAnnots.isEmpty() && !typeAnnots.isEmpty()) {
return ts.wildcard(isUpperBound, bound);
} else if (!newTypeAnnots.isEmpty()) {
return new WildcardTypeImpl(ts, isUpperBound(), bound, newTypeAnnots);
}
return this;
}
@Override
public TypeSystem getTypeSystem() {
return ts;
}
@Override
public @NonNull JTypeMirror getBound() {
return bound;
}
@Override
public boolean isUpperBound() {
return isUpperBound;
}
@Override
public String toString() {
return TypePrettyPrint.prettyPrint(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof JWildcardType)) {
return false;
}
JWildcardType that = (JWildcardType) o;
return isUpperBound == that.isUpperBound() && Objects.equals(bound, that.getBound());
}
@Override
public int hashCode() {
return Objects.hash(bound, isUpperBound);
}
}
| 2,570 | 26.945652 | 147 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/BasePrimitiveSymbol.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
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.symbols.internal.SymbolEquality;
import net.sourceforge.pmd.lang.java.symbols.internal.SymbolToStrings;
import net.sourceforge.pmd.lang.java.types.JPrimitiveType.PrimitiveTypeKind;
abstract class BasePrimitiveSymbol implements JClassSymbol {
private final TypeSystem ts;
BasePrimitiveSymbol(TypeSystem ts) {
this.ts = ts;
}
static final class VoidSymbol extends BasePrimitiveSymbol {
VoidSymbol(TypeSystem ts) {
super(ts);
}
@Override
public @NonNull String getBinaryName() {
return "void";
}
@Override
public String getCanonicalName() {
return "void";
}
@Override
public @NonNull String getSimpleName() {
return "void";
}
}
static final class RealPrimitiveSymbol extends BasePrimitiveSymbol {
private final PrimitiveTypeKind kind;
RealPrimitiveSymbol(TypeSystem ts, PrimitiveTypeKind kind) {
super(ts);
this.kind = kind;
}
@Override
public @NonNull String getBinaryName() {
return kind.getSimpleName();
}
@Override
public @Nullable String getCanonicalName() {
return kind.getSimpleName();
}
@Override
public @NonNull String getSimpleName() {
return kind.getSimpleName();
}
}
@Override
public @NonNull String getPackageName() {
return PRIMITIVE_PACKAGE;
}
@Override
public @Nullable JExecutableSymbol getEnclosingMethod() {
return null;
}
@Override
public List<JClassSymbol> getDeclaredClasses() {
return Collections.emptyList();
}
@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 List<JClassType> getSuperInterfaceTypes(Substitution substitution) {
return Collections.emptyList();
}
@Override
public @Nullable JClassType getSuperclassType(Substitution substitution) {
return null;
}
@Override
public @Nullable JClassSymbol getSuperclass() {
return null;
}
@Override
public List<JClassSymbol> getSuperInterfaces() {
return Collections.emptyList();
}
@Override
public @Nullable JTypeDeclSymbol getArrayComponent() {
return null;
}
@Override
public boolean isArray() {
return false;
}
@Override
public boolean isPrimitive() {
return true;
}
@Override
public boolean isEnum() {
return false;
}
@Override
public boolean isRecord() {
return false;
}
@Override
public boolean isAnnotation() {
return false;
}
@Override
public boolean isLocalClass() {
return false;
}
@Override
public boolean isAnonymousClass() {
return false;
}
@Override
public TypeSystem getTypeSystem() {
return ts;
}
@Override
public List<JTypeVar> getTypeParameters() {
return Collections.emptyList();
}
@Override
public int getModifiers() {
return Modifier.PUBLIC | Modifier.ABSTRACT | Modifier.FINAL;
}
@Override
public @Nullable JClassSymbol getEnclosingClass() {
return null;
}
@Override
public int hashCode() {
return SymbolEquality.CLASS.hash(this);
}
@Override
public boolean equals(Object obj) {
return SymbolEquality.CLASS.equals(this, obj);
}
@Override
public String toString() {
return SymbolToStrings.SHARED.toString(this);
}
}
| 4,678 | 21.280952 | 79 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/ast/ExprContext.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.ast;
import static net.sourceforge.pmd.lang.java.types.ast.ExprContext.ExprContextKind.ASSIGNMENT;
import static net.sourceforge.pmd.lang.java.types.ast.ExprContext.ExprContextKind.CAST;
import static net.sourceforge.pmd.lang.java.types.ast.ExprContext.ExprContextKind.INVOCATION;
import static net.sourceforge.pmd.lang.java.types.ast.ExprContext.ExprContextKind.MISSING;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.annotation.Experimental;
import net.sourceforge.pmd.lang.java.ast.InvocationNode;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.OverloadSelectionResult;
import net.sourceforge.pmd.lang.java.types.TypeConversion;
import net.sourceforge.pmd.util.AssertionUtil;
/**
* Context of an expression. This determines the target type of poly
* expressions, which is necessary for overload resolution. It also
* determines what kinds of conversions apply to the value to make it
* compatible with the context.
*/
@Experimental("The API is minimal until more use cases show up, and this is better tested.")
public abstract class ExprContext {
// note: most members of this class are quite low-level and should
// stay package-private for exclusive use by PolyResolution.
final ExprContextKind kind;
private ExprContext(ExprContextKind kind) {
this.kind = kind;
}
/**
* Returns the target type, or null if {@linkplain #isMissing() there is none}.
*/
// note: only meant for public use by rules
// note: this may triggers type resolution of the context
public abstract @Nullable JTypeMirror getTargetType();
/**
* Returns true if the given type is compatible with this context
* implicitly (without cast). Conversions may occur to make this
* possible. What conversions may occur depends on the kind of
* this context.
*
* <p>By convention, any type is compatible with a missing context.
*
* @param type A type which is checked against the target type
*/
public boolean acceptsType(@NonNull JTypeMirror type) {
AssertionUtil.requireParamNotNull("type", type);
JTypeMirror targetType = getTargetType();
return targetType == null
// todo there's a gritty detail about compound assignment operators
// with a primitive LHS, see https://github.com/pmd/pmd/issues/2023
|| (kind == CAST ? TypeConversion.isConvertibleInCastContext(type, targetType)
: TypeConversion.isConvertibleUsingBoxing(type, targetType));
}
/**
* Returns true if this context does not provide any target type.
* This is then a sentinel object.
*/
public boolean isMissing() {
return kind == MISSING;
}
/** Returns the kind of context this is. */
public ExprContextKind getKind() {
return kind;
}
final boolean canGiveContextToPoly(boolean lambdaOrMethodRef) {
return this.hasKind(ASSIGNMENT)
|| this.hasKind(INVOCATION)
|| this.hasKind(CAST) && lambdaOrMethodRef;
}
public @Nullable InvocationNode getInvocNodeIfInvocContext() {
return this instanceof InvocCtx ? ((InvocCtx) this).node : null;
}
public @NonNull ExprContext getToplevelCtx() {
return this; // todo
}
/**
* Returns the target type bestowed by this context ON A POLY EXPRESSION.
*
* @param lambdaOrMethodRef Whether the poly to be considered is a
* lambda or method ref. In this case, cast
* contexts can give a target type.
*/
public @Nullable JTypeMirror getPolyTargetType(boolean lambdaOrMethodRef) {
if (!canGiveContextToPoly(lambdaOrMethodRef)) {
return null;
}
return getTargetType();
}
static ExprContext newOtherContext(@NonNull JTypeMirror targetType, ExprContextKind kind) {
AssertionUtil.requireParamNotNull("target type", targetType);
return new RegularCtx(targetType, kind);
}
static ExprContext newInvocContext(InvocationNode invocNode, int argumentIndex) {
return new InvocCtx(argumentIndex, invocNode);
}
/**
* Returns an {@link ExprContext} instance which represents a
* missing context. Use {@link #isMissing()} instead of testing
* for equality.
*/
public static RegularCtx getMissingInstance() {
return RegularCtx.NO_CTX;
}
public boolean hasKind(ExprContextKind kind) {
return getKind() == kind;
}
private static final class InvocCtx extends ExprContext {
final int arg;
final InvocationNode node;
InvocCtx(int arg, InvocationNode node) {
super(INVOCATION);
this.arg = arg;
this.node = node;
}
@Override
public @Nullable JTypeMirror getTargetType() {
// this triggers type resolution of the enclosing expr.
OverloadSelectionResult overload = node.getOverloadSelectionInfo();
if (overload.isFailed()) {
return null;
}
return overload.ithFormalParam(arg);
}
@Override
public boolean isMissing() {
return false;
}
@Override
public String toString() {
return "InvocCtx{arg=" + arg + ", node=" + node + '}';
}
}
/**
* Kind of context.
*/
public enum ExprContextKind {
/** Invocation context (method arguments). */
INVOCATION,
/**
* Assignment context. This includes:
* <ul>
* <li>RHS of an assignment
* <li>Return statement
* <li>Array initializer
* <li>Superclass constructor invocation
* </ul>
*
* <p>An assignment context flows through ternary/switch branches.
* They are a context for poly expressions.
*/
ASSIGNMENT,
/**
* Cast context. Lambdas and method refs can use them as a
* target type, but no other expressions. Cast contexts do not
* flow through ternary/switch branches.
*/
CAST,
/**
* Numeric context. May determine that an (un)boxing or
* primitive widening conversion occurs. These is the context for
* operands of arithmetic expressions, array indices.
* <p>For instance:
* <pre>{@code
* Integer integer;
*
* array[integer] // Integer is unboxed to int
* integer + 1 // Integer is unboxed to int
* 0 + 1.0 // int (left) is widened to double
* integer + 1.0 // Integer is unboxed to int, then widened to double
* }</pre>
*/
NUMERIC,
/**
* String contexts, which convert the operand to a string using {@link String#valueOf(Object)},
* or the equivalent for a primitive type. They accept operands of any type.
* This is the context for the operands of a string concatenation expression,
* and for the message of an assert statement.
*/
STRING,
/** Kind for a standalone ternary (both branches are then in this context). */
TERNARY,
/** Kind for a missing context ({@link RegularCtx#NO_CTX}). */
MISSING,
/**
* Boolean contexts, which unbox their operand to a boolean.
* They accept operands of type boolean or Boolean. This is the
* context for e.g. the condition of an {@code if} statement, an
* assert statement, etc.
*
* <p>This provides a target type for conversions, but not for poly
* expressions.
*/
BOOLEAN,
}
static final class RegularCtx extends ExprContext {
private static final RegularCtx NO_CTX = new RegularCtx(null, MISSING);
final @Nullable JTypeMirror targetType;
RegularCtx(@Nullable JTypeMirror targetType, ExprContextKind kind) {
super(kind);
assert kind != INVOCATION;
this.targetType = targetType;
}
@Override
public @Nullable JTypeMirror getTargetType() {
return targetType;
}
@Override
public String toString() {
return "RegularCtx{kind=" + kind + ", targetType=" + targetType + '}';
}
}
}
| 8,700 | 32.856031 | 103 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/ast/LazyTypeResolver.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.ast;
import static net.sourceforge.pmd.lang.java.ast.BinaryOp.ADD;
import static net.sourceforge.pmd.lang.java.types.TypeConversion.binaryNumericPromotion;
import static net.sourceforge.pmd.lang.java.types.TypeConversion.capture;
import static net.sourceforge.pmd.lang.java.types.TypeConversion.unaryNumericPromotion;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.ast.SemanticErrorReporter;
import net.sourceforge.pmd.lang.java.ast.ASTAmbiguousName;
import net.sourceforge.pmd.lang.java.ast.ASTAnnotation;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTArrayAccess;
import net.sourceforge.pmd.lang.java.ast.ASTArrayAllocation;
import net.sourceforge.pmd.lang.java.ast.ASTArrayDimensions;
import net.sourceforge.pmd.lang.java.ast.ASTArrayInitializer;
import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.AccessType;
import net.sourceforge.pmd.lang.java.ast.ASTAssignmentExpression;
import net.sourceforge.pmd.lang.java.ast.ASTBooleanLiteral;
import net.sourceforge.pmd.lang.java.ast.ASTCastExpression;
import net.sourceforge.pmd.lang.java.ast.ASTCharLiteral;
import net.sourceforge.pmd.lang.java.ast.ASTClassLiteral;
import net.sourceforge.pmd.lang.java.ast.ASTConditionalExpression;
import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall;
import net.sourceforge.pmd.lang.java.ast.ASTEnumConstant;
import net.sourceforge.pmd.lang.java.ast.ASTExplicitConstructorInvocation;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTFieldAccess;
import net.sourceforge.pmd.lang.java.ast.ASTForeachStatement;
import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter;
import net.sourceforge.pmd.lang.java.ast.ASTInfixExpression;
import net.sourceforge.pmd.lang.java.ast.ASTLambdaExpression;
import net.sourceforge.pmd.lang.java.ast.ASTLambdaParameter;
import net.sourceforge.pmd.lang.java.ast.ASTMethodCall;
import net.sourceforge.pmd.lang.java.ast.ASTMethodReference;
import net.sourceforge.pmd.lang.java.ast.ASTNullLiteral;
import net.sourceforge.pmd.lang.java.ast.ASTNumericLiteral;
import net.sourceforge.pmd.lang.java.ast.ASTPattern;
import net.sourceforge.pmd.lang.java.ast.ASTPatternExpression;
import net.sourceforge.pmd.lang.java.ast.ASTStringLiteral;
import net.sourceforge.pmd.lang.java.ast.ASTSuperExpression;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchExpression;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchLabel;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchLike;
import net.sourceforge.pmd.lang.java.ast.ASTThisExpression;
import net.sourceforge.pmd.lang.java.ast.ASTType;
import net.sourceforge.pmd.lang.java.ast.ASTTypeParameter;
import net.sourceforge.pmd.lang.java.ast.ASTTypePattern;
import net.sourceforge.pmd.lang.java.ast.ASTUnaryExpression;
import net.sourceforge.pmd.lang.java.ast.ASTVariableAccess;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.ast.ASTVoidType;
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.TypeNode;
import net.sourceforge.pmd.lang.java.internal.JavaAstProcessor;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol;
import net.sourceforge.pmd.lang.java.symbols.JLocalVariableSymbol;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.NameResolver;
import net.sourceforge.pmd.lang.java.types.JArrayType;
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.JVariableSig;
import net.sourceforge.pmd.lang.java.types.JVariableSig.FieldSig;
import net.sourceforge.pmd.lang.java.types.Substitution;
import net.sourceforge.pmd.lang.java.types.TypeConversion;
import net.sourceforge.pmd.lang.java.types.TypeOps;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
import net.sourceforge.pmd.lang.java.types.TypesFromReflection;
import net.sourceforge.pmd.lang.java.types.TypingContext;
import net.sourceforge.pmd.lang.java.types.ast.ExprContext.ExprContextKind;
import net.sourceforge.pmd.lang.java.types.internal.infer.Infer;
import net.sourceforge.pmd.lang.java.types.internal.infer.TypeInferenceLogger;
/**
* Resolves types of expressions. This is used as the implementation of
* {@link TypeNode#getTypeMirror(TypingContext)} and is INTERNAL.
*/
@InternalApi
public final class LazyTypeResolver extends JavaVisitorBase<TypingContext, @NonNull JTypeMirror> {
private final TypeSystem ts;
private final PolyResolution polyResolution;
private final JClassType stringType;
private final JavaAstProcessor processor;
private final SemanticErrorReporter err;
private final Infer infer;
public LazyTypeResolver(JavaAstProcessor processor,
TypeInferenceLogger logger) {
this.ts = processor.getTypeSystem();
this.infer = new Infer(ts, processor.getJdkVersion(), logger);
this.polyResolution = new PolyResolution(infer);
this.stringType = (JClassType) TypesFromReflection.fromReflect(String.class, ts);
this.processor = processor;
this.err = processor.getLogger();
}
public ExprContext getConversionContextForExternalUse(ASTExpression e) {
return polyResolution.getConversionContextForExternalUse(e);
}
public ExprContext getTopLevelContextIncludingInvocation(TypeNode e) {
ExprContext toplevel = polyResolution.getTopLevelConversionContext(e);
while (toplevel.hasKind(ExprContextKind.INVOCATION)) {
ExprContext surrounding = polyResolution.getTopLevelConversionContext(toplevel.getInvocNodeIfInvocContext());
if (!surrounding.isMissing()) {
toplevel = surrounding;
} else {
break;
}
}
return toplevel;
}
public Infer getInfer() {
return infer;
}
public JavaAstProcessor getProcessor() {
return processor;
}
public TypeSystem getTypeSystem() {
return ts;
}
@Override
public JTypeMirror visitJavaNode(JavaNode node, TypingContext ctx) {
throw new IllegalArgumentException("Not a type node:" + node);
}
@Override
public JTypeMirror visit(ASTFormalParameter node, TypingContext ctx) {
return node.getVarId().getTypeMirror(ctx);
}
@Override
public JTypeMirror visit(ASTTypeParameter node, TypingContext ctx) {
return node.getSymbol().getTypeMirror();
}
@Override
public JTypeMirror visitTypeDecl(ASTAnyTypeDeclaration node, TypingContext ctx) {
return ts.declaration(node.getSymbol());
}
@Override
public JTypeMirror visit(ASTAnnotation node, TypingContext ctx) {
return node.getTypeNode().getTypeMirror(ctx);
}
@Override
public JTypeMirror visitType(ASTType node, TypingContext ctx) {
return InternalApiBridge.buildTypeFromAstInternal(ts, Substitution.EMPTY, node);
}
@Override
public JTypeMirror visit(ASTVoidType node, TypingContext ctx) {
return ts.NO_TYPE;
}
@Override
public JTypeMirror visit(ASTVariableDeclaratorId node, TypingContext ctx) {
boolean isTypeInferred = node.isTypeInferred();
if (isTypeInferred && node.getInitializer() != null) {
// var k = foo()
ASTExpression initializer = node.getInitializer();
return initializer == null ? ts.ERROR : TypeOps.projectUpwards(initializer.getTypeMirror(ctx));
} else if (isTypeInferred && node.isForeachVariable()) {
// for (var k : map.keySet())
ASTForeachStatement foreachStmt = node.ancestors(ASTForeachStatement.class).firstOrThrow();
JTypeMirror iterableType = foreachStmt.getIterableExpr().getTypeMirror(ctx);
iterableType = capture(iterableType);
if (iterableType instanceof JArrayType) {
return ((JArrayType) iterableType).getComponentType(); // component type is necessarily a type
} else {
JTypeMirror asSuper = iterableType.getAsSuper(ts.getClassSymbol(Iterable.class));
if (asSuper instanceof JClassType) {
if (asSuper.isRaw()) {
return ts.OBJECT;
}
JTypeMirror componentType = ((JClassType) asSuper).getTypeArgs().get(0);
return TypeOps.projectUpwards(componentType);
} else {
return ts.ERROR;
}
}
} else if (isTypeInferred && node.isLambdaParameter()) {
ASTLambdaParameter param = (ASTLambdaParameter) node.getParent();
ASTLambdaExpression lambda = (ASTLambdaExpression) node.getNthParent(3);
JTypeMirror contextualResult = ctx.apply(node.getSymbol());
if (contextualResult != null) {
return contextualResult;
}
// force resolution of the enclosing lambda
JMethodSig mirror = lambda.getFunctionalMethod();
if (isUnresolved(mirror)) {
return ts.UNKNOWN;
}
return mirror.getFormalParameters().get(param.getIndexInParent());
} else if (node.isEnumConstant()) {
TypeNode enumClass = node.getEnclosingType();
return enumClass.getTypeMirror(ctx);
}
ASTType typeNode = node.getTypeNode();
if (typeNode == null) {
return ts.ERROR;
}
// Type common to all declarations in the same statement
JTypeMirror baseType = typeNode.getTypeMirror(ctx);
ASTArrayDimensions extras = node.getExtraDimensions();
return extras != null
? ts.arrayType(baseType, extras.size())
: baseType;
}
/*
EXPRESSIONS
*/
@Override
public JTypeMirror visit(ASTAssignmentExpression node, TypingContext ctx) {
// The type of the assignment expression is the type of the variable after capture conversion
return TypeConversion.capture(node.getLeftOperand().getTypeMirror(ctx));
}
/**
* Poly expressions need context and are resolved by {@link PolyResolution}.
*
* <p>Note that some poly expression are only poly part of the time.
* In particular, method calls with explicit type arguments, and non-diamond
* constructor calls, are standalone. To reduce the number of branches in the
* code they still go through Infer, so that their method type is set like all
* the others.
*/
private JTypeMirror handlePoly(TypeNode node) {
return polyResolution.computePolyType(node);
}
@Override
public JTypeMirror visit(ASTMethodCall node, TypingContext ctx) {
return handlePoly(node);
}
@Override
public JTypeMirror visit(ASTConditionalExpression node, TypingContext ctx) {
return handlePoly(node);
}
@Override
public JTypeMirror visit(ASTLambdaExpression node, TypingContext ctx) {
return handlePoly(node);
}
@Override
public JTypeMirror visit(ASTSwitchExpression node, TypingContext ctx) {
return handlePoly(node);
}
@Override
public JTypeMirror visit(ASTMethodReference node, TypingContext ctx) {
return handlePoly(node);
}
@Override
public JTypeMirror visit(ASTConstructorCall node, TypingContext ctx) {
return handlePoly(node);
}
@Override
public JTypeMirror visit(ASTExplicitConstructorInvocation node, TypingContext ctx) {
return handlePoly(node);
}
@Override
public JTypeMirror visit(ASTEnumConstant node, TypingContext ctx) {
return handlePoly(node);
}
@Override
public JTypeMirror visit(ASTInfixExpression node, TypingContext ctx) {
BinaryOp op = node.getOperator();
switch (op) {
case CONDITIONAL_OR:
case CONDITIONAL_AND:
case EQ:
case NE:
case LE:
case GE:
case GT:
case INSTANCEOF:
case LT:
// HMM so we don't even check?
return ts.BOOLEAN;
case OR:
case XOR:
case AND: {
// those may be boolean or bitwise
final JTypeMirror lhs = node.getLeftOperand().getTypeMirror(ctx);
final JTypeMirror rhs = node.getRightOperand().getTypeMirror(ctx);
if (lhs.isNumeric() && rhs.isNumeric()) {
// NUMERIC(N) & NUMERIC(M) -> promote(N, M)
return binaryNumericPromotion(lhs, rhs);
} else if (lhs.equals(rhs)) {
// BOOL & BOOL -> BOOL
// UNRESOLVED & UNRESOLVED -> UNKNOWN
return lhs;
} else if (isUnresolved(lhs) ^ isUnresolved(rhs)) {
// UNRESOLVED & NUMERIC(N) -> promote(N)
// NUMERIC(N) & UNRESOLVED -> promote(N)
// BOOL & UNRESOLVED -> BOOL
// UNRESOLVED & BOOL -> BOOL
// UNRESOLVED & anything -> ERROR
JTypeMirror resolved = isUnresolved(lhs) ? rhs : lhs;
return resolved.isNumeric() ? unaryNumericPromotion(resolved)
: resolved == ts.BOOLEAN ? resolved // NOPMD #3205
: ts.ERROR;
} else {
// anything else, including error types & such: ERROR
return ts.ERROR;
}
}
case LEFT_SHIFT:
case RIGHT_SHIFT:
case UNSIGNED_RIGHT_SHIFT:
return unaryNumericPromotion(node.getLeftOperand().getTypeMirror(ctx));
case ADD:
case SUB:
case MUL:
case DIV:
case MOD:
final JTypeMirror lhs = node.getLeftOperand().getTypeMirror(ctx);
final JTypeMirror rhs = node.getRightOperand().getTypeMirror(ctx);
if (op == ADD && (lhs.equals(stringType) || rhs.equals(stringType))) {
// string concatenation
return stringType;
} else if (isUnresolved(lhs)) {
return rhs;
} else if (isUnresolved(rhs)) {
return lhs;
} else {
return binaryNumericPromotion(lhs, rhs);
}
default:
throw new AssertionError("Unknown operator for " + node);
}
}
private boolean isUnresolved(JTypeMirror t) {
return t == ts.UNKNOWN; // NOPMD CompareObjectsWithEquals
}
private boolean isUnresolved(JMethodSig m) {
return m == null || m == ts.UNRESOLVED_METHOD; // NOPMD CompareObjectsWithEquals
}
@Override
public JTypeMirror visit(ASTUnaryExpression node, TypingContext ctx) {
switch (node.getOperator()) {
case UNARY_PLUS:
case UNARY_MINUS:
case COMPLEMENT:
return unaryNumericPromotion(node.getOperand().getTypeMirror(ctx));
case NEGATION:
return ts.BOOLEAN;
case PRE_INCREMENT:
case PRE_DECREMENT:
case POST_INCREMENT:
case POST_DECREMENT:
return node.getOperand().getTypeMirror(ctx);
default:
throw new AssertionError("Unknown operator for " + node);
}
}
@Override
public JTypeMirror visit(ASTPatternExpression node, TypingContext ctx) {
ASTPattern pattern = node.getPattern();
if (pattern instanceof ASTTypePattern) {
return ((ASTTypePattern) pattern).getTypeNode().getTypeMirror(ctx);
}
throw new IllegalArgumentException("Unknown pattern " + pattern);
}
@Override
public JTypeMirror visit(ASTCastExpression node, TypingContext ctx) {
return node.getCastType().getTypeMirror(ctx);
}
@Override
public JTypeMirror visit(ASTNullLiteral node, TypingContext ctx) {
return ts.NULL_TYPE;
}
@Override
public JTypeMirror visit(ASTCharLiteral node, TypingContext ctx) {
return ts.CHAR;
}
@Override
public JTypeMirror visit(ASTStringLiteral node, TypingContext ctx) {
return stringType;
}
@Override
public JTypeMirror visit(ASTNumericLiteral node, TypingContext ctx) {
if (node.isIntegral()) {
return node.isLongLiteral() ? ts.LONG : ts.INT;
} else {
return node.isFloatLiteral() ? ts.FLOAT : ts.DOUBLE;
}
}
@Override
public JTypeMirror visit(ASTBooleanLiteral node, TypingContext ctx) {
return ts.BOOLEAN;
}
@Override
public JTypeMirror visit(ASTClassLiteral node, TypingContext ctx) {
JClassSymbol klassSym = ts.getClassSymbol(Class.class);
assert klassSym != null : Class.class + " is missing from the classpath?";
if (node.getTypeNode() instanceof ASTVoidType) {
// void.class : Class<Void>
return ts.parameterise(klassSym, listOf(ts.BOXED_VOID));
} else {
return ts.parameterise(klassSym, listOf(node.getTypeNode().getTypeMirror(ctx).box()));
}
}
@Override
public JTypeMirror visit(ASTArrayAllocation node, TypingContext ctx) {
return node.getTypeNode().getTypeMirror(ctx);
}
@Override
public JTypeMirror visit(ASTArrayInitializer node, TypingContext ctx) {
JavaNode parent = node.getParent();
if (parent instanceof ASTArrayAllocation) {
return ((ASTArrayAllocation) parent).getTypeMirror(ctx);
} else if (parent instanceof ASTVariableDeclarator) {
ASTVariableDeclaratorId id = ((ASTVariableDeclarator) parent).getVarId();
return id.isTypeInferred() ? ts.ERROR : id.getTypeMirror(ctx);
} else if (parent instanceof ASTArrayInitializer) {
JTypeMirror tm = ((ASTArrayInitializer) parent).getTypeMirror(ctx);
return tm instanceof JArrayType ? ((JArrayType) tm).getComponentType()
: ts.ERROR;
}
return ts.ERROR;
}
@Override
public JTypeMirror visit(ASTVariableAccess node, TypingContext ctx) {
if (node.getParent() instanceof ASTSwitchLabel) {
// may be an enum constant, in which case symbol table doesn't help (this is documented on JSymbolTable#variables())
ASTSwitchLike switchParent = node.ancestors(ASTSwitchLike.class).firstOrThrow();
JTypeMirror testedType = switchParent.getTestedExpression().getTypeMirror(ctx);
JTypeDeclSymbol testedSym = testedType.getSymbol();
if (testedSym instanceof JClassSymbol && ((JClassSymbol) testedSym).isEnum()) {
JFieldSymbol enumConstant = ((JClassSymbol) testedSym).getDeclaredField(node.getName());
if (enumConstant != null) {
// field exists and can be resolved
InternalApiBridge.setTypedSym(node, ts.sigOf(testedType, enumConstant));
}
return testedType;
} // fallthrough
}
@Nullable JVariableSig result = node.getSymbolTable().variables().resolveFirst(node.getName());
if (result == null) {
// An out-of-scope field. Use context to resolve it.
return polyResolution.getContextTypeForStandaloneFallback(node);
}
InternalApiBridge.setTypedSym(node, result);
JTypeMirror resultMirror = null;
if (result.getSymbol() instanceof JLocalVariableSymbol) {
ASTVariableDeclaratorId id = result.getSymbol().tryGetNode();
// id may be null if this is a fake formal param sym, for record components
if (id != null && id.isLambdaParameter()) {
// then the type of the parameter depends on the type
// of the lambda, which most likely depends on the overload
// resolution of an enclosing invocation context
resultMirror = id.getTypeMirror();
}
}
if (resultMirror == null) {
resultMirror = result.getTypeMirror();
}
// https://docs.oracle.com/javase/specs/jls/se14/html/jls-6.html#jls-6.5.6
// Only capture if the name is on the RHS
return node.getAccessType() == AccessType.READ ? TypeConversion.capture(resultMirror)
: resultMirror;
}
@Override
public @NonNull JTypeMirror visit(ASTLambdaParameter node, TypingContext ctx) {
if (node.getTypeNode() != null) {
// explicitly typed
return node.getTypeNode().getTypeMirror(ctx);
}
ASTLambdaExpression lambda = node.ancestors(ASTLambdaExpression.class).firstOrThrow();
lambda.getTypeMirror(ctx);
JMethodSig m = lambda.getFunctionalMethod(); // this forces resolution of the lambda
if (!isUnresolved(m)) {
if (m.getArity() != node.getOwner().getArity()) {
err.warning(node.getOwner(), "Lambda shape does not conform to the functional method {0}", m);
return ts.ERROR;
}
return m.getFormalParameters().get(node.getIndexInParent());
}
return ts.UNKNOWN;
}
@Override
public JTypeMirror visit(ASTFieldAccess node, TypingContext ctx) {
JTypeMirror qualifierT = capture(node.getQualifier().getTypeMirror(ctx));
if (isUnresolved(qualifierT)) {
return polyResolution.getContextTypeForStandaloneFallback(node);
}
@Nullable ASTAnyTypeDeclaration enclosingType = node.getEnclosingType();
@Nullable JClassSymbol enclosingSymbol =
enclosingType == null ? null : enclosingType.getSymbol();
NameResolver<FieldSig> fieldResolver =
TypeOps.getMemberFieldResolver(qualifierT, node.getRoot().getPackageName(), enclosingSymbol, node.getName());
FieldSig sig = fieldResolver.resolveFirst(node.getName()); // could be an ambiguity error
InternalApiBridge.setTypedSym(node, sig);
if (sig == null) {
return polyResolution.getContextTypeForStandaloneFallback(node);
}
// https://docs.oracle.com/javase/specs/jls/se14/html/jls-6.html#jls-6.5.6
// Only capture if the name is on the RHS
return node.getAccessType() == AccessType.READ ? TypeConversion.capture(sig.getTypeMirror())
: sig.getTypeMirror();
}
@Override
public JTypeMirror visit(ASTArrayAccess node, TypingContext ctx) {
JTypeMirror compType;
JTypeMirror arrType = node.getQualifier().getTypeMirror(ctx);
if (arrType instanceof JArrayType) {
compType = ((JArrayType) arrType).getComponentType();
} else if (isUnresolved(arrType)) {
compType = polyResolution.getContextTypeForStandaloneFallback(node);
} else {
compType = ts.ERROR;
}
return capture(compType);
}
@Override
public JTypeMirror visit(ASTSuperExpression node, TypingContext ctx) {
if (node.getQualifier() != null) {
return node.getQualifier().getTypeMirror(ctx);
} else {
return ((JClassType) node.getEnclosingType().getTypeMirror(ctx)).getSuperClass();
}
}
@Override
public JTypeMirror visit(ASTThisExpression node, TypingContext ctx) {
return node.getQualifier() != null
? node.getQualifier().getTypeMirror(ctx)
: node.getEnclosingType().getTypeMirror(ctx);
}
@Override
public JTypeMirror visit(ASTAmbiguousName node, TypingContext ctx) {
return ts.UNKNOWN;
}
}
| 24,568 | 38.755663 | 128 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/ast/PolyResolution.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.ast;
import static java.util.Arrays.asList;
import static net.sourceforge.pmd.lang.java.types.TypeConversion.isConvertibleUsingBoxing;
import static net.sourceforge.pmd.util.AssertionUtil.shouldNotReachHere;
import static net.sourceforge.pmd.util.CollectionUtil.all;
import static net.sourceforge.pmd.util.CollectionUtil.map;
import java.util.List;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTArgumentList;
import net.sourceforge.pmd.lang.java.ast.ASTArrayAccess;
import net.sourceforge.pmd.lang.java.ast.ASTArrayInitializer;
import net.sourceforge.pmd.lang.java.ast.ASTAssertStatement;
import net.sourceforge.pmd.lang.java.ast.ASTAssignmentExpression;
import net.sourceforge.pmd.lang.java.ast.ASTCastExpression;
import net.sourceforge.pmd.lang.java.ast.ASTConditionalExpression;
import net.sourceforge.pmd.lang.java.ast.ASTEnumConstant;
import net.sourceforge.pmd.lang.java.ast.ASTExplicitConstructorInvocation;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTForeachStatement;
import net.sourceforge.pmd.lang.java.ast.ASTIfStatement;
import net.sourceforge.pmd.lang.java.ast.ASTInfixExpression;
import net.sourceforge.pmd.lang.java.ast.ASTLambdaExpression;
import net.sourceforge.pmd.lang.java.ast.ASTLoopStatement;
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTMethodReference;
import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchArrowBranch;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchExpression;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchLabel;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchLike;
import net.sourceforge.pmd.lang.java.ast.ASTType;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator;
import net.sourceforge.pmd.lang.java.ast.ASTVoidType;
import net.sourceforge.pmd.lang.java.ast.ASTYieldStatement;
import net.sourceforge.pmd.lang.java.ast.BinaryOp;
import net.sourceforge.pmd.lang.java.ast.InternalApiBridge;
import net.sourceforge.pmd.lang.java.ast.InvocationNode;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.ast.TypeNode;
import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.JMethodSig;
import net.sourceforge.pmd.lang.java.types.JPrimitiveType;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.OverloadSelectionResult;
import net.sourceforge.pmd.lang.java.types.TypeConversion;
import net.sourceforge.pmd.lang.java.types.TypeOps;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
import net.sourceforge.pmd.lang.java.types.TypeTestUtil;
import net.sourceforge.pmd.lang.java.types.TypesFromReflection;
import net.sourceforge.pmd.lang.java.types.ast.ExprContext.ExprContextKind;
import net.sourceforge.pmd.lang.java.types.ast.ExprContext.RegularCtx;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.BranchingMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.FunctionalExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.InvocationMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.Infer;
import net.sourceforge.pmd.lang.java.types.internal.infer.MethodCallSite;
import net.sourceforge.pmd.lang.java.types.internal.infer.PolySite;
import net.sourceforge.pmd.lang.java.types.internal.infer.ast.JavaExprMirrors;
import net.sourceforge.pmd.util.AssertionUtil;
/**
* Routines to handle context around poly expressions.
*/
final class PolyResolution {
private final Infer infer;
private final TypeSystem ts;
private final JavaExprMirrors exprMirrors;
private final ExprContext booleanCtx;
private final ExprContext stringCtx;
private final ExprContext intCtx;
PolyResolution(Infer infer) {
this.infer = infer;
this.ts = infer.getTypeSystem();
this.exprMirrors = JavaExprMirrors.forTypeResolution(infer);
this.stringCtx = newStringCtx(ts);
this.booleanCtx = newNonPolyContext(ts.BOOLEAN);
this.intCtx = newNumericContext(ts.INT);
}
private boolean isPreJava8() {
return infer.isPreJava8();
}
JTypeMirror computePolyType(final TypeNode e) {
if (!canBePoly(e)) {
throw shouldNotReachHere("Unknown poly " + e);
}
ExprContext ctx = getTopLevelConversionContext(e);
InvocationNode outerInvocNode = ctx.getInvocNodeIfInvocContext();
if (outerInvocNode != null) {
return polyTypeInvocationCtx(e, outerInvocNode);
}
return polyTypeOtherCtx(e, ctx);
}
private JTypeMirror polyTypeOtherCtx(TypeNode e, ExprContext ctx) {
// we have a context, that is not an invocation
if (e instanceof InvocationNode) {
// The original expr was an invocation, but we have
// a context type (eg assignment context)
JTypeMirror targetType = ctx.getPolyTargetType(false);
return inferInvocation((InvocationNode) e, e, targetType);
} else if (e instanceof ASTSwitchExpression || e instanceof ASTConditionalExpression) {
// Those are standalone if possible, otherwise they take
// the target type
// in java 7 they are always standalone
if (isPreJava8()) {
// safe cast because ASTSwitchExpression doesn't exist pre java 13
ASTConditionalExpression conditional = (ASTConditionalExpression) e;
return computeStandaloneConditionalType(
this.ts,
conditional.getThenBranch().getTypeMirror(),
conditional.getElseBranch().getTypeMirror()
);
}
// Note that this creates expr mirrors for all subexpressions,
// and may trigger inference on them (which does not go through PolyResolution).
// Because this process may fail if the conditional is not standalone,
// the ctors for expr mirrors must have only trivial side-effects.
// See comment in MethodRefMirrorImpl
JTypeMirror target = ctx.getPolyTargetType(false);
if (target != null) {
// then it is a poly expression
// only reference conditional expressions take the target type,
// but the spec special-cases some forms of conditionals ("numeric" and "boolean")
// The mirror recognizes these special cases
BranchingMirror polyMirror = exprMirrors.getPolyBranchingMirror((ASTExpression) e);
JTypeMirror standaloneType = polyMirror.getStandaloneType();
if (standaloneType != null) { // then it is one of those special cases
polyMirror.setStandalone(); // record this fact
return standaloneType;
}
// otherwise it's the target type
return target;
} else {
// then it is standalone
BranchingMirror branchingMirror = exprMirrors.getStandaloneBranchingMirror((ASTExpression) e);
branchingMirror.setStandalone(); // record this fact
JTypeMirror standalone = branchingMirror.getStandaloneType();
if (standalone != null) {
return standalone;
} else if (!ctx.canGiveContextToPoly(false)) {
// null standalone, force resolution anyway, because there is no context
// this is more general than ExprMirror#getStandaloneType, it's not a bug
if (e instanceof ASTSwitchExpression) {
// todo merge this fallback into SwitchMirror
// That would be less easily testable that what's below...
List<JTypeMirror> branches = ((ASTSwitchExpression) e).getYieldExpressions().toList(TypeNode::getTypeMirror);
return computeStandaloneConditionalType(ts, branches);
} else {
throw AssertionUtil.shouldNotReachHere("ConditionalMirrorImpl returns non-null for conditionals");
}
}
return ts.ERROR;
}
} else if (e instanceof ASTMethodReference || e instanceof ASTLambdaExpression) {
// these may use a cast as a target type
JTypeMirror targetType = ctx.getPolyTargetType(true);
return inferLambdaOrMref((ASTExpression) e, targetType);
} else {
throw shouldNotReachHere("Unknown poly " + e);
}
}
// only outside of invocation context
private JTypeMirror inferLambdaOrMref(ASTExpression e, @Nullable JTypeMirror targetType) {
FunctionalExprMirror mirror = exprMirrors.getTopLevelFunctionalMirror(e);
PolySite<FunctionalExprMirror> site = infer.newFunctionalSite(mirror, targetType);
infer.inferFunctionalExprInUnambiguousContext(site);
JTypeMirror result = InternalApiBridge.getTypeMirrorInternal(e);
assert result != null : "Should be unknown";
return result;
}
private @NonNull JTypeMirror polyTypeInvocationCtx(TypeNode e, InvocationNode ctxInvoc) {
// an outer invocation ctx
if (ctxInvoc instanceof ASTExpression) {
// method call or regular constructor call
// recurse, that will fetch the outer context
ctxInvoc.getTypeMirror();
return fetchCascaded(e);
} else {
return inferInvocation(ctxInvoc, e, null);
}
}
/**
* Given an invocation context (ctxNode), infer its most specific
* method, which will set the type of the 'enclosed' poly expression.
* The 'targetType' can influence the invocation type of the method
* (not applicability).
*
* <p>Eg:
*
* <pre>{@code
*
* <T> T coerce(int i) {
* return null;
* }
*
* <K> Stream<K> streamK() {
* return Stream.of(1, 2).map(this::coerce);
* }
*
* }</pre>
*
* <p>There is only one applicable method for this::coerce so the
* method reference is exact. However the type argument {@code <T>}
* of coerce has no bound. The target type {@code Stream<K>} is
* incorporated and we infer that coerce's type argument is {@code <K>}.
*
* <p>This is also why the following fails type inference:
*
* <pre>{@code
*
* <K> List<K> streamK2() {
* // type checks when written this::<K>coerce
* return Stream.of(1, 2).map(this::coerce).collect(Collectors.toList());
* }
*
* }</pre>
*/
private JTypeMirror inferInvocation(InvocationNode ctxNode, TypeNode actualResultTarget, @Nullable JTypeMirror targetType) {
InvocationMirror mirror = exprMirrors.getTopLevelInvocationMirror(ctxNode);
MethodCallSite site = infer.newCallSite(mirror, targetType);
infer.inferInvocationRecursively(site);
// errors are on the call site if any
return fetchCascaded(actualResultTarget);
}
/**
* Fetch the resolved value when it was inferred as part of overload
* resolution of an enclosing invocation context.
*/
private @NonNull JTypeMirror fetchCascaded(TypeNode e) {
// Some types are set as part of overload resolution
// Conditional expressions also have their type set if they're
// standalone
JTypeMirror type = InternalApiBridge.getTypeMirrorInternal(e);
if (type != null) {
return type;
}
if (e.getParent().getParent() instanceof InvocationNode) {
// invocation ctx
InvocationNode parentInvoc = (InvocationNode) e.getParent().getParent();
OverloadSelectionResult info = parentInvoc.getOverloadSelectionInfo();
if (!info.isFailed()) {
JTypeMirror targetT = info.ithFormalParam(e.getIndexInParent());
if (e instanceof ASTLambdaExpression || e instanceof ASTMethodReference) {
// their types are not completely set
return inferLambdaOrMref((ASTExpression) e, targetT);
}
return targetT;
}
}
// if we're here, we failed
return fallbackIfCtxDidntSet(e);
}
/**
* If resolution of the outer context failed, like if we call an unknown
* method, we may still be able to derive the types of the arguments. We
* treat them as if they occur as standalone expressions.
* TODO would using error-type as a target type be better? could coerce
* generic method params to error naturally
*/
private @NonNull JTypeMirror fallbackIfCtxDidntSet(@Nullable TypeNode e) {
// retry with no context
return polyTypeOtherCtx(e, ExprContext.getMissingInstance());
// infer.LOG.polyResolutionFailure(e);
}
/**
* If true, the expression may depends on its target type. There may not
* be a target type though - this is given by the {@link #contextOf(JavaNode, boolean, boolean)}.
*
* <p>If false, then the expression is standalone and its type is
* only determined by the type of its subexpressions.
*/
private static boolean canBePoly(TypeNode e) {
return e instanceof ASTLambdaExpression
|| e instanceof ASTMethodReference
|| e instanceof ASTConditionalExpression
|| e instanceof ASTSwitchExpression
|| e instanceof InvocationNode;
}
/**
* Fallback for some standalone expressions, that may use some context
* to set their type. This must not trigger any type inference process
* that may need this expression. So if this expression is in an invocation
* context, that context must not be called.
*/
JTypeMirror getContextTypeForStandaloneFallback(ASTExpression e) {
// Some symbol is not resolved
// go backwards from the context to get it.
// The case mentioned by the doc is removed. We could be smarter
// with how we retry failed invocation resolution, see history
// of this comment
@NonNull ExprContext ctx = getTopLevelConversionContext(e);
if (e.getParent() instanceof ASTSwitchLabel) {
ASTSwitchLike switchLike = e.ancestors(ASTSwitchLike.class).firstOrThrow();
// this may trigger some inference, which doesn't matter
// as it is out of context
return switchLike.getTestedExpression().getTypeMirror();
}
if (ctx instanceof RegularCtx) {
JTypeMirror targetType = ctx.getPolyTargetType(false);
if (targetType != null) {
return targetType;
}
}
return ts.UNKNOWN;
}
/**
* Not meant to be used by the main typeres paths, only for rules.
*/
ExprContext getConversionContextForExternalUse(ASTExpression e) {
return contextOf(e, false, false);
}
ExprContext getTopLevelConversionContext(TypeNode e) {
return contextOf(e, false, true);
}
private static @Nullable JTypeMirror returnTargetType(ASTReturnStatement context) {
Node methodDecl =
context.ancestors().first(
it -> it instanceof ASTMethodDeclaration
|| it instanceof ASTLambdaExpression
|| it instanceof ASTAnyTypeDeclaration
);
if (methodDecl == null || methodDecl instanceof ASTAnyTypeDeclaration) {
// in initializer, or constructor decl, return with expression is forbidden
// (this is an error)
return null;
} else if (methodDecl instanceof ASTLambdaExpression) {
// return within a lambda
// "assignment context", deferred to lambda inference
JMethodSig fun = ((ASTLambdaExpression) methodDecl).getFunctionalMethod();
return fun == null ? null : fun.getReturnType();
} else {
@NonNull ASTType resultType = ((ASTMethodDeclaration) methodDecl).getResultTypeNode();
return resultType instanceof ASTVoidType ? null // (this is an error)
: resultType.getTypeMirror();
}
}
/**
* Returns the node on which the type of the given node depends.
* This addresses the fact that poly expressions depend on their
* surrounding context for a target type. So when someone asks
* for the type of a poly, we have to determine the type of the
* context before we can determine the type of the poly.
*
* <p>The returned context may never be a conditional or switch,
* those just forward an outer context to their branches.
*
* <p>If there is no context node, returns null.
*
* Examples:
* <pre>
*
* new Bar<>(foo()) // contextOf(methodCall) = constructorCall
*
* this(foo()) // contextOf(methodCall) = explicitConstructorInvoc
*
* a = foo() // contextOf(methodCall) = assignmentExpression
* a = (Cast) foo() // contextOf(methodCall) = castExpression
* return foo(); // contextOf(methodCall) = returnStatement
*
* foo(a ? () -> b // the context of each lambda, and of the conditional, is the methodCall
* : () -> c)
*
* foo(); // expression statement, no target type
*
* 1 + (a ? foo() : 2) // contextOf(methodCall) = null
* // foo() here has no target type, because the enclosing conditional has none
*
*
* </pre>
*/
private @NonNull ExprContext contextOf(final JavaNode node, boolean onlyInvoc, boolean internalUse) {
final JavaNode papa = node.getParent();
if (papa instanceof ASTArgumentList) {
// invocation context, return *the first method*
// eg in
// lhs = foo(bar(bog())),
// contextOf(bog) = bar, contextOf(bar) = foo, contextOf(foo) = lhs
// when asked the type of 'foo', we return 'bar'
// we recurse indirectly and ask 'bar' for its type
// it asks 'foo', which binds to 'lhs', and infers all types
// we can't just recurse directly up, because then contextOf(bog) = lhs,
// and that's not true (bog() is in an invocation context)
final InvocationNode papi = (InvocationNode) papa.getParent();
if (papi instanceof ASTExplicitConstructorInvocation || papi instanceof ASTEnumConstant) {
return ExprContext.newInvocContext(papi, node.getIndexInParent());
} else {
if (isPreJava8()) {
// in java < 8 invocation contexts don't provide a target type
return ExprContext.getMissingInstance();
}
// Constructor or method call, maybe there's another context around
// We want to fetch the outermost invocation node, but not further
ExprContext outerCtx = contextOf(papi, /*onlyInvoc:*/true, internalUse);
return outerCtx.canGiveContextToPoly(false)
? outerCtx
// otherwise we're done, this is the outermost context
: ExprContext.newInvocContext(papi, node.getIndexInParent());
}
} else if (doesCascadesContext(papa, node, internalUse)) {
// switch/conditional
return contextOf(papa, onlyInvoc, internalUse);
}
if (onlyInvoc) {
return ExprContext.getMissingInstance();
}
if (papa instanceof ASTArrayInitializer) {
JTypeMirror target = TypeOps.getArrayComponent(((ASTArrayInitializer) papa).getTypeMirror());
return newAssignmentCtx(target);
} else if (papa instanceof ASTCastExpression) {
JTypeMirror target = ((ASTCastExpression) papa).getCastType().getTypeMirror();
return newCastCtx(target);
} else if (papa instanceof ASTAssignmentExpression && node.getIndexInParent() == 1) { // second operand
JTypeMirror target = ((ASTAssignmentExpression) papa).getLeftOperand().getTypeMirror();
return newAssignmentCtx(target);
} else if (papa instanceof ASTReturnStatement) {
return newAssignmentCtx(returnTargetType((ASTReturnStatement) papa));
} else if (papa instanceof ASTVariableDeclarator
&& !((ASTVariableDeclarator) papa).getVarId().isTypeInferred()) {
return newAssignmentCtx(((ASTVariableDeclarator) papa).getVarId().getTypeMirror());
} else if (papa instanceof ASTYieldStatement) {
// break with value (switch expr)
ASTSwitchExpression owner = ((ASTYieldStatement) papa).getYieldTarget();
return contextOf(owner, false, internalUse);
} else if (node instanceof ASTExplicitConstructorInvocation
&& ((ASTExplicitConstructorInvocation) node).isSuper()) {
// the superclass type is taken as a target type for inference,
// when the super ctor is generic/ the superclass is generic
return newSuperCtorCtx(node.getEnclosingType().getTypeMirror().getSuperClass());
}
if (!internalUse) {
// Only ASTExpression#getConversionContext needs this level of detail
// These anyway do not give a context to poly expression so can be ignored
// for poly resolution.
return conversionContextOf(node, papa);
}
// stop recursion
return ExprContext.getMissingInstance();
}
// more detailed
private ExprContext conversionContextOf(JavaNode node, JavaNode papa) {
if (papa instanceof ASTArrayAccess && node.getIndexInParent() == 1) {
// array index
return intCtx;
} else if (papa instanceof ASTAssertStatement) {
return node.getIndexInParent() == 0 ? booleanCtx // condition
: stringCtx; // message
} else if (papa instanceof ASTIfStatement
|| papa instanceof ASTLoopStatement && !(papa instanceof ASTForeachStatement)) {
return booleanCtx; // condition
} else if (papa instanceof ASTConditionalExpression) {
if (node.getIndexInParent() == 0) {
return booleanCtx; // the condition
} else {
// a branch
if (isPreJava8()) {
return ExprContext.getMissingInstance();
}
assert InternalApiBridge.isStandaloneInternal((ASTConditionalExpression) papa)
: "Expected standalone ternary, otherwise doesCascadeContext(..) would have returned true";
return newStandaloneTernaryCtx(((ASTConditionalExpression) papa).getTypeMirror());
}
} else if (papa instanceof ASTInfixExpression) {
// numeric contexts, maybe
BinaryOp op = ((ASTInfixExpression) papa).getOperator();
JTypeMirror nodeType = ((ASTExpression) node).getTypeMirror();
JTypeMirror otherType = JavaAstUtils.getOtherOperandIfInInfixExpr(node).getTypeMirror();
JTypeMirror ctxType = ((ASTInfixExpression) papa).getTypeMirror();
switch (op) {
case CONDITIONAL_OR:
case CONDITIONAL_AND:
return booleanCtx;
case OR:
case XOR:
case AND:
return ctxType == ts.BOOLEAN ? booleanCtx : newNumericContext(ctxType); // NOPMD CompareObjectsWithEquals
case LEFT_SHIFT:
case RIGHT_SHIFT:
case UNSIGNED_RIGHT_SHIFT:
return node.getIndexInParent() == 1 ? intCtx
: newNumericContext(nodeType.unbox());
case EQ:
case NE:
if (otherType.isPrimitive() != nodeType.isPrimitive()) {
return newNonPolyContext(otherType.unbox());
}
return ExprContext.getMissingInstance();
case ADD:
if (TypeTestUtil.isA(String.class, ctxType)) {
// string concat expr
return stringCtx;
}
// fallthrough
case SUB:
case MUL:
case DIV:
case MOD:
return newNumericContext(ctxType); // binary promoted by LazyTypeResolver
case LE:
case GE:
case GT:
case LT:
return newNumericContext(TypeConversion.binaryNumericPromotion(nodeType, otherType));
default:
return ExprContext.getMissingInstance();
}
} else {
return ExprContext.getMissingInstance();
}
}
/**
* Identifies a node that can forward an invocation/assignment context
* inward. If their parent has no context, then they don't either.
*/
private boolean doesCascadesContext(JavaNode node, JavaNode child, boolean internalUse) {
if (child.getParent() != node) {
// means the "node" is a "stop recursion because no context" result in contextOf
return false;
} else if (isPreJava8()) {
// in java < 8, context doesn't flow through ternaries
return false;
} else if (!internalUse
&& node instanceof ASTConditionalExpression
&& child.getIndexInParent() != 0) {
// conditional branch
((ASTConditionalExpression) node).getTypeMirror(); // force resolution
return !InternalApiBridge.isStandaloneInternal((ASTConditionalExpression) node);
}
return node instanceof ASTSwitchExpression && child.getIndexInParent() != 0 // not the condition
|| node instanceof ASTSwitchArrowBranch
|| node instanceof ASTConditionalExpression && child.getIndexInParent() != 0 // not the condition
// lambdas "forward the context" when you have nested lambdas, eg: `x -> y -> f(x, y)`
|| node instanceof ASTLambdaExpression && child.getIndexInParent() == 1; // the body expression
}
// test only
static JTypeMirror computeStandaloneConditionalType(TypeSystem ts, JTypeMirror t2, JTypeMirror t3) {
return computeStandaloneConditionalType(ts, asList(t2, t3));
}
/**
* Compute the type of a conditional or switch expression. This is
* how Javac does it for now, and it's exactly an extension of the
* rules for ternary operators to an arbitrary number of branches.
*
* todo can we merge this into the logic of the BranchingMirror implementations?
*/
private static JTypeMirror computeStandaloneConditionalType(TypeSystem ts, List<JTypeMirror> branchTypes) {
// There is a corner case with constant values & ternaries, which we don't handle.
if (branchTypes.isEmpty()) {
return ts.OBJECT;
}
JTypeMirror head = branchTypes.get(0);
List<JTypeMirror> tail = branchTypes.subList(1, branchTypes.size());
if (all(tail, head::equals)) {
return head;
}
List<JTypeMirror> unboxed = map(branchTypes, JTypeMirror::unbox);
if (all(unboxed, JTypeMirror::isPrimitive)) {
for (JPrimitiveType a : ts.allPrimitives) {
if (all(unboxed, it -> it.isConvertibleTo(a).bySubtyping())) {
// then all types are convertible to a
return a;
}
}
}
List<JTypeMirror> boxed = map(branchTypes, JTypeMirror::box);
for (JTypeMirror a : boxed) {
if (all(unboxed, it -> isConvertibleUsingBoxing(it, a))) {
// then all types are convertible to a through boxing
return a;
}
}
// at worse returns Object
return ts.lub(branchTypes);
}
static ExprContext newAssignmentCtx(JTypeMirror targetType) {
if (targetType == null) {
// invalid syntax
return ExprContext.getMissingInstance();
}
return ExprContext.newOtherContext(targetType, ExprContextKind.ASSIGNMENT);
}
static ExprContext newNonPolyContext(JTypeMirror targetType) {
return ExprContext.newOtherContext(targetType, ExprContextKind.BOOLEAN);
}
static ExprContext newStringCtx(TypeSystem ts) {
JClassType stringType = (JClassType) TypesFromReflection.fromReflect(String.class, ts);
return ExprContext.newOtherContext(stringType, ExprContextKind.STRING);
}
static ExprContext newNumericContext(JTypeMirror targetType) {
if (targetType.isPrimitive()) {
assert targetType.isNumeric() : "Not a numeric type - " + targetType;
return ExprContext.newOtherContext(targetType, ExprContextKind.NUMERIC);
}
return ExprContext.getMissingInstance(); // error
}
static ExprContext newCastCtx(JTypeMirror targetType) {
return ExprContext.newOtherContext(targetType, ExprContextKind.CAST);
}
static ExprContext newSuperCtorCtx(JTypeMirror superclassType) {
return ExprContext.newOtherContext(superclassType, ExprContextKind.ASSIGNMENT);
}
static ExprContext newStandaloneTernaryCtx(JTypeMirror ternaryType) {
return ExprContext.newOtherContext(ternaryType, ExprContextKind.TERNARY);
}
}
| 30,327 | 42.202279 | 133 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/InternalMethodTypeItf.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal;
import java.util.List;
import java.util.function.Function;
import org.checkerframework.checker.nullness.qual.Nullable;
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.SubstVar;
/**
* Internal API of {@link JMethodSig}. These methods are internal to
* the inference framework.
*/
public interface InternalMethodTypeItf {
/**
* Returns a new method type with the given return type and all the
* same characteristics as this one.
*/
JMethodSig withReturnType(JTypeMirror returnType);
JMethodSig markAsAdapted();
/**
* Returns a new method type with the given type parameters. Nothing
* is done to the other types presented by this object. If null, resets
* them to the value of the symbol (but this takes care of the enclosing
* type subst in bounds).
*/
JMethodSig withTypeParams(@Nullable List<JTypeVar> tparams);
JMethodSig subst(Function<? super SubstVar, ? extends JTypeMirror> fun);
/**
* @throws IllegalArgumentException If the type of the owner is not appropriate
*/
JMethodSig withOwner(JTypeMirror newOwner);
JMethodSig originalMethod();
JMethodSig adaptedMethod();
}
| 1,483 | 27 | 83 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/IncorporationAction.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import static net.sourceforge.pmd.lang.java.types.TypeOps.isConvertible;
import static net.sourceforge.pmd.lang.java.types.TypeOps.isSameTypeInInference;
import java.util.ArrayList;
import java.util.Set;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.TypeOps.Convertibility;
import net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar.BoundKind;
/**
* An action to execute during the incorporation phase.
* Actions are targeted on a specific ivar (or bound),
* so that the whole set is not reviewed if there are
* no changes.
*/
abstract class IncorporationAction {
final InferenceVar ivar;
final boolean doApplyToInstVar;
IncorporationAction(InferenceVar ivar) {
this(ivar, false);
}
IncorporationAction(InferenceVar ivar, boolean doApplyToInstVar) {
this.ivar = ivar;
this.doApplyToInstVar = doApplyToInstVar;
}
abstract void apply(InferenceContext ctx);
/**
* Check that a bound is compatible with the other current bounds
* of an ivar.
*/
static class CheckBound extends IncorporationAction {
private final BoundKind myKind;
private final JTypeMirror myBound;
CheckBound(InferenceVar ivar, BoundKind kind, JTypeMirror bound) {
super(ivar);
myKind = kind;
this.myBound = bound;
}
/**
* The list of bound kinds to be checked. If the new bound is
* equality, then all other bounds need to be checked. Otherwise,
* if eg the bound is {@code alpha <: T}, then we must check
* that {@code S <: T} holds for all bounds {@code S <: alpha}.
*/
Set<BoundKind> boundsToCheck() {
return myKind.complementSet(true);
}
@Override
public void apply(InferenceContext ctx) {
for (BoundKind k : boundsToCheck()) {
for (JTypeMirror b : ivar.getBounds(k)) {
if (!checkBound(b, k, ctx)) {
throw ResolutionFailedException.incompatibleBound(ctx.logger, ivar, myKind, myBound, k, b);
}
}
}
}
/**
* Check compatibility between this bound and another.
*/
private boolean checkBound(JTypeMirror otherBound, BoundKind otherKind, InferenceContext ctx) {
// myKind != EQ => otherKind != myKind
int compare = myKind.compareTo(otherKind);
// these tests perform side-effects on the mentioned inference vars,
// effectively setting constraints on them
if (compare > 0) {
// myBound <: alpha, alpha <: otherBound
return checkBound(false, myBound, otherBound, ctx);
} else if (compare < 0) {
// otherBound <: alpha, alpha <: myBound
return checkBound(false, otherBound, myBound, ctx);
} else {
return checkBound(true, myBound, otherBound, ctx);
}
}
/**
* If 'eq', checks that {@code T = S}, else checks that {@code T <: S}.
*/
boolean checkBound(boolean eq, JTypeMirror t, JTypeMirror s, InferenceContext ctx) {
// eq bounds are so rare we shouldn't care if they're cached
return eq ? isSameTypeInInference(t, s)
: checkSubtype(t, s, ctx);
}
private boolean checkSubtype(JTypeMirror t, JTypeMirror s, InferenceContext ctx) {
if (ctx.getSupertypeCheckCache().isCertainlyASubtype(t, s)) {
return true; // supertype was already cached
}
Convertibility isConvertible = isConvertible(t, s);
boolean doCache = true;
if (isConvertible.withUncheckedWarning()) {
ctx.setNeedsUncheckedConversion();
// cannot cache those, or the side effect
// will not occur on every context
doCache = false;
}
boolean result = isConvertible.somehow();
if (doCache && result) {
ctx.getSupertypeCheckCache().remember(t, s);
}
return result;
}
@Override
public String toString() {
return "Check " + myKind.format(ivar, myBound);
}
}
/**
* Replace a free vars in bounds with its instantiation, and check
* that the inferred type conforms to all bounds.
*/
static class SubstituteInst extends IncorporationAction {
private final JTypeMirror inst;
SubstituteInst(InferenceVar ivar, JTypeMirror inst) {
super(ivar, true);
this.inst = inst;
}
@Override
public void apply(InferenceContext ctx) {
if (inst != null) {
for (InferenceVar freeVar : ctx.getFreeVars()) {
freeVar.substBounds(it -> ivar.isEquivalentTo(it) ? inst : it);
}
// check instantiation is compatible
new CheckBound(ivar, BoundKind.EQ, inst).apply(ctx);
}
}
@Override
public String toString() {
return "Substitute " + ivar + " with " + inst;
}
}
/** Propagate all bounds of an ivar. */
static class PropagateAllBounds extends IncorporationAction {
PropagateAllBounds(InferenceVar ivar) {
super(ivar);
}
@Override
void apply(InferenceContext ctx) {
for (BoundKind kind : BoundKind.values()) {
for (JTypeMirror bound : new ArrayList<>(ivar.getBounds(kind))) { //copy to avoid comodification
new PropagateBounds(ivar, kind, bound).apply(ctx);
}
}
}
@Override
public String toString() {
return "Propagate all bounds of " + ivar;
}
}
/**
* Propagates the bounds of an ivar to the ivars already appearing
* in its bounds.
*/
static class PropagateBounds extends IncorporationAction {
private final BoundKind kind;
private final JTypeMirror bound;
PropagateBounds(InferenceVar ivar, BoundKind kind, JTypeMirror bound) {
super(ivar);
this.kind = kind;
this.bound = bound;
}
@Override
public void apply(InferenceContext ctx) {
InferenceVar alpha = ivar;
// forward propagation
// alpha <: T
// && alpha >: beta ~> beta <: T | beta <: alpha <: T
// && alpha = beta ~> beta <: T | beta = alpha <: T
// alpha >: T
// && alpha <: beta ~> beta >: T | T <: alpha <: beta
// && alpha = beta ~> beta >: T | T <: alpha = beta
for (JTypeMirror b : alpha.getBounds(kind.complement())) {
if (b instanceof InferenceVar) {
InferenceVar beta = (InferenceVar) b;
beta.addBound(kind, ctx.ground(bound));
}
}
if (bound instanceof InferenceVar) {
InferenceVar beta = (InferenceVar) bound;
if (kind == BoundKind.EQ) {
beta.adoptAllBounds(alpha);
return;
}
// symmetric propagation
// alpha <: beta ~> beta >: alpha
// alpha >: beta ~> beta <: alpha
beta.addBound(kind.complement(), alpha);
// backwards propagation
// alpha <: beta
// && beta = T ~> alpha <: T
// && beta <: T ~> alpha <: T
// alpha >: beta
// && beta = T ~> alpha >: T
// && beta >: T ~> alpha >: T
for (JTypeMirror b : beta.getBounds(kind)) {
alpha.addBound(kind, b);
}
}
}
@Override
public String toString() {
return "Propagate bound " + kind.format(ivar, bound);
}
}
}
| 8,377 | 31.223077 | 115 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/PhaseOverloadSet.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import static net.sourceforge.pmd.lang.java.types.TypeOps.areOverrideEquivalent;
import static net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.TypeSpecies.getSpecies;
import static net.sourceforge.pmd.util.OptionalBool.NO;
import static net.sourceforge.pmd.util.OptionalBool.UNKNOWN;
import static net.sourceforge.pmd.util.OptionalBool.YES;
import static net.sourceforge.pmd.util.OptionalBool.definitely;
import java.util.List;
import org.checkerframework.checker.nullness.qual.NonNull;
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.Substitution;
import net.sourceforge.pmd.lang.java.types.TypeConversion;
import net.sourceforge.pmd.lang.java.types.TypeOps;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.BranchingMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.InvocationMirror.MethodCtDecl;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.LambdaExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.MethodRefMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.TypeSpecies;
import net.sourceforge.pmd.util.OptionalBool;
/**
* An {@link OverloadSet} that is specific to an invocation expression
* and resolution phase. It selects the most specific methods using the
* actual values of arguments, as specified in https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2.5.
*/
final class PhaseOverloadSet extends OverloadSet<MethodCtDecl> {
// TODO by mocking a call site we may be able to remove that logic
// Basically infer m1 against m2 with the same core routines as the
// main Infer.
// m1 is more specific than m2 if m2 can handle more calls than m1
// so try to infer applicability of m2 for argument types == formal param types of m1
// yeah but this would ignore the shape of lambdas, we'd only get constraints
// like f1(m1) <: f1(m2), ignoring that a lambda may be compatible with both types
private final Infer infer;
private final MethodResolutionPhase phase;
private final MethodCallSite site;
PhaseOverloadSet(Infer infer, MethodResolutionPhase phase, MethodCallSite site) {
this.infer = infer;
this.phase = phase;
this.site = site;
}
public MethodResolutionPhase getPhase() {
return phase;
}
public MethodCallSite getSite() {
return site;
}
public Infer getInfer() {
return infer;
}
/**
* It's a given that the method is applicable to the site.
*
* <p>https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2.5
*/
@Override
@SuppressWarnings("PMD.UselessOverridingMethod")
void add(MethodCtDecl sig) {
super.add(sig);
}
public @NonNull MethodCtDecl getMostSpecificOrLogAmbiguity(TypeInferenceLogger logger) {
assert nonEmpty();
List<MethodCtDecl> overloads = getOverloadsMutable();
MethodCtDecl main = overloads.get(0);
if (overloads.size() != 1) {
logger.ambiguityError(site, main, overloads);
main = main.asFailed();
}
return main;
}
@Override
protected OptionalBool shouldTakePrecedence(MethodCtDecl m1, MethodCtDecl m2) {
return isMoreSpecific(m1.getMethodType().internalApi().adaptedMethod(),
m2.getMethodType().internalApi().adaptedMethod());
}
private OptionalBool isMoreSpecific(@NonNull JMethodSig m1, @NonNull JMethodSig m2) {
OptionalBool m1OverM2 = isMoreSpecificForExpr(m1, m2);
if (m1OverM2.isKnown()) {
return m1OverM2;
} else if (areOverrideEquivalent(m1, m2)) {
JTypeMirror observingSite = site.getExpr().getReceiverType();
if (observingSite == null) {
observingSite = site.getExpr().getEnclosingType();
}
return OverloadSet.shouldAlwaysTakePrecedence(m1, m2, observingSite);
}
return UNKNOWN;
}
private OptionalBool isMoreSpecificForExpr(JMethodSig m1, JMethodSig m2) {
boolean m1OverM2 = isInferredMoreSpecific(m1, m2);
boolean m2OverM1 = isInferredMoreSpecific(m2, m1);
if (m1OverM2 ^ m2OverM1) {
return definitely(m1OverM2);
}
return UNKNOWN;
}
private boolean isInferredMoreSpecific(JMethodSig m1, JMethodSig m2) {
// https://docs.oracle.com/javase/specs/jls/se8/html/jls-18.html#jls-18.5.4
try {
return doInfer(m1, m2);
} catch (ResolutionFailedException e) {
return false;
}
}
private boolean doInfer(JMethodSig m1, JMethodSig m2) {
MethodCallSite site = this.site.cloneForSpecificityCheck(infer);
InferenceContext ctx = infer.newContextFor(m2);
// even if m1 is generic, the type parameters of m1 are treated as type variables, not inference variables.
JMethodSig m2p = ctx.mapToIVars(m2);
List<ExprMirror> es = site.getExpr().getArgumentExpressions();
List<JTypeMirror> m1Formals = m1.getFormalParameters();
List<JTypeMirror> m2Formals = m2p.getFormalParameters();
int k = es.size();
for (int i = 0; i < k; i++) {
JTypeMirror ti = phase.ithFormal(m2Formals, i);
JTypeMirror si = phase.ithFormal(m1Formals, i);
ExprMirror ei = es.get(i);
if (si.equals(ti)) {
continue;
}
// needs to go before subtyping checks, because those will always succeed
if (unresolvedTypeFallback(si, ti, ei) == NO) {
return false;
}
if (si.isSubtypeOf(ti)) {
return true;
} else if (ti.isSubtypeOf(si)) {
return false;
}
JMethodSig sfun = TypeOps.findFunctionalInterfaceMethod(si);
JMethodSig tfun = TypeOps.findFunctionalInterfaceMethod(ti);
if (sfun == null || tfun == null) {
if (phase.canBox()) {
JTypeMirror stdExprTy = ei.getStandaloneType();
if (stdExprTy != null
// there is a boxing or unboxing conversion happening
&& stdExprTy.isPrimitive() != si.isPrimitive()
&& stdExprTy.isPrimitive() != ti.isPrimitive()) {
// si or ti is more specific if it only involves
// the boxing/unboxing conversion, without widening
// afterwards.
if (stdExprTy.box().equals(si.box())) {
return true;
} else if (stdExprTy.box().equals(ti.box())) {
return false;
}
}
}
infer.checkConvertibleOrDefer(ctx, si, ti, ei, phase, site);
continue;
}
// otherwise they're both functional interfaces
if (!isFunctionTypeMoreSpecific(ctx, si, sfun, tfun, ei, site)) {
return false;
}
}
if (phase.requiresVarargs() && m2Formals.size() == k + 1) {
// that is, the invocation has no arguments for the varargs, eg Stream.of()
infer.checkConvertibleOrDefer(ctx, phase.ithFormal(m1Formals, k), m2Formals.get(k), site.getExpr(), phase, site);
}
ctx.solve();
ctx.callListeners();
return true;
}
private @NonNull OptionalBool unresolvedTypeFallback(JTypeMirror si, JTypeMirror ti, ExprMirror argExpr) {
JTypeMirror standalone = argExpr.getStandaloneType();
if (standalone != null && TypeOps.isUnresolved(standalone)) {
if (standalone.equals(si)) {
return YES;
} else if (standalone.equals(ti)) {
return NO;
}
}
return UNKNOWN;
}
private boolean isFunctionTypeMoreSpecific(InferenceContext ctx,
JTypeMirror si,
JMethodSig sfun,
JMethodSig tfun,
ExprMirror ei, MethodCallSite site) {
if (sfun.getArity() != tfun.getArity()
|| sfun.getTypeParameters().size() != tfun.getTypeParameters().size()) {
return false;
}
// Note that the following is not implemented entirely
// The rest is described in https://docs.oracle.com/javase/specs/jls/se13/html/jls-18.html#jls-18.5.4
JMethodSig capturedSFun = TypeOps.findFunctionalInterfaceMethod(TypeConversion.capture(si));
assert capturedSFun != null;
if (!TypeOps.haveSameTypeParams(capturedSFun, sfun)) {
return false;
}
List<JTypeVar> sparams = sfun.getTypeParameters();
List<JTypeVar> tparams = tfun.getTypeParameters();
Substitution tToS = Substitution.mapping(tparams, sparams);
for (int j = 0; j < sparams.size(); j++) {
JTypeVar aj = sparams.get(j);
JTypeVar bj = tparams.get(j);
JTypeMirror x = aj.getUpperBound();
JTypeMirror y = bj.getUpperBound();
if (TypeOps.mentionsAny(x, sfun.getTypeParameters()) && !ctx.isGround(y)) {
return false;
} else {
TypeOps.isSameTypeInInference(x, y.subst(tToS)); // adds an equality constraint
}
}
// todo something about formal params
JTypeMirror rs = sfun.getReturnType();
JTypeMirror rt = tfun.getReturnType();
return (!TypeOps.mentionsAny(rs, sparams) || ctx.isGround(rt))
&& addGenericExprConstraintsRecursive(ctx, ei, rs, rt, tToS, site);
}
private boolean addGenericExprConstraintsRecursive(InferenceContext ctx, ExprMirror ei, JTypeMirror rs, JTypeMirror rt, Substitution tToS, MethodCallSite site) {
if (ei instanceof LambdaExprMirror) {
// Otherwise, if ei is an explicitly typed lambda expression:
//
// If RT is void, true.
//
// todo: Otherwise, if RS and RT are functional interface types, and ei has at least one result expression, then for each result expression in ei, this entire second step is repeated to infer constraints under which RS is more specific than RT θ' for the given result expression.
//
// Otherwise, if RS is a primitive type and RT is not, and ei has at least one result expression, and each result expression of ei is a standalone expression (§15.2) of a primitive type, true.
//
// Otherwise, if RT is a primitive type and RS is not, and ei has at least one result expression, and each result expression of ei is either a standalone expression of a reference type or a poly expression, true.
//
// Otherwise, ‹RS <: RT θ'›.
LambdaExprMirror lambda = (LambdaExprMirror) ei;
if (!lambda.isExplicitlyTyped()) {
return false;
}
if (getSpecies(rt) != getSpecies(rs)) {
TypeSpecies requiredSpecies = getSpecies(rs);
boolean sameSpecies = true;
boolean atLeastOne = false;
for (ExprMirror rexpr : lambda.getResultExpressions()) {
atLeastOne = true;
sameSpecies &= requiredSpecies == rexpr.getStandaloneSpecies();
}
if (sameSpecies && atLeastOne) {
return true;
}
}
infer.checkConvertibleOrDefer(ctx, rs, rt.subst(tToS), ei, phase, site);
return true;
} else if (ei instanceof MethodRefMirror) {
// Otherwise, if ei is an exact method reference:
//
// If RT is void, true.
//
// Otherwise, if RS is a primitive type and RT is not, and the compile-time declaration for ei has a primitive return type, true.
//
// Otherwise if RT is a primitive type and RS is not, and the compile-time declaration for ei has a reference return type, true.
//
// Otherwise, ‹RS <: RT θ'›.
JMethodSig exact = ExprOps.getExactMethod((MethodRefMirror) ei);
if (exact == null) {
return false;
}
if (getSpecies(rs) != getSpecies(rt)
&& getSpecies(exact.getReturnType()) == getSpecies(rs)) {
return true;
}
infer.checkConvertibleOrDefer(ctx, rs, rt.subst(tToS), ei, phase, site);
return true;
} else if (ei instanceof BranchingMirror) {
return ((BranchingMirror) ei).branchesMatch(e -> addGenericExprConstraintsRecursive(ctx, e, rs, rt, tToS, site));
}
return false;
}
}
| 13,416 | 39.412651 | 294 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/PolySite.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.PolyExprMirror;
/**
* Context of a poly expression. Includes info about an expected target
* type, and the expression mirror.
*/
public class PolySite<E extends PolyExprMirror> {
private final JTypeMirror expectedType;
private final E expr;
PolySite(E expr, @Nullable JTypeMirror expectedType) {
this.expectedType = expectedType;
this.expr = expr;
}
@Nullable
JTypeMirror getExpectedType() {
return expectedType;
}
public final E getExpr() {
return expr;
}
@Override
public String toString() {
return "PolySite:" + expr;
}
}
| 960 | 21.348837 | 84 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/InferenceContext.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import static net.sourceforge.pmd.lang.java.types.TypeOps.asList;
import static net.sourceforge.pmd.util.CollectionUtil.intersect;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
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.JTypeVisitable;
import net.sourceforge.pmd.lang.java.types.SubstVar;
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.lang.java.types.internal.infer.ExprMirror.InvocationMirror.MethodCtDecl;
import net.sourceforge.pmd.lang.java.types.internal.infer.IncorporationAction.CheckBound;
import net.sourceforge.pmd.lang.java.types.internal.infer.IncorporationAction.PropagateAllBounds;
import net.sourceforge.pmd.lang.java.types.internal.infer.IncorporationAction.PropagateBounds;
import net.sourceforge.pmd.lang.java.types.internal.infer.IncorporationAction.SubstituteInst;
import net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar.BoundKind;
import net.sourceforge.pmd.lang.java.types.internal.infer.VarWalkStrategy.GraphWalk;
/**
* Context of a type inference process. This object maintains a set of
* unique inference variables. Inference variables maintain the set of
* bounds that apply to them.
*/
final class InferenceContext {
// ivar/ctx ids are globally unique, & repeatable in debug output if you do exactly the same run
private static int varId = 0;
private static int ctxId = 0;
private final Map<InstantiationListener, Set<InferenceVar>> instantiationListeners = new HashMap<>();
private final Set<InferenceVar> freeVars = new LinkedHashSet<>();
private final Set<InferenceVar> inferenceVars = new LinkedHashSet<>();
private final Deque<IncorporationAction> incorporationActions = new ArrayDeque<>();
final TypeSystem ts;
private final SupertypeCheckCache supertypeCheckCache;
final TypeInferenceLogger logger;
private Substitution mapping = Substitution.EMPTY;
private @Nullable InferenceContext parent;
private boolean needsUncheckedConversion;
private final int id;
/**
* Create an inference context from a set of type variables to instantiate.
* This creates inference vars and adds the initial bounds as described in
*
* https://docs.oracle.com/javase/specs/jls/se9/html/jls-18.html#jls-18.1.3
*
* under the purple rectangle.
*
* @param ts The global type system
* @param supertypeCheckCache Super type check cache, shared by all
* inference runs in the same compilation unit
* (stored in {@link Infer}).
* @param tvars Initial tvars which will be turned
* into ivars
* @param logger Logger for events related to ivar bounds
*/
@SuppressWarnings("PMD.AssignmentToNonFinalStatic") // ctxId
InferenceContext(TypeSystem ts, SupertypeCheckCache supertypeCheckCache, List<JTypeVar> tvars, TypeInferenceLogger logger) {
this.ts = ts;
this.supertypeCheckCache = supertypeCheckCache;
this.logger = logger;
this.id = ctxId++;
for (JTypeVar p : tvars) {
addVarImpl(p);
}
for (InferenceVar ivar : inferenceVars) {
addPrimaryBound(ivar);
}
}
public int getId() {
return id;
}
private void addPrimaryBound(InferenceVar ivar) {
for (JTypeMirror ui : asList(ivar.getBaseVar().getUpperBound())) {
ivar.addPrimaryBound(BoundKind.UPPER, mapToIVars(ui));
}
}
/** Add a variable to this context. */
InferenceVar addVar(JTypeVar tvar) {
InferenceVar ivar = addVarImpl(tvar);
addPrimaryBound(ivar);
for (InferenceVar otherIvar : inferenceVars) {
// remove remaining occurrences of type params
otherIvar.substBounds(this::mapToIVars);
}
return ivar;
}
/** Add a variable to this context. */
private InferenceVar addVarImpl(@NonNull JTypeVar tvar) {
InferenceVar ivar = new InferenceVar(this, tvar, varId++);
freeVars.add(ivar);
inferenceVars.add(ivar);
mapping = mapping.plus(tvar, ivar);
return ivar;
}
/**
* Replace all type variables in the given type with corresponding
* inference vars.
*/
JTypeMirror mapToIVars(JTypeMirror t) {
return TypeOps.subst(t, mapping);
}
/**
* Replace all type variables in the given type with corresponding
* inference vars.
*/
JMethodSig mapToIVars(JMethodSig t) {
return t.subst(mapping);
}
/**
* Returns true if the type mentions no free inference variables.
* This is what the JLS calls a "proper type".
*/
boolean isGround(JTypeVisitable t) {
return !TypeOps.mentionsAny(t, freeVars);
}
/**
* Returns true if the type mentions no free inference variables.
*/
boolean areAllGround(Collection<? extends JTypeVisitable> ts) {
for (JTypeVisitable t : ts) {
if (!isGround(t)) {
return false;
}
}
return true;
}
Set<InferenceVar> freeVarsIn(Iterable<? extends JTypeVisitable> types) {
Set<InferenceVar> vars = new LinkedHashSet<>();
for (InferenceVar ivar : freeVars) {
for (JTypeVisitable t : types) {
if (TypeOps.mentions(t, ivar)) {
vars.add(ivar);
}
}
}
return vars;
}
Set<InferenceVar> freeVarsIn(JTypeVisitable t) {
return freeVarsIn(Collections.singleton(t));
}
/**
* Replace instantiated inference vars with their instantiation in the given type.
*/
JTypeMirror ground(JTypeMirror t) {
return t.subst(InferenceContext::groundSubst);
}
JClassType ground(JClassType t) {
return t.subst(InferenceContext::groundSubst);
}
/**
* Replace instantiated inference vars with their instantiation in the given type.
*/
JMethodSig ground(JMethodSig t) {
return t.subst(InferenceContext::groundSubst);
}
void setNeedsUncheckedConversion() {
this.needsUncheckedConversion = true;
}
/**
* Whether incorporation/solving required an unchecked conversion.
* This means the invocation type of the overload must be erased.
*
* @see MethodCtDecl#needsUncheckedConversion()
*/
boolean needsUncheckedConversion() {
return this.needsUncheckedConversion;
}
SupertypeCheckCache getSupertypeCheckCache() {
return supertypeCheckCache;
}
private static JTypeMirror groundSubst(SubstVar var) {
if (var instanceof InferenceVar) {
JTypeMirror inst = ((InferenceVar) var).getInst();
if (inst != null) {
return inst;
}
}
return var;
}
/**
* Replace instantiated inference vars with their instantiation in the given type,
* or else replace them with a failed type.
*/
static JMethodSig finalGround(JMethodSig t) {
return t.subst(s -> {
if (!(s instanceof InferenceVar)) {
return s;
} else {
InferenceVar ivar = (InferenceVar) s;
return ivar.getInst() != null ? ivar.getInst() : s.getTypeSystem().ERROR;
}
});
}
/**
* Copy variable in this inference context to the given context
*/
void duplicateInto(final InferenceContext that) {
that.inferenceVars.addAll(this.inferenceVars);
that.freeVars.addAll(this.freeVars);
that.incorporationActions.addAll(this.incorporationActions);
that.instantiationListeners.putAll(this.instantiationListeners);
this.parent = that;
// propagate existing bounds into the new context
for (InferenceVar freeVar : this.freeVars) {
that.incorporationActions.add(new PropagateAllBounds(freeVar));
}
}
void addInstantiationListener(Set<? extends JTypeMirror> relevantTypes, InstantiationListener listener) {
Set<InferenceVar> free = freeVarsIn(relevantTypes);
if (free.isEmpty()) {
listener.onInstantiation(this);
return;
}
instantiationListeners.put(listener, free);
}
/**
* Call the listeners registered with {@link #addInstantiationListener(Set, InstantiationListener)}.
* Listeners are used to perform deferred checks, like checking
* compatibility of a formal parameter with an expression when the
* formal parameter is not ground.
*/
void callListeners() {
if (instantiationListeners.isEmpty()) {
return;
}
Set<InferenceVar> solved = new LinkedHashSet<>(inferenceVars);
solved.removeAll(freeVars);
for (Entry<InstantiationListener, Set<InferenceVar>> entry : new LinkedHashSet<>(instantiationListeners.entrySet())) {
if (solved.containsAll(entry.getValue())) {
try {
entry.getKey().onInstantiation(this);
} catch (ResolutionFailedException ignored) {
// that is a compile-time error, but that
// shouldn't affect PMD
// This can happen eg when an assertion fails in a
// subcontext that depends on this one, which is waiting
// for more inference to happen
// TODO investigate
} catch (Exception e) {
e.printStackTrace();
} finally {
instantiationListeners.remove(entry.getKey());
}
}
}
}
Set<InferenceVar> getFreeVars() {
return Collections.unmodifiableSet(freeVars);
}
private void onVarInstantiated(InferenceVar ivar) {
if (parent != null) {
parent.onVarInstantiated(ivar);
return;
}
logger.ivarInstantiated(this, ivar, ivar.getInst());
incorporationActions.addFirst(new SubstituteInst(ivar, ivar.getInst()) {
@Override
public void apply(InferenceContext ctx) {
freeVars.removeIf(it -> it.getInst() != null);
super.apply(ctx);
}
});
}
void onBoundAdded(InferenceVar ivar, BoundKind kind, JTypeMirror bound, boolean isPrimary) {
// guard against α <: Object
// all variables have it, it's useless to propagate it
if (kind != BoundKind.UPPER || bound != ts.OBJECT) { // NOPMD CompareObjectsWithEquals
if (parent != null) {
parent.onBoundAdded(ivar, kind, bound, isPrimary);
return;
}
logger.boundAdded(this, ivar, kind, bound, isPrimary);
incorporationActions.add(new CheckBound(ivar, kind, bound));
incorporationActions.add(new PropagateBounds(ivar, kind, bound));
}
}
void onIvarMerged(InferenceVar prev, InferenceVar delegate) {
if (parent != null) {
parent.onIvarMerged(prev, delegate);
return;
}
logger.ivarMerged(this, prev, delegate);
mapping = mapping.plus(prev.getBaseVar(), delegate);
incorporationActions.addFirst(new SubstituteInst(prev, delegate));
}
/**
* Runs the incorporation hooks registered for the free vars.
*
* @throws ResolutionFailedException If some propagated bounds are incompatible
*/
void incorporate() {
if (incorporationActions.isEmpty()) {
return;
}
IncorporationAction hook = incorporationActions.pollFirst();
while (hook != null) {
if (hook.doApplyToInstVar || hook.ivar.getInst() == null) {
hook.apply(this);
}
hook = incorporationActions.pollFirst();
}
}
/**
* @throws ResolutionFailedException Because it calls {@link #incorporate()}
*/
void solve() {
solve(false);
}
boolean solve(boolean onlyBoundedVars) {
return solve(new GraphWalk(this, onlyBoundedVars));
}
/**
* Solve a single var, this does not solve its dependencies, so that
* if some bounds are not ground, instantiation will be wrong.
*/
void solve(InferenceVar var) {
solve(new GraphWalk(var));
}
private boolean solve(VarWalkStrategy walker) {
incorporate();
while (walker.hasNext()) {
Set<InferenceVar> varsToSolve = walker.next();
boolean progress = true;
//repeat until all variables are solved
outer:
while (!intersect(freeVars, varsToSolve).isEmpty() && progress) {
progress = false;
for (List<ReductionStep> wave : ReductionStep.WAVES) {
if (solveBatchProgressed(varsToSolve, wave)) {
incorporate();
progress = true;
callListeners();
continue outer;
}
}
}
}
return freeVars.isEmpty();
}
/**
* Tries to solve as much of varsToSolve as possible using some reduction steps.
* Returns the set of solved variables during this step.
*/
private boolean solveBatchProgressed(Set<InferenceVar> varsToSolve, List<ReductionStep> wave) {
for (InferenceVar ivar : intersect(varsToSolve, freeVars)) {
for (ReductionStep step : wave) {
if (step.accepts(ivar, this)) {
ivar.setInst(step.solve(ivar, this));
onVarInstantiated(ivar);
return true;
}
}
}
return false;
}
public boolean isEmpty() {
return inferenceVars.isEmpty();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("Inference context " + getId()).append('\n');
for (InferenceVar ivar : inferenceVars) {
sb.append(ivar);
if (ivar.getInst() != null) {
sb.append(" := ").append(ivar.getInst()).append('\n');
} else {
ivar.formatBounds(sb).append('\n');
}
}
return sb.toString();
}
/** A callback called when a set of variables have been solved. */
public interface InstantiationListener {
/**
* Called when the set of dependencies provided to {@link #addInstantiationListener(Set, InstantiationListener)}
* have been solved. The parameter is not necessarily the context
* on which this has been registered, because contexts adopt the
* inference variables of their children in some cases, to solve
* them together. Use {@link #ground(JClassType)} with the context
* parameter, not the context on which the callback was registered.
*/
void onInstantiation(InferenceContext solvedCtx);
}
}
| 15,984 | 32.794926 | 128 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/InferenceVarSym.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
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.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolVisitor;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
class InferenceVarSym implements JTypeDeclSymbol {
private final TypeSystem ts;
private final InferenceVar var;
InferenceVarSym(TypeSystem ts, InferenceVar var) {
this.ts = ts;
this.var = var;
}
@Override
public @NonNull String getSimpleName() {
return var.getName();
}
@Override
public TypeSystem getTypeSystem() {
return ts;
}
@Override
public <R, P> R acceptVisitor(SymbolVisitor<R, P> visitor, P param) {
return visitor.visitTypeDecl(this, param);
}
@Override
public int getModifiers() {
return 0;
}
@Override
public @Nullable JClassSymbol getEnclosingClass() {
return null;
}
@Override
public @NonNull String getPackageName() {
return "";
}
@Override
public String toString() {
return "InferenceVar(" + getSimpleName() + ')';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InferenceVarSym that = (InferenceVarSym) o;
return var.equals(that.var);
}
@Override
public int hashCode() {
return var.hashCode();
}
}
| 1,801 | 22.402597 | 79 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/TypeInferenceLogger.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import java.io.PrintStream;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.types.JMethodSig;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.TypePrettyPrint;
import net.sourceforge.pmd.lang.java.types.TypePrettyPrint.TypePrettyPrinter;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.CtorInvocationMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.InvocationMirror.MethodCtDecl;
import net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar.BoundKind;
import net.sourceforge.pmd.util.StringUtil;
/**
* A strategy to log the execution traces of {@link Infer}.
*/
@SuppressWarnings("PMD.UncommentedEmptyMethodBody")
public interface TypeInferenceLogger {
// computeCompileTimeDecl
default void polyResolutionFailure(JavaNode node) { }
default void noApplicableCandidates(MethodCallSite site) { }
default void noCompileTimeDeclaration(MethodCallSite site) { }
default void startInference(JMethodSig sig, MethodCallSite site, MethodResolutionPhase phase) { }
default void endInference(@Nullable JMethodSig result) { }
default void fallbackInvocation(JMethodSig ctdecl, MethodCallSite site) { }
default void skipInstantiation(JMethodSig partiallyInferred, MethodCallSite site) { }
default void ambiguityError(MethodCallSite site, @Nullable MethodCtDecl selected, List<MethodCtDecl> m1) { }
// instantiateImpl
default void ctxInitialization(InferenceContext ctx, JMethodSig sig) { }
default void startArgsChecks() { }
default void startArg(int i, ExprMirror expr, JTypeMirror formal) { }
default void skipArgAsNonPertinent(int i, ExprMirror expr) { }
default void functionalExprNeedsInvocationCtx(JTypeMirror targetT, ExprMirror expr) { }
default void endArg() { }
default void endArgsChecks() { }
default void startReturnChecks() { }
default void endReturnChecks() { }
default void propagateAndAbort(InferenceContext context, InferenceContext parent) { }
// ivar events
default void boundAdded(InferenceContext ctx, InferenceVar var, BoundKind kind, JTypeMirror bound, boolean isSubstitution) { }
default void ivarMerged(InferenceContext ctx, InferenceVar var, InferenceVar delegate) { }
default void ivarInstantiated(InferenceContext ctx, InferenceVar var, JTypeMirror inst) { }
/**
* Log that the instantiation of the method type m for the given
* call site failed. The exception provides a detail message.
* Such an event is perfectly normal and may happen repeatedly
* when performing overload resolution.
*
* <p>Exceptions occuring in an {@link MethodResolutionPhase#isInvocation() invocation phase}
* are compile-time errors though.
*
* @param exception Failure record
*/
default void logResolutionFail(ResolutionFailure exception) { }
default boolean isNoop() {
return false;
}
/**
* Return an instance for concurrent use in another thread.
* If this is Noop, then return the same instance because it's
* thread-safe.
*/
TypeInferenceLogger newInstance();
static TypeInferenceLogger noop() {
return SimpleLogger.NOOP;
}
class SimpleLogger implements TypeInferenceLogger {
static final TypeInferenceLogger NOOP = new TypeInferenceLogger() {
@Override
public boolean isNoop() {
return true;
}
@Override
public TypeInferenceLogger newInstance() {
return this;
}
};
protected final PrintStream out;
protected static final int LEVEL_INCREMENT = 4;
private int level;
private String indent;
protected static final String ANSI_RESET = "\u001B[0m";
protected static final String ANSI_BLUE = "\u001B[34m";
protected static final String ANSI_PURPLE = "\u001B[35m";
protected static final String ANSI_GRAY = "\u001B[37m";
protected static final String ANSI_RED = "\u001B[31m";
protected static final String ANSI_YELLOW = "\u001B[33m";
private static final String TO_BLUE =
Matcher.quoteReplacement(ANSI_BLUE) + "$0" + Matcher.quoteReplacement(ANSI_RESET);
private static final String TO_WHITE =
Matcher.quoteReplacement(ANSI_GRAY) + "$0" + Matcher.quoteReplacement(ANSI_RESET);
private static final Pattern IVAR_PATTERN = Pattern.compile("['^][α-ωa-z]\\d*");
private static final Pattern IDENT_PATTERN = Pattern.compile("\\b(?<!['^])(?!extends|super|capture|of|)[\\w]++(?!\\.)<?|-?>++");
protected String color(Object str, String color) {
return SystemUtils.IS_OS_UNIX ? color + str + ANSI_RESET : str.toString();
}
protected static String colorIvars(Object str) {
return doColor(str, IVAR_PATTERN, TO_BLUE);
}
protected static String colorPunct(Object str) {
return doColor(str, IDENT_PATTERN, TO_WHITE);
}
protected static String doColor(Object str, Pattern pattern, String replacement) {
if (SystemUtils.IS_OS_UNIX) {
return pattern.matcher(str.toString()).replaceAll(replacement);
}
return str.toString();
}
public SimpleLogger(PrintStream out) {
this.out = out;
updateLevel(0);
}
protected int getLevel() {
return level;
}
protected void updateLevel(int increment) {
level += increment;
indent = StringUtils.repeat(' ', level);
}
protected void println(String str) {
out.print(indent);
out.println(str);
}
protected void endSection(String footer) {
updateLevel(-LEVEL_INCREMENT);
println(footer);
}
protected void startSection(String header) {
println(header);
updateLevel(+LEVEL_INCREMENT);
}
@Override
public void logResolutionFail(ResolutionFailure exception) {
if (exception.getCallSite() instanceof MethodCallSite && exception != ResolutionFailure.UNKNOWN) { // NOPMD CompareObjectsWithEquals
((MethodCallSite) exception.getCallSite()).acceptFailure(exception);
}
}
@Override
public void noApplicableCandidates(MethodCallSite site) {
if (!site.isLogEnabled()) {
return;
}
@Nullable JTypeMirror receiver = site.getExpr().getErasedReceiverType();
if (receiver != null) {
JTypeDeclSymbol symbol = receiver.getSymbol();
if (symbol == null || symbol.isUnresolved()) {
return;
}
}
if (site.getExpr() instanceof CtorInvocationMirror) {
startSection("[WARNING] No potentially applicable constructors in "
+ ((CtorInvocationMirror) site.getExpr()).getNewType());
} else {
startSection("[WARNING] No potentially applicable methods in " + receiver);
}
printExpr(site.getExpr());
Iterator<JMethodSig> iter = site.getExpr().getAccessibleCandidates().iterator();
if (iter.hasNext()) {
startSection("Accessible signatures:");
iter.forEachRemaining(it -> println(ppMethod(it)));
endSection("");
} else {
println("No accessible signatures");
}
endSection("");
}
@Override
public void noCompileTimeDeclaration(MethodCallSite site) {
if (!site.isLogEnabled()) {
return;
}
startSection("[WARNING] Compile-time declaration resolution failed.");
printExpr(site.getExpr());
summarizeFailures(site);
endSection("");
}
private void summarizeFailures(MethodCallSite site) {
startSection("Summary of failures:");
site.getResolutionFailures()
.forEach((phase, failures) -> {
startSection(phase.toString() + ":");
failures.forEach(it -> println(String.format("%-64s // while checking %s", it.getReason(), ppMethod(it.getFailedMethod()))));
endSection("");
});
endSection("");
}
@Override
public void fallbackInvocation(JMethodSig ctdecl, MethodCallSite site) {
if (!site.isLogEnabled()) {
return;
}
startSection("[WARNING] Invocation type resolution failed");
printExpr(site.getExpr());
summarizeFailures(site);
println("-> Falling back on " + ppHighlight(ctdecl)
+ " (this may cause future mistakes)");
endSection("");
}
@Override
public void ambiguityError(MethodCallSite site, @Nullable MethodCtDecl selected, List<MethodCtDecl> methods) {
println("");
printExpr(site.getExpr());
startSection("[WARNING] Ambiguity error: all methods are maximally specific");
for (MethodCtDecl m : methods) {
println(color(m.getMethodType().internalApi().originalMethod(), ANSI_RED));
}
if (selected != null) {
endSection("Will select " + color(selected.getMethodType().internalApi().originalMethod(), ANSI_BLUE));
} else {
endSection(""); // no fallback?
}
}
protected void printExpr(ExprMirror expr) {
String exprText = expr.getLocation().getText().toString();
exprText = exprText.replaceAll("\\R\\s+", "");
exprText = StringUtil.escapeJava(StringUtils.truncate(exprText, 100));
println("At: " + fileLocation(expr));
println("Expr: " + color(exprText, ANSI_YELLOW));
}
private String fileLocation(ExprMirror mirror) {
return mirror.getLocation().getReportLocation().startPosToStringWithFile();
}
protected @NonNull String ppMethod(JMethodSig sig) {
return TypePrettyPrint.prettyPrint(sig, new TypePrettyPrinter().printMethodHeader(false));
}
protected @NonNull String ppHighlight(JMethodSig sig) {
String s = ppMethod(sig);
int paramStart = s.indexOf('(');
String name = s.substring(0, paramStart);
String rest = s.substring(paramStart);
return color(name, ANSI_BLUE) + colorIvars(colorPunct(rest));
}
protected @NonNull String ppBound(InferenceVar ivar, BoundKind kind, JTypeMirror bound) {
return ivar + kind.getSym() + colorIvars(colorPunct(bound));
}
@Override
public TypeInferenceLogger newInstance() {
return new SimpleLogger(out);
}
}
/**
* This is mega verbose, should only be used for unit tests.
*/
class VerboseLogger extends SimpleLogger {
private final Deque<Integer> marks = new ArrayDeque<>();
public VerboseLogger(PrintStream out) {
super(out);
mark();
}
void mark() {
marks.push(getLevel());
}
void rollback(String lastWords) {
int pop = marks.pop();
updateLevel(pop - getLevel()); // back to normal
if (!lastWords.isEmpty()) {
updateLevel(+LEVEL_INCREMENT);
println(lastWords);
updateLevel(-LEVEL_INCREMENT);
}
}
@Override
public void startInference(JMethodSig sig, MethodCallSite site, MethodResolutionPhase phase) {
mark();
startSection(String.format("Phase %-17s%s", phase, ppHighlight(sig)));
}
@Override
public void ctxInitialization(InferenceContext ctx, JMethodSig sig) {
println(String.format("Context %-11d%s", ctx.getId(), ppHighlight(ctx.mapToIVars(sig))));
}
@Override
public void endInference(@Nullable JMethodSig result) {
rollback(result != null ? "Success: " + ppHighlight(result)
: "FAILED! SAD!");
}
@Override
public void skipInstantiation(JMethodSig partiallyInferred, MethodCallSite site) {
println("Skipping instantiation of " + partiallyInferred + ", it's already complete");
}
@Override
public void startArgsChecks() {
startSection("ARGUMENTS");
}
@Override
public void startReturnChecks() {
startSection("RETURN");
}
@Override
public void propagateAndAbort(InferenceContext context, InferenceContext parent) {
println("Ctx " + parent.getId() + " adopts " + color(context.getFreeVars(), ANSI_BLUE) + " from ctx "
+ context.getId());
}
@Override
public void startArg(int i, ExprMirror expr, JTypeMirror formalType) {
startSection("Checking arg " + i + " against " + formalType);
printExpr(expr);
}
@Override
public void skipArgAsNonPertinent(int i, ExprMirror expr) {
startSection("Argument " + i + " is not pertinent to applicability");
printExpr(expr);
endSection("");
}
@Override
public void functionalExprNeedsInvocationCtx(JTypeMirror targetT, ExprMirror expr) {
println("Target type is not a functional interface yet: " + targetT);
println("Will wait for invocation phase before discarding.");
}
@Override
public void endArgsChecks() {
endSection("");
}
@Override
public void endArg() {
endSection("");
}
@Override
public void endReturnChecks() {
endSection("");
}
@Override
public void boundAdded(InferenceContext ctx, InferenceVar ivar, BoundKind kind, JTypeMirror bound, boolean isSubstitution) {
String message = isSubstitution ? "Changed bound" : "New bound";
println(addCtxInfo(ctx, message) + ppBound(ivar, kind, bound));
}
@Override
public void ivarMerged(InferenceContext ctx, InferenceVar var, InferenceVar delegate) {
println(addCtxInfo(ctx, "Ivar merged") + var + " <=> " + delegate);
}
@Override
public void ivarInstantiated(InferenceContext ctx, InferenceVar var, JTypeMirror inst) {
println(addCtxInfo(ctx, "Ivar instantiated") + color(var + " := ", ANSI_BLUE) + colorIvars(inst));
}
private @NonNull String addCtxInfo(InferenceContext ctx, String event) {
return String.format("%-20s(ctx %d): ", event, ctx.getId());
}
@Override
public void logResolutionFail(ResolutionFailure exception) {
super.logResolutionFail(exception);
println("Failed: " + exception.getReason());
}
@Override
public TypeInferenceLogger newInstance() {
return new VerboseLogger(out);
}
}
}
| 16,126 | 33.68172 | 145 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/MethodCallSite.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.InvocationMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.InvocationMirror.MethodCtDecl;
import net.sourceforge.pmd.lang.java.types.internal.infer.TypeInferenceLogger.SimpleLogger;
/**
* Poly site for an invocation expression. Includes info about an ongoing
* outer inference process if any, as well as an expected target type.
* The target type might depend on inference of the outer context, by
* mentioning free type variables. In that case they're resolved together.
*/
public class MethodCallSite extends PolySite<InvocationMirror> {
private final InferenceContext localInferenceContext;
private final MethodCallSite outerSite;
private boolean logEnabled = true;
private final Map<MethodResolutionPhase, List<ResolutionFailure>> errors = new EnumMap<>(MethodResolutionPhase.class);
private boolean isInInvocation = false;
private boolean canSkipInvocation = true;
private boolean needsUncheckedConversion = false;
private final boolean isSpecificityCheck;
MethodCallSite(InvocationMirror expr,
@Nullable JTypeMirror expectedType,
@Nullable MethodCallSite outerSite,
@NonNull InferenceContext infCtx,
boolean isSpecificityCheck) {
super(expr, expectedType);
this.outerSite = outerSite;
this.localInferenceContext = infCtx;
this.isSpecificityCheck = isSpecificityCheck;
}
boolean isSpecificityCheck() {
return isSpecificityCheck;
}
MethodCallSite cloneForSpecificityCheck(Infer infer) {
return new MethodCallSite(
getExpr(),
getExpectedType(),
null,
infer.emptyContext(),
true
);
}
void acceptFailure(ResolutionFailure exception) {
if (logEnabled) {
errors.computeIfAbsent(exception.getPhase(), k -> new ArrayList<>()).add(exception);
}
}
public boolean isLogEnabled() {
return logEnabled;
}
void setLogging(boolean enabled) {
logEnabled = enabled;
}
void setInInvocation() {
isInInvocation = true;
}
void maySkipInvocation(boolean canSkipInvocation) {
this.canSkipInvocation &= canSkipInvocation;
}
boolean canSkipInvocation() {
return canSkipInvocation;
}
boolean isInFinalInvocation() {
return (outerSite == null || outerSite.isInFinalInvocation()) && isInInvocation;
}
/**
* Returns a list of error messages encountered during the inference.
* For this list to be populated, the {@link Infer} must use
* a {@link SimpleLogger}.
*
* <p>Failures in the invocation phase are compile-time errors.
*/
public Map<MethodResolutionPhase, List<ResolutionFailure>> getResolutionFailures() {
return Collections.unmodifiableMap(errors);
}
void clearFailures() {
errors.clear();
}
boolean needsUncheckedConversion() {
return needsUncheckedConversion;
}
void setNeedsUncheckedConversion() {
needsUncheckedConversion = true;
}
void resetInferenceData() {
canSkipInvocation = true;
needsUncheckedConversion = false;
isInInvocation = false;
}
void loadInferenceData(MethodCtDecl ctdecl) {
canSkipInvocation = ctdecl.canSkipInvocation();
needsUncheckedConversion = ctdecl.needsUncheckedConversion();
}
/**
* Returns the inference context of the target site. This is relevant
* in invocation contexts, in which the inference context of an argument
* needs to be propagated to the outer context.
*/
@NonNull
InferenceContext getOuterCtx() {
return localInferenceContext;
}
@Override
public String toString() {
return "CallSite:" + getExpr();
}
}
| 4,412 | 29.434483 | 122 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/SupertypeCheckCache.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import net.sourceforge.pmd.lang.java.types.JPrimitiveType;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
/**
* Caches some results of subtyping checks.
*/
final class SupertypeCheckCache {
private final Map<JTypeMirror, Set<JTypeMirror>> cache = new LinkedHashMap<JTypeMirror, Set<JTypeMirror>>() {
// Even with a relatively small cache size, the hit ratio is
// very high (around 75% on the tests we have here, discounting
// the stress tests)
// TODO refresh numbers using a real codebase
private static final int MAX_SIZE = 50;
@Override
protected boolean removeEldestEntry(Entry<JTypeMirror, Set<JTypeMirror>> eldest) {
return size() > MAX_SIZE;
}
};
/**
* Returns true if t is certainly a subtype of s. Otherwise it
* needs to be recomputed.
*/
boolean isCertainlyASubtype(JTypeMirror t, JTypeMirror s) {
Set<JTypeMirror> superTypesOfT = cache.get(t);
return superTypesOfT != null && superTypesOfT.contains(s);
}
void remember(JTypeMirror t, JTypeMirror s) {
if (shouldCache(t) && shouldCache(s)) {
cache.computeIfAbsent(t, k -> new HashSet<>()).add(s);
}
}
private boolean shouldCache(JTypeMirror t) {
// some types are never cached
return !(t instanceof InferenceVar) && !(t instanceof JPrimitiveType);
}
}
| 1,701 | 29.392857 | 113 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ExprMirror.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import static net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.TypeSpecies.UNKNOWN;
import static net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.TypeSpecies.getSpecies;
import static net.sourceforge.pmd.lang.java.types.internal.infer.MethodResolutionPhase.STRICT;
import java.util.List;
import java.util.function.Predicate;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.symbols.JConstructorSymbol;
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.OverloadSelectionResult;
import net.sourceforge.pmd.lang.java.types.TypeOps;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
import net.sourceforge.pmd.lang.java.types.TypingContext;
/**
* Adapter class to manipulate expressions. The framework
* ideally keeps focus on types and doesn't have a dependency
* on the AST. Only the impl package can have such dependencies.
*/
public interface ExprMirror {
/**
* Returns a node which is used as a location to report messages.
* Do not use this any other way.
*/
JavaNode getLocation();
/**
* If this expression is of a standalone form, returns the type of
* the expression. Otherwise returns null.
*
* <p>Note that standalone types can directly be set on the type
* node.
*
* @return The type of the expression if it is standalone
*/
@Nullable JTypeMirror getStandaloneType();
/**
* For a standalone expr, finish type inference by computing properties
* that are guarded by the type res lock. For instance for a standalone
* ctor call, the standalone type is trivially known (it's the type node).
* But we still need to do overload resolution.
*/
default void finishStandaloneInference(@NonNull JTypeMirror standaloneType) {
// do nothing
}
/**
* Set the type of the underlying ast node. Used when we need
* to find out the type of a poly to infer the type of another,
* that way, we don't repeat computation.
*/
void setInferredType(JTypeMirror mirror);
/** Return the value set in the last call to {@link #setInferredType(JTypeMirror)}. */
@Nullable JTypeMirror getInferredType();
/**
* Returns typing information for the lambdas parameters in scope
* in this expression and its subexpressions. When overload resolution
* involves lambdas, we might have to try several target types for each
* lambda. Each of those may give a different type to the lambda parameters,
* and hence, to every expression in the lambda body. These "tentative"
* typing are kept in the {@link TypingContext} object and only
* committed to the AST for the overload that is selected in the end.
*/
TypingContext getTypingContext();
/**
* Returns the species that this expression produces. The species
* may be known even if the expr is not standalone. For example a
* diamond constructor call is not standalone, but its species is
* obviously REFERENCE.
*
* <p>This is used for specificity tests for lambdas. They use species
* because invocation needs to be done exactly once, and the actual
* type of the expression may differ depending on the selected overload.
* Eg given the signatures {@code <T>foo(Supplier<T>)} and {@code foo(Runnable)},
* the expression {@code foo(() -> new List<>())} must select the supplier
* overload, even before the invocation type of {@code List<>} is known.
* The overload selection compares the expected species of both function
* types (REFERENCE for Supplier, VOID for Runnable), and determines that
* the supplier is more appropriate.
*/
default @NonNull TypeSpecies getStandaloneSpecies() {
JTypeMirror std = getStandaloneType();
return std == null ? UNKNOWN : getSpecies(std);
}
/**
* Returns true if this mirror and its subexpressions are equivalent
* to the underlying AST node. This is only relevant when making mirrors
* that are not exactly equal to the AST node (eg, omitting explicit type arguments),
* in order to check if the transformation does not change the meaning of the program.
* It verifies that method and constructor calls are overload-selected
* to the same compile-time declaration, and that nested lambdas
* have the same type as in the AST.
*
* <p>This mirror's state, as filled-in during type resolution by
* {@link Infer} using the various setters of {@link ExprMirror}
* interfaces, is compared to the AST's corresponding state. Consequently,
* if this state is missing (meaning, that no overload resolution
* has been run using this mirror), the analysis cannot be performed
* and an exception is thrown.
*
* @throws IllegalStateException If this mirror has not been used for overload resolution
*/
boolean isEquivalentToUnderlyingAst();
/** A general category of types. */
enum TypeSpecies {
PRIMITIVE,
REFERENCE,
VOID,
UNKNOWN;
public static TypeSpecies getSpecies(JTypeMirror t) {
if (t.isPrimitive()) {
return PRIMITIVE;
} else if (t.isVoid()) {
return VOID;
} else if (TypeOps.isSpecialUnresolved(t)) {
return UNKNOWN;
}
return REFERENCE;
}
}
interface PolyExprMirror extends ExprMirror {
/**
* Returns the class declaration wherein this invocation occurs.
* Returns null if it's unresolved.
*/
@NonNull JClassType getEnclosingType();
@Override
default @Nullable JTypeMirror getStandaloneType() {
return null;
}
/**
* If inference failed to determine the type of this node, returns
* a fallback for it. This should not query the context of the expression,
* or nodes whose type is unstable because it may be being inferred.
*
* <p>If no fallback should be used, returns null.
*/
default @Nullable JTypeMirror unresolvedType() {
return null;
}
}
/** Mirrors a conditional or switch expression. */
interface BranchingMirror extends PolyExprMirror {
/**
* Returns true if every result expression matches the given
* predicate.
*/
boolean branchesMatch(Predicate<? super ExprMirror> condition);
/**
* Record on the AST node that is is a standalone expression.
* This accounts for special cases in the spec which are made
* for numeric and boolean conditional expressions. For those
* types of standalone exprs, the branches may have an additional
* implicit unboxing/widening conversion, that does not depend
* on the usual target type (the context of the ternary itself),
* but just on the other branch.
*/
default void setStandalone() {
// do nothing by default
}
@Override
default boolean isEquivalentToUnderlyingAst() {
return branchesMatch(ExprMirror::isEquivalentToUnderlyingAst);
}
}
/**
* Mirror of some expression that targets a functional interface type:
* lambda or method reference.
*/
interface FunctionalExprMirror extends PolyExprMirror {
/**
* For a method ref or lambda, this is the type of the functional interface.
* E.g. in {@code stringStream.map(String::isEmpty)}, this is
* {@code java.util.function.Function<java.lang.String, java.lang.Boolean>}
*
* <p>May be null if we're resetting some partial data.
*/
@Override
void setInferredType(@Nullable JTypeMirror mirror);
/**
* This is the method that is overridden in getInferredType.
* E.g. in {@code stringStream.map(String::isEmpty)}, this is
* {@code java.util.function.Function<java.lang.String, java.lang.Boolean>.apply(java.lang.String) ->
* java.lang.Boolean}
*
* <p>May be null if we're resetting some partial data.
*/
void setFunctionalMethod(@Nullable JMethodSig methodType);
}
/**
* Mirror of a method reference expression.
*/
interface MethodRefMirror extends FunctionalExprMirror {
/** True if this references a ctor. */
boolean isConstructorRef();
/**
* Returns the type to search as defined by the first section of
* <a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.13.1">JLS§15.13.1</a>
* , except it may also return an array type (the jls makes an exception for it,
* while we don't).
*/
JTypeMirror getTypeToSearch();
/**
* Returns the type of the left hand-side, if it is not an expression.
* Note that the following qualifier super forms are considered "expressions",
* that have a context-dependent type (depends on the type of the {@code this} expr):
* <pre>
* super :: [TypeArguments] Identifier
* TypeName.super :: [TypeArguments] Identifier
* </pre>
*/
@Nullable
JTypeMirror getLhsIfType();
/**
* Returns the name of the invoked method, or {@link JConstructorSymbol#CTOR_NAME}
* if this is a constructor reference.
*/
String getMethodName();
/** Returns the explicit type arguments (the ones to the right of the "::"). */
@NonNull List<JTypeMirror> getExplicitTypeArguments();
/**
* This is the method that is referenced.
* E.g. in {@code stringStream.map(String::isEmpty)}, this is
* {@code java.lang.String.isEmpty() -> boolean}
*/
void setCompileTimeDecl(JMethodSig methodType);
/**
* UNRESOLVED_METHOD if not yet computed, null if computed but
* inexact, otherwise the real method.
*/
@Nullable
JMethodSig getCachedExactMethod();
void setCachedExactMethod(@Nullable JMethodSig sig);
}
/** Mirrors a lambda expression. */
interface LambdaExprMirror extends FunctionalExprMirror {
/**
* Returns the types of the explicit parameters. If the lambda
* is implicitly typed, then returns null.
*
* <p>Note that a degenerate case of explicitly typed lambda
* expression is a lambda with zero formal parameters.
*/
@Nullable List<JTypeMirror> getExplicitParameterTypes();
/**
* See {@link #getExplicitParameterTypes()}.
*/
default boolean isExplicitlyTyped() {
return getExplicitParameterTypes() != null;
}
/**
* Return the number of parameters of the lambda, regardless of
* whether it's explicitly typed or not.
*/
int getParamCount();
/**
* Returns all the expressions that appear in {@code return}
* statements within the lambda. If this is an expression-bodied
* lambda, returns the expression.
*/
Iterable<ExprMirror> getResultExpressions();
/**
* Returns true if the body is value-compatible {@literal (JLS§15.27.2)}.
* <blockquote>
* A block lambda body is value-compatible if it cannot complete
* normally (§14.21) and every return statement in the block
* has the form return Expression;.
* </blockquote>
*/
boolean isValueCompatible();
/**
* Returns true if the body is void-compatible {@literal (JLS§15.27.2)}.
* <blockquote>
* A block lambda body is void-compatible if every return
* statement in the block has the form return;.
* </blockquote>
*/
boolean isVoidCompatible();
void updateTypingContext(JMethodSig groundFun);
}
/**
* Adapter over a method or constructor invocation expression.
*/
interface InvocationMirror extends PolyExprMirror {
/**
* Enumerates *accessible* method (or ctor) signatures with
* *the same name* as this invocation. Name and accessibility
* will not be checked later.
*
* The details on how to determine this are here:
*
* https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.12.1
*/
Iterable<JMethodSig> getAccessibleCandidates();
/**
* Returns the erased receiver type. This is only used to adapt the
* {@code Object::getClass} method, other types of invocations don't
* need to implement this.
*/
default @Nullable JTypeMirror getErasedReceiverType() {
return null;
}
/**
* Returns the erased receiver type. This is only used for method
* invocations.
*/
@Nullable JTypeMirror getReceiverType();
/**
* Returns the explicit type arguments, eg in {@code Arrays.<String>asList("q")},
* or {@code new <String> Foo("q")}. If none are mentioned, returns an empty list.
*/
List<JTypeMirror> getExplicitTypeArguments();
/**
* @throws IndexOutOfBoundsException If there's no explicit type argument at the given index
*/
JavaNode getExplicitTargLoc(int i);
/**
* Returns the name of the invoked method. If this is a
* constructor call, returns {@link JConstructorSymbol#CTOR_NAME}.
*/
String getName();
/** Returns the expressions corresponding to the arguments of the call. */
List<ExprMirror> getArgumentExpressions();
int getArgumentCount();
void setCtDecl(MethodCtDecl methodType);
/**
* Returns the method type set with {@link #setCtDecl(MethodCtDecl)}
* or null if that method was never called. This is used to perform
* overload resolution exactly once per call site.
*/
@Nullable MethodCtDecl getCtDecl();
/**
* Information about the overload-resolution for a specific method.
*/
class MethodCtDecl implements OverloadSelectionResult {
// note this data is gathered by the MethodCallSite during
// applicability inference, stashed in this object, and
// restored when we do invocation.
private final JMethodSig methodType;
private final MethodResolutionPhase resolvePhase;
private final boolean canSkipInvocation;
private final boolean needsUncheckedConversion;
private final boolean failed;
MethodCtDecl(JMethodSig methodType,
MethodResolutionPhase resolvePhase,
boolean canSkipInvocation,
boolean needsUncheckedConversion,
boolean failed) {
this.methodType = methodType;
this.resolvePhase = resolvePhase;
this.canSkipInvocation = canSkipInvocation;
this.needsUncheckedConversion = needsUncheckedConversion;
this.failed = failed;
}
// package-private:
MethodCtDecl withMethod(JMethodSig method) {
return withMethod(method, failed);
}
MethodCtDecl withMethod(JMethodSig method, boolean failed) {
return new MethodCtDecl(method, resolvePhase, canSkipInvocation, needsUncheckedConversion, failed);
}
MethodCtDecl asFailed() {
return withMethod(methodType, true);
}
boolean canSkipInvocation() {
return canSkipInvocation;
}
MethodResolutionPhase getResolvePhase() {
return resolvePhase;
}
static MethodCtDecl unresolved(TypeSystem ts) {
return new MethodCtDecl(ts.UNRESOLVED_METHOD, STRICT, true, false, true);
}
// public:
@Override
public JMethodSig getMethodType() {
return methodType;
}
@Override
public boolean needsUncheckedConversion() {
return needsUncheckedConversion;
}
@Override
public boolean isVarargsCall() {
return resolvePhase.requiresVarargs();
}
@Override
public JTypeMirror ithFormalParam(int i) {
return resolvePhase.ithFormal(getMethodType().getFormalParameters(), i);
}
@Override
public boolean isFailed() {
return failed;
}
@Override
public String toString() {
return "CtDecl[phase=" + resolvePhase + ", method=" + methodType + ']';
}
}
}
/**
* An invocation mirror reflecting a constructor invocation expression.
*/
interface CtorInvocationMirror extends InvocationMirror {
/**
* Return the type name being instantiated. If the constructor call
* is a diamond invocation (or no type args), returns the generic type declaration.
* Otherwise returns the parameterised type. If the call declares
* an anonymous class, then this does *not* return the anonymous
* type, but its explicit supertype.
*
* <ul>
* <li>e.g. for {@code new ArrayList<>()}, returns {@code ArrayList<T>}.
* <li>e.g. for {@code new ArrayList()}, returns {@code ArrayList}.
* <li>e.g. for {@code new ArrayList<String>()}, returns {@code ArrayList<String>}.
* <li>e.g. for {@code new Runnable() {}} (anonymous), returns {@code Runnable}.
* </ul>
*
* <p>Note that this returns a {@link JClassType} in valid code.
* Other return values may be eg {@link TypeSystem#UNKNOWN}, or
* a {@link JTypeVar}, but indicate malformed code.
*/
@NonNull JTypeMirror getNewType();
/**
* True if this creates an anonymous class. Since java 9 those
* can also be diamond-inferred.
*/
boolean isAnonymous();
/**
* Return true if this is a diamond constructor call. In that
* case the type parameters of the created instance must be inferred.
* Returns false if the constructor call mentions no type arguments.
* <ul>
* <li>e.g. for {@code new ArrayList<>()}, returns true.
* <li>e.g. for {@code new ArrayList()}, returns false.
* <li>e.g. for {@code new ArrayList<String>()}, returns false.
* </ul>
*/
boolean isDiamond();
/**
* {@inheritDoc}
*
* <p>Returns the constructor of the {@link #getNewType()}. If
* this is an anonymous class declaration implementing an interface,
* then returns the constructors of class {@link Object}.
*
* <p>This default implementation uses {@link #getAccessibleCandidates(JTypeMirror)},
* which should be implemented instead.
*/
@Override
default Iterable<JMethodSig> getAccessibleCandidates() {
return getAccessibleCandidates(getNewType());
}
/**
* Returns the accessible candidates for this node, as if {@link #getNewType()}
* returned the type passed as parameter. Since candidates depend on the
* new type, this allows us to write simple "spy" wrappers to redo an invocation
* in different conditions (ie, pretending the newtype is the parameter)
*
* @param newType Assumed value of {@link #getNewType()}
*/
Iterable<JMethodSig> getAccessibleCandidates(JTypeMirror newType);
/** Must return {@link JConstructorSymbol#CTOR_NAME}. */
@Override
default String getName() {
return JConstructorSymbol.CTOR_NAME;
}
}
}
| 20,842 | 34.20777 | 115 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/MethodResolutionPhase.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import net.sourceforge.pmd.lang.java.types.JArrayType;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
/**
* @author Clément Fournier
*/
enum MethodResolutionPhase {
/** No boxing is allowed, arity must match. */
STRICT,
/** Boxing required, arity must match. */
LOOSE,
/**
* Boxing required, arity is extended for varargs.
* If a non-varargs method failed the LOOSE phase,
* it has no chance of succeeding in VARARGS phase.
*/
VARARGS {
@Override
public JTypeMirror ithFormal(List<JTypeMirror> formals, int i) {
assert i >= 0;
if (i >= formals.size() - 1) {
JTypeMirror lastFormal = formals.get(formals.size() - 1);
return ((JArrayType) lastFormal).getComponentType();
}
return formals.get(i);
}
},
INVOC_STRICT,
INVOC_LOOSE,
INVOC_VARARGS {
@Override
public JTypeMirror ithFormal(List<JTypeMirror> formals, int i) {
return VARARGS.ithFormal(formals, i);
}
};
/**
* Phases used to determine applicability.
*/
static final Set<MethodResolutionPhase> APPLICABILITY_TESTS = EnumSet.of(STRICT, LOOSE, VARARGS);
/**
* For non-varargs phases, returns the type of the ith parameter.
* For varargs phases, returns the ith variable arity parameter type
* (https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2.4).
*
* <p>The index i starts at 0, while in the JLS it starts at 1.
*/
public JTypeMirror ithFormal(List<JTypeMirror> formals, int i) {
assert i >= 0 && i < formals.size();
return formals.get(i);
}
MethodResolutionPhase asInvoc() {
switch (this) {
case STRICT:
return INVOC_STRICT;
case LOOSE:
return INVOC_LOOSE;
case VARARGS:
return INVOC_VARARGS;
default:
return this;
}
}
boolean requiresVarargs() {
return this == INVOC_VARARGS || this == VARARGS;
}
boolean canBox() {
return this != STRICT;
}
/**
* Last step, performed on the most specific applicable method.
* This adds constraints on the arguments that are not
* pertinent to applicability to infer all the tvars.
*/
boolean isInvocation() {
return this == INVOC_STRICT || this == INVOC_LOOSE || this == INVOC_VARARGS;
}
}
| 2,703 | 26.591837 | 101 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/OverloadSet.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import static net.sourceforge.pmd.lang.java.types.TypeOps.areOverrideEquivalent;
import static net.sourceforge.pmd.util.OptionalBool.NO;
import static net.sourceforge.pmd.util.OptionalBool.UNKNOWN;
import static net.sourceforge.pmd.util.OptionalBool.YES;
import static net.sourceforge.pmd.util.OptionalBool.definitely;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.stream.Collector;
import org.apache.commons.lang3.NotImplementedException;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
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.TypeOps;
import net.sourceforge.pmd.util.OptionalBool;
/**
* Tracks a set of overloads, automatically pruning override-equivalent
* methods if possible.
*/
public abstract class OverloadSet<T> {
private final List<T> overloads = new ArrayList<>();
OverloadSet() {
// package-private
}
void add(T sig) {
ListIterator<T> iterator = overloads.listIterator();
while (iterator.hasNext()) {
T existing = iterator.next();
switch (shouldTakePrecedence(existing, sig)) {
case YES:
// new sig is less specific than an existing one, don't add it
return;
case NO:
// new sig is more specific than an existing one
iterator.remove();
break;
case UNKNOWN:
// neither sig is more specific
break;
default:
throw new AssertionError();
}
}
overloads.add(sig);
}
protected abstract OptionalBool shouldTakePrecedence(T m1, T m2);
List<T> getOverloadsMutable() {
return overloads;
}
boolean nonEmpty() {
return !overloads.isEmpty();
}
/**
* Returns a collector that can apply to a stream of method signatures,
* and that collects them into a set of method, where none override one another.
* Do not use this in a parallel stream. Do not use this to collect constructors.
* Do not use this if your stream contains methods that have different names.
*
* @param commonSubtype Site where the signatures are observed. The owner of every method
* in the stream must be a supertype of this type
*
* @return A collector
*/
public static Collector<JMethodSig, ?, List<JMethodSig>> collectMostSpecific(JTypeMirror commonSubtype) {
return Collector.of(
() -> new ContextIndependentSet(commonSubtype),
OverloadSet::add,
(left, right) -> {
throw new NotImplementedException("Cannot use this in a parallel stream");
},
o -> Collections.unmodifiableList(o.getOverloadsMutable())
);
}
static final class ContextIndependentSet extends OverloadSet<JMethodSig> {
private final JTypeMirror viewingSite;
private String name;
ContextIndependentSet(JTypeMirror viewingSite) {
this.viewingSite = viewingSite;
}
@Override
protected OptionalBool shouldTakePrecedence(JMethodSig m1, JMethodSig m2) {
return areOverrideEquivalent(m1, m2)
? shouldAlwaysTakePrecedence(m1, m2, viewingSite)
: OptionalBool.UNKNOWN;
}
@Override
void add(JMethodSig sig) {
if (name == null) {
name = sig.getName();
}
assert sig.getName().equals(name) : "Not the right name!";
assert !sig.isConstructor() : "Constructors they cannot override each other";
super.add(sig);
}
}
/**
* Given that m1 and m2 are override-equivalent, should m1 be chosen
* over m2 (YES/NO), for ANY call expression, or could both be applicable
* given suitable expressions. This handles a few cases about shadowing/overriding/hiding
* that are not covered strictly by the definition of "specificity".
*
* <p>If m1 and m2 are equal, returns the first one by convention.
*/
static OptionalBool shouldAlwaysTakePrecedence(@NonNull JMethodSig m1, @NonNull JMethodSig m2, @NonNull JTypeMirror commonSubtype) {
// select
// 1. the non-bridge
// 2. the one that overrides the other
// 3. the non-abstract method
// Symbols don't reflect bridge methods anymore
// if (m1.isBridge() != m2.isBridge()) {
// return definitely(!m1.isBridge());
// } else
if (TypeOps.overrides(m1, m2, commonSubtype)) {
return YES;
} else if (TypeOps.overrides(m2, m1, commonSubtype)) {
return NO;
} else if (m1.isAbstract() ^ m2.isAbstract()) {
return definitely(!m1.isAbstract());
} else if (m1.isAbstract() && m2.isAbstract()) { // last ditch effort
// both are unrelated abstract, inherited into 'site'
// their signature would be merged into the site
// if exactly one is declared in a class, prefer it
// if both are declared in a class, ambiguity error (recall, neither overrides the other)
// if both are declared in an interface, select any of them
boolean m1InClass = m1.getSymbol().getEnclosingClass().isClass();
boolean m2Class = m2.getSymbol().getEnclosingClass().isClass();
return m1InClass && m2Class ? UNKNOWN : definitely(m1InClass);
}
if (Modifier.isPrivate(m1.getModifiers() | m2.getModifiers())
&& commonSubtype instanceof JClassType) {
// One of them is private, which means, they can't be overridden,
// so they failed the above test
// Maybe it's shadowing then
return shadows(m1, m2, (JClassType) commonSubtype);
}
return UNKNOWN;
}
/**
* Returns whether m1 shadows m2 in the body of the given site, ie
* m1 is declared in a class C1 that encloses the site, and m2 is declared
* in a type that strictly encloses C1.
*
* <p>Assumes m1 and m2 are override-equivalent, and declared in different
* classes.
*/
// test only
static OptionalBool shadows(JMethodSig m1, JMethodSig m2, JClassType site) {
final JClassSymbol c1 = m1.getSymbol().getEnclosingClass();
final JClassSymbol c2 = m2.getSymbol().getEnclosingClass();
// We go outward from the `site`. The height measure is the distance
// from the site (ie, the reverted depth of each class)
int height = 0;
int c1Height = -1;
int c2Height = -1;
JClassSymbol c = site.getSymbol();
while (c != null) {
if (c.equals(c1)) {
c1Height = height;
}
if (c.equals(c2)) {
c2Height = height;
}
c = c.getEnclosingClass();
height++;
}
if (c1Height < 0 || c2Height < 0 || c1Height == c2Height) {
return UNKNOWN;
}
return definitely(c1Height < c2Height);
}
}
| 7,609 | 34.896226 | 136 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ExprOps.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import static net.sourceforge.pmd.lang.java.types.TypeConversion.capture;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
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.JMethodSig;
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;
import net.sourceforge.pmd.lang.java.types.TypingContext;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.BranchingMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.FunctionalExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.InvocationMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.InvocationMirror.MethodCtDecl;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.LambdaExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.MethodRefMirror;
import net.sourceforge.pmd.util.CollectionUtil;
@SuppressWarnings("PMD.CompareObjectsWithEquals")
final class ExprOps {
private final Infer infer;
private final TypeSystem ts;
ExprOps(Infer infer) {
this.infer = infer;
this.ts = infer.getTypeSystem();
assert ts != null;
}
/**
* Returns true if the argument expression is potentially
* compatible with type t, as specified by JLS§15.12.2.1:
*
* https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.12.1
*
* @param m Method for which the potential applicability is being tested
* @param e Argument expression
* @param t Formal parameter type
*/
boolean isPotentiallyCompatible(JMethodSig m, ExprMirror e, JTypeMirror t) {
if (e instanceof BranchingMirror) {
// A conditional expression (§15.25) is potentially compatible with a type if each
// of its second and third operand expressions are potentially compatible with that type.
BranchingMirror cond = (BranchingMirror) e;
return cond.branchesMatch(branch -> isPotentiallyCompatible(m, branch, t));
}
boolean isLambdaOrRef = e instanceof FunctionalExprMirror;
if (isLambdaOrRef) {
if (t instanceof JTypeVar) {
// A lambda expression or a method reference expression is potentially compatible with
// a type variable if the type variable is a type parameter of the candidate method.
return m.getTypeParameters().contains(t);
}
JMethodSig fun = TypeOps.findFunctionalInterfaceMethod(t);
if (fun == null) {
// t is not a functional interface
return false;
}
if (e instanceof LambdaExprMirror) {
LambdaExprMirror lambda = (LambdaExprMirror) e;
if (fun.getArity() != lambda.getParamCount()) {
return false;
}
boolean expectsVoid = fun.getReturnType() == ts.NO_TYPE;
return expectsVoid && lambda.isVoidCompatible() || lambda.isValueCompatible();
} else {
// is method reference
// TODO need to look for potentially applicable methods
return true;
}
}
// A class instance creation expression, a method invocation expression, or an expression of
// a standalone form (§15.2) is potentially compatible with any type.
// (ie anything else)
return true;
}
/**
* Returns true if the the argument expression is pertinent
* to applicability for the potentially applicable method m,
* called at site 'invoc', as specified by JLS§15.12.2.2:
*
* https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.12.2.2
*
* @param arg Argument expression
* @param m Method type
* @param formalType Type of the formal parameter
* @param invoc Invocation expression
*/
static boolean isPertinentToApplicability(ExprMirror arg, JMethodSig m, JTypeMirror formalType, InvocationMirror invoc) {
// An argument expression is considered pertinent to applicability
// for a potentially applicable method m unless it has one of the following forms:
if (arg instanceof LambdaExprMirror) {
LambdaExprMirror lambda = (LambdaExprMirror) arg;
// An implicitly typed lambda expression(§ 15.27 .1).
if (!lambda.isExplicitlyTyped()) {
return false;
}
// An explicitly typed lambda expression where at least
// one result expression is not pertinent to applicability.
for (ExprMirror it : lambda.getResultExpressions()) {
if (!isPertinentToApplicability(it, m, formalType, invoc)) {
return false;
}
}
// If m is a generic method and the method invocation does
// not provide explicit type arguments, an explicitly typed
// lambda expression for which the corresponding target type
// (as derived from the signature of m) is a type parameter of m.
return !m.isGeneric()
|| !invoc.getExplicitTypeArguments().isEmpty()
|| !formalType.isTypeVariable();
}
if (arg instanceof MethodRefMirror) {
// An inexact method reference expression(§ 15.13 .1).
return getExactMethod((MethodRefMirror) arg) != null
// If m is a generic method and the method invocation does
// not provide explicit type arguments, an exact method
// reference expression for which the corresponding target type
// (as derived from the signature of m) is a type parameter of m.
&& (!m.isGeneric()
|| !invoc.getExplicitTypeArguments().isEmpty()
|| !formalType.isTypeVariable());
}
if (arg instanceof BranchingMirror) {
// A conditional expression (§15.25) is potentially compatible with a type if each
// of its second and third operand expressions are potentially compatible with that type.
BranchingMirror cond = (BranchingMirror) arg;
return cond.branchesMatch(branch -> isPertinentToApplicability(branch, m, formalType, invoc));
}
return true;
}
/**
* Returns null if the method reference is inexact.
*/
static @Nullable JMethodSig getExactMethod(MethodRefMirror mref) {
JMethodSig cached = mref.getCachedExactMethod();
if (cached == null) { // inexact
return null;
}
if (cached.getTypeSystem().UNRESOLVED_METHOD == cached) {
cached = computeExactMethod(mref);
mref.setCachedExactMethod(cached); // set to null if inexact, sentinel is UNRESOLVED_METHOD
}
return cached;
}
private static @Nullable JMethodSig computeExactMethod(MethodRefMirror mref) {
final @Nullable JTypeMirror lhs = mref.getLhsIfType();
List<JMethodSig> accessible;
if (mref.isConstructorRef()) {
if (lhs == null) {
// ct error, already reported as a missing symbol in our system
return null;
} else if (lhs.isArray()) {
// A method reference expression of the form ArrayType :: new is always exact.
// But: If a method reference expression has the form ArrayType :: new, then ArrayType
// must denote a type that is reifiable (§4.7), or a compile-time error occurs.
if (lhs.isReifiable()) {
JTypeDeclSymbol symbol = lhs.getSymbol();
assert symbol instanceof JClassSymbol && ((JClassSymbol) symbol).isArray()
: "Reifiable array should present a symbol! " + lhs;
return lhs.getConstructors().get(0);
} else {
// todo compile time error
return null;
}
} else {
if (lhs.isRaw() || !(lhs instanceof JClassType)) {
return null;
}
accessible = TypeOps.filterAccessible(lhs.getConstructors(),
mref.getEnclosingType().getSymbol());
}
} else {
JClassType enclosing = mref.getEnclosingType();
accessible = mref.getTypeToSearch()
.streamMethods(TypeOps.accessibleMethodFilter(mref.getMethodName(), enclosing.getSymbol()))
.collect(OverloadSet.collectMostSpecific(enclosing));
}
if (accessible.size() == 1) {
JMethodSig candidate = accessible.get(0);
if (candidate.isVarargs()
|| candidate.isGeneric() && mref.getExplicitTypeArguments().isEmpty()) {
return null;
}
candidate = candidate.subst(Substitution.mapping(candidate.getTypeParameters(), mref.getExplicitTypeArguments()));
if (lhs != null && lhs.isRaw()) {
// can be raw if the method doesn't mention type vars
// of the original owner, ie the erased method is the
// same as the generic method.
JClassType lhsClass = (JClassType) candidate.getDeclaringType();
JMethodSig unerased = candidate.internalApi().withOwner(lhsClass.getGenericTypeDeclaration()).internalApi().originalMethod();
if (TypeOps.mentionsAny(unerased, lhsClass.getFormalTypeParams())) {
return null;
}
}
// For exact method references, the return type is Class<? extends T> (no erasure).
// So it's mref::getTypeToSearch and not mref.getTypeToSearch()::getErasure
return adaptGetClass(candidate, mref::getTypeToSearch);
} else {
return null;
}
}
// for inexact method refs
@Nullable MethodCtDecl findInexactMethodRefCompileTimeDecl(MethodRefMirror mref, JMethodSig targetType) {
// https://docs.oracle.com/javase/specs/jls/se14/html/jls-15.html#jls-15.13.1
JTypeMirror lhsIfType = mref.getLhsIfType();
boolean acceptLowerArity = lhsIfType != null && lhsIfType.isClassOrInterface() && !mref.isConstructorRef();
MethodCallSite site1 = infer.newCallSite(methodRefAsInvocation(mref, targetType, false), null);
site1.setLogging(!acceptLowerArity); // if we do only one search, then failure matters
MethodCtDecl ctd1 = infer.determineInvocationTypeOrFail(site1);
JMethodSig m1 = ctd1.getMethodType();
if (acceptLowerArity) {
// then we need to perform two searches, one with arity n, looking for static methods,
// one with n-1, looking for instance methods
MethodCallSite site2 = infer.newCallSite(methodRefAsInvocation(mref, targetType, true), null);
site2.setLogging(false);
MethodCtDecl ctd2 = infer.determineInvocationTypeOrFail(site2);
JMethodSig m2 = ctd2.getMethodType();
// If the first search produces a most specific method that is static,
// and the set of applicable methods produced by the second search
// contains no non-static methods, then the compile-time declaration
// is the most specific method of the first search.
if (m1 != ts.UNRESOLVED_METHOD && m1.isStatic() && (m2 == ts.UNRESOLVED_METHOD || m2.isStatic())) {
return ctd1;
} else if (m2 != ts.UNRESOLVED_METHOD && !m2.isStatic() && (m1 == ts.UNRESOLVED_METHOD || !m1.isStatic())) {
// Otherwise, if the set of applicable methods produced by the
// first search contains no static methods, and the second search
// produces a most specific method that is non-static, then the
// compile-time declaration is the most specific method of the second search.
return ctd2;
}
// Otherwise, there is no compile-time declaration.
return null;
} else if (m1 == ts.UNRESOLVED_METHOD || m1.isStatic()) {
// if the most specific applicable method is static, there is no compile-time declaration.
return null;
} else {
// Otherwise, the compile-time declaration is the most specific applicable method.
return ctd1;
}
}
static InvocationMirror methodRefAsInvocation(final MethodRefMirror mref, JMethodSig targetType, boolean asInstanceMethod) {
// the arguments are treated as if they were of the type
// of the formal parameters of the candidate
List<JTypeMirror> formals = targetType.getFormalParameters();
if (asInstanceMethod && !formals.isEmpty()) {
formals = formals.subList(1, formals.size()); // skip first param (receiver)
}
List<ExprMirror> arguments = CollectionUtil.map(
formals,
fi -> new ExprMirror() {
@Override
public void setInferredType(JTypeMirror mirror) {
// do nothing
}
@Override
public @Nullable JTypeMirror getInferredType() {
throw new UnsupportedOperationException();
}
@Override
public JavaNode getLocation() {
return mref.getLocation();
}
@Override
public JTypeMirror getStandaloneType() {
return fi;
}
@Override
public String toString() {
return "formal : " + fi;
}
@Override
public TypingContext getTypingContext() {
return mref.getTypingContext();
}
@Override
public boolean isEquivalentToUnderlyingAst() {
throw new UnsupportedOperationException("Cannot invoque isSemanticallyEquivalent on this mirror, it doesn't have a backing AST node: " + this);
}
}
);
return new InvocationMirror() {
private MethodCtDecl mt;
@Override
public JavaNode getLocation() {
return mref.getLocation();
}
@Override
public Iterable<JMethodSig> getAccessibleCandidates() {
return ExprOps.getAccessibleCandidates(mref, asInstanceMethod, targetType);
}
@Override
public JTypeMirror getErasedReceiverType() {
return mref.getTypeToSearch().getErasure();
}
@Override
public @Nullable JTypeMirror getReceiverType() {
return mref.getTypeToSearch();
}
@Override
public List<JTypeMirror> getExplicitTypeArguments() {
return mref.getExplicitTypeArguments();
}
@Override
public JavaNode getExplicitTargLoc(int i) {
throw new IndexOutOfBoundsException();
}
@Override
public String getName() {
return mref.getMethodName();
}
@Override
public List<ExprMirror> getArgumentExpressions() {
return arguments;
}
@Override
public int getArgumentCount() {
return arguments.size();
}
@Override
public void setCtDecl(MethodCtDecl methodType) {
this.mt = methodType;
}
@Override
public @Nullable MethodCtDecl getCtDecl() {
return mt;
}
JTypeMirror inferred;
@Override
public void setInferredType(JTypeMirror mirror) {
// todo is this useful for method refs?
inferred = mirror;
}
@Override
public JTypeMirror getInferredType() {
return inferred;
}
@Override
public @NonNull JClassType getEnclosingType() {
return mref.getEnclosingType();
}
@Override
public String toString() {
return "Method ref adapter (for " + mref + ")";
}
@Override
public TypingContext getTypingContext() {
return mref.getTypingContext();
}
@Override
public boolean isEquivalentToUnderlyingAst() {
throw new UnsupportedOperationException("Cannot invoque isSemanticallyEquivalent on this mirror, it doesn't have a backing AST node: " + this);
}
};
}
private static Iterable<JMethodSig> getAccessibleCandidates(MethodRefMirror mref, boolean asInstanceMethod, JMethodSig targetType) {
JMethodSig exactMethod = getExactMethod(mref);
if (exactMethod != null) {
return Collections.singletonList(exactMethod);
} else {
final JTypeMirror actualTypeToSearch;
{
JTypeMirror typeToSearch = mref.getTypeToSearch();
if (typeToSearch.isArray() && mref.isConstructorRef()) {
// ArrayType :: new
return typeToSearch.getConstructors();
} else if (typeToSearch instanceof JClassType && mref.isConstructorRef()) {
// ClassType :: [TypeArguments] new
// TODO treatment of raw constructors is whacky
return TypeOps.lazyFilterAccessible(typeToSearch.getConstructors(), mref.getEnclosingType().getSymbol());
}
if (asInstanceMethod && typeToSearch.isRaw() && typeToSearch instanceof JClassType
&& targetType.getArity() > 0) {
// In the second search, if P1, ..., Pn is not empty
// and P1 is a subtype of ReferenceType, then the
// method reference expression is treated as if it were
// a method invocation expression with argument expressions
// of types P2, ..., Pn. If ReferenceType is a raw type,
// and there exists a parameterization of this type, G<...>,
// that is a supertype of P1, the type to search is the result
// of capture conversion (§5.1.10) applied to G<...>; otherwise,
// the type to search is the same as the type of the first search.
JClassType type = (JClassType) typeToSearch;
JTypeMirror p1 = targetType.getFormalParameters().get(0);
JTypeMirror asSuper = p1.getAsSuper(type.getSymbol());
if (asSuper != null && asSuper.isParameterizedType()) {
typeToSearch = capture(asSuper);
}
}
actualTypeToSearch = typeToSearch;
}
// Primary :: [TypeArguments] Identifier
// ExpressionName :: [TypeArguments] Identifier
// super :: [TypeArguments] Identifier
// TypeName.super :: [TypeArguments] Identifier
// ReferenceType :: [TypeArguments] Identifier
boolean acceptsInstanceMethods = canUseInstanceMethods(actualTypeToSearch, targetType, mref);
Predicate<JMethodSymbol> prefilter = TypeOps.accessibleMethodFilter(mref.getMethodName(), mref.getEnclosingType().getSymbol())
.and(m -> Modifier.isStatic(m.getModifiers())
|| acceptsInstanceMethods);
return actualTypeToSearch.streamMethods(prefilter).collect(Collectors.toList());
}
}
private static boolean canUseInstanceMethods(JTypeMirror typeToSearch, JMethodSig sig, MethodRefMirror mref) {
// For example, if you write
// stringStream.map(Objects::toString),
// The type to search is Objects. But Objects inherits Object.toString(),
// which could not be called on a string (String.toString() != Objects.toString()).
if (mref.getLhsIfType() != null && !sig.getFormalParameters().isEmpty()) {
// ReferenceType :: [TypeArguments] Identifier
JTypeMirror firstFormal = sig.getFormalParameters().get(0);
return firstFormal.isSubtypeOf(typeToSearch);
}
return true;
}
/**
* Calls to {@link Object#getClass()} on a type {@code T} have type
* {@code Class<? extends |T|>}. If the selected method is that method, then
* we need to replace its return type (the symbol has return type {@link Object}).
*
* <p>For exact method reference expressions, the type is {@code <? extends T>} (no erasure).
*
* @param sig Selected signature
* @param replacementReturnType Lazily created, because in many cases it's not necessary
*
* @return Signature, adapted if it is {@link Object#getClass()}
*/
static JMethodSig adaptGetClass(JMethodSig sig, Supplier<JTypeMirror> replacementReturnType) {
TypeSystem ts = sig.getTypeSystem();
if ("getClass".equals(sig.getName()) && sig.getDeclaringType().equals(ts.OBJECT)) {
return sig.internalApi().withReturnType(getClassReturn(replacementReturnType.get(), ts)).internalApi().markAsAdapted();
}
return sig;
}
private static JTypeMirror getClassReturn(JTypeMirror erasedReceiverType, TypeSystem ts) {
return ts.parameterise(ts.getClassSymbol(Class.class), listOf(ts.wildcard(true, erasedReceiverType)));
}
static boolean isContextDependent(JMethodSig m) {
m = m.internalApi().adaptedMethod();
return m.isGeneric() && TypeOps.mentionsAny(m.getReturnType(), m.getTypeParameters());
}
}
| 23,336 | 41.200723 | 163 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ReductionStep.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.TypeOps;
import net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar.BoundKind;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* Reduction steps on a variable. If its bounds match a certain pattern,
* it will be instantiated by one of these reductions.
*/
enum ReductionStep {
/**
* Instantiate an inference variable using one of its equality bounds.
*/
EQ(BoundKind.EQ) {
@Override
JTypeMirror solve(InferenceVar uv, InferenceContext inferenceContext) {
return filterBounds(uv, inferenceContext).get(0);
}
},
/**
* Instantiate an inference variables using its (ground) lower bounds. Such
* bounds are merged together using lub().
*/
LOWER(BoundKind.LOWER) {
@Override
JTypeMirror solve(InferenceVar uv, InferenceContext infCtx) {
return infCtx.ts.lub(filterBounds(uv, infCtx));
}
},
/**
* Instantiate an inference variables using its (ground) upper bounds. Such
* bounds are merged together using glb().
*/
UPPER(BoundKind.UPPER) {
@Override
JTypeMirror solve(InferenceVar uv, InferenceContext infCtx) {
return infCtx.ts.glb(filterBounds(uv, infCtx));
}
},
/**
* Like the former; the only difference is that this step can only be applied
* if all upper/lower bounds are ground.
*/
CAPTURED(BoundKind.UPPER) {
@Override
public boolean accepts(InferenceVar t, InferenceContext inferenceContext) {
return t.isCaptured()
&& inferenceContext.areAllGround(t.getBounds(BoundKind.LOWER))
&& inferenceContext.areAllGround(t.getBounds(BoundKind.UPPER));
}
@Override
JTypeMirror solve(InferenceVar uv, InferenceContext infCtx) {
JTypeMirror upper = !UPPER.filterBounds(uv, infCtx).isEmpty()
? UPPER.solve(uv, infCtx)
: infCtx.ts.OBJECT;
JTypeMirror lower = !LOWER.filterBounds(uv, infCtx).isEmpty()
? LOWER.solve(uv, infCtx)
: infCtx.ts.NULL_TYPE;
return uv.getBaseVar().cloneWithBounds(lower, upper);
}
},
/**
* Special case of {@link #UPPER}, that applies to f-bounds.
* This is just spitballing, Javac doesn't do this.
*
* I use this for fbounds, like a context that has stuff like this
* {@code β { β <: java.lang.Enum<β> } }. These usually get more bounds
* via arguments, but unchecked casts may deny a more specific bound.
* This should probably only apply when the call site doesn't need unchecked
* conversions. This is a
*/
FBOUND(BoundKind.UPPER) {
@Override
public boolean accepts(InferenceVar t, InferenceContext inferenceContext) {
Set<JTypeMirror> ubounds = t.getBounds(BoundKind.UPPER);
Set<InferenceVar> freeVars = inferenceContext.freeVarsIn(ubounds);
return CollectionUtil.asSingle(freeVars) == t; // NOPMD - contains only itself in its upper bounds
}
@Override
JTypeMirror solve(InferenceVar uv, InferenceContext infCtx) {
return infCtx.ts.glb(TypeOps.erase(uv.getBounds(BoundKind.UPPER)));
}
};
/**
* Sequence of steps to use in order when solving.
*/
static final List<List<ReductionStep>> WAVES =
listOf(
listOf(EQ, LOWER, UPPER, CAPTURED),
listOf(EQ, LOWER, FBOUND, UPPER, CAPTURED));
// ^^^^^^
final BoundKind kind;
ReductionStep(BoundKind kind) {
this.kind = kind;
}
/**
* Find an instantiated type for a given inference variable within
* a given inference context
*/
abstract JTypeMirror solve(InferenceVar uv, InferenceContext infCtx);
/**
* Can the inference variable be instantiated using this step?
*/
public boolean accepts(InferenceVar t, InferenceContext infCtx) {
return !t.isCaptured() && !filterBounds(t, infCtx).isEmpty();
}
protected boolean acceptsBound(JTypeMirror bound, InferenceContext infCtx) {
return infCtx.isGround(bound) && bound != infCtx.ts.NULL_TYPE; // NOPMD CompareObjectsWithEquals
}
/**
* Return the subset of ground bounds in a given bound set (i.e. eq/lower/upper)
*/
List<JTypeMirror> filterBounds(InferenceVar ivar, InferenceContext infCtx) {
List<JTypeMirror> res = new ArrayList<>();
for (JTypeMirror bound : ivar.getBounds(kind)) {
if (acceptsBound(bound, infCtx)) {
res.add(bound);
}
}
return res;
}
}
| 5,160 | 32.512987 | 110 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/VarWalkStrategy.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import net.sourceforge.pmd.lang.java.types.internal.infer.Graph.UniqueGraph;
import net.sourceforge.pmd.lang.java.types.internal.infer.Graph.Vertex;
import net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar.BoundKind;
import net.sourceforge.pmd.util.IteratorUtil;
/**
* Strategy to walk the set of remaining free variables. Interdependent
* variables must be solved together.
*/
interface VarWalkStrategy extends Iterator<Set<InferenceVar>> {
/**
* Picks the next batch of inference vars to resolve.
* Interdependent variables must be solved together.
*/
@Override
Set<InferenceVar> next();
/**
* Returns true if there is no more batch to process.
*/
@Override
boolean hasNext();
/**
* Walk a DAG of the dependencies. Building the model is
* is linear instead of exponential like for the other strategy.
*/
class GraphWalk implements VarWalkStrategy {
private final Iterator<Set<InferenceVar>> iterator;
GraphWalk(InferenceContext infCtx, boolean onlyBoundedVars) {
this.iterator = buildGraphIterator(infCtx, onlyBoundedVars);
}
GraphWalk(InferenceVar var) {
this.iterator = IteratorUtil.singletonIterator(Collections.singleton(var));
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Set<InferenceVar> next() {
return iterator.next();
}
Iterator<Set<InferenceVar>> buildGraphIterator(InferenceContext ctx, boolean onlyBoundedVars) {
Set<InferenceVar> freeVars = ctx.getFreeVars();
if (freeVars.isEmpty()) {
return Collections.emptyIterator();
} else if (freeVars.size() == 1) {
if (onlyBoundedVars && freeVars.iterator().next().hasOnlyPrimaryBound()) {
return Collections.emptyIterator();
}
// common case
return IteratorUtil.singletonIterator(freeVars);
}
// Builds a graph representing the dependencies
// between free ivars in the context.
Graph<InferenceVar> graph = new UniqueGraph<>();
for (InferenceVar ivar : freeVars) {
if (onlyBoundedVars && ivar.hasOnlyPrimaryBound()) {
continue;
}
Vertex<InferenceVar> vertex = graph.addLeaf(ivar);
Set<InferenceVar> dependencies = ctx.freeVarsIn(ivar.getBounds(BoundKind.ALL));
for (InferenceVar dep : dependencies) {
Vertex<InferenceVar> target = graph.addLeaf(dep);
graph.addEdge(vertex, target);
}
}
// Here, "α depends on β" is modelled by an edge α -> β
// Merge strongly connected components into a "super node".
// Eg α -> β -> α is replaced with a single node [α,β] to
// remove the cycle. Each node then has a batch of variables
// that must be solved together. The resulting graph is a
// directed acyclic graph
graph.mergeCycles();
if (graph.getVertices().size() == 1) {
// All variables are interdependent
return IteratorUtil.singletonIterator(freeVars);
}
// Next we do a topological sort of the DAG
// This means the iterator will yield batches of vars
// in such a way that if a batch A has a dependency on
// a batch B, then B will be yielded before A
// meaning we'll solve variables in the correct order,
// which also respects the JLS
return graph.topologicalSort().iterator();
}
}
}
| 4,069 | 33.201681 | 103 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ExprCheckHelper.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import static net.sourceforge.pmd.lang.java.types.TypeConversion.capture;
import static net.sourceforge.pmd.lang.java.types.TypeOps.areSameTypesInInference;
import static net.sourceforge.pmd.lang.java.types.TypeOps.asClassType;
import static net.sourceforge.pmd.lang.java.types.TypeOps.findFunctionalInterfaceMethod;
import static net.sourceforge.pmd.lang.java.types.TypeOps.mentionsAny;
import static net.sourceforge.pmd.lang.java.types.TypeOps.nonWildcardParameterization;
import static net.sourceforge.pmd.lang.java.types.internal.infer.ExprOps.methodRefAsInvocation;
import static net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar.BoundKind.EQ;
import static net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar.BoundKind.LOWER;
import static net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar.BoundKind.UPPER;
import java.util.List;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
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.JWildcardType;
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.lang.java.types.internal.infer.ExprMirror.BranchingMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.FunctionalExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.InvocationMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.InvocationMirror.MethodCtDecl;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.LambdaExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.MethodRefMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.PolyExprMirror;
import net.sourceforge.pmd.util.CollectionUtil;
@SuppressWarnings("PMD.CompareObjectsWithEquals")
final class ExprCheckHelper {
private final InferenceContext infCtx;
private final MethodResolutionPhase phase;
private final ExprChecker checker;
private final @Nullable MethodCallSite site;
private final Infer infer;
private final TypeSystem ts;
ExprCheckHelper(InferenceContext infCtx,
MethodResolutionPhase phase,
ExprChecker checker,
@Nullable MethodCallSite site,
Infer infer) {
this.infCtx = infCtx;
this.phase = phase;
this.checker = checker;
this.site = site;
this.infer = infer;
this.ts = infer.getTypeSystem();
}
/**
* Recurse on all relevant subexpressions to add constraints.
* E.g when a parameter must be a {@code Supplier<T>},
* then for the lambda {@code () -> "string"} we add a constraint
* that {@code T} must be a subtype of string.
*
* <p>Instead of gathering expressions explicitly into a bound set,
* we explore the structure of the expression and:
* 1. if it's standalone, we immediately add a constraint {@code type(<arg>) <: formalType}
* 2. otherwise, it depends on the form of the expression
* i) if it's a method or constructor invocation:
* i.i) we instantiate it. If that method is generic, we add its
* inference variables in this context and solve them globally.
* i.ii) we add a constraint linking the return type of the invocation and the formal type
* ii) if it's a lambda:
* ii.i) we ensure that the formalType is a functional interface
* ii.ii) we find the lambda's return expressions and add constraints
* on each one recursively with this algorithm.
*
*
* @param targetType Target, not necessarily ground
* @param expr Expression
*
* @return true if it's compatible (or we don't have enough info, and the check is deferred)
*
* @throws ResolutionFailedException If the expr is not compatible, and we want to add a message for the reason
*/
boolean isCompatible(JTypeMirror targetType, ExprMirror expr) {
final boolean isStandalone;
{
JTypeMirror standalone = expr.getStandaloneType();
if (standalone != null) {
if (mayMutateExpr()) {
expr.setInferredType(standalone);
expr.finishStandaloneInference(standalone);
}
isStandalone = true;
// defer check if fi is not ground
checker.checkExprConstraint(infCtx, standalone, targetType);
if (!(expr instanceof PolyExprMirror)) {
return true;
}
// otherwise fallthrough, we potentially need to finish
// inferring some things on the polys
} else {
isStandalone = false;
}
}
if (expr instanceof FunctionalExprMirror) { // those are never standalone
JClassType funType = getProbablyFunctItfType(targetType, expr);
if (funType == null) {
/*
* The functional expression has an inference variable as a target type,
* and that ivar does not have enough bounds to be resolved to a functional interface type yet.
*
* <p>This should not prevent ctdecl resolution to proceed. The additional
* bounds may be contributed by the invocation constraints of an enclosing
* inference process.
*/
infer.LOG.functionalExprNeedsInvocationCtx(targetType, expr);
return true; // deferred to invocation
}
if (expr instanceof LambdaExprMirror) {
LambdaExprMirror lambda = (LambdaExprMirror) expr;
try {
return isLambdaCompatible(funType, lambda);
} catch (ResolutionFailedException e) {
// need to cleanup the partial data
if (mayMutateExpr()) {
lambda.setInferredType(null);
lambda.setFunctionalMethod(null);
}
if (site != null) {
site.maySkipInvocation(false);
}
throw e;
}
} else {
return isMethodRefCompatible(funType, (MethodRefMirror) expr);
}
} else if (expr instanceof InvocationMirror) {
// then the argument is a poly invoc expression itself
// in that case we need to infer that as well
return isInvocationCompatible(targetType, (InvocationMirror) expr, isStandalone);
} else if (expr instanceof BranchingMirror) {
return ((BranchingMirror) expr).branchesMatch(it -> isCompatible(targetType, it));
}
return false;
}
private boolean isInvocationCompatible(JTypeMirror targetType, InvocationMirror invoc, boolean isStandalone) {
MethodCallSite nestedSite = infer.newCallSite(invoc, targetType, this.site, this.infCtx, isSpecificityCheck());
MethodCtDecl argCtDecl = infer.determineInvocationTypeOrFail(nestedSite);
JMethodSig mostSpecific = argCtDecl.getMethodType();
JTypeMirror actualType = mostSpecific.getReturnType();
if (argCtDecl == infer.FAILED_INVOCATION) {
throw ResolutionFailedException.incompatibleFormal(infer.LOG, invoc, ts.ERROR, targetType);
} else if (argCtDecl == infer.NO_CTDECL) {
JTypeMirror fallback = invoc.unresolvedType();
if (fallback != null) {
actualType = fallback;
}
// else it's ts.UNRESOLVED
if (mayMutateExpr()) {
invoc.setInferredType(fallback);
invoc.setCtDecl(infer.NO_CTDECL);
}
}
if (site != null) {
site.maySkipInvocation(nestedSite.canSkipInvocation());
}
// now if the return type of the arg is polymorphic and unsolved,
// there are some additional bounds on our own infCtx
if (!isStandalone) {
// If the expr was standalone, the constraint was already added.
// We must take care not to duplicate the constraint, because if
// it's eg checking a wildcard parameterized type, we could have
// two equality constraints on separate captures of the same wild -> incompatible
checker.checkExprConstraint(infCtx, actualType, targetType);
}
if (!argCtDecl.isFailed() && mayMutateExpr()) {
infCtx.addInstantiationListener(
infCtx.freeVarsIn(mostSpecific),
solved -> {
JMethodSig ground = solved.ground(mostSpecific);
invoc.setInferredType(ground.getReturnType());
invoc.setCtDecl(argCtDecl.withMethod(ground));
}
);
}
return true;
}
private @Nullable JClassType getProbablyFunctItfType(final JTypeMirror targetType, ExprMirror expr) {
JClassType asClass;
if (targetType instanceof InferenceVar && site != null) {
if (site.isInFinalInvocation()) {
asClass = asClassType(softSolve(targetType)); // null if not funct itf
} else {
return null; // defer
}
} else {
asClass = asClassType(targetType);
}
if (asClass == null) {
throw ResolutionFailedException.notAFunctionalInterface(infer.LOG, targetType, expr);
}
return asClass;
}
// we can't ask the infctx to solve the ivar, as that would require all bounds to be ground
// We want however to be able to add constraints on the functional interface type's inference variables
// This is useful to infer lambdas generic in their return type
// Eg Function<String, R>, where R is not yet instantiated at the time
// we check the argument, should not be ground: we want the lambda to
// add a constraint on R according to its return expressions.
@SuppressWarnings("PMD.CompareObjectsWithEquals")
private @Nullable JTypeMirror softSolve(JTypeMirror t) {
if (!(t instanceof InferenceVar)) {
return t;
}
InferenceVar ivar = (InferenceVar) t;
Set<JTypeMirror> bounds = ivar.getBounds(EQ);
if (bounds.size() == 1) {
return bounds.iterator().next();
}
bounds = ivar.getBounds(LOWER);
if (!bounds.isEmpty()) {
JTypeMirror lub = ts.lub(bounds);
return lub != ivar ? softSolve(lub) : null;
}
bounds = ivar.getBounds(UPPER);
if (!bounds.isEmpty()) {
JTypeMirror glb = ts.glb(bounds);
return glb != ivar ? softSolve(glb) : null;
}
return null;
}
private boolean isMethodRefCompatible(@NonNull JClassType functionalItf, MethodRefMirror mref) {
// See JLS§18.2.1. Expression Compatibility Constraints
// A constraint formula of the form ‹MethodReference → T›,
// where T mentions at least one inference variable, is reduced as follows:
// If T is not a functional interface type, or if T is a functional interface
// type that does not have a function type (§9.9), the constraint reduces to false.
JClassType nonWildcard = nonWildcardParameterization(functionalItf);
if (nonWildcard == null) {
throw ResolutionFailedException.notAFunctionalInterface(infer.LOG, functionalItf, mref);
}
JMethodSig fun = findFunctionalInterfaceMethod(nonWildcard);
if (fun == null) {
throw ResolutionFailedException.notAFunctionalInterface(infer.LOG, functionalItf, mref);
}
JMethodSig exactMethod = ExprOps.getExactMethod(mref);
if (exactMethod != null) {
// if the method reference is exact (§15.13.1), then let P1, ..., Pn be the parameter
// types of the function type of T, and let F1, ..., Fk be
// the parameter types of the potentially applicable method
List<JTypeMirror> ps = fun.getFormalParameters();
List<JTypeMirror> fs = exactMethod.getFormalParameters();
int n = ps.size();
int k = fs.size();
if (n == k + 1) {
// The parameter of type P1 is to act as the target reference of the invocation.
// The method reference expression necessarily has the form ReferenceType :: [TypeArguments] Identifier.
// The constraint reduces to ‹P1 <: ReferenceType› and, for all i (2 ≤ i ≤ n), ‹Pi → Fi-1›.
JTypeMirror lhs = mref.getLhsIfType();
if (lhs == null) {
// then the constraint reduces to false (it may be,
// that the candidate is wrong, so that n is wrong ^^)
return false;
}
// The receiver may not be boxed
JTypeMirror receiver = ps.get(0);
if (receiver.isPrimitive()) {
throw ResolutionFailedException.cannotInvokeInstanceMethodOnPrimitive(infer.LOG, receiver, mref);
}
checker.checkExprConstraint(infCtx, receiver, lhs);
for (int i = 1; i < n; i++) {
checker.checkExprConstraint(infCtx, ps.get(i), fs.get(i - 1));
}
} else if (n != k) {
throw ResolutionFailedException.incompatibleArity(infer.LOG, k, n, mref);
} else {
// n == k
for (int i = 0; i < n; i++) {
checker.checkExprConstraint(infCtx, ps.get(i), fs.get(i));
}
}
// If the function type's result is not void, let R be its
// return type.
//
JTypeMirror r = fun.getReturnType();
if (r != ts.NO_TYPE) {
// Then, if the result of the potentially applicable
// compile-time declaration is void, the constraint reduces to false.
JTypeMirror r2 = exactMethod.getReturnType();
if (r2 == ts.NO_TYPE) {
return false;
}
// Otherwise, the constraint reduces to ‹R' → R›, where R' is the
// result of applying capture conversion (§5.1.10) to the return
// type of the potentially applicable compile-time declaration.
checker.checkExprConstraint(infCtx, capture(r2), r);
}
completeMethodRefInference(mref, nonWildcard, fun, exactMethod, true);
} else {
// Otherwise, the method reference is inexact, and:
// (If one or more of the function's formal parameter types
// is not a proper type, the constraint reduces to false.)
// This is related to the input variable trickery used
// to resolve input vars before resolving the constraint:
// https://docs.oracle.com/javase/specs/jls/se12/html/jls-18.html#jls-18.5.2.2
// here we defer the check until the variables are ground
infCtx.addInstantiationListener(
infCtx.freeVarsIn(fun.getFormalParameters()),
solvedCtx -> solveInexactMethodRefCompatibility(mref, solvedCtx.ground(nonWildcard), solvedCtx.ground(fun))
);
}
return true;
}
private void solveInexactMethodRefCompatibility(MethodRefMirror mref, JClassType nonWildcard, JMethodSig fun) {
// Otherwise, a search for a compile-time declaration is performed, as specified in §15.13.1.
@Nullable MethodCtDecl ctdecl0 = infer.exprOps.findInexactMethodRefCompileTimeDecl(mref, fun);
// If there is no compile-time declaration for the method reference, the constraint reduces to false.
if (ctdecl0 == null) {
throw ResolutionFailedException.noCtDeclaration(infer.LOG, fun, mref);
}
JMethodSig ctdecl = ctdecl0.getMethodType();
// Otherwise, there is a compile-time declaration, and: (let R be the result of the function type)
JTypeMirror r = fun.getReturnType();
if (r == ts.NO_TYPE) {
// If R is void, the constraint reduces to true.
completeMethodRefInference(mref, nonWildcard, fun, ctdecl, false);
return;
}
boolean fixInstantiation = false;
// Otherwise, if the method reference expression elides TypeArguments, and the compile-time
// declaration is a generic method, and the return type of the compile-time declaration mentions
// at least one of the method's type parameters, then:
if (mref.getExplicitTypeArguments().isEmpty() && ExprOps.isContextDependent(ctdecl)) {
// If R mentions one of the type parameters of the function type, the constraint reduces to false.
if (mentionsAny(r, fun.getTypeParameters())) {
// Rationale from JLS
// In this case, a constraint in terms of R might lead an inference variable to
// be bound by an out-of-scope type variable. Since instantiating an inference
// variable with an out-of-scope type variable is nonsensical, we prefer to
// avoid the situation by giving up immediately whenever the possibility arises.
// Apparently javac allows compiling stuff like that. There's a test case in
// MethodRefInferenceTest, which was found in our codebase.
// We try one last thing to avoid the possibility of referencing out-of-scope stuff
if (!TypeOps.haveSameTypeParams(ctdecl, fun)) {
// then we really can't do anything
throw ResolutionFailedException.unsolvableDependency(infer.LOG);
} else {
fixInstantiation = true;
}
}
// JLS:
// If R does not mention one of the type parameters of the function type, then the
// constraint reduces to the bound set B3 which would be used to determine the
// method reference's compatibility when targeting the return type of the function
// type, as defined in §18.5.2.1. B3 may contain new inference variables, as well
// as dependencies between these new variables and the inference variables in T.
if (phase.isInvocation()) {
JMethodSig sig = inferMethodRefInvocation(mref, fun, ctdecl0);
if (fixInstantiation) {
// We know that fun & sig have the same type params
// We need to fix those that are out-of-scope
sig = sig.subst(Substitution.mapping(fun.getTypeParameters(), sig.getTypeParameters()));
}
completeMethodRefInference(mref, nonWildcard, fun, sig, false);
}
} else {
// Otherwise, let R' be the result of applying capture conversion (§5.1.10) to the return
// type of the invocation type (§15.12.2.6) of the compile-time declaration. If R' is void,
// the constraint reduces to false; otherwise, the constraint reduces to ‹R' → R›.
if (ctdecl.getReturnType() == ts.NO_TYPE) {
throw ResolutionFailedException.incompatibleReturn(infer.LOG, mref, ctdecl.getReturnType(), r);
} else {
checker.checkExprConstraint(infCtx, capture(ctdecl.getReturnType()), r);
completeMethodRefInference(mref, nonWildcard, fun, ctdecl, false);
}
}
}
private void completeMethodRefInference(MethodRefMirror mref, JClassType groundTargetType, JMethodSig functionalMethod, JMethodSig ctDecl, boolean isExactMethod) {
if ((phase.isInvocation() || isExactMethod) && mayMutateExpr()) {
// if exact, then the arg is relevant to applicability and there
// may not be an invocation round
infCtx.addInstantiationListener(
infCtx.freeVarsIn(groundTargetType),
solved -> {
mref.setInferredType(solved.ground(groundTargetType));
mref.setFunctionalMethod(solved.ground(functionalMethod).internalApi().withOwner(solved.ground(functionalMethod.getDeclaringType())));
mref.setCompileTimeDecl(solved.ground(ctDecl));
}
);
}
}
JMethodSig inferMethodRefInvocation(MethodRefMirror mref, JMethodSig targetType, MethodCtDecl ctdecl) {
InvocationMirror wrapper = methodRefAsInvocation(mref, targetType, false);
wrapper.setCtDecl(ctdecl);
MethodCallSite mockSite = infer.newCallSite(wrapper, /* expected */ targetType.getReturnType(), site, infCtx, isSpecificityCheck());
return infer.determineInvocationTypeOrFail(mockSite).getMethodType();
}
/**
* Only executed if {@link MethodResolutionPhase#isInvocation()},
* as per {@link ExprOps#isPertinentToApplicability(ExprMirror, JMethodSig, JTypeMirror, InvocationMirror)}.
*/
private boolean isLambdaCompatible(@NonNull JClassType functionalItf, LambdaExprMirror lambda) {
JClassType groundTargetType = groundTargetType(functionalItf, lambda);
if (groundTargetType == null) {
throw ResolutionFailedException.notAFunctionalInterface(infer.LOG, functionalItf, lambda);
}
JMethodSig groundFun = findFunctionalInterfaceMethod(groundTargetType);
if (groundFun == null) {
throw ResolutionFailedException.notAFunctionalInterface(infer.LOG, functionalItf, lambda);
}
// might be partial, whatever
// We use that, so that the parameters may at least have a type
// in the body of the lambda, to infer its return type
// this is because the lazy type resolver uses the functional
// method to resolve the type of a LambdaParameter
if (mayMutateExpr()) {
lambda.setInferredType(groundTargetType);
lambda.setFunctionalMethod(groundFun);
// set the final type when done
if (phase.isInvocation()) {
infCtx.addInstantiationListener(
infCtx.freeVarsIn(groundTargetType),
solved -> {
JClassType solvedGround = solved.ground(groundTargetType);
lambda.setInferredType(solvedGround);
lambda.setFunctionalMethod(solved.ground(groundFun).internalApi().withOwner(solved.ground(groundFun.getDeclaringType())));
}
);
}
}
return isLambdaCongruent(functionalItf, groundTargetType, groundFun, lambda);
}
private boolean mayMutateExpr() {
return !isSpecificityCheck();
}
private boolean isSpecificityCheck() {
return site != null && site.isSpecificityCheck();
}
// functionalItf = T
// groundTargetType = T'
@SuppressWarnings("PMD.UnusedFormalParameter")
private boolean isLambdaCongruent(@NonNull JClassType functionalItf,
@NonNull JClassType groundTargetType,
@NonNull JMethodSig groundFun,
LambdaExprMirror lambda) {
if (groundFun.isGeneric()) {
throw ResolutionFailedException.lambdaCannotTargetGenericFunction(infer.LOG, groundFun, lambda);
}
// If the number of lambda parameters differs from the number
// of parameter types of the function type, the constraint
// reduces to false.
if (groundFun.getArity() != lambda.getParamCount()) {
throw ResolutionFailedException.incompatibleArity(infer.LOG, lambda.getParamCount(), groundFun.getArity(), lambda);
}
// If the function type's result is void and the lambda body is
// neither a statement expression nor a void-compatible block,
// the constraint reduces to false.
JTypeMirror result = groundFun.getReturnType();
if (result == ts.NO_TYPE && !lambda.isVoidCompatible()) {
throw ResolutionFailedException.lambdaCannotTargetVoidMethod(infer.LOG, lambda);
}
// If the function type's result is not void and the lambda
// body is a block that is not value-compatible, the constraint
// reduces to false.
if (result != ts.NO_TYPE && !lambda.isValueCompatible()) {
throw ResolutionFailedException.lambdaCannotTargetValueMethod(infer.LOG, lambda);
}
// If the lambda parameters have explicitly declared types F1, ..., Fn
// and the function type has parameter types G1, ..., Gn, then
// i) for all i (1 ≤ i ≤ n), ‹Fi = Gi›
if (lambda.isExplicitlyTyped()
&& !areSameTypesInInference(groundFun.getFormalParameters(), lambda.getExplicitParameterTypes())) {
throw ResolutionFailedException.mismatchedLambdaParameters(infer.LOG, groundFun, lambda.getExplicitParameterTypes(), lambda);
}
// and ii) ‹T' <: T›.
// if (!groundTargetType.isSubtypeOf(functionalItf)) {
// return false;
// }
// finally, add bounds
if (result != ts.NO_TYPE) {
infCtx.addInstantiationListener(
infCtx.freeVarsIn(groundFun.getFormalParameters()),
solvedCtx -> {
if (mayMutateExpr()) {
lambda.setInferredType(solvedCtx.ground(groundTargetType));
JMethodSig solvedGroundFun = solvedCtx.ground(groundFun);
lambda.setFunctionalMethod(solvedGroundFun);
lambda.updateTypingContext(solvedGroundFun);
}
JTypeMirror groundResult = solvedCtx.ground(result);
for (ExprMirror expr : lambda.getResultExpressions()) {
if (!isCompatible(groundResult, expr)) {
return;
}
}
});
}
if (mayMutateExpr()) { // we know that the lambda matches now
lambda.updateTypingContext(groundFun);
}
return true;
}
private @Nullable JClassType groundTargetType(JClassType type, LambdaExprMirror lambda) {
List<JTypeMirror> targs = type.getTypeArgs();
if (CollectionUtil.none(targs, it -> it instanceof JWildcardType)) {
return type;
}
if (lambda.isExplicitlyTyped() && lambda.getParamCount() > 0) {
// TODO infer, normally also for lambdas with no param, i'm just lazy
// https://docs.oracle.com/javase/specs/jls/se9/html/jls-18.html#jls-18.5.3
return null;
} else {
return nonWildcardParameterization(type);
}
}
@FunctionalInterface
interface ExprChecker {
/**
* In JLS terms, adds a constraint formula {@code < exprType -> formalType >}.
*
* <p>This method throws ResolutionFailedException if the constraint
* can be asserted as false immediately. Otherwise the check is
* deferred until both types have been inferred (but bounds on the
* type vars are added).
*/
void checkExprConstraint(InferenceContext infCtx, JTypeMirror exprType, JTypeMirror formalType) throws ResolutionFailedException;
}
}
| 28,227 | 45.27541 | 167 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/InferenceVar.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import java.util.Collections;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Function;
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.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.JTypeVar;
import net.sourceforge.pmd.lang.java.types.JTypeVisitor;
import net.sourceforge.pmd.lang.java.types.SubstVar;
import net.sourceforge.pmd.lang.java.types.TypePrettyPrint;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
/**
* Represents an inference variable. Inference variables are just
* placeholder for types, used during the inference process.
* After type inference they should have been erased and hence this
* type is of no importance outside the implementation of this framework.
*/
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public final class InferenceVar implements JTypeMirror, SubstVar {
// we used to use greek letters (for style), but they're hard to type
private static final String NAMES = "abcdefghijklmnopqrstuvwxyz"; // + "αβγδεζηθκλμνξπρςυφχψω"
private final InferenceContext ctx;
private JTypeVar tvar;
private final int id;
// Equal ivars share the same BoundSet
private BoundSet boundSet = new BoundSet();
private boolean hasNonTrivialBound;
InferenceVar(InferenceContext ctx, JTypeVar tvar, int id) {
this.ctx = ctx;
this.tvar = tvar;
this.id = id;
}
@Override
public JTypeMirror withAnnotations(PSet<SymAnnot> newTypeAnnots) {
return this;
}
@Override
public PSet<SymAnnot> getTypeAnnotations() {
return HashTreePSet.empty();
}
public String getName() {
// note: the type inference logger depends on this naming pattern
String prefix = isCaptured() ? "^" : "'";
return prefix + NAMES.charAt(id % NAMES.length()) + generationNum();
}
@Override
public TypeSystem getTypeSystem() {
return ctx.ts;
}
/**
* Returns the bounds of a certain kind that apply to
* this variable.
*/
Set<JTypeMirror> getBounds(BoundKind kind) {
return boundSet.bounds.getOrDefault(kind, Collections.emptySet());
}
Set<JTypeMirror> getBounds(Set<BoundKind> kinds) {
Set<JTypeMirror> bounds = new LinkedHashSet<>();
for (BoundKind k : kinds) {
bounds.addAll(getBounds(k));
}
return bounds;
}
/**
* Adds a new bound on this variable.
*/
public void addBound(BoundKind kind, JTypeMirror type) {
this.hasNonTrivialBound = true;
addBound(kind, type, false);
}
public void addPrimaryBound(BoundKind kind, JTypeMirror type) {
addBound(kind, type, true);
}
/**
* @param isPrimaryBound Whether this is the default bound conferred
* by the bound on a type parameter declaration.
* This is treated specially by java 7 inference.
*/
private void addBound(BoundKind kind, JTypeMirror type, boolean isPrimaryBound) {
if (this.isEquivalentTo(type)) {
// may occur because of transitive propagation
// alpha <: alpha is always true and not interesting
return;
}
if (boundSet.bounds.computeIfAbsent(kind, k -> new LinkedHashSet<>()).add(type)) {
ctx.onBoundAdded(this, kind, type, isPrimaryBound);
}
}
/**
* Returns true if the node has no bounds except the ones given
* by the upper bound of the type parameter. In the Java 7 inference
* process, this indicates that we should use additional constraints
* binding the return type of the method to the target type (determined by
* an assignment context).
*
* <p>Remove this if you remove support for java 7 at some point.
*/
boolean hasOnlyPrimaryBound() {
return !hasNonTrivialBound;
}
/**
* Returns the instantiation of this inference variable if
* it has already been determined. Returns null otherwise.
*/
@Nullable
JTypeMirror getInst() {
return boundSet.inst;
}
void setInst(JTypeMirror inst) {
this.boundSet.inst = inst;
}
/**
* Apply a substitution to the bounds of this variable. Called when
* an ivar is instantiated.
*
* @param substitution The substitution to apply
*/
void substBounds(Function<? super SubstVar, ? extends JTypeMirror> substitution) {
for (Entry<BoundKind, Set<JTypeMirror>> entry : boundSet.bounds.entrySet()) {
BoundKind kind = entry.getKey();
Set<JTypeMirror> prevBounds = entry.getValue();
// put the new bounds before updating
Set<JTypeMirror> newBounds = new LinkedHashSet<>();
boundSet.bounds.put(kind, newBounds);
for (JTypeMirror prev : prevBounds) {
// add substituted bound
JTypeMirror newBound = prev.subst(substitution);
if (newBound == prev || prevBounds.contains(newBound)) { // NOPMD CompareObjectsWithEquals
// not actually new, don't call listeners, etc
newBounds.add(newBound);
} else {
addBound(kind, newBound);
}
}
}
if (tvar.isCaptured()) {
tvar = tvar.substInBounds(substitution);
}
}
JTypeVar getBaseVar() {
return tvar;
}
boolean isCaptured() {
return tvar.isCaptured();
}
public boolean isEquivalentTo(JTypeMirror t) {
return this == t || t instanceof InferenceVar
&& ((InferenceVar) t).boundSet == this.boundSet; // NOPMD CompareObjectsWithEquals
}
public boolean isSubtypeNoSideEffect(@NonNull JTypeMirror other) {
return isEquivalentTo(other) || other.isTop();
}
public boolean isSupertypeNoSideEffect(@NonNull JTypeMirror other) {
return isEquivalentTo(other) || other.isBottom();
}
/**
* Sets the bounds of this ivar and the other to the union of both sets.
*/
void adoptAllBounds(InferenceVar candidate) {
if (isEquivalentTo(candidate)) {
return;
}
for (BoundKind kind : BoundKind.values()) {
for (JTypeMirror bound : candidate.getBounds(kind)) {
addBound(kind, bound);
}
}
candidate.boundSet = this.boundSet;
ctx.onIvarMerged(candidate, this);
}
@Override
public @Nullable JTypeDeclSymbol getSymbol() {
JTypeMirror inst = getInst();
return inst != null ? inst.getSymbol()
: new InferenceVarSym(ctx.ts, this);
}
@Override
public JTypeMirror subst(Function<? super SubstVar, ? extends @NonNull JTypeMirror> subst) {
return subst.apply(this);
}
@Override
public <T, P> T acceptVisitor(JTypeVisitor<T, P> visitor, P p) {
return visitor.visitInferenceVar(this, p);
}
@Override
public String toString() {
return TypePrettyPrint.prettyPrint(this);
}
private String generationNum() {
int n = id / NAMES.length();
return n == 0 ? "" : "" + n;
}
StringBuilder formatBounds(StringBuilder sb) {
sb.append(" {");
boolean any = false;
for (BoundKind bk : BoundKind.ALL) {
for (JTypeMirror bound : getBounds(bk)) {
sb.append(any ? ", " : " ").append(bk.format(this, bound));
any = true;
}
}
sb.append(any ? " }" : "}");
return sb;
}
public enum BoundKind {
UPPER(" <: ") {
@Override
public BoundKind complement() {
return LOWER;
}
@Override
public Set<BoundKind> complementSet(boolean eqIsAll) {
return EQ_LOWER;
}
},
EQ(" = ") {
@Override
public BoundKind complement() {
return this;
}
@Override
public Set<BoundKind> complementSet(boolean eqIsAll) {
return eqIsAll ? ALL : JUST_EQ;
}
},
LOWER(" >: ") {
@Override
public BoundKind complement() {
return UPPER;
}
@Override
public Set<BoundKind> complementSet(boolean eqIsAll) {
return EQ_UPPER;
}
};
// These sets are shared because otherwise *literal millions* of enumsets are created, with the same constants
static final Set<BoundKind> ALL = EnumSet.allOf(BoundKind.class);
static final Set<BoundKind> EQ_LOWER = EnumSet.of(EQ, LOWER);
private static final Set<BoundKind> EQ_UPPER = EnumSet.of(EQ, UPPER);
private static final Set<BoundKind> JUST_EQ = Collections.singleton(EQ);
private final String sym;
BoundKind(String sym) {
this.sym = sym;
}
public String format(JTypeMirror ivar, JTypeMirror bound) {
return ivar + sym + bound;
}
/**
* Returns the complementary bound kind.
* <pre>
* complement(LOWER) = UPPER
* complement(UPPER) = LOWER
* complement(EQ) = EQ
* </pre>
*/
public abstract BoundKind complement();
/**
* Returns the complement of this kind. There's two ways to complement EQ:
* - With eqIsAll, this returns all constants.
* - Otherwise this returns just EQ.
*/
public abstract Set<BoundKind> complementSet(boolean eqIsAll);
String getSym() {
return sym;
}
@Override
public String toString() {
return sym;
}
}
/** Equal inference vars share the same boundset. */
private static final class BoundSet {
JTypeMirror inst;
Map<BoundKind, Set<JTypeMirror>> bounds = new EnumMap<>(BoundKind.class);
}
}
| 10,673 | 28.983146 | 118 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ResolutionFailure.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.types.JMethodSig;
/**
* An exception occurring during overload resolution. Some of those
* are completely normal and prune incompatible overloads. There is
* a compile-time error if no compile-time declaration is identified
* though (all potentially applicable methods fail), or if after the
* CTdecl is selected, its invocation fails (eg a param that was not
* pertinent to applicability is incompatible with the declared formal).
*/
public class ResolutionFailure {
static final ResolutionFailure UNKNOWN = new ResolutionFailure(null, "log is disabled");
private JMethodSig failedMethod;
private PolySite<?> callSite;
private MethodResolutionPhase phase;
private final String reason;
private final @Nullable JavaNode location;
ResolutionFailure(@Nullable JavaNode location, String reason) {
this.location = location;
this.reason = reason;
}
void addContext(JMethodSig m, PolySite<?> callSite, MethodResolutionPhase phase) {
this.failedMethod = m;
this.callSite = callSite;
this.phase = phase;
}
/**
* Returns the location on which the failure should be reported.
*/
public @Nullable JavaNode getLocation() {
return location != null ? location
: callSite != null ? callSite.getExpr().getLocation()
: null;
}
/**
* Returns the method type that was being checked against the call site.
*/
public JMethodSig getFailedMethod() {
return failedMethod;
}
/**
* Returns the phase in which the failure occurred. Failures in invocation
* phase should be compile-time errors.
*/
public MethodResolutionPhase getPhase() {
return phase;
}
/** Returns the reason for the failure. */
public String getReason() {
return reason;
}
/** Returns the call site for the failure. */
public PolySite<?> getCallSite() {
return callSite;
}
@Override
public String toString() {
return "ResolutionFailure{"
+ "failedMethod=" + failedMethod
+ ", callSite=" + callSite
+ ", phase=" + phase
+ ", reason='" + reason + '\''
+ ", location=" + location
+ '}';
}
}
| 2,639 | 28.662921 | 92 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/Graph.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import static java.lang.Math.min;
import static net.sourceforge.pmd.util.CollectionUtil.union;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import net.sourceforge.pmd.util.GraphUtil;
import net.sourceforge.pmd.util.GraphUtil.DotColor;
/**
* A graph to walk over ivar dependencies in an efficient way.
* This is not a general purpose implementation, there's no cleanup
* of the vertices whatsoever, meaning each algo ({@link #mergeCycles()}
* and {@link #topologicalSort()}) can only be done once reliably.
*/
class Graph<T> {
/** Undefined index for Tarjan's algo. */
private static final int UNDEFINED = -1;
private final Set<Vertex<T>> vertices = new LinkedHashSet<>();
// direct successors
private final Map<Vertex<T>, Set<Vertex<T>>> successors = new HashMap<>();
Vertex<T> addLeaf(T data) {
Vertex<T> v = new Vertex<>(this, Collections.singleton(data));
vertices.add(v);
return v;
}
/**
* Implicitly add both nodes to the graph and record a directed
* edge between the first and the second.
*/
void addEdge(Vertex<T> start, Vertex<T> end) {
Objects.requireNonNull(end);
Objects.requireNonNull(start);
vertices.add(start);
vertices.add(end);
if (start == end) { // NOPMD CompareObjectsWithEquals
// no self loop allowed (for tarjan), and besides an
// inference variable depending on itself is trivial
return;
}
successors.computeIfAbsent(start, k -> new LinkedHashSet<>()).add(end);
}
// test only
Set<Vertex<T>> successorsOf(Vertex<T> node) {
return successors.getOrDefault(node, Collections.emptySet());
}
Set<Vertex<T>> getVertices() {
return vertices;
}
/**
* Returns a list in which the vertices of this graph are sorted
* in the following way:
*
* if there exists an edge u -> v, then u comes AFTER v in the list.
*/
List<Set<T>> topologicalSort() {
List<Set<T>> sorted = new ArrayList<>(vertices.size());
for (Vertex<T> n : vertices) {
toposort(n, sorted);
}
return sorted;
}
private void toposort(Vertex<T> v, List<Set<T>> sorted) {
if (v.mark) {
return;
}
for (Vertex<T> w : successorsOf(v)) {
toposort(w, sorted);
}
v.mark = true;
sorted.add(v.getData());
}
/**
* Merge strongly connected components into a single node each.
* This turns the graph into a DAG. This modifies the graph in
* place, no cleanup of the vertices is performed.
*/
void mergeCycles() {
// https://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
TarjanState<T> state = new TarjanState<>();
for (Vertex<T> vertex : new ArrayList<>(vertices)) {
if (vertex.index == UNDEFINED) {
strongConnect(state, vertex);
}
}
}
private void strongConnect(TarjanState<T> state, Vertex<T> v) {
v.index = state.index;
v.lowLink = state.index;
state.index++;
state.stack.push(v);
v.onStack = true;
for (Vertex<T> w : new ArrayList<>(successorsOf(v))) {
if (w.index == UNDEFINED) {
// Successor has not yet been visited; recurse on it
strongConnect(state, w);
v.lowLink = min(w.lowLink, v.lowLink);
} else if (w.onStack) {
// Successor w is in stack S and hence in the current SCC
// If w is not on stack, then (v, w) is a cross-edge in the DFS tree and must be ignored
// Note: The next line may look odd - but is correct.
// It says w.index not w.lowlink; that is deliberate and from the original paper
v.lowLink = min(v.lowLink, w.index);
}
}
// If v is a root node, pop the stack and generate an SCC
if (v.lowLink == v.index) {
Vertex<T> w;
do {
w = state.stack.pop();
w.onStack = false;
// merge w into v
v.absorb(w);
} while (w != v); // NOPMD CompareObjectsWithEquals
}
}
void onAbsorb(Vertex<T> vertex, Vertex<T> toMerge) {
Set<Vertex<T>> succ = union(successorsOf(vertex), successorsOf(toMerge));
succ.remove(toMerge);
succ.remove(vertex);
successors.put(vertex, succ);
successors.remove(toMerge);
vertices.remove(toMerge);
successors.values().forEach(it -> it.remove(toMerge));
}
@Override
public String toString() {
return GraphUtil.toDot(
vertices,
this::successorsOf,
v -> DotColor.BLACK,
v -> v.data.toString()
);
}
private static final class TarjanState<T> {
int index;
Deque<Vertex<T>> stack = new ArrayDeque<>();
}
static final class Vertex<T> {
private final Graph<T> owner;
private final Set<T> data;
// Tarjan state
private int index = UNDEFINED;
private int lowLink = UNDEFINED;
private boolean onStack = false;
// Toposort state
private boolean mark;
private Vertex(Graph<T> owner, Set<T> data) {
this.owner = owner;
this.data = new LinkedHashSet<>(data);
}
public Set<T> getData() {
return data;
}
/** Absorbs the given node into this node. */
private void absorb(Vertex<T> toMerge) {
if (this == toMerge) { // NOPMD CompareObjectsWithEquals
return;
}
this.data.addAll(toMerge.data);
owner.onAbsorb(this, toMerge);
}
@Override
public String toString() {
return data.toString();
}
}
/** Maintains uniqueness of nodes wrt data. */
static class UniqueGraph<T> extends Graph<T> {
private final Map<T, Vertex<T>> vertexMap = new HashMap<>();
@Override
Vertex<T> addLeaf(T data) {
if (vertexMap.containsKey(data)) {
return vertexMap.get(data);
}
Vertex<T> v = super.addLeaf(data);
vertexMap.put(data, v);
return v;
}
@Override
void onAbsorb(Vertex<T> vertex, Vertex<T> toMerge) {
super.onAbsorb(vertex, toMerge);
for (T ivar : toMerge.getData()) {
vertexMap.put(ivar, vertex);
}
}
}
}
| 7,047 | 28.991489 | 104 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/Infer.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import static net.sourceforge.pmd.lang.java.types.TypeConversion.capture;
import static net.sourceforge.pmd.lang.java.types.TypeConversion.isWilcardParameterized;
import static net.sourceforge.pmd.lang.java.types.TypeOps.asList;
import static net.sourceforge.pmd.lang.java.types.TypeOps.subst;
import static net.sourceforge.pmd.lang.java.types.internal.infer.ExprOps.isPertinentToApplicability;
import static net.sourceforge.pmd.lang.java.types.internal.infer.MethodResolutionPhase.INVOC_LOOSE;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static net.sourceforge.pmd.util.CollectionUtil.setOf;
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.types.JArrayType;
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.Substitution;
import net.sourceforge.pmd.lang.java.types.TypeOps;
import net.sourceforge.pmd.lang.java.types.TypeOps.Convertibility;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprCheckHelper.ExprChecker;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.CtorInvocationMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.FunctionalExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.InvocationMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.InvocationMirror.MethodCtDecl;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.LambdaExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.MethodRefMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.PolyExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar.BoundKind;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* Main entry point for type inference.
*/
@SuppressWarnings({"PMD.FieldNamingConventions", "PMD.CompareObjectsWithEquals"})
public final class Infer {
final ExprOps exprOps;
public final TypeInferenceLogger LOG; // SUPPRESS CHECKSTYLE just easier to read I think
private final boolean isPreJava8;
private final TypeSystem ts;
final MethodCtDecl NO_CTDECL; // SUPPRESS CHECKSTYLE same
/** This is a sentinel for when the CTDecl was resolved, but invocation failed. */
final MethodCtDecl FAILED_INVOCATION; // SUPPRESS CHECKSTYLE same
private final SupertypeCheckCache supertypeCheckCache = new SupertypeCheckCache();
/**
* Creates a new instance.
*
* @param ts Type system
* @param jdkVersion JDK version to use. Type inference was changed
* in Java 8 to propagate the context type.
* @param logger Strategy to log failures
*/
public Infer(TypeSystem ts, int jdkVersion, TypeInferenceLogger logger) {
this.ts = ts;
this.isPreJava8 = jdkVersion < 8;
this.LOG = logger;
this.NO_CTDECL = MethodCtDecl.unresolved(ts);
this.FAILED_INVOCATION = MethodCtDecl.unresolved(ts);
this.exprOps = new ExprOps(this);
}
public boolean isPreJava8() {
return isPreJava8;
}
public TypeSystem getTypeSystem() {
return ts;
}
public TypeInferenceLogger getLogger() {
return LOG;
}
public PolySite<FunctionalExprMirror> newFunctionalSite(FunctionalExprMirror mirror, @Nullable JTypeMirror expectedType) {
return new PolySite<>(mirror, expectedType);
}
public MethodCallSite newCallSite(InvocationMirror expr, @Nullable JTypeMirror expectedType) {
return newCallSite(expr, expectedType, null, null, false);
}
/** Site for a nested poly expr. */
// package
MethodCallSite newCallSite(InvocationMirror expr,
@Nullable JTypeMirror expectedType,
@Nullable MethodCallSite outerSite,
@Nullable InferenceContext outerCtx,
boolean isSpecificityCheck) {
return new MethodCallSite(expr, expectedType, outerSite, outerCtx != null ? outerCtx : emptyContext(), isSpecificityCheck);
}
InferenceContext emptyContext() {
return newContextFor(Collections.emptyList());
}
@NonNull
InferenceContext newContextFor(JMethodSig m) {
return newContextFor(m.getTypeParameters());
}
InferenceContext newContextFor(List<JTypeVar> tvars) {
return new InferenceContext(ts, supertypeCheckCache, tvars, LOG);
}
/**
* Infer lambdas and method references that have a target type: cast contexts,
* and some assignment contexts (not inferred, not return from lambda).
*/
public void inferFunctionalExprInUnambiguousContext(PolySite<FunctionalExprMirror> site) {
FunctionalExprMirror expr = site.getExpr();
JTypeMirror expected = site.getExpectedType();
try {
if (expected == null) {
throw ResolutionFailedException.missingTargetTypeForFunctionalExpr(LOG, expr);
}
addBoundOrDefer(null, emptyContext(), INVOC_LOOSE, expr, expected);
} catch (ResolutionFailedException rfe) {
rfe.getFailure().addContext(null, site, null);
LOG.logResolutionFail(rfe.getFailure());
// here we set expected if not null, the lambda will have the target type
expr.setInferredType(expected == null ? ts.UNKNOWN : expected);
if (expr instanceof MethodRefMirror) {
MethodRefMirror mref = (MethodRefMirror) expr;
mref.setFunctionalMethod(ts.UNRESOLVED_METHOD);
mref.setCompileTimeDecl(ts.UNRESOLVED_METHOD);
} else {
LambdaExprMirror lambda = (LambdaExprMirror) expr;
lambda.setFunctionalMethod(ts.UNRESOLVED_METHOD);
}
}
}
/**
* Determines the most specific applicable method for the given call site.
*
* <p>The returned method type may be {@link TypeSystem#UNRESOLVED_METHOD},
* in which case no method is applicable (compile-time error).
*
* <p>The returned method type may contain un-instantiated inference
* variables, which depend on the target type. In that case those
* variables and their bounds will have been duplicated into the
* inference context of the [site].
*
* <p>The given call site should mention information like the expected
* return type, to help inference. This should be non-null if we're
* in an invocation or assignment context, otherwise can be left blank.
*/
public void inferInvocationRecursively(MethodCallSite site) {
MethodCtDecl ctdecl = goToInvocationWithFallback(site);
InvocationMirror expr = site.getExpr();
expr.setCtDecl(ctdecl);
if (ctdecl == NO_CTDECL) {
expr.setInferredType(fallbackType(expr));
} else {
expr.setInferredType(ctdecl.getMethodType().getReturnType());
}
}
private MethodCtDecl goToInvocationWithFallback(MethodCallSite site) {
MethodCtDecl ctdecl = getCompileTimeDecl(site);
if (ctdecl == NO_CTDECL) { // NOPMD CompareObjectsWithEquals
return NO_CTDECL;
}
site.clearFailures();
// do invocation
{ // reduce scope of invocType, outside of here it's failed
final MethodCtDecl invocType = finishInstantiation(site, ctdecl);
if (invocType != FAILED_INVOCATION) { // NOPMD CompareObjectsWithEquals
return invocType;
}
}
// ok we failed, we can still use some info from the ctdecl
JMethodSig fallback = deleteTypeParams(ctdecl.getMethodType().internalApi().adaptedMethod());
LOG.fallbackInvocation(fallback, site);
return ctdecl.withMethod(fallback, true);
}
private JTypeMirror fallbackType(PolyExprMirror expr) {
JTypeMirror t = expr.unresolvedType();
return t == null ? ts.UNKNOWN : t;
}
// If the invocation fails, replace type parameters with a placeholder,
// to not hide a bad failure, while preserving the method if possible
private JMethodSig deleteTypeParams(JMethodSig m) {
if (!m.isGeneric()) {
return m;
}
List<JTypeVar> tparams = m.getTypeParameters();
List<JTypeMirror> nErrors = Collections.nCopies(tparams.size(), ts.ERROR);
return m.subst(Substitution.mapping(tparams, nErrors));
}
/**
* Similar to {@link #inferInvocationRecursively(MethodCallSite)} for
* subexpressions. This never returns a fallback method.
*
* <p>A return of {@link #NO_CTDECL} indicates no overload is applicable.
* <p>A return of {@link #FAILED_INVOCATION} means there is a maximally
* specific compile-time declaration, but it failed invocation, meaning,
* it couldn't be linked to its context. If so, the outer inference process
* must be terminated with a failure.
* <p>This ne
*
* <p>The returned method type may contain un-instantiated inference
* variables, which depend on the target type. In that case those
* variables and their bounds will have been duplicated into the
* inference context of the [site].
*/
@NonNull MethodCtDecl determineInvocationTypeOrFail(MethodCallSite site) {
MethodCtDecl ctdecl = getCompileTimeDecl(site);
if (ctdecl == NO_CTDECL) { // NOPMD CompareObjectsWithEquals
return ctdecl;
}
return finishInstantiation(site, ctdecl);
}
public @NonNull MethodCtDecl getCompileTimeDecl(MethodCallSite site) {
if (site.getExpr().getCtDecl() == null) {
MethodCtDecl ctdecl = computeCompileTimeDecl(site);
site.getExpr().setCtDecl(ctdecl); // cache it for later
}
return site.getExpr().getCtDecl();
}
/**
* Determines the most specific applicable method for the given call site.
*
* <p>The returned method type may be null, in which case no method is
* applicable (compile-time error).
*/
private @NonNull MethodCtDecl computeCompileTimeDecl(MethodCallSite site) {
/*
* The process starts with a set of candidates and refines it
* iteratively. Applicability/best applicability are the only
* ones which needs inference.
*
* visible ⊇ accessible ⊇ potentially applicable ⊇ applicable ⊇ best applicable
*/
List<JMethodSig> potentiallyApplicable = new ArrayList<>();
for (JMethodSig it : site.getExpr().getAccessibleCandidates()) {
if (isPotentiallyApplicable(it, site.getExpr())) {
potentiallyApplicable.add(it);
}
}
if (potentiallyApplicable.isEmpty()) {
LOG.noApplicableCandidates(site);
return NO_CTDECL;
}
for (MethodResolutionPhase phase : MethodResolutionPhase.APPLICABILITY_TESTS) {
PhaseOverloadSet applicable = new PhaseOverloadSet(this, phase, site);
for (JMethodSig m : potentiallyApplicable) {
site.resetInferenceData();
MethodCtDecl candidate = logInference(site, phase, m);
if (!candidate.isFailed()) {
applicable.add(candidate);
}
}
if (applicable.nonEmpty()) {
MethodCtDecl bestApplicable = applicable.getMostSpecificOrLogAmbiguity(LOG);
JMethodSig adapted = ExprOps.adaptGetClass(bestApplicable.getMethodType(),
site.getExpr()::getErasedReceiverType);
return bestApplicable.withMethod(adapted);
}
}
LOG.noCompileTimeDeclaration(site);
return NO_CTDECL;
}
@NonNull MethodCtDecl finishInstantiation(MethodCallSite site, MethodCtDecl ctdecl) {
JMethodSig m = ctdecl.getMethodType();
InvocationMirror expr = site.getExpr();
site.loadInferenceData(ctdecl);
site.setInInvocation();
if (site.canSkipInvocation()) {
assert assertReturnIsGround(m);
expr.setInferredType(m.getReturnType());
LOG.skipInstantiation(m, site);
return ctdecl;
}
// start the inference over with the original method, including
// arguments that are not pertinent to applicability (lambdas)
// to instantiate all tvars
return logInference(site,
ctdecl.getResolvePhase().asInvoc(),
ctdecl.getMethodType().internalApi().adaptedMethod());
}
// this is skipped when running without assertions
private boolean assertReturnIsGround(JMethodSig t) {
subst(t.getReturnType(), var -> {
assert !(var instanceof InferenceVar)
: "Expected a ground type " + t;
assert !(var instanceof JTypeVar) || !t.getTypeParameters().contains(var)
: "Some type parameters have not been instantiated";
return var;
});
return true;
}
private @NonNull MethodCtDecl logInference(MethodCallSite site, MethodResolutionPhase phase, JMethodSig m) {
LOG.startInference(m, site, phase);
@Nullable JMethodSig candidate = instantiateMethodOrCtor(site, phase, m);
LOG.endInference(candidate);
if (candidate == null) {
return FAILED_INVOCATION;
} else {
return new MethodCtDecl(candidate,
phase,
site.canSkipInvocation(),
site.needsUncheckedConversion(),
false);
}
}
private @Nullable JMethodSig instantiateMethodOrCtor(MethodCallSite site, MethodResolutionPhase phase, JMethodSig m) {
return site.getExpr() instanceof CtorInvocationMirror ? instantiateConstructor(m, site, phase)
: instantiateMethod(m, site, phase);
}
/**
* Infer type arguments for the given method at the method call.
* Returns null if no instantiations exist, ie the method is not
* applicable.
*
* @param m Candidate method
* @param site Descriptor of the context of the call.
* @param phase Phase in which the method is reviewed
*/
private @Nullable JMethodSig instantiateMethod(JMethodSig m,
MethodCallSite site,
MethodResolutionPhase phase) {
if (phase.requiresVarargs() && !m.isVarargs()) {
return null; // don't log such a dumb mistake
}
try {
return instantiateMaybeNoInfer(m, site, phase);
} catch (ResolutionFailedException e) {
ResolutionFailure failure = e.getFailure();
failure.addContext(m, site, phase);
LOG.logResolutionFail(failure);
return null;
}
}
private @Nullable JMethodSig instantiateConstructor(JMethodSig cons,
MethodCallSite site,
MethodResolutionPhase phase) {
CtorInvocationMirror expr = (CtorInvocationMirror) site.getExpr();
JTypeMirror newTypeMaybeInvalid = expr.getNewType();
if (!(newTypeMaybeInvalid instanceof JClassType)) {
// no constructor, note also, that array type constructors
// don't go through these routines because there's no overloading
// of array ctors. They're handled entirely in LazyTypeResolver.
return null;
}
JClassType newType = (JClassType) newTypeMaybeInvalid;
boolean isAdapted = needsAdaptation(expr, newType);
JMethodSig adapted = isAdapted
? adaptGenericConstructor(cons, newType, expr)
: cons;
site.maySkipInvocation(!isAdapted);
@Nullable JMethodSig result = instantiateMethod(adapted, site, phase);
if (isAdapted && result != null) {
// undo the adaptation
JTypeMirror rtype = result.getReturnType();
if (!rtype.isInterface()) {
// this is for anonymous class ctors
// an interface cannot declare a constructor
result = result.internalApi().withOwner(rtype);
}
return result.internalApi().withTypeParams(null);
}
return result;
}
private boolean needsAdaptation(CtorInvocationMirror expr, JClassType newType) {
return expr.isDiamond()
|| newType.isParameterizedType() // ???
|| expr.isAnonymous();
}
/**
* Transform the constructor of a generic class so that its type parameters
* mention the type params of the declaring class. This enables diamond
* inference, we just treat the class type params to infer as
* additional inference variables.
*
* <p>E.g. for
*
* {@code class ArrayList<T> { ArrayList() {} } }
*
* the constructor is represented as a method type:
*
* {@code <T> ArrayList<T> new() }
*
* the return type being that of the created instance.
*/
private static JMethodSig adaptGenericConstructor(JMethodSig cons, JClassType newType, CtorInvocationMirror expr) {
assert cons.isConstructor() : cons + " should be a constructor";
if (cons.getDeclaringType().isArray()) {
// array methods do not need to be adapted and don't support it
return cons;
}
// replace the return type so that anonymous class ctors return the supertype
JMethodSig adaptedSig = cons.internalApi().withReturnType(newType).internalApi().markAsAdapted();
List<JTypeVar> newTypeFormals = newType.getFormalTypeParams();
if (newTypeFormals.isEmpty()) {
// non-generic type
return adaptedSig;
} else {
// else transform the constructor to add the type parameters
// of the constructed type
List<JTypeVar> consParams = cons.getTypeParameters();
if (consParams.size() > cons.getSymbol().getTypeParameterCount()) {
// it's already been adapted
assert consParams.equals(CollectionUtil.concatView(cons.getSymbol().getTypeParameters(), newTypeFormals));
return adaptedSig;
} else if (!expr.isDiamond()) {
// it doesn't need adaptation, we're not doing diamond inference
return adaptedSig;
}
List<JTypeVar> tparams = CollectionUtil.concatView(consParams, newTypeFormals);
// type parameters are not part of the adapted signature, so that when we reset
// the signature for invocation inference, we don't duplicate new type parameters
return adaptedSig.internalApi().withTypeParams(tparams).internalApi().markAsAdapted();
}
}
/**
* Catch the easy cases before starting inference.
*/
private JMethodSig instantiateMaybeNoInfer(JMethodSig m, MethodCallSite site, MethodResolutionPhase phase) {
if (!m.isGeneric()) {
// non-generic methods may mention explicit type arguments
// for compatibility, they must be ignored.
// check that the arguments are conformant
// the inference context is empty because all param types are ground.
addArgsConstraints(emptyContext(), m, site, phase);
return m;
}
InvocationMirror expr = site.getExpr();
List<JTypeMirror> explicitTargs = expr.getExplicitTypeArguments();
if (!explicitTargs.isEmpty()) {
// we have explicit type arguments
List<JTypeVar> tparams = m.getTypeParameters();
if (tparams.size() != explicitTargs.size()) {
// normally checked by isPotentiallyApplicable
throw ResolutionFailedException.incompatibleTypeParamCount(LOG, site.getExpr(), m, explicitTargs.size(), tparams.size());
}
Substitution explicitSubst = Substitution.mapping(tparams, explicitTargs);
for (int i = 0; i < tparams.size(); i++) {
JTypeMirror explicit = explicitTargs.get(i);
JTypeMirror upperBound = tparams.get(i).getUpperBound().subst(explicitSubst);
if (explicit.isConvertibleTo(upperBound).never()) {
throw ResolutionFailedException.incompatibleBound(LOG, explicit, upperBound, expr.getExplicitTargLoc(i));
}
}
JMethodSig subst = m.subst(explicitSubst);
// check that the arguments are conformant
// the inference context is empty because all param types are ground.
addArgsConstraints(emptyContext(), subst, site, phase);
return subst;
}
site.maySkipInvocation(!ExprOps.isContextDependent(m) && site.getOuterCtx().isGround(m.getReturnType()));
return instantiateImpl(m, site, phase);
}
/**
* Perform actual inference. If the method is return-type-polymorphic,
* then we delegate the solving to the call site's inference context,
* which knows more, however we add inference vars and their constraints
* to it.
*/
private JMethodSig instantiateImpl(JMethodSig m, MethodCallSite site, MethodResolutionPhase phase) {
InferenceContext infCtx = newContextFor(m); // b0
LOG.ctxInitialization(infCtx, m);
try {
if (phase.isInvocation() && !isPreJava8) {
m = doReturnChecksAndChangeReturnType(m, site, infCtx);
}
addArgsConstraints(infCtx, m, site, phase); // c
infCtx.incorporate(); // b2
if (phase.isInvocation()) {
boolean shouldPropagate = shouldPropagateOutwards(m.getReturnType(), site, infCtx);
//propagate outwards if needed
if (shouldPropagate) {
// propagate inference context outwards and exit
// the outer context will solve the variables and call listeners
// of this context
LOG.propagateAndAbort(infCtx, site.getOuterCtx());
infCtx.duplicateInto(site.getOuterCtx());
return infCtx.mapToIVars(m);
}
}
// this may throw for incompatible bounds
boolean isDone = infCtx.solve(/*onlyBoundedVars:*/isPreJava8());
if (isPreJava8() && !isDone) {
// this means we're not in an invocation context,
// if we are, we must ignore it in java 7
if (site.getOuterCtx().isEmpty()) {
// Then add the return contraints late
// Java 7 only uses the context type if the arguments are not enough
// https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.8
m = doReturnChecksAndChangeReturnType(m, site, infCtx);
}
// otherwise force solving remaining vars
infCtx.solve();
}
if (infCtx.needsUncheckedConversion()) {
site.setNeedsUncheckedConversion();
}
// instantiate vars and return
return InferenceContext.finalGround(infCtx.mapToIVars(m));
} finally {
// Note that even if solve succeeded, listeners checking deferred
// bounds may still throw ResolutionFailedException, in which case
// by the laws of finally, this exception will be thrown and the
// return value will be ignored.
infCtx.callListeners();
}
}
private JMethodSig doReturnChecksAndChangeReturnType(JMethodSig m, MethodCallSite site, InferenceContext infCtx) {
LOG.startReturnChecks();
JTypeMirror actualResType = addReturnConstraints(infCtx, m, site); // b3
LOG.endReturnChecks();
m = m.internalApi().withReturnType(actualResType);
return m;
}
private boolean shouldPropagateOutwards(JTypeMirror resultType, MethodCallSite target, InferenceContext inferenceContext) {
return !isPreJava8
&& !target.getOuterCtx().isEmpty() //enclosing context is a generic method
&& !inferenceContext.isGround(resultType) //return type contains inference vars
&& !(resultType instanceof InferenceVar //no eager instantiation is required (as per 18.5.2)
&& needsEagerInstantiation((InferenceVar) resultType, target.getExpectedType(), inferenceContext));
}
/**
* Add more constraints on the inference vars based on the expected
* return type at the call site. This is described in
*
* https://docs.oracle.com/javase/specs/jls/se9/html/jls-18.html#jls-18.5.2.1
*
* under "Let B3 be the bound set derived from B2 as follows."
*
* <p>This binds the ivars of this context to those of the outer context.
*/
private JTypeMirror addReturnConstraints(InferenceContext infCtx, JMethodSig m, MethodCallSite site) {
/*
Remember: calling stuff like isConvertible or isSubtype
adds constraints on the type variables that are found there.
*/
JTypeMirror resultType = m.getReturnType();
if (site.needsUncheckedConversion()) {
// if unchecked conversion is necessary, the result type,
// and all thrown exception types, are erased.
resultType = resultType.getErasure();
}
resultType = infCtx.mapToIVars(resultType);
InferenceContext outerInfCtx = site.getOuterCtx();
if (!infCtx.isGround(resultType) && !outerInfCtx.isEmpty() && resultType instanceof JClassType) {
JClassType resClass = capture((JClassType) resultType);
resultType = resClass;
for (JTypeMirror targ : resClass.getTypeArgs()) {
if (targ instanceof JTypeVar && ((JTypeVar) targ).isCaptured()) {
infCtx.addVar((JTypeVar) targ);
}
}
resultType = infCtx.mapToIVars(resultType);
}
JTypeMirror actualRes = site.getExpectedType();
if (actualRes == null) {
actualRes = ts.OBJECT;
}
if (resultType instanceof InferenceVar) {
InferenceVar retVar = (InferenceVar) resultType;
if (needsEagerInstantiation(retVar, actualRes, infCtx)) {
infCtx.solve(retVar);
infCtx.callListeners();
if (isConvertible(retVar.getInst(), actualRes, true).never()) {
actualRes = ts.OBJECT;
}
} else if (actualRes.isPrimitive()) {
actualRes = actualRes.box();
}
}
if (isConvertible(resultType, outerInfCtx.mapToIVars(actualRes), true).never()) {
throw ResolutionFailedException.incompatibleReturn(LOG, site.getExpr(), resultType, actualRes);
}
return resultType;
}
/**
* Returns true if the inference var needs to be instantiated eagerly,
* as described in JLS§18.5.2.1. (Poly Method Invocation Compatibility)
*
* https://docs.oracle.com/javase/specs/jls/se9/html/jls-18.html#jls-18.5.2.1
*
* @param alpha Inference var
* @param t Target type of the invocation
* @param infCtx Inference context
*/
private boolean needsEagerInstantiation(InferenceVar alpha, JTypeMirror t, InferenceContext infCtx) {
if (t == null) {
return false;
}
if (t.isPrimitive()) {
// T is a primitive type, and one of the primitive wrapper classes is an instantiation,
// upper bound, or lower bound for alpha in B2.
for (JTypeMirror b : alpha.getBounds(BoundKind.ALL)) {
if (b.isBoxedPrimitive()) {
return true;
}
}
return false;
}
// T is a reference type, but is not a wildcard-parameterized type, and either
if (!t.isPrimitive() && !isWilcardParameterized(t)) {
// i) B2 contains a bound of one of the forms alpha = S or S <: alpha,
// where S is a wildcard-parameterized type, or
for (JTypeMirror s : alpha.getBounds(BoundKind.EQ_LOWER)) {
if (isWilcardParameterized(s)) {
return true;
}
}
// ii) B2 contains two bounds of the forms S1 <: alpha and S2 <: alpha,
// where S1 and S2 have supertypes that are two different
// parameterizations of the same generic class or interface.
for (JTypeMirror aLowerBound : alpha.getBounds(BoundKind.LOWER)) {
for (JTypeMirror anotherLowerBound : alpha.getBounds(BoundKind.LOWER)) {
if (aLowerBound != anotherLowerBound // NOPMD CompareObjectsWithEquals
&& infCtx.isGround(aLowerBound)
&& infCtx.isGround(anotherLowerBound)
&& commonSuperWithDiffParameterization(aLowerBound, anotherLowerBound)) {
return true;
}
}
}
}
// T is a parameterization of a generic class or interface, G,
// and B2 contains a bound of one of the forms alpha = S or S <: alpha,
// where there exists no type of the form G<...> that is a
// supertype of S, but the raw type G is a supertype of S
if (t.isParameterizedType()) {
for (JTypeMirror b : alpha.getBounds(BoundKind.EQ_LOWER)) {
JTypeMirror sup = b.getAsSuper(((JClassType) t).getSymbol());
if (sup != null && sup.isRaw()) {
return true;
}
}
}
return false;
}
private boolean commonSuperWithDiffParameterization(JTypeMirror t, JTypeMirror s) {
JTypeMirror lubResult = ts.lub(listOf(t, s));
if (lubResult.isBottom() || lubResult.isTop()) {
return false;
}
for (JTypeMirror sup : asList(lubResult)) {
if (sup.isParameterizedType()) {
JClassSymbol sym = ((JClassType) sup).getSymbol();
JTypeMirror asSuperOfT = t.getAsSuper(sym);
JTypeMirror asSuperOfS = s.getAsSuper(sym);
if (!asSuperOfS.equals(asSuperOfT)) {
return true;
}
}
}
return false;
}
/**
* Generate bounds on the ivars based on the expected/actual types
* of the arguments to the call. This is described in
*
* https://docs.oracle.com/javase/specs/jls/se9/html/jls-18.html#jls-18.5.1
*
* as being the set C.
*
* <p>For invocation applicability inference (phases {@link MethodResolutionPhase#STRICT STRICT}
* through {@link MethodResolutionPhase#VARARGS VARARGS}), only arguments
* that are {@linkplain ExprOps#isPertinentToApplicability(ExprMirror, JMethodSig, JTypeMirror, InvocationMirror)
* pertinent to applicability}
* are considered. Arguments like lambdas do not influence the applicability
* check beyond checking their basic 'shape' (number of params)
* to check that the method is {@linkplain #isPotentiallyApplicable(JMethodSig, InvocationMirror) potentially
* applicable}, which is done very much earlier.
* So they don't add constraints during those first phases.
*
* <p>When we have found an applicable method and are instantiating it
* (phases {@link MethodResolutionPhase#INVOC_STRICT INVOC_STRICT} through {@link
* MethodResolutionPhase#INVOC_VARARGS INVOC_VARARGS}),
* all arguments are considered so as to yield sharper bounds.
*
* @param infCtx Inference context
* @param m Tested method
* @param site Invocation expression
* @param phase Phase (determines what constraints are allowed)
*/
private void addArgsConstraints(InferenceContext infCtx, JMethodSig m, MethodCallSite site, MethodResolutionPhase phase) {
LOG.startArgsChecks();
InvocationMirror expr = site.getExpr();
boolean varargsRequired = phase.requiresVarargs();
if (!varargsRequired && m.getArity() != expr.getArgumentCount()) {
throw ResolutionFailedException.incompatibleArity(LOG, expr.getArgumentCount(), m.getArity(), expr);
}
List<JTypeMirror> fs = m.getFormalParameters();
@Nullable
JArrayType varargsParam = varargsRequired && m.isVarargs() ? (JArrayType) fs.get(fs.size() - 1) : null;
int lastP = varargsParam == null ? fs.size() : fs.size() - 1;
List<ExprMirror> args = expr.getArgumentExpressions();
for (int i = 0; i < lastP; i++) {
ExprMirror ei = args.get(i);
if (phase.isInvocation() || isPertinentToApplicability(ei, m, fs.get(i), expr)) {
JTypeMirror stdType = ei.getStandaloneType();
JTypeMirror fi = infCtx.mapToIVars(fs.get(i));
LOG.startArg(i, ei, fi);
if (!phase.canBox()) {
// these are cases where applicability is impossible (in strict ctx)
if (stdType != null && stdType.isPrimitive() != fi.isPrimitive() && stdType != ts.UNKNOWN) {
throw ResolutionFailedException.incompatibleFormal(LOG, ei, stdType, fi);
}
}
addBoundOrDefer(site, infCtx, phase, ei, fi);
LOG.endArg();
} else {
// then the final reinvocation is necessary
site.maySkipInvocation(false);
LOG.skipArgAsNonPertinent(i, ei);
}
}
if (varargsRequired && varargsParam != null) {
JTypeMirror varargsComponent = infCtx.mapToIVars(varargsParam.getComponentType());
// possibly some varargs arguments left
for (int i = lastP; i < args.size(); i++) {
ExprMirror ei = args.get(i);
if (phase.isInvocation() || isPertinentToApplicability(ei, m, varargsComponent, expr)) {
LOG.startArg(i, ei, varargsComponent);
addBoundOrDefer(site, infCtx, phase, ei, varargsComponent);
LOG.endArg();
} else {
site.maySkipInvocation(false);
LOG.skipArgAsNonPertinent(i, ei);
}
}
}
LOG.endArgsChecks();
}
/**
* This corresponds to the attribution of expression compatibility
* constraints in https://docs.oracle.com/javase/specs/jls/se9/html/jls-18.html#jls-18.2.1
* although it's not implemented as described.
*
* See {@link ExprCheckHelper#isCompatible(JTypeMirror, ExprMirror)}.
*/
private void addBoundOrDefer(@Nullable MethodCallSite site, InferenceContext infCtx, MethodResolutionPhase phase, @NonNull ExprMirror arg, @NonNull JTypeMirror formalType) {
ExprChecker exprChecker =
(ctx, exprType, formalType1) -> checkConvertibleOrDefer(ctx, exprType, formalType1, arg, phase, site);
ExprCheckHelper helper = new ExprCheckHelper(infCtx, phase, exprChecker, site, this);
if (!helper.isCompatible(formalType, arg)) {
throw ResolutionFailedException.incompatibleFormalExprNoReason(LOG, arg, formalType);
}
}
/**
* Add a compatibility constraint between an exprType and a formalType.
* This asserts {@code exprType <: formalType}, the arg parameter is only
* used for reporting.
*
* <p>This method is called back to by {@link ExprCheckHelper#isCompatible(JTypeMirror, ExprMirror)}.
*/
void checkConvertibleOrDefer(InferenceContext infCtx, JTypeMirror exprType, JTypeMirror formalType, ExprMirror arg, MethodResolutionPhase phase, @Nullable MethodCallSite site) {
if (!infCtx.isGround(formalType) || !infCtx.isGround(exprType)) {
// defer the check
infCtx.addInstantiationListener(setOf(formalType, exprType), solvedCtx -> checkConvertibleOrDefer(solvedCtx, exprType, formalType, arg, phase, site));
}
JTypeMirror groundE = infCtx.ground(exprType);
JTypeMirror groundF = infCtx.ground(formalType);
// This method call does all the work of adding constraints
// If groundE or groundF are in fact not ground, then constraints
// on the ivars that appear within them are implicitly added during
// the subtyping check. The call then returns true and we return
// normally
// If they are ground, then they must conform to each other else
// the exception stops the resolution process.
Convertibility isConvertible = isConvertible(groundE, groundF, phase.canBox());
if (isConvertible.never()) {
throw ResolutionFailedException.incompatibleFormal(LOG, arg, groundE, groundF);
} else if (isConvertible.withUncheckedWarning() && site != null) {
site.setNeedsUncheckedConversion();
}
}
/**
* Convertibility in *invocation* context.
*
* https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.3
*/
static Convertibility isConvertible(JTypeMirror exprType, JTypeMirror formalType, boolean canBox) {
if (exprType == formalType) { // NOPMD CompareObjectsWithEquals
// fast path
return Convertibility.SUBTYPING;
}
if (canBox && exprType.isPrimitive() ^ formalType.isPrimitive()) {
// then boxing conversions may be useful
Convertibility result = TypeOps.isConvertible(exprType.box(), formalType.box());
if (!result.never()) {
return result;
} else {
return TypeOps.isConvertible(exprType.unbox(), formalType.unbox());
}
}
return TypeOps.isConvertible(exprType, formalType);
}
/**
* Returns true if the method is potentially applicable to the invocation
* expression expr, as specified in JLS§15.12.2.1.
*
* https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.12.2.1
*
* <p>This assumes the name of the method matches the expression, and
* the method is accessible.
*
* @param m Method to test
* @param expr Invocation expression
*/
private boolean isPotentiallyApplicable(JMethodSig m, InvocationMirror expr) {
if (m.isGeneric()
&& !expr.getExplicitTypeArguments().isEmpty()
&& expr.getExplicitTypeArguments().size() != m.getTypeParameters().size()) {
return false;
}
List<ExprMirror> args = expr.getArgumentExpressions();
if (!m.isVarargs()) {
// we can avoid computing formal parameters by using getArity here
if (args.size() != m.getArity()) {
return false;
}
List<JTypeMirror> fs = m.getFormalParameters();
for (int i = 0; i < args.size(); i++) {
if (!exprOps.isPotentiallyCompatible(m, args.get(i), fs.get(i))) {
return false;
}
}
} else {
List<JTypeMirror> fs = m.getFormalParameters();
// test first n-1 params
int varargIdx = fs.size() - 1;
for (int i = 0; i < varargIdx; i++) {
if (i >= args.size()) {
// not enough arguments
return false;
}
if (!exprOps.isPotentiallyCompatible(m, args.get(i), fs.get(i))) {
return false;
}
}
if (args.size() == varargIdx - 1) {
return true;
}
if (args.size() == fs.size()) {
ExprMirror last = args.get(varargIdx);
JArrayType t = (JArrayType) fs.get(varargIdx);
return exprOps.isPotentiallyCompatible(m, last, t)
|| exprOps.isPotentiallyCompatible(m, last, t.getComponentType());
}
if (args.size() > fs.size()) {
JTypeMirror t = ((JArrayType) fs.get(varargIdx)).getComponentType();
for (int i = varargIdx; i < args.size(); i++) {
if (!exprOps.isPotentiallyCompatible(m, args.get(i), t)) {
return false;
}
}
}
}
return true;
}
}
| 41,785 | 39.84653 | 181 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ResolutionFailedException.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import static net.sourceforge.pmd.lang.java.types.internal.infer.ResolutionFailure.UNKNOWN;
import java.util.List;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.types.JMethodSig;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.TypePrettyPrint;
import net.sourceforge.pmd.lang.java.types.TypePrettyPrint.TypePrettyPrinter;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.MethodRefMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar.BoundKind;
/**
* Carrier for {@link ResolutionFailure}. Throwing an exception is the
* best way to abort resolution, but creating a new exception each time
* is wasteful and unnecessary. There is one exception instance per thread
* and the {@link ResolutionFailure} is set on it before it's thrown.
*/
final class ResolutionFailedException extends RuntimeException {
private static final ThreadLocal<ResolutionFailedException> SHARED = ThreadLocal.withInitial(ResolutionFailedException::new);
private static final boolean SHARE_EXCEPTION = true;
private ResolutionFailure failure;
private ResolutionFailedException() {
}
public ResolutionFailure getFailure() {
return failure;
}
public void setFailure(ResolutionFailure location) {
this.failure = location;
}
static ResolutionFailedException getSharedInstance() {
return SHARED.get();
}
@Override
public String toString() {
return "ResolutionFailedException:failure=" + failure;
}
// If the logger is noop we don't even create the failure.
// These failures are extremely frequent (and normal), and type pretty-printing is expensive
static ResolutionFailedException incompatibleBound(TypeInferenceLogger logger, InferenceVar ivar, BoundKind k1, JTypeMirror b1, BoundKind k2, JTypeMirror b2) {
// in javac it's "no instance of type variables exist ..."
return getShared(logger.isNoop() ? UNKNOWN : new ResolutionFailure(
null,
"Incompatible bounds: " + k1.format(ivar, b1) + " and " + k2.format(ivar, b2)
));
}
static ResolutionFailedException incompatibleBound(TypeInferenceLogger logger, JTypeMirror actual, JTypeMirror formal, JavaNode explicitTarg) {
return getShared(logger.isNoop() ? UNKNOWN : new ResolutionFailure(
explicitTarg,
"Incompatible bounds: " + actual + " does not conform to " + formal
));
}
static ResolutionFailedException incompatibleTypeParamCount(TypeInferenceLogger logger, ExprMirror site, JMethodSig m, int found, int required) {
return getShared(logger.isNoop() ? UNKNOWN : new ResolutionFailure(site.getLocation(), "Wrong number of type arguments"));
}
static ResolutionFailedException incompatibleFormal(TypeInferenceLogger logger, ExprMirror arg, JTypeMirror found, JTypeMirror required) {
return getShared(logger.isNoop() ? UNKNOWN : new ResolutionFailure(
// this constructor is pretty expensive due to the pretty printing when log is enabled
arg.getLocation(),
"Incompatible formals: " + isNotConvertibleMessage(found, required)
));
}
static ResolutionFailedException incompatibleReturn(TypeInferenceLogger logger, ExprMirror expr, JTypeMirror found, JTypeMirror required) {
// in javac it's "no instance of type variables exist ..."
return getShared(logger.isNoop() ? UNKNOWN : new ResolutionFailure(
expr.getLocation(),
"Incompatible return type: " + isNotConvertibleMessage(found, required)
));
}
private static @NonNull String isNotConvertibleMessage(JTypeMirror found, JTypeMirror required) {
String fs = found.toString();
String rs = required.toString();
if (fs.equals(rs)) {
// This often happens with type variables, which usually
// are named T,K,V,U,S, etc. This makes name conflicts harder
// to see
// Better would be to pretty print in a location-aware way:
// hidden/out of scope tvars would be qualified
final TypePrettyPrinter PRETTY_PRINTER_CONFIG = new TypePrettyPrinter().qualifyTvars(true);
fs = TypePrettyPrint.prettyPrint(found, PRETTY_PRINTER_CONFIG);
rs = TypePrettyPrint.prettyPrint(required, PRETTY_PRINTER_CONFIG);
}
return fs + " is not convertible to " + rs;
}
static ResolutionFailedException incompatibleFormalExprNoReason(TypeInferenceLogger logger, ExprMirror arg, JTypeMirror required) {
return getShared(logger.isNoop() ? UNKNOWN : new ResolutionFailure(
arg.getLocation(),
"Argument expression is not compatible with " + required
));
}
static ResolutionFailedException notAVarargsMethod(TypeInferenceLogger logger, ExprMirror expr) {
return getShared(logger.isNoop() ? UNKNOWN : new ResolutionFailure(
expr.getLocation(),
"Method is not varargs"
));
}
static ResolutionFailedException unsolvableDependency(TypeInferenceLogger logger) {
return getShared(logger.isNoop() ? UNKNOWN
: new ResolutionFailure(null,
"Unsolvable inference variable dependency"));
}
static ResolutionFailedException incompatibleArity(TypeInferenceLogger logger, int found, int required, ExprMirror location) {
return getShared(logger.isNoop() ? UNKNOWN
: new ResolutionFailure(location.getLocation(),
"Incompatible arity: " + found + " != " + required));
}
static ResolutionFailedException lambdaCannotTargetVoidMethod(TypeInferenceLogger logger, ExprMirror location) {
return getShared(logger.isNoop() ? UNKNOWN
: new ResolutionFailure(location.getLocation(),
"Lambda cannot target void method"));
}
static ResolutionFailedException lambdaCannotTargetValueMethod(TypeInferenceLogger logger, ExprMirror location) {
return getShared(logger.isNoop() ? UNKNOWN
: new ResolutionFailure(location.getLocation(),
"Lambda cannot target non-void method"));
}
static ResolutionFailedException boundMethodRef(TypeInferenceLogger logger, ExprMirror location) {
return getShared(logger.isNoop() ? UNKNOWN
: new ResolutionFailure(location.getLocation(),
"Lambda cannot target non-void method"));
}
static ResolutionFailedException mismatchedLambdaParameters(TypeInferenceLogger logger, JMethodSig expected, List<JTypeMirror> found, ExprMirror location) {
return getShared(logger.isNoop() ? UNKNOWN
: new ResolutionFailure(location.getLocation(),
"Mismatched lambda parameter types: found " + found + " cannot be parameters of " + expected));
}
static ResolutionFailedException cannotInvokeInstanceMethodOnPrimitive(TypeInferenceLogger logger, JTypeMirror actual, ExprMirror location) {
return getShared(logger.isNoop() ? UNKNOWN
: new ResolutionFailure(location.getLocation(),
"Cannot invoke instance method on primitive: "
+ actual));
}
static ResolutionFailedException noCtDeclaration(TypeInferenceLogger logger, JMethodSig fun, MethodRefMirror mref) {
return getShared(logger.isNoop() ? UNKNOWN
: new ResolutionFailure(mref.getLocation(),
"No compile time declaration found conforming to: "
+ fun));
}
static ResolutionFailedException notAFunctionalInterface(TypeInferenceLogger logger, JTypeMirror failedCandidate, ExprMirror loc) {
return getShared(logger.isNoop() ? UNKNOWN
: new ResolutionFailure(loc.getLocation(),
"Not a functional interface: " + failedCandidate));
}
static ResolutionFailedException missingTargetTypeForFunctionalExpr(TypeInferenceLogger logger, ExprMirror loc) {
return getShared(logger.isNoop() ? UNKNOWN
: new ResolutionFailure(loc.getLocation(),
"Missing target type for functional expression"));
}
static ResolutionFailedException lambdaCannotTargetGenericFunction(TypeInferenceLogger logger, JMethodSig fun, ExprMirror loc) {
return getShared(logger.isNoop() ? UNKNOWN
: new ResolutionFailure(loc.getLocation(),
"Lambda expression cannot target a generic method: "
+ fun));
}
static ResolutionFailedException boundCallableReference(TypeInferenceLogger logger, JMethodSig fun, ExprMirror loc) {
return getShared(logger.isNoop() ? UNKNOWN
: new ResolutionFailure(loc.getLocation(),
"Lambda expression cannot target a generic method: "
+ fun));
}
private static @NonNull ResolutionFailedException getShared(ResolutionFailure failure) {
ResolutionFailedException instance = SHARE_EXCEPTION ? getSharedInstance()
: new ResolutionFailedException();
instance.setFailure(failure);
return instance;
}
}
| 10,635 | 49.407583 | 163 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ast/BasePolyMirror.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer.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.InternalApiBridge;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.ast.TypeNode;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.PolyExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ast.JavaExprMirrors.MirrorMaker;
abstract class BasePolyMirror<T extends JavaNode> extends BaseExprMirror<T> implements PolyExprMirror {
private final MirrorMaker subexprMaker;
private JTypeMirror inferredType;
BasePolyMirror(JavaExprMirrors mirrors, T myNode, @Nullable ExprMirror parent, MirrorMaker subexprMaker) {
super(mirrors, myNode, parent);
this.subexprMaker = subexprMaker;
}
protected ExprMirror createSubexpression(ASTExpression subexpr) {
return subexprMaker.createMirrorForSubexpression(subexpr, this, subexprMaker);
}
@Override
public void setInferredType(JTypeMirror mirror) {
this.inferredType = mirror;
if (myNode instanceof TypeNode && mayMutateAst()) {
InternalApiBridge.setTypeMirrorInternal((TypeNode) myNode, mirror);
}
}
@Override
public JTypeMirror getInferredType() {
return inferredType;
}
@Override
public @NonNull JClassType getEnclosingType() {
return myNode.getEnclosingType().getTypeMirror();
}
}
| 1,889 | 34 | 110 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ast/ConditionalMirrorImpl.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer.ast;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import java.util.function.Predicate;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.ASTConditionalExpression;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTMethodCall;
import net.sourceforge.pmd.lang.java.ast.InternalApiBridge;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.TypeConversion;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.BranchingMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.MethodCallSite;
import net.sourceforge.pmd.lang.java.types.internal.infer.ast.JavaExprMirrors.MirrorMaker;
class ConditionalMirrorImpl extends BasePolyMirror<ASTConditionalExpression> implements BranchingMirror {
ExprMirror thenBranch;
ExprMirror elseBranch;
private final boolean mayBePoly;
ConditionalMirrorImpl(JavaExprMirrors mirrors, ASTConditionalExpression expr, boolean isStandalone, @Nullable ExprMirror parent, MirrorMaker subexprMaker) {
super(mirrors, expr, parent, subexprMaker);
thenBranch = mirrors.getBranchMirrorSubexpression(myNode.getThenBranch(), isStandalone, this, subexprMaker);
elseBranch = mirrors.getBranchMirrorSubexpression(myNode.getElseBranch(), isStandalone, this, subexprMaker);
this.mayBePoly = !isStandalone;
}
@Override
public boolean branchesMatch(Predicate<? super ExprMirror> condition) {
return condition.test(thenBranch) && condition.test(elseBranch);
}
@Override
public void setStandalone() {
if (mayMutateAst()) {
InternalApiBridge.setStandaloneTernary(myNode);
}
}
@Override
public @Nullable JTypeMirror getStandaloneType() {
// may have been set by an earlier call
JTypeMirror current = InternalApiBridge.getTypeMirrorInternal(myNode);
if (current != null && (current.unbox().isPrimitive() || !mayBePoly)) {
// standalone
return current;
}
JTypeMirror condType = getConditionalStandaloneType(this, myNode);
if (condType != null) {
InternalApiBridge.setTypeMirrorInternal(myNode, condType);
}
assert mayBePoly || condType != null : "This conditional expression is standalone!";
return condType;
}
/**
* Conditional expressions are standalone iff both their branches
* are of a primitive type (or a primitive wrapper type), or they
* appear in a cast context. This may involve inferring the compile-time
* declaration of a method call.
*
* https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25
*/
private JTypeMirror getConditionalStandaloneType(ConditionalMirrorImpl mirror, ASTConditionalExpression cond) {
@Nullable JTypeMirror thenType = standaloneExprTypeInConditional(mirror.thenBranch, cond.getThenBranch());
if (mayBePoly && (thenType == null || !thenType.unbox().isPrimitive())) {
return null; // then it's a poly
}
@Nullable JTypeMirror elseType = standaloneExprTypeInConditional(mirror.elseBranch, cond.getElseBranch());
if (mayBePoly && (elseType == null || !elseType.unbox().isPrimitive())) {
return null; // then it's a poly
}
if (thenType == null || elseType == null) {
// this is a standalone conditional (mayBePoly == false),
// otherwise we would have returned null early.
if (thenType == null ^ elseType == null) {
return thenType == null ? elseType : thenType; // the one that is non-null
}
return factory.ts.NULL_TYPE;
}
// both are non-null
// this is a standalone, the following returns non-null
if (elseType.unbox().equals(thenType.unbox())) {
// eg (Integer, Integer) -> Integer but (Integer, int) -> int
return thenType.equals(elseType) ? thenType : thenType.unbox();
}
if (thenType.isNumeric() && elseType.isNumeric()) {
return TypeConversion.binaryNumericPromotion(thenType.unbox(), elseType.unbox());
}
// Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1
// be the type that results from applying boxing conversion to S1, and let T2 be the type
// that results from applying boxing conversion to S2. The type of the conditional expression
// is the result of applying capture conversion (§5.1.10) to lub(T1, T2).
return TypeConversion.capture(factory.ts.lub(listOf(thenType.box(), elseType.box())));
}
private JTypeMirror standaloneExprTypeInConditional(ExprMirror mirror, ASTExpression e) {
if (mirror instanceof StandaloneExprMirror) {
// An expression of a standalone form (§15.2) that has type boolean or Boolean.
// An expression of a standalone form (§15.2) with a type that is convertible to a numeric type (§4.2, §5.1.8).
return mirror.getStandaloneType();
}
if (mirror instanceof CtorInvocationMirror) {
// A class instance creation expression (§15.9) for class Boolean.
// A class instance creation expression (§15.9) for a class that is convertible to a numeric type.
return ((CtorInvocationMirror) mirror).getNewType().unbox();
}
if (mirror instanceof BranchingMirror) {
// A boolean conditional expression.
// A numeric conditional expression.
return mirror.getStandaloneType();
}
if (e instanceof ASTMethodCall) {
/*
A method invocation expression (§15.12) for which the chosen most specific method (§15.12.2.5) has return type boolean or Boolean.
Note that, for a generic method, this is the type before instantiating the method's type arguments.
*/
JTypeMirror current = InternalApiBridge.getTypeMirrorInternal(e);
if (current != null) {
// don't redo the compile-time decl resolution
// The CTDecl is cached on the mirror, not the node
return current;
}
MethodCallSite site = factory.infer.newCallSite((InvocationMirror) mirror, null);
return factory.infer.getCompileTimeDecl(site)
.getMethodType()
.getReturnType();
}
return null;
}
}
| 6,871 | 41.95 | 160 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ast/BaseFunctionalMirror.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer.ast;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.FunctionalExpression;
import net.sourceforge.pmd.lang.java.ast.InternalApiBridge;
import net.sourceforge.pmd.lang.java.types.JMethodSig;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.FunctionalExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ast.JavaExprMirrors.MirrorMaker;
/**
*
*/
abstract class BaseFunctionalMirror<N extends FunctionalExpression> extends BasePolyMirror<N> implements FunctionalExprMirror {
private JMethodSig inferredMethod;
BaseFunctionalMirror(JavaExprMirrors mirrors, N myNode, @Nullable ExprMirror parent, MirrorMaker subexprMaker) {
super(mirrors, myNode, parent, subexprMaker);
}
@Override
public void setFunctionalMethod(JMethodSig methodType) {
this.inferredMethod = methodType;
if (mayMutateAst()) {
InternalApiBridge.setFunctionalMethod(myNode, methodType);
}
}
protected JMethodSig getInferredMethod() {
return inferredMethod;
}
}
| 1,323 | 33.842105 | 127 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ast/MethodRefMirrorImpl.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer.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.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTList;
import net.sourceforge.pmd.lang.java.ast.ASTMethodReference;
import net.sourceforge.pmd.lang.java.ast.ASTTypeExpression;
import net.sourceforge.pmd.lang.java.ast.InternalApiBridge;
import net.sourceforge.pmd.lang.java.ast.TypeNode;
import net.sourceforge.pmd.lang.java.types.JMethodSig;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.MethodRefMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ast.JavaExprMirrors.MirrorMaker;
import net.sourceforge.pmd.util.AssertionUtil;
import net.sourceforge.pmd.util.CollectionUtil;
final class MethodRefMirrorImpl extends BaseFunctionalMirror<ASTMethodReference> implements MethodRefMirror {
private JMethodSig exactMethod;
private JMethodSig ctdecl;
MethodRefMirrorImpl(JavaExprMirrors mirrors, ASTMethodReference lambda, ExprMirror parent, MirrorMaker subexprMaker) {
super(mirrors, lambda, parent, subexprMaker);
exactMethod = mirrors.ts.UNRESOLVED_METHOD;
// this is in case of failure: if the inference doesn't succeed
// and doesn't end up calling those, then we still have a non-null
// result in there.
setFunctionalMethod(mirrors.ts.UNRESOLVED_METHOD);
setCompileTimeDecl(mirrors.ts.UNRESOLVED_METHOD);
// don't call this one as it would mean to the node "don't recompute my type"
// even if a parent conditional failed its standalone test
// setInferredType(mirrors.ts.UNKNOWN);
}
@Override
public boolean isEquivalentToUnderlyingAst() {
AssertionUtil.validateState(ctdecl != null, "overload resolution is not complete");
// must bind to the same ctdecl.
return myNode.getReferencedMethod().equals(ctdecl);
}
@Override
public boolean isConstructorRef() {
return myNode.isConstructorReference();
}
@Override
public JTypeMirror getLhsIfType() {
ASTExpression lhsType = myNode.getQualifier();
return lhsType instanceof ASTTypeExpression
? lhsType.getTypeMirror()
: null;
}
@Override
public JTypeMirror getTypeToSearch() {
return myNode.getLhs().getTypeMirror();
}
@Override
public String getMethodName() {
return myNode.getMethodName();
}
@Override
public void setCompileTimeDecl(JMethodSig methodType) {
this.ctdecl = methodType;
InternalApiBridge.setCompileTimeDecl(myNode, methodType);
}
@Override
public @NonNull List<JTypeMirror> getExplicitTypeArguments() {
return CollectionUtil.map(
ASTList.orEmpty(myNode.getExplicitTypeArguments()),
TypeNode::getTypeMirror
);
}
@Override
public JMethodSig getCachedExactMethod() {
return exactMethod;
}
@Override
public void setCachedExactMethod(@Nullable JMethodSig sig) {
exactMethod = sig;
}
}
| 3,440 | 32.735294 | 122 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ast/LambdaMirrorImpl.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer.ast;
import java.util.Collections;
import java.util.List;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.ASTAssignmentExpression;
import net.sourceforge.pmd.lang.java.ast.ASTBlock;
import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTLambdaExpression;
import net.sourceforge.pmd.lang.java.ast.ASTLambdaParameter;
import net.sourceforge.pmd.lang.java.ast.ASTLambdaParameterList;
import net.sourceforge.pmd.lang.java.ast.ASTMethodCall;
import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement;
import net.sourceforge.pmd.lang.java.ast.ASTThrowStatement;
import net.sourceforge.pmd.lang.java.ast.ASTUnaryExpression;
import net.sourceforge.pmd.lang.java.ast.TypeNode;
import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol;
import net.sourceforge.pmd.lang.java.types.JMethodSig;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.TypingContext;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.LambdaExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ast.JavaExprMirrors.MirrorMaker;
import net.sourceforge.pmd.util.AssertionUtil;
class LambdaMirrorImpl extends BaseFunctionalMirror<ASTLambdaExpression> implements LambdaExprMirror {
private final List<JVariableSymbol> formalSymbols;
LambdaMirrorImpl(JavaExprMirrors mirrors, ASTLambdaExpression lambda, @Nullable ExprMirror parent, MirrorMaker subexprMaker) {
super(mirrors, lambda, parent, subexprMaker);
if (isExplicitlyTyped()) {
formalSymbols = Collections.emptyList();
} else {
// we'll have one tentative binding per formal param
formalSymbols = myNode.getParameters().toStream().toList(p -> p.getVarId().getSymbol());
// initialize the typing context
TypingContext parentCtx = parent == null ? TypingContext.DEFAULT : parent.getTypingContext();
List<JTypeMirror> unknownFormals = Collections.nCopies(formalSymbols.size(), null);
setTypingContext(parentCtx.andThenZip(formalSymbols, unknownFormals));
}
}
@Override
public boolean isEquivalentToUnderlyingAst() {
JTypeMirror inferredType = getInferredType();
JMethodSig inferredMethod = getInferredMethod();
AssertionUtil.validateState(inferredType != null && inferredMethod != null,
"overload resolution is not complete");
ASTLambdaParameterList astFormals = myNode.getParameters();
List<JTypeMirror> thisFormals = inferredMethod.getFormalParameters();
for (int i = 0; i < thisFormals.size(); i++) {
if (!thisFormals.get(i).equals(astFormals.get(i).getTypeMirror())) {
return false;
}
}
// The intuition is that if all lambda parameters and enclosing
// parameters in the mirror mean the same as in the node,
// then all expressions occurring in the lambda must mean the
// same too.
return true;
}
@Override
public @Nullable List<JTypeMirror> getExplicitParameterTypes() {
ASTLambdaParameterList parameters = myNode.getParameters();
if (parameters.size() == 0) {
return Collections.emptyList();
}
List<JTypeMirror> types = parameters.toStream()
.map(ASTLambdaParameter::getTypeNode)
.toList(TypeNode::getTypeMirror);
return types.isEmpty() ? null : types;
}
@Override
public int getParamCount() {
return myNode.getParameters().size();
}
@Override
public List<ExprMirror> getResultExpressions() {
ASTBlock block = myNode.getBlock();
if (block == null) {
return Collections.singletonList(createSubexpression(myNode.getExpression()));
} else {
return block.descendants(ASTReturnStatement.class)
.map(ASTReturnStatement::getExpr)
.toList(this::createSubexpression);
}
}
@Override
public void updateTypingContext(JMethodSig groundFun) {
if (!isExplicitlyTyped()) {
// update bindings
setTypingContext(getTypingContext().andThenZip(formalSymbols, groundFun.getFormalParameters()));
}
}
@Override
public boolean isValueCompatible() {
ASTBlock block = myNode.getBlock();
return block == null || isLambdaBodyCompatible(block, false);
}
@Override
public boolean isVoidCompatible() {
ASTBlock block = myNode.getBlock();
if (block == null) {
return isExpressionStatement(myNode.getExpression());
} else {
return isLambdaBodyCompatible(block, true);
}
}
/**
* Malformed bodies may be neither (it's a compile error)
*/
private static boolean isLambdaBodyCompatible(ASTBlock body, boolean voidCompatible) {
boolean noReturnsWithExpr = body.descendants(ASTReturnStatement.class).none(it -> it.getExpr() != null);
if (noReturnsWithExpr && !voidCompatible) {
// normally we should be determining whether the block must complete abruptly on all paths
return body.descendants(ASTThrowStatement.class).nonEmpty();
}
return noReturnsWithExpr == voidCompatible;
}
/**
* Return true if the expression may return void.
*/
private static boolean isExpressionStatement(ASTExpression body) {
// statement expression
return body instanceof ASTMethodCall
|| body instanceof ASTConstructorCall
|| body instanceof ASTAssignmentExpression
|| body instanceof ASTUnaryExpression && !((ASTUnaryExpression) body).getOperator().isPure();
}
}
| 6,205 | 39.562092 | 130 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ast/CtorInvocMirror.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer.ast;
import static net.sourceforge.pmd.lang.java.types.TypeOps.lazyFilterAccessible;
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.ast.ASTConstructorCall;
import net.sourceforge.pmd.lang.java.ast.ASTEnumConstant;
import net.sourceforge.pmd.lang.java.ast.ASTExplicitConstructorInvocation;
import net.sourceforge.pmd.lang.java.ast.ASTType;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator;
import net.sourceforge.pmd.lang.java.symbols.table.internal.JavaResolvers;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.JMethodSig;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.CtorInvocationMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ast.JavaExprMirrors.MirrorMaker;
import net.sourceforge.pmd.util.IteratorUtil;
class CtorInvocMirror extends BaseInvocMirror<ASTConstructorCall> implements CtorInvocationMirror {
CtorInvocMirror(JavaExprMirrors mirrors, ASTConstructorCall call, ExprMirror parent, MirrorMaker subexprMaker) {
super(mirrors, call, parent, subexprMaker);
}
@Override
public @NonNull JClassType getEnclosingType() {
if (myNode.isAnonymousClass()) {
// protected constructors are visible when building
// an anonymous class instance todo is that tested?
return myNode.getAnonymousClassDeclaration().getTypeMirror();
}
return super.getEnclosingType();
}
@Override
public JTypeMirror getStandaloneType() {
if (isDiamond()) {
return null;
}
return getNewType();
}
@Override
public void finishStandaloneInference(@NonNull JTypeMirror standaloneType) {
if (mayMutateAst()) {
setCtDecl(getStandaloneCtdecl());
}
}
@Override
public @NonNull TypeSpecies getStandaloneSpecies() {
return TypeSpecies.REFERENCE;
}
@Override
public @Nullable JTypeMirror unresolvedType() {
JTypeMirror newT = getNewType();
if (myNode.usesDiamondTypeArgs()) {
if (myNode.getParent() instanceof ASTVariableDeclarator) {
// Foo<String> s = new Foo<>();
ASTType explicitType = ((ASTVariableDeclarator) myNode.getParent()).getVarId().getTypeNode();
if (explicitType != null) {
return explicitType.getTypeMirror();
}
}
if (newT instanceof JClassType) {
JClassType classt = (JClassType) newT;
// eg new Foo<>() -> Foo</*error*/>
List<JTypeMirror> fakeTypeArgs = Collections.nCopies(classt.getSymbol().getTypeParameterCount(), factory.ts.ERROR);
newT = classt.withTypeArguments(fakeTypeArgs);
}
}
return newT;
}
private List<JMethodSig> getVisibleCandidates(@NonNull JTypeMirror newType) {
if (myNode.isAnonymousClass()) {
return newType.isInterface() ? myNode.getTypeSystem().OBJECT.getConstructors()
: newType.getConstructors();
}
return newType.getConstructors();
}
@Override
public Iterable<JMethodSig> getAccessibleCandidates(JTypeMirror newType) {
List<JMethodSig> visibleCandidates = getVisibleCandidates(newType);
return lazyFilterAccessible(visibleCandidates, getEnclosingType().getSymbol());
}
@Override
public @NonNull JTypeMirror getNewType() {
JTypeMirror typeMirror = myNode.getTypeNode().getTypeMirror();
if (typeMirror instanceof JClassType) {
JClassType classTypeMirror = (JClassType) typeMirror;
if (isDiamond()) {
classTypeMirror = classTypeMirror.getGenericTypeDeclaration();
}
return classTypeMirror;
} else {
// this might happen if the type is not known (e.g. ts.UNKNOWN)
// or invalid (eg new T()), where T is a type variable
return typeMirror;
}
}
@Override
public boolean isDiamond() {
return myNode.usesDiamondTypeArgs();
}
@Override
public boolean isAnonymous() {
return myNode.isAnonymousClass();
}
static class EnumCtorInvocMirror extends BaseInvocMirror<ASTEnumConstant> implements CtorInvocationMirror {
EnumCtorInvocMirror(JavaExprMirrors mirrors, ASTEnumConstant call, ExprMirror parent, MirrorMaker subexprMaker) {
super(mirrors, call, parent, subexprMaker);
}
@Override
public Iterable<JMethodSig> getAccessibleCandidates(JTypeMirror newType) {
return newType.getConstructors();
}
@Override
public @NonNull JClassType getNewType() {
return getEnclosingType();
}
@Override
public boolean isAnonymous() {
return myNode.isAnonymousClass();
}
@Override
public boolean isDiamond() {
return false;
}
@Override
public @Nullable JTypeMirror unresolvedType() {
return getNewType();
}
}
static class ExplicitCtorInvocMirror extends BaseInvocMirror<ASTExplicitConstructorInvocation> implements CtorInvocationMirror {
ExplicitCtorInvocMirror(JavaExprMirrors mirrors, ASTExplicitConstructorInvocation call, ExprMirror parent, MirrorMaker subexprMaker) {
super(mirrors, call, parent, subexprMaker);
}
@Override
public Iterable<JMethodSig> getAccessibleCandidates(JTypeMirror newType) {
if (myNode.isThis()) {
return getEnclosingType().getConstructors();
}
return IteratorUtil.mapIterator(
newType.getConstructors(),
iter -> IteratorUtil.filter(iter, ctor -> JavaResolvers.isAccessibleIn(getEnclosingType().getSymbol().getNestRoot(), ctor.getSymbol(), true))
);
}
@Override
public @NonNull JClassType getNewType() {
// note that actually, for a qualified super ctor call,
// the new type should be reparameterized using the LHS.
// In valid code though, both are equivalent, todo unless the superclass is raw
// eg new Outer<String>().super()
JClassType encl = getEnclosingType();
return myNode.isThis() ? encl : encl.getSuperClass();
}
@Override
public @Nullable JTypeMirror unresolvedType() {
if (myNode.isThis()) {
return myNode.getEnclosingType().getTypeMirror();
} else {
return myNode.getEnclosingType().getTypeMirror().getSuperClass();
}
}
@Override
public boolean isAnonymous() {
return false;
}
@Override
public boolean isDiamond() {
return false;
}
}
}
| 7,399 | 34.07109 | 157 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ast/JavaExprMirrors.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer.ast;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.ASTConditionalExpression;
import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall;
import net.sourceforge.pmd.lang.java.ast.ASTEnumConstant;
import net.sourceforge.pmd.lang.java.ast.ASTExplicitConstructorInvocation;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTLambdaExpression;
import net.sourceforge.pmd.lang.java.ast.ASTMethodCall;
import net.sourceforge.pmd.lang.java.ast.ASTMethodReference;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchExpression;
import net.sourceforge.pmd.lang.java.ast.InvocationNode;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.BranchingMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.FunctionalExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.InvocationMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.Infer;
import net.sourceforge.pmd.lang.java.types.internal.infer.ast.CtorInvocMirror.EnumCtorInvocMirror;
import net.sourceforge.pmd.util.AssertionUtil;
/** Façade that creates {@link ExprMirror} instances. */
public final class JavaExprMirrors {
final Infer infer;
final TypeSystem ts;
private final boolean mayMutateAst;
private final MirrorMaker defaultSubexprMaker = this::makeSubexprDefault;
private JavaExprMirrors(Infer infer, boolean mayMutateAst) {
this.infer = infer;
this.ts = infer.getTypeSystem();
this.mayMutateAst = mayMutateAst;
}
public MirrorMaker defaultMirrorMaker() {
return defaultSubexprMaker;
}
/**
* This will mutate the AST, only one must be used per compilation unit.
*/
public static JavaExprMirrors forTypeResolution(Infer infer) {
return new JavaExprMirrors(infer, true);
}
/**
* The mirrors produced by this factory will not be able to mutate
* the AST. This lets the mirror be decorated to "pretend" the expression
* is something slightly different, without corrupting the data in the AST.
*/
public static JavaExprMirrors forObservation(Infer infer) {
return new JavaExprMirrors(infer, false);
}
boolean mayMutateAst() {
return mayMutateAst;
}
ExprMirror makeSubexprDefault(ASTExpression e, @Nullable ExprMirror parent, MirrorMaker subexprMaker) {
if (e instanceof InvocationNode) {
return getInvocationMirror((InvocationNode) e, parent, subexprMaker);
} else if (e instanceof ASTLambdaExpression || e instanceof ASTMethodReference) {
return getFunctionalMirror(e, parent, subexprMaker);
} else if (e instanceof ASTConditionalExpression) {
return new ConditionalMirrorImpl(this, (ASTConditionalExpression) e, false, parent, subexprMaker);
} else if (e instanceof ASTSwitchExpression) {
return new SwitchMirror(this, (ASTSwitchExpression) e, false, parent, subexprMaker);
} else {
// Standalone
return new StandaloneExprMirror(this, e, parent);
}
}
ExprMirror getBranchMirrorSubexpression(ASTExpression e, boolean isStandalone, @NonNull BranchingMirror parent, MirrorMaker subexprMaker) {
if (e instanceof ASTConditionalExpression) {
return new ConditionalMirrorImpl(this, (ASTConditionalExpression) e, isStandalone, parent, subexprMaker);
} else if (e instanceof ASTSwitchExpression) {
return new SwitchMirror(this, (ASTSwitchExpression) e, isStandalone, parent, subexprMaker);
} else {
return subexprMaker.createMirrorForSubexpression(e, parent, subexprMaker);
}
}
public InvocationMirror getTopLevelInvocationMirror(InvocationNode e) {
return getInvocationMirror(e, defaultMirrorMaker());
}
public InvocationMirror getInvocationMirror(InvocationNode e, MirrorMaker subexprMaker) {
return getInvocationMirror(e, null, subexprMaker);
}
private InvocationMirror getInvocationMirror(InvocationNode e, @Nullable ExprMirror parent, MirrorMaker subexprMaker) {
if (e instanceof ASTMethodCall) {
return new MethodInvocMirror(this, (ASTMethodCall) e, parent, subexprMaker);
} else if (e instanceof ASTConstructorCall) {
return new CtorInvocMirror(this, (ASTConstructorCall) e, parent, subexprMaker);
} else if (e instanceof ASTExplicitConstructorInvocation) {
return new CtorInvocMirror.ExplicitCtorInvocMirror(this, (ASTExplicitConstructorInvocation) e, parent, subexprMaker);
} else if (e instanceof ASTEnumConstant) {
return new EnumCtorInvocMirror(this, (ASTEnumConstant) e, parent, subexprMaker);
}
throw AssertionUtil.shouldNotReachHere("" + e);
}
/**
* A mirror that implements the rules for standalone conditional
* expressions correctly. getStandaloneType will work differently
* than the one yielded by {@link #getPolyBranchingMirror(ASTExpression)}
*/
public BranchingMirror getStandaloneBranchingMirror(ASTExpression e) {
if (e instanceof ASTConditionalExpression) {
return new ConditionalMirrorImpl(this, (ASTConditionalExpression) e, true, null, defaultMirrorMaker());
} else if (e instanceof ASTSwitchExpression) {
return new SwitchMirror(this, (ASTSwitchExpression) e, true, null, defaultMirrorMaker());
}
throw AssertionUtil.shouldNotReachHere("" + e);
}
/**
* @see #getStandaloneBranchingMirror(ASTExpression)
*/
public BranchingMirror getPolyBranchingMirror(ASTExpression e) {
if (e instanceof ASTConditionalExpression) {
return new ConditionalMirrorImpl(this, (ASTConditionalExpression) e, false, null, defaultMirrorMaker());
} else if (e instanceof ASTSwitchExpression) {
return new SwitchMirror(this, (ASTSwitchExpression) e, false, null, defaultMirrorMaker());
}
throw AssertionUtil.shouldNotReachHere("" + e);
}
public FunctionalExprMirror getTopLevelFunctionalMirror(ASTExpression e) {
return getFunctionalMirror(e, null, defaultMirrorMaker());
}
FunctionalExprMirror getFunctionalMirror(ASTExpression e, @Nullable ExprMirror parent, MirrorMaker subexprMaker) {
if (e instanceof ASTLambdaExpression) {
return new LambdaMirrorImpl(this, (ASTLambdaExpression) e, parent, subexprMaker);
} else if (e instanceof ASTMethodReference) {
return new MethodRefMirrorImpl(this, (ASTMethodReference) e, parent, subexprMaker);
}
throw AssertionUtil.shouldNotReachHere("" + e);
}
@FunctionalInterface
public interface MirrorMaker {
ExprMirror createMirrorForSubexpression(ASTExpression e, ExprMirror parent, MirrorMaker self);
}
}
| 7,282 | 43.680982 | 143 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ast/StandaloneExprMirror.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer.ast;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror;
class StandaloneExprMirror extends BaseExprMirror<ASTExpression> implements ExprMirror {
StandaloneExprMirror(JavaExprMirrors factory, ASTExpression myNode, @Nullable ExprMirror parent) {
super(factory, myNode, parent);
}
@Override
public @Nullable JTypeMirror getStandaloneType() {
return myNode.getTypeMirror(getTypingContext());
}
@Override
public void setInferredType(JTypeMirror mirror) {
// do nothing
}
@Override
public @Nullable JTypeMirror getInferredType() {
return null;
}
@Override
public boolean isEquivalentToUnderlyingAst() {
return myNode.getTypeMirror().equals(getStandaloneType());
}
}
| 1,102 | 27.282051 | 102 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ast/BaseExprMirror.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer.ast;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.TypingContext;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror;
abstract class BaseExprMirror<T extends JavaNode> implements ExprMirror {
final JavaExprMirrors factory;
final T myNode;
private final ExprMirror parent;
private TypingContext typingContext;
BaseExprMirror(JavaExprMirrors factory, T myNode, ExprMirror parent) {
this.factory = factory;
this.myNode = myNode;
this.parent = parent;
}
@Override
public JavaNode getLocation() {
return myNode;
}
@Override
public String toString() {
return "Mirror of: " + myNode;
}
protected boolean mayMutateAst() {
return this.factory.mayMutateAst();
}
@Override
public TypingContext getTypingContext() {
if (typingContext != null) {
return typingContext;
} else if (parent != null) {
return parent.getTypingContext();
} else {
return TypingContext.DEFAULT;
}
}
public void setTypingContext(TypingContext typingCtx) {
this.typingContext = typingCtx;
}
/**
* TODO get the type mirror like LazyTypeResolver does, but with a
* contextual mapping of symbol -> type. Lambda parameters may have
* a different type in this mirror hierarchy as they have in the AST.
*/
protected JTypeMirror typeOf(ASTExpression e) {
return e.getTypeMirror();
}
}
| 1,813 | 27.34375 | 79 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ast/BaseInvocMirror.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer.ast;
import java.util.List;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.ASTArgumentList;
import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall;
import net.sourceforge.pmd.lang.java.ast.ASTList;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.ast.InternalApiBridge;
import net.sourceforge.pmd.lang.java.ast.InvocationNode;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.ast.TypeNode;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.InvocationMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.MethodCallSite;
import net.sourceforge.pmd.lang.java.types.internal.infer.ast.JavaExprMirrors.MirrorMaker;
import net.sourceforge.pmd.util.AssertionUtil;
import net.sourceforge.pmd.util.CollectionUtil;
abstract class BaseInvocMirror<T extends InvocationNode> extends BasePolyMirror<T> implements InvocationMirror {
private MethodCtDecl ctDecl;
private List<ExprMirror> args;
BaseInvocMirror(JavaExprMirrors mirrors, T call, @Nullable ExprMirror parent, MirrorMaker subexprMaker) {
super(mirrors, call, parent, subexprMaker);
}
@Override
public boolean isEquivalentToUnderlyingAst() {
MethodCtDecl ctDecl = getCtDecl();
AssertionUtil.validateState(ctDecl != null, "overload resolution is not complete");
if (ctDecl.isFailed()) {
return false; // be conservative
}
if (!myNode.getMethodType().getSymbol().equals(ctDecl.getMethodType().getSymbol())) {
return false;
} else if (myNode instanceof ASTConstructorCall && ((ASTConstructorCall) myNode).isAnonymousClass()
&& !((ASTConstructorCall) myNode).getTypeNode().getTypeMirror().equals(getInferredType())) {
// check anon class has same type args
return false;
} else if (myNode.getParent() instanceof ASTVariableDeclarator) {
ASTVariableDeclaratorId varId = ((ASTVariableDeclarator) myNode.getParent()).getVarId();
if (varId.isTypeInferred() && !getInferredType().equals(varId.getTypeMirror())) {
return false;
}
}
return CollectionUtil.all(this.getArgumentExpressions(), ExprMirror::isEquivalentToUnderlyingAst);
}
protected MethodCtDecl getStandaloneCtdecl() {
MethodCallSite site = factory.infer.newCallSite(this, null);
// this is cached for later anyway
return factory.infer.getCompileTimeDecl(site);
}
@Override
public List<JTypeMirror> getExplicitTypeArguments() {
return ASTList.orEmptyStream(myNode.getExplicitTypeArguments())
.toStream()
.map(TypeNode::getTypeMirror)
.collect(Collectors.toList());
}
@Override
public JavaNode getExplicitTargLoc(int i) {
return ASTList.orEmptyStream(myNode.getExplicitTypeArguments()).get(i);
}
@Override
public List<ExprMirror> getArgumentExpressions() {
if (this.args == null) {
ASTArgumentList args = myNode.getArguments();
this.args = CollectionUtil.map(ASTList.orEmpty(args), this::createSubexpression);
}
return args;
}
@Override
public int getArgumentCount() {
return ASTList.sizeOrZero(myNode.getArguments());
}
@Override
public void setCtDecl(MethodCtDecl methodType) {
ctDecl = methodType;
if (mayMutateAst()) {
InternalApiBridge.setOverload(myNode, methodType);
}
}
@Override
public @Nullable MethodCtDecl getCtDecl() {
return ctDecl;
}
@Override
public @Nullable JTypeMirror getReceiverType() {
return null;
}
}
| 4,221 | 36.035088 | 112 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ast/MethodInvocMirror.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer.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.ASTAnonymousClassDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTMethodCall;
import net.sourceforge.pmd.lang.java.ast.ASTTypeExpression;
import net.sourceforge.pmd.lang.java.types.JMethodSig;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.TypeConversion;
import net.sourceforge.pmd.lang.java.types.TypeOps;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.InvocationMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ast.JavaExprMirrors.MirrorMaker;
class MethodInvocMirror extends BaseInvocMirror<ASTMethodCall> implements InvocationMirror {
MethodInvocMirror(JavaExprMirrors mirrors, ASTMethodCall call, @Nullable ExprMirror parent, MirrorMaker subexprMaker) {
super(mirrors, call, parent, subexprMaker);
}
@Override
public @Nullable JTypeMirror getStandaloneType() {
JMethodSig ctdecl = getStandaloneCtdecl().getMethodType();
return isContextDependent(ctdecl) ? null : ctdecl.getReturnType();
}
private static boolean isContextDependent(JMethodSig m) {
m = m.internalApi().adaptedMethod();
return m.isGeneric() && TypeOps.mentionsAny(m.getReturnType(), m.getTypeParameters());
}
@Override
public @NonNull TypeSpecies getStandaloneSpecies() {
return TypeSpecies.getSpecies(getStandaloneCtdecl().getMethodType().getReturnType());
}
@Override
public List<JMethodSig> getAccessibleCandidates() {
ASTExpression lhs = myNode.getQualifier();
if (lhs == null) {
// already filters accessibility
return myNode.getSymbolTable().methods().resolve(getName());
} else {
JTypeMirror lhsType;
if (lhs instanceof ASTConstructorCall) {
ASTConstructorCall ctor = (ASTConstructorCall) lhs;
ASTAnonymousClassDeclaration anon = ctor.getAnonymousClassDeclaration();
// put methods declared in the anonymous class in scope
lhsType = anon != null ? anon.getTypeMirror(getTypingContext())
: ctor.getTypeMirror(getTypingContext()); // may resolve diamonds
} else {
lhsType = lhs.getTypeMirror(getTypingContext());
}
lhsType = TypeConversion.capture(lhsType);
boolean staticOnly = lhs instanceof ASTTypeExpression;
return TypeOps.getMethodsOf(lhsType, getName(), staticOnly, myNode.getEnclosingType().getSymbol());
}
}
@Override
public JTypeMirror getErasedReceiverType() {
return getReceiverType().getErasure();
}
@Override
public @NonNull JTypeMirror getReceiverType() {
ASTExpression qualifier = myNode.getQualifier();
if (qualifier != null) {
return qualifier.getTypeMirror(getTypingContext());
} else {
return myNode.getEnclosingType().getTypeMirror();
}
}
@Override
public String getName() {
return myNode.getMethodName();
}
}
| 3,611 | 37.021053 | 123 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ast/SwitchMirror.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer.ast;
import java.util.List;
import java.util.function.Predicate;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchExpression;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.BranchingMirror;
import net.sourceforge.pmd.lang.java.types.internal.infer.ast.JavaExprMirrors.MirrorMaker;
import net.sourceforge.pmd.util.CollectionUtil;
class SwitchMirror extends BasePolyMirror<ASTSwitchExpression> implements BranchingMirror {
// todo this is undertested for invocation contexts
private final List<ExprMirror> branches;
SwitchMirror(JavaExprMirrors mirrors, ASTSwitchExpression myNode, boolean isStandalone, @Nullable ExprMirror parent, MirrorMaker subexprMaker) {
super(mirrors, myNode, parent, subexprMaker);
branches = myNode.getYieldExpressions().toList(it -> factory.getBranchMirrorSubexpression(it, isStandalone, this, subexprMaker));
}
@Override
public boolean branchesMatch(Predicate<? super ExprMirror> condition) {
return CollectionUtil.all(branches, condition);
}
}
| 1,331 | 38.176471 | 148 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/internal/JavaDesignerBindings.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTAnnotation;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr;
import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType;
import net.sourceforge.pmd.lang.java.ast.ASTCompactConstructorDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTFieldAccess;
import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTInfixExpression;
import net.sourceforge.pmd.lang.java.ast.ASTLambdaExpression;
import net.sourceforge.pmd.lang.java.ast.ASTMethodCall;
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTMethodReference;
import net.sourceforge.pmd.lang.java.ast.ASTPrimitiveType;
import net.sourceforge.pmd.lang.java.ast.ASTVariableAccess;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.ast.AccessNode;
import net.sourceforge.pmd.lang.java.ast.InvocationNode;
import net.sourceforge.pmd.lang.java.ast.JModifier;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.ast.JavaVisitorBase;
import net.sourceforge.pmd.lang.java.ast.TypeNode;
import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.rule.xpath.Attribute;
import net.sourceforge.pmd.util.designerbindings.DesignerBindings.DefaultDesignerBindings;
import net.sourceforge.pmd.util.designerbindings.RelatedNodesSelector;
public final class JavaDesignerBindings extends DefaultDesignerBindings {
public static final JavaDesignerBindings INSTANCE = new JavaDesignerBindings();
private JavaDesignerBindings() {
}
@Override
public Attribute getMainAttribute(Node node) {
if (node instanceof JavaNode) {
Attribute attr = node.acceptVisitor(MainAttrVisitor.INSTANCE, null);
if (attr != null) {
return attr;
}
}
return super.getMainAttribute(node);
}
@Override
public TreeIconId getIcon(Node node) {
if (node instanceof ASTFieldDeclaration) {
return TreeIconId.FIELD;
} else if (node instanceof ASTAnyTypeDeclaration) {
return TreeIconId.CLASS;
} else if (node instanceof ASTMethodDeclaration) {
return TreeIconId.METHOD;
} else if (node instanceof ASTConstructorDeclaration
|| node instanceof ASTCompactConstructorDeclaration) {
return TreeIconId.CONSTRUCTOR;
} else if (node instanceof ASTVariableDeclaratorId) {
return TreeIconId.VARIABLE;
}
return super.getIcon(node);
}
@Override
public Collection<AdditionalInfo> getAdditionalInfo(Node node) {
List<AdditionalInfo> info = new ArrayList<>(super.getAdditionalInfo(node));
if (node instanceof ASTLambdaExpression) {
ASTLambdaExpression lambda = (ASTLambdaExpression) node;
info.add(new AdditionalInfo("Function type: " + lambda.getFunctionalMethod()));
}
if (node instanceof ASTMethodReference) {
ASTMethodReference lambda = (ASTMethodReference) node;
info.add(new AdditionalInfo("Function type: " + lambda.getFunctionalMethod()));
info.add(new AdditionalInfo("CTDecl: " + lambda.getReferencedMethod()));
}
if (node instanceof InvocationNode) {
InvocationNode invoc = (InvocationNode) node;
info.add(new AdditionalInfo("Function: " + invoc.getMethodType()));
info.add(new AdditionalInfo("VarargsCall: " + invoc.getOverloadSelectionInfo().isVarargsCall()));
info.add(new AdditionalInfo("Unchecked: " + invoc.getOverloadSelectionInfo().needsUncheckedConversion()));
info.add(new AdditionalInfo("Failed: " + invoc.getOverloadSelectionInfo().isFailed()));
}
if (node instanceof TypeNode) {
JTypeMirror typeMirror = ((TypeNode) node).getTypeMirror();
info.add(new AdditionalInfo("Type: " + typeMirror));
}
if (node instanceof AccessNode) {
String effective = formatModifierSet(((AccessNode) node).getModifiers().getEffectiveModifiers());
String explicit = formatModifierSet(((AccessNode) node).getModifiers().getExplicitModifiers());
info.add(new AdditionalInfo("pmd-java:modifiers(): " + effective));
info.add(new AdditionalInfo("pmd-java:explicitModifiers(): " + explicit));
}
return info;
}
@NonNull
private String formatModifierSet(Set<JModifier> modifierSet) {
return modifierSet.stream().map(JModifier::toString).collect(Collectors.joining(", ", "(", ")"));
}
@Override
public RelatedNodesSelector getRelatedNodesSelector() {
return n -> {
if (n instanceof ASTNamedReferenceExpr) {
JVariableSymbol sym = ((ASTNamedReferenceExpr) n).getReferencedSym();
if (sym != null && sym.tryGetNode() != null) {
return Collections.unmodifiableList(sym.tryGetNode().getLocalUsages());
}
}
return Collections.emptyList();
};
}
private static final class MainAttrVisitor extends JavaVisitorBase<Void, Attribute> {
private static final MainAttrVisitor INSTANCE = new MainAttrVisitor();
@Override
public Attribute visitJavaNode(JavaNode node, Void data) {
return null; // don't recurse
}
@Override
public Attribute visit(ASTInfixExpression node, Void data) {
return new Attribute(node, "Operator", node.getOperator().toString());
}
@Override
public Attribute visitTypeDecl(ASTAnyTypeDeclaration node, Void data) {
return new Attribute(node, "SimpleName", node.getSimpleName());
}
@Override
public Attribute visit(ASTAnnotation node, Void data) {
return new Attribute(node, "SimpleName", node.getSimpleName());
}
@Override
public Attribute visit(ASTClassOrInterfaceType node, Void data) {
return new Attribute(node, "SimpleName", node.getSimpleName());
}
@Override
public Attribute visit(ASTPrimitiveType node, Void data) {
return new Attribute(node, "Kind", node.getKind().getSimpleName());
}
@Override
public Attribute visit(ASTMethodCall node, Void data) {
return new Attribute(node, "MethodName", node.getMethodName());
}
@Override
public Attribute visit(ASTMethodReference node, Void data) {
return new Attribute(node, "MethodName", node.getMethodName());
}
@Override
public Attribute visit(ASTFieldAccess node, Void data) {
return new Attribute(node, "Name", node.getName());
}
@Override
public Attribute visit(ASTVariableAccess node, Void data) {
return new Attribute(node, "Name", node.getName());
}
@Override
public Attribute visit(ASTMethodDeclaration node, Void data) {
return new Attribute(node, "Name", node.getName());
}
@Override
public Attribute visit(ASTVariableDeclaratorId node, Void data) {
return new Attribute(node, "Name", node.getName());
}
}
}
| 8,025 | 39.13 | 118 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/internal/JavaLanguageProperties.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.internal;
import org.apache.commons.lang3.EnumUtils;
import net.sourceforge.pmd.lang.JvmLanguagePropertyBundle;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.java.JavaLanguageModule;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
/**
* @author Clément Fournier
*/
public class JavaLanguageProperties extends JvmLanguagePropertyBundle {
static final PropertyDescriptor<InferenceLoggingVerbosity> INTERNAL_INFERENCE_LOGGING_VERBOSITY =
PropertyFactory.enumProperty("xTypeInferenceLogging",
EnumUtils.getEnumMap(InferenceLoggingVerbosity.class))
.desc("Verbosity of the type inference logging")
.defaultValue(InferenceLoggingVerbosity.DISABLED)
.build();
public JavaLanguageProperties() {
super(JavaLanguageModule.getInstance());
definePropertyDescriptor(INTERNAL_INFERENCE_LOGGING_VERBOSITY);
}
public static boolean isPreviewEnabled(LanguageVersion version) {
return version.getVersion().endsWith("-preview");
}
public static int getInternalJdkVersion(LanguageVersion version) {
// Todo that's ugly..
String verString = version.getVersion();
if (isPreviewEnabled(version)) {
verString = verString.substring(0, verString.length() - "-preview".length());
}
if (verString.startsWith("1.")) {
verString = verString.substring(2);
}
return Integer.parseInt(verString);
}
public enum InferenceLoggingVerbosity {
DISABLED, SIMPLE, VERBOSE
}
}
| 1,834 | 33.622642 | 101 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/internal/JavaAstProcessor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.internal;
import static net.sourceforge.pmd.lang.java.symbols.table.internal.JavaSemanticErrors.CANNOT_RESOLVE_SYMBOL;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.benchmark.TimeTracker;
import net.sourceforge.pmd.lang.ast.NodeStream;
import net.sourceforge.pmd.lang.ast.SemanticErrorReporter;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.InternalApiBridge;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
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.internal.UnresolvedClassStore;
import net.sourceforge.pmd.lang.java.symbols.internal.ast.SymbolResolutionPass;
import net.sourceforge.pmd.lang.java.symbols.table.internal.ReferenceCtx;
import net.sourceforge.pmd.lang.java.symbols.table.internal.SymbolTableResolver;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
import net.sourceforge.pmd.lang.java.types.internal.infer.TypeInferenceLogger;
/**
* Processes the output of the parser before rules get access to the AST.
* This performs all semantic analyses in layered passes.
*
* <p>This is the root context object for file-specific context. Instances
* do not need to be thread-safe. Global information about eg the classpath
* is held in a {@link TypeSystem} instance.
*
* <p>The object lives as long as a file, it is accessible from nodes
* using {@link InternalApiBridge#getProcessor(JavaNode)}.
*/
public final class JavaAstProcessor {
private final TypeInferenceLogger typeInferenceLogger;
private final JavaLanguageProcessor globalProc;
private final SemanticErrorReporter logger;
private SymbolResolver symResolver;
private final UnresolvedClassStore unresolvedTypes;
private final ASTCompilationUnit acu;
private JavaAstProcessor(JavaLanguageProcessor globalProc,
SemanticErrorReporter logger,
TypeInferenceLogger typeInfLogger,
ASTCompilationUnit acu) {
this.symResolver = globalProc.getTypeSystem().bootstrapResolver();
this.globalProc = globalProc;
this.logger = logger;
this.typeInferenceLogger = typeInfLogger;
this.unresolvedTypes = new UnresolvedClassStore(globalProc.getTypeSystem());
this.acu = acu;
}
public UnresolvedClassStore getUnresolvedStore() {
return unresolvedTypes;
}
/**
* Find a symbol from the auxclasspath. If not found, will create
* an unresolved symbol.
*/
public @NonNull JClassSymbol findSymbolCannotFail(String name) {
return findSymbolCannotFail(null, name);
}
/**
* Find a symbol from the auxclasspath. If not found, will create
* an unresolved symbol, and may report the failure if the location is non-null.
*/
public @NonNull JClassSymbol findSymbolCannotFail(@Nullable JavaNode location, String canoName) {
JClassSymbol found = getSymResolver().resolveClassFromCanonicalName(canoName);
if (found == null) {
if (location != null) {
reportCannotResolveSymbol(location, canoName);
}
return makeUnresolvedReference(canoName, 0);
}
return found;
}
public void reportCannotResolveSymbol(@NonNull JavaNode location, String canoName) {
getLogger().warning(location, CANNOT_RESOLVE_SYMBOL, canoName);
}
public JClassSymbol makeUnresolvedReference(String canonicalName, int typeArity) {
return unresolvedTypes.makeUnresolvedReference(canonicalName, typeArity);
}
public JClassSymbol makeUnresolvedReference(JTypeDeclSymbol outer, String simpleName, int typeArity) {
if (outer instanceof JClassSymbol) {
return unresolvedTypes.makeUnresolvedReference((JClassSymbol) outer, simpleName, typeArity);
}
return makeUnresolvedReference("error." + simpleName, typeArity);
}
public SymbolResolver getSymResolver() {
return symResolver;
}
public SemanticErrorReporter getLogger() {
return logger;
}
public int getJdkVersion() {
return JavaLanguageProperties.getInternalJdkVersion(acu.getLanguageVersion());
}
/**
* Performs semantic analysis on the given source file.
*/
public void process() {
SymbolResolver knownSyms = TimeTracker.bench("Symbol resolution", () -> SymbolResolutionPass.traverse(this, acu));
// Now symbols are on the relevant nodes
this.symResolver = SymbolResolver.layer(knownSyms, this.symResolver);
// this needs to be initialized before the symbol table resolution
// as scopes depend on type resolution in some cases.
InternalApiBridge.initTypeResolver(acu, this, typeInferenceLogger);
TimeTracker.bench("Symbol table resolution", () -> SymbolTableResolver.traverse(this, acu));
TimeTracker.bench("AST disambiguation", () -> InternalApiBridge.disambigWithCtx(NodeStream.of(acu), ReferenceCtx.root(this, acu)));
TimeTracker.bench("Force type resolution", () -> InternalApiBridge.forceTypeResolutionPhase(this, acu));
TimeTracker.bench("Comment assignment", () -> InternalApiBridge.assignComments(acu));
TimeTracker.bench("Usage resolution", () -> InternalApiBridge.usageResolution(this, acu));
TimeTracker.bench("Override resolution", () -> InternalApiBridge.overrideResolution(this, acu));
}
public TypeSystem getTypeSystem() {
return globalProc.getTypeSystem();
}
public static void process(JavaLanguageProcessor globalProcessor,
SemanticErrorReporter semanticErrorReporter,
ASTCompilationUnit ast) {
process(globalProcessor, semanticErrorReporter, globalProcessor.newTypeInfLogger(), ast);
}
public static void process(JavaLanguageProcessor globalProcessor,
SemanticErrorReporter semanticErrorReporter,
TypeInferenceLogger typeInfLogger,
ASTCompilationUnit ast) {
JavaAstProcessor astProc = new JavaAstProcessor(
globalProcessor,
semanticErrorReporter,
typeInfLogger,
ast
);
astProc.process();
}
}
| 6,762 | 39.497006 | 139 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/internal/JavaViolationDecorator.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.internal;
import java.util.Map;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTBodyDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter;
import net.sourceforge.pmd.lang.java.ast.ASTInitializer;
import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.reporting.ViolationDecorator;
import net.sourceforge.pmd.util.IteratorUtil;
final class JavaViolationDecorator implements ViolationDecorator {
static final ViolationDecorator INSTANCE = new JavaViolationDecorator();
@Override
public void decorate(Node violationNode, Map<String, String> additionalInfo) {
JavaNode javaNode = (JavaNode) violationNode;
setIfNonNull(RuleViolation.VARIABLE_NAME, getVariableNameIfExists(javaNode), additionalInfo);
setIfNonNull(RuleViolation.METHOD_NAME, getMethodName(javaNode), additionalInfo);
setIfNonNull(RuleViolation.CLASS_NAME, getClassName(javaNode), additionalInfo);
setIfNonNull(RuleViolation.PACKAGE_NAME, javaNode.getRoot().getPackageName(), additionalInfo);
}
private @Nullable String getClassName(JavaNode javaNode) {
ASTAnyTypeDeclaration enclosing = null;
if (javaNode instanceof ASTAnyTypeDeclaration) {
enclosing = (ASTAnyTypeDeclaration) javaNode;
}
if (enclosing == null) {
enclosing = javaNode.getEnclosingType();
}
if (enclosing == null) {
enclosing = javaNode.getRoot().getTypeDeclarations().first(ASTAnyTypeDeclaration::isPublic);
}
if (enclosing == null) {
enclosing = javaNode.getRoot().getTypeDeclarations().first();
}
if (enclosing != null) {
return enclosing.getSimpleName();
}
return null;
}
private void setIfNonNull(String key, String value, Map<String, String> additionalInfo) {
if (value != null) {
additionalInfo.put(key, value);
}
}
private static @Nullable String getMethodName(@NonNull JavaNode javaNode) {
@Nullable ASTBodyDeclaration enclosingDecl =
javaNode.ancestorsOrSelf()
.filterIs(ASTBodyDeclaration.class)
.first();
if (enclosingDecl instanceof ASTMethodOrConstructorDeclaration) {
return ((ASTMethodOrConstructorDeclaration) enclosingDecl).getName();
} else if (enclosingDecl instanceof ASTInitializer) {
return ((ASTInitializer) enclosingDecl).isStatic() ? "<clinit>" : "<init>";
}
return null;
}
private static String getVariableNames(Iterable<ASTVariableDeclaratorId> iterable) {
return IteratorUtil.toStream(iterable.iterator())
.map(ASTVariableDeclaratorId::getName)
.collect(Collectors.joining(", "));
}
private static @Nullable String getVariableNameIfExists(JavaNode node) {
if (node instanceof ASTFieldDeclaration) {
return getVariableNames((ASTFieldDeclaration) node);
} else if (node instanceof ASTLocalVariableDeclaration) {
return getVariableNames((ASTLocalVariableDeclaration) node);
} else if (node instanceof ASTVariableDeclarator) {
return ((ASTVariableDeclarator) node).getVarId().getName();
} else if (node instanceof ASTVariableDeclaratorId) {
return ((ASTVariableDeclaratorId) node).getName();
} else if (node instanceof ASTFormalParameter) {
return getVariableNameIfExists(node.firstChild(ASTVariableDeclaratorId.class));
} else if (node instanceof ASTExpression) {
return getVariableNameIfExists(node.getParent());
}
return null;
}
}
| 4,556 | 41.588785 | 104 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/internal/JavaMetricsProvider.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.internal;
import static net.sourceforge.pmd.util.CollectionUtil.setOf;
import java.util.Set;
import net.sourceforge.pmd.lang.java.metrics.JavaMetrics;
import net.sourceforge.pmd.lang.metrics.LanguageMetricsProvider;
import net.sourceforge.pmd.lang.metrics.Metric;
/**
* @author Clément Fournier
*/
class JavaMetricsProvider implements LanguageMetricsProvider {
private final Set<Metric<?, ?>> metrics = setOf(
JavaMetrics.ACCESS_TO_FOREIGN_DATA,
JavaMetrics.CYCLO,
JavaMetrics.NPATH,
JavaMetrics.NCSS,
JavaMetrics.LINES_OF_CODE,
JavaMetrics.FAN_OUT,
JavaMetrics.WEIGHED_METHOD_COUNT,
JavaMetrics.WEIGHT_OF_CLASS,
JavaMetrics.NUMBER_OF_ACCESSORS,
JavaMetrics.NUMBER_OF_PUBLIC_FIELDS,
JavaMetrics.TIGHT_CLASS_COHESION
);
@Override
public Set<Metric<?, ?>> getMetrics() {
return metrics;
}
}
| 1,039 | 25.666667 | 79 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/internal/JavaLanguageProcessor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.internal;
import java.util.List;
import java.util.Objects;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.ViolationSuppressor;
import net.sourceforge.pmd.lang.LanguageVersionHandler;
import net.sourceforge.pmd.lang.ast.Parser;
import net.sourceforge.pmd.lang.impl.BatchLanguageProcessor;
import net.sourceforge.pmd.lang.java.ast.JavaParser;
import net.sourceforge.pmd.lang.java.internal.JavaLanguageProperties.InferenceLoggingVerbosity;
import net.sourceforge.pmd.lang.java.rule.xpath.internal.BaseContextNodeTestFun;
import net.sourceforge.pmd.lang.java.rule.xpath.internal.GetCommentOnFunction;
import net.sourceforge.pmd.lang.java.rule.xpath.internal.GetModifiersFun;
import net.sourceforge.pmd.lang.java.rule.xpath.internal.MatchesSignatureFunction;
import net.sourceforge.pmd.lang.java.rule.xpath.internal.MetricFunction;
import net.sourceforge.pmd.lang.java.rule.xpath.internal.NodeIsFunction;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
import net.sourceforge.pmd.lang.java.types.internal.infer.TypeInferenceLogger;
import net.sourceforge.pmd.lang.java.types.internal.infer.TypeInferenceLogger.SimpleLogger;
import net.sourceforge.pmd.lang.java.types.internal.infer.TypeInferenceLogger.VerboseLogger;
import net.sourceforge.pmd.lang.metrics.LanguageMetricsProvider;
import net.sourceforge.pmd.lang.rule.xpath.impl.XPathHandler;
import net.sourceforge.pmd.reporting.ViolationDecorator;
import net.sourceforge.pmd.util.designerbindings.DesignerBindings;
/**
* @author Clément Fournier
*/
public class JavaLanguageProcessor extends BatchLanguageProcessor<JavaLanguageProperties>
implements LanguageVersionHandler {
private final LanguageMetricsProvider myMetricsProvider = new JavaMetricsProvider();
private final JavaParser parser;
private final JavaParser parserWithoutProcessing;
private TypeSystem typeSystem;
public JavaLanguageProcessor(JavaLanguageProperties properties, TypeSystem typeSystem) {
super(properties);
this.typeSystem = typeSystem;
String suppressMarker = properties.getSuppressMarker();
this.parser = new JavaParser(suppressMarker, this, true);
this.parserWithoutProcessing = new JavaParser(suppressMarker, this, false);
}
public JavaLanguageProcessor(JavaLanguageProperties properties) {
this(properties, TypeSystem.usingClassLoaderClasspath(properties.getAnalysisClassLoader()));
}
@Override
public @NonNull LanguageVersionHandler services() {
return this;
}
@Override
public Parser getParser() {
return parser;
}
public JavaParser getParserWithoutProcessing() {
return parserWithoutProcessing;
}
public TypeSystem getTypeSystem() {
return typeSystem;
}
TypeInferenceLogger newTypeInfLogger() {
InferenceLoggingVerbosity verbosity = getProperties().getProperty(JavaLanguageProperties.INTERNAL_INFERENCE_LOGGING_VERBOSITY);
if (verbosity == InferenceLoggingVerbosity.VERBOSE) {
return new VerboseLogger(System.err);
} else if (verbosity == InferenceLoggingVerbosity.SIMPLE) {
return new SimpleLogger(System.err);
} else {
return TypeInferenceLogger.noop();
}
}
@Override
public DesignerBindings getDesignerBindings() {
return JavaDesignerBindings.INSTANCE;
}
@Override
public XPathHandler getXPathHandler() {
return XPATH_HANDLER;
}
@Override
public List<ViolationSuppressor> getExtraViolationSuppressors() {
return AnnotationSuppressionUtil.ALL_JAVA_SUPPRESSORS;
}
@Override
public ViolationDecorator getViolationDecorator() {
return JavaViolationDecorator.INSTANCE;
}
@Override
public LanguageMetricsProvider getLanguageMetricsProvider() {
return myMetricsProvider;
}
private static final XPathHandler XPATH_HANDLER =
XPathHandler.getHandlerForFunctionDefs(
BaseContextNodeTestFun.TYPE_IS_EXACTLY,
BaseContextNodeTestFun.TYPE_IS,
BaseContextNodeTestFun.HAS_ANNOTATION,
MatchesSignatureFunction.INSTANCE,
NodeIsFunction.INSTANCE,
GetModifiersFun.GET_EFFECTIVE,
GetModifiersFun.GET_EXPLICIT,
MetricFunction.INSTANCE,
GetCommentOnFunction.INSTANCE
);
public void setTypeSystem(TypeSystem ts) {
this.typeSystem = Objects.requireNonNull(ts);
}
}
| 4,651 | 35.34375 | 135 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/internal/AnnotationSuppressionUtil.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.internal;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.Report.SuppressedViolation;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.ViolationSuppressor;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTAnnotation;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter;
import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTMemberValue;
import net.sourceforge.pmd.lang.java.ast.ASTMemberValuePair;
import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration;
import net.sourceforge.pmd.lang.java.ast.Annotatable;
import net.sourceforge.pmd.lang.java.rule.errorprone.ImplicitSwitchFallThroughRule;
import net.sourceforge.pmd.lang.java.types.TypeTestUtil;
/**
* Helper methods to suppress violations based on annotations.
*
* An annotation suppresses a rule if the annotation is a {@link SuppressWarnings},
* and if the set of suppressed warnings ({@link SuppressWarnings#value()})
* contains at least one of those:
* <ul>
* <li>"PMD" (suppresses all rules);
* <li>"PMD.rulename", where rulename is the name of the given rule;
* <li>"all" (conventional value to suppress all warnings).
* </ul>
*
* <p>Additionally, the following values suppress a specific set of rules:
* <ul>
* <li>{@code "unused"}: suppresses rules like UnusedLocalVariable or UnusedPrivateField;
* <li>{@code "serial"}: suppresses BeanMembersShouldSerialize, NonSerializableClass and MissingSerialVersionUID;
* <li>TODO "fallthrough" #1899
* </ul>
*/
final class AnnotationSuppressionUtil {
private static final Set<String> UNUSED_RULES
= new HashSet<>(Arrays.asList("UnusedPrivateField", "UnusedLocalVariable", "UnusedPrivateMethod",
"UnusedFormalParameter", "UnusedAssignment", "SingularField"));
private static final Set<String> SERIAL_RULES =
new HashSet<>(Arrays.asList("BeanMembersShouldSerialize", "NonSerializableClass", "MissingSerialVersionUID"));
static final ViolationSuppressor JAVA_ANNOT_SUPPRESSOR = new ViolationSuppressor() {
@Override
public String getId() {
return "@SuppressWarnings";
}
@Override
public Report.SuppressedViolation suppressOrNull(RuleViolation rv, @NonNull Node node) {
if (contextSuppresses(node, rv.getRule())) {
return new SuppressedViolation(rv, this, null);
}
return null;
}
};
static final List<ViolationSuppressor> ALL_JAVA_SUPPRESSORS = listOf(JAVA_ANNOT_SUPPRESSOR);
private AnnotationSuppressionUtil() {
}
static boolean contextSuppresses(Node node, Rule rule) {
boolean result = suppresses(node, rule);
if (!result && node instanceof ASTCompilationUnit) {
for (int i = 0; !result && i < node.getNumChildren(); i++) {
result = AnnotationSuppressionUtil.suppresses(node.getChild(i), rule);
}
}
if (!result) {
Node parent = node.getParent();
while (!result && parent != null) {
result = AnnotationSuppressionUtil.suppresses(parent, rule);
parent = parent.getParent();
}
}
return result;
}
/**
* Returns true if the node has an annotation that suppresses the
* given rule.
*/
private static boolean suppresses(final Node node, Rule rule) {
Annotatable suppressor = getSuppressor(node);
return suppressor != null && hasSuppressWarningsAnnotationFor(suppressor, rule);
}
@Nullable
private static Annotatable getSuppressor(Node node) {
if (node instanceof ASTAnyTypeDeclaration
|| node instanceof ASTMethodOrConstructorDeclaration
// also works for ASTResource when Resource uses LocalVariableDeclaration
|| node instanceof ASTLocalVariableDeclaration
|| node instanceof ASTFieldDeclaration
|| node instanceof ASTFormalParameter) {
return (Annotatable) node;
} else {
return null;
}
}
private static boolean hasSuppressWarningsAnnotationFor(final Annotatable node, Rule rule) {
return node.getDeclaredAnnotations().any(it -> annotationSuppresses(it, rule));
}
// @formatter:on
private static boolean annotationSuppresses(ASTAnnotation annotation, Rule rule) {
if (TypeTestUtil.isA(SuppressWarnings.class, annotation)) {
for (ASTMemberValue value : annotation.getFlatValue(ASTMemberValuePair.VALUE_ATTR)) {
Object constVal = value.getConstValue();
if (constVal instanceof String) {
String stringVal = (String) constVal;
if ("PMD".equals(stringVal)
|| ("PMD." + rule.getName()).equals(stringVal) // NOPMD uselessparentheses false positive
// Check for standard annotations values
|| "all".equals(stringVal)
|| "serial".equals(stringVal) && SERIAL_RULES.contains(rule.getName())
|| "unused".equals(stringVal) && UNUSED_RULES.contains(rule.getName())
|| "fallthrough".equals(stringVal) && rule instanceof ImplicitSwitchFallThroughRule
) {
return true;
}
}
}
}
return false;
}
}
| 6,190 | 38.941935 | 118 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/cpd/JavaTokenizer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.io.IOException;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Properties;
import net.sourceforge.pmd.cpd.impl.JavaCCTokenizer;
import net.sourceforge.pmd.cpd.token.JavaCCTokenFilter;
import net.sourceforge.pmd.cpd.token.TokenFilter;
import net.sourceforge.pmd.lang.TokenManager;
import net.sourceforge.pmd.lang.ast.impl.javacc.CharStream;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccTokenDocument;
import net.sourceforge.pmd.lang.java.ast.InternalApiBridge;
import net.sourceforge.pmd.lang.java.ast.JavaTokenKinds;
public class JavaTokenizer extends JavaCCTokenizer {
public static final String CPD_START = "\"CPD-START\"";
public static final String CPD_END = "\"CPD-END\"";
private boolean ignoreAnnotations;
private boolean ignoreLiterals;
private boolean ignoreIdentifiers;
private ConstructorDetector constructorDetector;
public void setProperties(Properties properties) {
ignoreAnnotations = Boolean.parseBoolean(properties.getProperty(IGNORE_ANNOTATIONS, "false"));
ignoreLiterals = Boolean.parseBoolean(properties.getProperty(IGNORE_LITERALS, "false"));
ignoreIdentifiers = Boolean.parseBoolean(properties.getProperty(IGNORE_IDENTIFIERS, "false"));
}
@Override
public void tokenize(SourceCode sourceCode, Tokens tokenEntries) throws IOException {
constructorDetector = new ConstructorDetector(ignoreIdentifiers);
super.tokenize(sourceCode, tokenEntries);
}
@Override
protected JavaccTokenDocument.TokenDocumentBehavior tokenBehavior() {
return InternalApiBridge.javaTokenDoc();
}
@Override
protected TokenManager<JavaccToken> makeLexerImpl(CharStream sourceCode) {
return JavaTokenKinds.newTokenManager(sourceCode);
}
@Override
protected TokenFilter<JavaccToken> getTokenFilter(TokenManager<JavaccToken> tokenManager) {
return new JavaTokenFilter(tokenManager, ignoreAnnotations);
}
@Override
protected TokenEntry processToken(Tokens tokenEntries, JavaccToken javaToken) {
String image = javaToken.getImage();
constructorDetector.restoreConstructorToken(tokenEntries, javaToken);
if (ignoreLiterals && (javaToken.kind == JavaTokenKinds.STRING_LITERAL
|| javaToken.kind == JavaTokenKinds.CHARACTER_LITERAL
|| javaToken.kind == JavaTokenKinds.INTEGER_LITERAL
|| javaToken.kind == JavaTokenKinds.FLOATING_POINT_LITERAL)) {
image = String.valueOf(javaToken.kind);
}
if (ignoreIdentifiers && javaToken.kind == JavaTokenKinds.IDENTIFIER) {
image = String.valueOf(javaToken.kind);
}
constructorDetector.processToken(javaToken);
return new TokenEntry(image, javaToken.getReportLocation());
}
public void setIgnoreLiterals(boolean ignore) {
this.ignoreLiterals = ignore;
}
public void setIgnoreIdentifiers(boolean ignore) {
this.ignoreIdentifiers = ignore;
}
public void setIgnoreAnnotations(boolean ignoreAnnotations) {
this.ignoreAnnotations = ignoreAnnotations;
}
/**
* The {@link JavaTokenFilter} extends the {@link JavaCCTokenFilter} to discard
* Java-specific tokens.
* <p>
* By default, it discards semicolons, package and import statements, and
* enables annotation-based CPD suppression. Optionally, all annotations can be ignored, too.
* </p>
*/
private static class JavaTokenFilter extends JavaCCTokenFilter {
private boolean isAnnotation = false;
private boolean nextTokenEndsAnnotation = false;
private int annotationStack = 0;
private boolean discardingSemicolon = false;
private boolean discardingKeywords = false;
private boolean discardingSuppressing = false;
private boolean discardingAnnotations = false;
private boolean ignoreAnnotations = false;
JavaTokenFilter(final TokenManager<JavaccToken> tokenManager, final boolean ignoreAnnotations) {
super(tokenManager);
this.ignoreAnnotations = ignoreAnnotations;
}
@Override
protected void analyzeToken(final JavaccToken token) {
detectAnnotations(token);
skipSemicolon(token);
skipPackageAndImport(token);
skipAnnotationSuppression(token);
if (ignoreAnnotations) {
skipAnnotations();
}
}
private void skipPackageAndImport(final JavaccToken currentToken) {
if (currentToken.kind == JavaTokenKinds.PACKAGE || currentToken.kind == JavaTokenKinds.IMPORT) {
discardingKeywords = true;
} else if (discardingKeywords && currentToken.kind == JavaTokenKinds.SEMICOLON) {
discardingKeywords = false;
}
}
private void skipSemicolon(final JavaccToken currentToken) {
if (currentToken.kind == JavaTokenKinds.SEMICOLON) {
discardingSemicolon = true;
} else if (discardingSemicolon) {
discardingSemicolon = false;
}
}
private void skipAnnotationSuppression(final JavaccToken currentToken) {
// if processing an annotation, look for a CPD-START or CPD-END
if (isAnnotation) {
if (!discardingSuppressing && currentToken.kind == JavaTokenKinds.STRING_LITERAL
&& CPD_START.equals(currentToken.getImage())) {
discardingSuppressing = true;
} else if (discardingSuppressing && currentToken.kind == JavaTokenKinds.STRING_LITERAL
&& CPD_END.equals(currentToken.getImage())) {
discardingSuppressing = false;
}
}
}
private void skipAnnotations() {
if (!discardingAnnotations && isAnnotation) {
discardingAnnotations = true;
} else if (discardingAnnotations && !isAnnotation) {
discardingAnnotations = false;
}
}
@Override
protected boolean isLanguageSpecificDiscarding() {
return discardingSemicolon || discardingKeywords || discardingAnnotations
|| discardingSuppressing;
}
private void detectAnnotations(JavaccToken currentToken) {
if (isAnnotation && nextTokenEndsAnnotation) {
isAnnotation = false;
nextTokenEndsAnnotation = false;
}
if (isAnnotation) {
if (currentToken.kind == JavaTokenKinds.LPAREN) {
annotationStack++;
} else if (currentToken.kind == JavaTokenKinds.RPAREN) {
annotationStack--;
if (annotationStack == 0) {
nextTokenEndsAnnotation = true;
}
} else if (annotationStack == 0 && currentToken.kind != JavaTokenKinds.IDENTIFIER
&& currentToken.kind != JavaTokenKinds.LPAREN) {
isAnnotation = false;
}
}
if (currentToken.kind == JavaTokenKinds.AT) {
isAnnotation = true;
}
}
}
/**
* The {@link ConstructorDetector} consumes token by token and maintains
* state. It can detect, whether the current token belongs to a constructor
* method identifier and if so, is able to restore it when using
* ignoreIdentifiers.
*/
private static class ConstructorDetector {
private boolean ignoreIdentifiers;
private Deque<TypeDeclaration> classMembersIndentations;
private int currentNestingLevel;
private boolean storeNextIdentifier;
private String prevIdentifier;
ConstructorDetector(boolean ignoreIdentifiers) {
this.ignoreIdentifiers = ignoreIdentifiers;
currentNestingLevel = 0;
classMembersIndentations = new LinkedList<>();
}
public void processToken(JavaccToken currentToken) {
if (!ignoreIdentifiers) {
return;
}
switch (currentToken.kind) {
case JavaTokenKinds.IDENTIFIER:
if ("enum".equals(currentToken.getImage())) {
// If declaring an enum, add a new block nesting level at
// which constructors may exist
pushTypeDeclaration();
} else if (storeNextIdentifier) {
classMembersIndentations.peek().name = currentToken.getImage();
storeNextIdentifier = false;
}
// Store this token
prevIdentifier = currentToken.getImage();
break;
case JavaTokenKinds.CLASS:
// If declaring a class, add a new block nesting level at which
// constructors may exist
pushTypeDeclaration();
break;
case JavaTokenKinds.LBRACE:
currentNestingLevel++;
break;
case JavaTokenKinds.RBRACE:
// Discard completed blocks
if (!classMembersIndentations.isEmpty()
&& classMembersIndentations.peek().indentationLevel == currentNestingLevel) {
classMembersIndentations.pop();
}
currentNestingLevel--;
break;
default:
/*
* Did we find a "class" token not followed by an identifier? i.e:
* expectThrows(IllegalStateException.class, () -> {
* newSearcher(r).search(parentQuery.build(), c);
* });
*/
if (storeNextIdentifier) {
classMembersIndentations.pop();
storeNextIdentifier = false;
}
break;
}
}
private void pushTypeDeclaration() {
TypeDeclaration cd = new TypeDeclaration(currentNestingLevel + 1);
classMembersIndentations.push(cd);
storeNextIdentifier = true;
}
public void restoreConstructorToken(Tokens tokenEntries, JavaccToken currentToken) {
if (!ignoreIdentifiers) {
return;
}
if (currentToken.kind == JavaTokenKinds.LPAREN) {
// was the previous token a constructor? If so, restore the
// identifier
if (!classMembersIndentations.isEmpty()
&& classMembersIndentations.peek().name.equals(prevIdentifier)) {
int lastTokenIndex = tokenEntries.size() - 1;
TokenEntry lastToken = tokenEntries.getTokens().get(lastTokenIndex);
lastToken.setImage(prevIdentifier);
}
}
}
}
private static class TypeDeclaration {
int indentationLevel;
String name;
TypeDeclaration(int indentationLevel) {
this.indentationLevel = indentationLevel;
}
}
}
| 11,486 | 36.786184 | 108 | java |
pmd | pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/cpd/JavaLanguage.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.Properties;
import net.sourceforge.pmd.lang.java.JavaLanguageModule;
public class JavaLanguage extends AbstractLanguage {
public JavaLanguage() {
this(System.getProperties());
}
public JavaLanguage(Properties properties) {
super(JavaLanguageModule.NAME, JavaLanguageModule.TERSE_NAME, new JavaTokenizer(), JavaLanguageModule.EXTENSIONS);
setProperties(properties);
}
@Override
public final void setProperties(Properties properties) {
JavaTokenizer tokenizer = (JavaTokenizer) getTokenizer();
tokenizer.setProperties(properties);
}
}
| 745 | 26.62963 | 122 | java |
pmd | pmd-master/pmd-doc/src/test/java/net/sourceforge/pmd/docs/MockedFileWriter.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.docs;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
public class MockedFileWriter implements FileWriter {
public static class FileEntry {
private String filename;
private String content;
public String getFilename() {
return filename;
}
public String getContent() {
return content;
}
}
private List<FileEntry> data = new ArrayList<>();
@Override
public void write(Path path, List<String> lines) throws IOException {
FileEntry entry = new FileEntry();
entry.filename = path.toString();
entry.content = StringUtils.join(lines, System.getProperty("line.separator"));
data.add(entry);
}
public List<FileEntry> getData() {
return data;
}
public void reset() {
data.clear();
}
public static String normalizeLineSeparators(String s) {
return s.replaceAll("\\R", System.lineSeparator());
}
}
| 1,192 | 22.392157 | 86 | java |
pmd | pmd-master/pmd-doc/src/test/java/net/sourceforge/pmd/docs/EscapeUtilsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.docs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
class EscapeUtilsTest {
@Test
void testEscapeMarkdown() {
assertEquals("This is a \\\\backslash", EscapeUtils.escapeMarkdown("This is a \\backslash"));
assertEquals("This \"\\*\" is not a emphasis", EscapeUtils.escapeMarkdown("This \"*\" is not a emphasis"));
assertEquals("This \"\\*\\*\" is not a strong style", EscapeUtils.escapeMarkdown("This \"**\" is not a strong style"));
assertEquals("This \"\\[foo\\]\" does not start a link", EscapeUtils.escapeMarkdown("This \"[foo]\" does not start a link"));
assertEquals("This \"\\~bar\\~\" is not a strike-through", EscapeUtils.escapeMarkdown("This \"~bar~\" is not a strike-through"));
assertEquals("That's \"\\|\" just a bar", EscapeUtils.escapeMarkdown("That's \"|\" just a bar"));
assertEquals("This \"\\_\" is just a underscore", EscapeUtils.escapeMarkdown("This \"_\" is just a underscore"));
}
@Test
void testEscapeHtmlWithinMarkdownSingleLine() {
assertEquals("a <script> tag outside of `<script>` backticks should be escaped",
EscapeUtils.escapeSingleLine("a <script> tag outside of `<script>` backticks should be escaped"));
assertEquals("a <script> "tag" outside of `<script>` backticks should be escaped <multiple> times `<strong>`.",
EscapeUtils.escapeSingleLine("a <script> \"tag\" outside of `<script>` backticks should be escaped <multiple> times `<strong>`."));
assertEquals("URLS: a https://pmd.github.io or a <https://pmd.github.io> are turned into links",
EscapeUtils.escapeSingleLine("URLS: a https://pmd.github.io or a <https://pmd.github.io> are turned into links"));
assertEquals("multiple URLS: <https://pmd.github.io> and <https://pmd.github.io> are two links",
EscapeUtils.escapeSingleLine("multiple URLS: <https://pmd.github.io> and <https://pmd.github.io> are two links"));
assertEquals("URL: <http://www.google.com> is a url without ssl",
EscapeUtils.escapeSingleLine("URL: <http://www.google.com> is a url without ssl"));
assertEquals("> this is a quote line",
EscapeUtils.escapeSingleLine("> this is a quote line"));
assertEquals("combination of URLs and backticks: <https://pmd.github.io> but `<script>` <strong>escaped</strong>",
EscapeUtils.escapeSingleLine("combination of URLs and backticks: <https://pmd.github.io> but `<script>` <strong>escaped</strong>"));
assertEquals("combination of URLs and backticks: `<script>` <strong>escaped</strong> but <https://pmd.github.io>",
EscapeUtils.escapeSingleLine("combination of URLs and backticks: `<script>` <strong>escaped</strong> but <https://pmd.github.io>"));
}
@Test
void testEscapeHtmlWithinMarkdownBlocks() {
String text = "paragraph\n\n> quote <script>\n> quote line \"2\"\n>quote line `<script>` 3\n\n"
+ "next paragraph\n\n code <script> \"a < b\"\n code line 2\n\n"
+ "next paragraph\n\n```\ncode <script> \"a < b\"\ncode line 2\n```\n\n"
+ "next paragraph\n\n```java\nString = \"code <script> with syntax highlighting\";\ncode line 2\n```\n";
String expected = "paragraph\n\n> quote <script>\n> quote line "2"\n>quote line `<script>` 3\n\n"
+ "next paragraph\n\n code <script> \"a < b\"\n code line 2\n\n"
+ "next paragraph\n\n```\ncode <script> \"a < b\"\ncode line 2\n```\n\n"
+ "next paragraph\n\n```java\nString = \"code <script> with syntax highlighting\";\ncode line 2\n```\n";
List<String> escaped = EscapeUtils.escapeLines(Arrays.asList(text.split("\n")));
assertEquals(Arrays.asList(expected.split("\n")), escaped);
}
}
| 4,137 | 66.836066 | 148 | java |
pmd | pmd-master/pmd-doc/src/test/java/net/sourceforge/pmd/docs/SidebarGeneratorTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.docs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.lang3.SystemUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.DumperOptions.FlowStyle;
import org.yaml.snakeyaml.DumperOptions.LineBreak;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.representer.Representer;
import net.sourceforge.pmd.RuleSet;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.LanguageRegistry;
class SidebarGeneratorTest {
private MockedFileWriter writer = new MockedFileWriter();
@BeforeEach
void setup() {
writer.reset();
}
@Test
void testSidebar() throws IOException {
Map<Language, List<RuleSet>> rulesets = new TreeMap<>();
RuleSet ruleSet1 = RuleSet.create("test", "test", "bestpractices.xml", Collections.emptyList(), Collections.emptyList(), Collections.emptyList());
RuleSet ruleSet2 = RuleSet.create("test2", "test", "codestyle.xml", Collections.emptyList(), Collections.emptyList(), Collections.emptyList());
rulesets.put(LanguageRegistry.PMD.getLanguageById("java"), Arrays.asList(ruleSet1, ruleSet2));
rulesets.put(LanguageRegistry.PMD.getLanguageById("ecmascript"), Arrays.asList(ruleSet1));
rulesets.put(LanguageRegistry.PMD.getLanguageById("scala"), Collections.emptyList());
SidebarGenerator generator = new SidebarGenerator(writer, FileSystems.getDefault().getPath(".."));
List<Map<String, Object>> result = generator.generateRuleReferenceSection(rulesets);
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(FlowStyle.BLOCK);
if (SystemUtils.IS_OS_WINDOWS) {
dumperOptions.setLineBreak(LineBreak.WIN);
}
String yaml = new Yaml(new SafeConstructor(new LoaderOptions()), new Representer(dumperOptions), dumperOptions).dump(result);
String expected = MockedFileWriter.normalizeLineSeparators(
IOUtil.readToString(SidebarGeneratorTest.class.getResourceAsStream("sidebar.yml"), StandardCharsets.UTF_8));
assertEquals(expected, yaml);
}
}
| 2,720 | 40.227273 | 154 | java |
pmd | pmd-master/pmd-doc/src/test/java/net/sourceforge/pmd/docs/RuleTagCheckerTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.docs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.nio.file.FileSystems;
import java.util.List;
import org.junit.jupiter.api.Test;
class RuleTagCheckerTest {
@Test
void testAllChecks() throws Exception {
RuleTagChecker checker = new RuleTagChecker(FileSystems.getDefault().getPath("src/test/resources/ruletagchecker"));
List<String> issues = checker.check();
assertEquals(7, issues.size());
assertEquals("ruletag-examples.md: 9: Rule tag for \"java/bestpractices/AvoidPrintStackTrace\" is not closed properly",
issues.get(0));
assertEquals("ruletag-examples.md:12: Rule \"java/notexistingcategory/AvoidPrintStackTrace\" is not found",
issues.get(1));
assertEquals("ruletag-examples.md:14: Rule \"java/bestpractices/NotExistingRule\" is not found",
issues.get(2));
assertEquals("ruletag-examples.md:16: Rule tag for \"java/bestpractices/OtherRule has a missing quote",
issues.get(3));
assertEquals("ruletag-examples.md:17: Rule tag for java/bestpractices/OtherRule\" has a missing quote",
issues.get(4));
assertEquals("ruletag-examples.md:21: Rule tag for \"OtherRule has a missing quote", issues.get(5));
assertEquals("ruletag-examples.md:22: Rule tag for OtherRule\" has a missing quote", issues.get(6));
}
}
| 1,533 | 40.459459 | 127 | java |
pmd | pmd-master/pmd-doc/src/test/java/net/sourceforge/pmd/docs/RuleSetResolverTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.docs;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.RuleSetLoader;
import net.sourceforge.pmd.internal.util.IOUtil;
class RuleSetResolverTest {
private static final List<String> EXCLUDED_RULESETS = listOf(
IOUtil.normalizePath("pmd-test/src/main/resources/rulesets/dummy/basic.xml")
);
@Test
void resolveAllRulesets() {
Path basePath = FileSystems.getDefault().getPath(".").resolve("..").toAbsolutePath().normalize();
List<String> additionalRulesets = GenerateRuleDocsCmd.findAdditionalRulesets(basePath);
filterRuleSets(additionalRulesets);
assertFalse(additionalRulesets.isEmpty());
for (String filename : additionalRulesets) {
new RuleSetLoader().warnDeprecated(false).loadFromResource(filename); // will throw if invalid
}
}
@Test
void testAdditionalRulesetPattern() {
String filePath = IOUtil.normalizePath("/home/foo/pmd/pmd-java/src/main/resources/rulesets/java/quickstart.xml");
assertTrue(GenerateRuleDocsCmd.ADDITIONAL_RULESET_PATTERN.matcher(filePath).matches());
}
private void filterRuleSets(List<String> additionalRulesets) {
additionalRulesets.removeIf(this::isExcluded);
}
private boolean isExcluded(String fileName) {
return EXCLUDED_RULESETS.stream().anyMatch(fileName::endsWith);
}
}
| 1,766 | 31.722222 | 121 | java |
pmd | pmd-master/pmd-doc/src/test/java/net/sourceforge/pmd/docs/RuleDocGeneratorTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.docs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import net.sourceforge.pmd.RuleSet;
import net.sourceforge.pmd.RuleSetLoader;
import net.sourceforge.pmd.docs.MockedFileWriter.FileEntry;
import net.sourceforge.pmd.internal.util.IOUtil;
class RuleDocGeneratorTest {
private MockedFileWriter writer = new MockedFileWriter();
private Path root;
@TempDir
public Path folder;
@BeforeEach
void setup() throws IOException {
writer.reset();
root = Files.createTempDirectory(folder, null);
Files.createDirectories(root.resolve("docs/_data/sidebars"));
List<String> mockedSidebar = Arrays.asList(
"entries:",
"- title: sidebar",
" folders:",
" - title: 1",
" - title: 2",
" - title: 3",
" - title: Rules");
Files.write(root.resolve("docs/_data/sidebars/pmd_sidebar.yml"), mockedSidebar);
}
private static String loadResource(String name) throws IOException {
return MockedFileWriter.normalizeLineSeparators(
IOUtil.readToString(RuleDocGeneratorTest.class.getResourceAsStream(name), StandardCharsets.UTF_8));
}
@Test
void testSingleRuleset() throws IOException {
RuleDocGenerator generator = new RuleDocGenerator(writer, root);
RuleSetLoader rsl = new RuleSetLoader().includeDeprecatedRuleReferences(true);
RuleSet ruleset = rsl.loadFromResource("rulesets/ruledoctest/sample.xml");
generator.generate(Arrays.asList(ruleset),
Arrays.asList(
"rulesets/ruledoctest/sample-deprecated.xml",
"rulesets/ruledoctest/other-ruleset.xml"));
assertEquals(3, writer.getData().size());
FileEntry languageIndex = writer.getData().get(0);
assertTrue(IOUtil.normalizePath(languageIndex.getFilename()).endsWith(Paths.get("docs", "pages", "pmd", "rules", "java.md").toString()));
assertEquals(loadResource("/expected/java.md"), languageIndex.getContent());
FileEntry ruleSetIndex = writer.getData().get(1);
assertTrue(IOUtil.normalizePath(ruleSetIndex.getFilename()).endsWith(Paths.get("docs", "pages", "pmd", "rules", "java", "sample.md").toString()));
assertEquals(loadResource("/expected/sample.md"), ruleSetIndex.getContent());
FileEntry sidebar = writer.getData().get(2);
assertTrue(IOUtil.normalizePath(sidebar.getFilename()).endsWith(Paths.get("docs", "_data", "sidebars", "pmd_sidebar.yml").toString()));
assertEquals(loadResource("/expected/pmd_sidebar.yml"), sidebar.getContent());
}
}
| 3,199 | 37.554217 | 154 | java |
pmd | pmd-master/pmd-doc/src/main/java/net/sourceforge/pmd/docs/EscapeUtils.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.docs;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.text.StringEscapeUtils;
public final class EscapeUtils {
private static final String BACKTICK = "`";
private static final String URL_START = "<http";
private static final String QUOTE_START = ">";
private static final Pattern RULE_TAG = Pattern.compile("\\{%\\s+rule\\s+"([^&]+)"\\s*\\%}");
private EscapeUtils() {
// This is a utility class
}
public static String escapeMarkdown(String unescaped) {
return unescaped.replace("\\", "\\\\")
.replace("*", "\\*")
.replace("_", "\\_")
.replace("~", "\\~")
.replace("[", "\\[")
.replace("]", "\\]")
.replace("|", "\\|");
}
public static String escapeSingleLine(String line) {
StringBuilder escaped = new StringBuilder(line.length() + 16);
String currentLine = line;
if (currentLine.startsWith(QUOTE_START)) {
escaped.append(currentLine.substring(0, 1));
currentLine = currentLine.substring(1);
}
int url = currentLine.indexOf(URL_START);
while (url > -1) {
String before = currentLine.substring(0, url);
before = escapeBackticks(escaped, before);
escaped.append(StringEscapeUtils.escapeHtml4(before));
int urlEnd = currentLine.indexOf(">", url) + 1;
// add the url unescaped
escaped.append(currentLine.substring(url, urlEnd));
currentLine = currentLine.substring(urlEnd);
url = currentLine.indexOf(URL_START);
}
currentLine = escapeBackticks(escaped, currentLine);
escaped.append(StringEscapeUtils.escapeHtml4(currentLine));
return escaped.toString();
}
private static String escapeBackticks(StringBuilder escaped, String linePart) {
String currentLine = linePart;
int pos = currentLine.indexOf(BACKTICK);
boolean needsEscaping = true;
while (pos > -1) {
String before = currentLine.substring(0, pos);
if (needsEscaping) {
escaped.append(StringEscapeUtils.escapeHtml4(before));
escaped.append(BACKTICK);
needsEscaping = false;
} else {
escaped.append(before);
escaped.append(BACKTICK);
needsEscaping = true;
}
currentLine = currentLine.substring(pos + 1);
pos = currentLine.indexOf(BACKTICK);
}
return currentLine;
}
public static List<String> escapeLines(List<String> lines) {
boolean needsEscape = true;
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
if (line.startsWith("```")) {
needsEscape = !needsEscape;
}
if (needsEscape && !line.startsWith(" ")) {
line = escapeSingleLine(line);
line = preserveRuleTagQuotes(line);
}
lines.set(i, line);
}
return lines;
}
/**
* If quotes are used for rule tags, e.g. {@code {% rule "OtherRule" %}}, these
* quotes might have been escaped for html, but it's actually markdown/jekyll/liquid
* and not html. This undoes the escaping.
* @param text the already escaped text that might contain rule tags
* @return text with the fixed rule tags
*/
public static String preserveRuleTagQuotes(String text) {
Matcher m = RULE_TAG.matcher(text);
return m.replaceAll("{% rule \"$1\" %}");
}
}
| 3,846 | 34.62037 | 107 | java |
pmd | pmd-master/pmd-doc/src/main/java/net/sourceforge/pmd/docs/DeadLinksChecker.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.docs;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.internal.util.IOUtil;
/**
* Checks links to local pages for non-existing link-targets.
*/
public class DeadLinksChecker {
private static final Logger LOG = LoggerFactory.getLogger(DeadLinksChecker.class);
private static final String CHECK_EXTERNAL_LINKS_PROPERTY = "pmd.doc.checkExternalLinks";
private static final boolean CHECK_EXTERNAL_LINKS = Boolean.parseBoolean(System.getProperty(CHECK_EXTERNAL_LINKS_PROPERTY));
// Markdown-Link: something in []'s followed by something in ()'s
// ignoring an optional prefix "{{ baseurl }}"
private static final Pattern LOCAL_LINK_PATTERN = Pattern.compile("(!)?\\[.*?]\\((?:\\{\\{\\s*baseurl\\s*\\}\\})?(.*?)\\)");
// Markdown permalink-header and captions
private static final Pattern MD_HEADER_PERMALINK = Pattern.compile("permalink:\\s*(.*)");
private static final Pattern MD_CAPTION = Pattern.compile("^##+\\s+(.*)$", Pattern.MULTILINE);
// list of link targets, where the link detection doesn't work
private static final Pattern EXCLUDED_LINK_TARGETS = Pattern.compile(
"^pmd_userdocs_cli_reference\\.html.*" // anchors in the CLI reference are a plain HTML include
);
// the link is actually pointing to a file in the pmd project
private static final String LOCAL_FILE_PREFIX = "https://github.com/pmd/pmd/blob/master/";
// don't check links to PMD bugs/issues/pull-requests (performance optimization)
private static final List<String> IGNORED_URL_PREFIXES = Collections.unmodifiableList(Arrays.asList(
"https://github.com/pmd/pmd/issues/",
"https://github.com/pmd/pmd/pull/",
"https://sourceforge.net/p/pmd/bugs/"
));
// prevent checking the same link multiple times
private final Map<String, CompletableFuture<Integer>> urlResponseCache = new ConcurrentHashMap<>();
private final ExecutorService executorService = Executors.newCachedThreadPool();
public void checkDeadLinks(Path rootDirectory) {
final Path pagesDirectory = rootDirectory.resolve("docs/pages");
final Path docsDirectory = rootDirectory.resolve("docs");
if (!Files.isDirectory(pagesDirectory)) {
// docsDirectory is implicitly checked by this statement too
LOG.error("can't check for dead links, didn't find \"pages\" directory at: {}", pagesDirectory);
System.exit(1);
}
// read all .md-files in the pages directory
final List<Path> mdFiles = listMdFiles(pagesDirectory);
// Stores file path to the future deadlinks. If a future evaluates to null, the link is not dead
final Map<Path, List<Future<String>>> fileToDeadLinks = new HashMap<>();
// make a list of all valid link targets
final Set<String> htmlPages = extractLinkTargets(mdFiles);
// scan all .md-files for dead local links
int scannedFiles = 0;
int foundExternalLinks = 0;
int checkedExternalLinks = 0;
for (Path mdFile : mdFiles) {
final String pageContent = fileToString(mdFile);
scannedFiles++;
// iterate line-by-line for better reporting the line numbers
final String[] lines = pageContent.split("\r?\n");
for (int index = 0; index < lines.length; index++) {
final String line = lines[index];
final int lineNo = index + 1;
final Matcher matcher = LOCAL_LINK_PATTERN.matcher(line);
linkCheck:
while (matcher.find()) {
final String linkText = matcher.group();
final boolean isImageLink = matcher.group(1) != null;
final String linkTarget = matcher.group(2);
boolean linkOk;
if (linkTarget.charAt(0) == '/') {
// links must never start with / - they must be relative or start with https?//...
linkOk = false;
} else if (linkTarget.startsWith(LOCAL_FILE_PREFIX)) {
String localLinkPart = linkTarget.substring(LOCAL_FILE_PREFIX.length());
if (localLinkPart.contains("#")) {
localLinkPart = localLinkPart.substring(0, localLinkPart.indexOf('#'));
}
final Path localFile = rootDirectory.resolve(localLinkPart);
linkOk = Files.isRegularFile(localFile);
if (!linkOk) {
LOG.warn("local file not found: {}", localFile);
LOG.warn(" linked by: {}", linkTarget);
}
} else if (linkTarget.startsWith("http://") || linkTarget.startsWith("https://")) {
foundExternalLinks++;
if (!CHECK_EXTERNAL_LINKS) {
LOG.debug("ignoring check of external url: {}", linkTarget);
continue;
}
for (String ignoredUrlPrefix : IGNORED_URL_PREFIXES) {
if (linkTarget.startsWith(ignoredUrlPrefix)) {
LOG.debug("not checking link: {}", linkTarget);
continue linkCheck;
}
}
checkedExternalLinks++;
linkOk = true;
Future<String> futureMessage =
getCachedFutureResponse(linkTarget)
.thenApply(c -> c >= 400)
// It's important not to use the matcher in this mapper!
// It may be exhausted at the time of execution
.thenApply(dead -> dead ? String.format("%8d: %s", lineNo, linkText) : null);
addDeadLink(fileToDeadLinks, mdFile, futureMessage);
} else {
// ignore local anchors
if (linkTarget.startsWith("#")) {
continue;
}
// ignore some pages where automatic link detection doesn't work
if (EXCLUDED_LINK_TARGETS.matcher(linkTarget).matches()) {
continue;
}
if (isImageLink) {
Path localResource = docsDirectory.resolve(linkTarget);
linkOk = Files.exists(localResource);
} else {
linkOk = linkTarget.isEmpty() || htmlPages.contains(linkTarget);
}
// maybe a local file
if (!linkOk) {
Path localResource = docsDirectory.resolve(linkTarget);
linkOk = Files.exists(localResource);
}
}
if (!linkOk) {
RunnableFuture<String> futureTask = new FutureTask<>(() -> String.format("%8d: %s", lineNo, linkText));
// execute this task immediately in this thread.
// External links are checked by another executor and don't end up here.
futureTask.run();
addDeadLink(fileToDeadLinks, mdFile, futureTask);
}
}
}
}
executorService.shutdown();
LOG.info("Scanned {} files for dead links.", scannedFiles);
LOG.info(" Found {} external links, {} of those where checked.", foundExternalLinks, checkedExternalLinks);
if (!CHECK_EXTERNAL_LINKS) {
LOG.info("External links weren't checked, set -D" + CHECK_EXTERNAL_LINKS_PROPERTY + "=true to enable it.");
}
Map<Path, List<String>> joined = joinFutures(fileToDeadLinks);
if (joined.isEmpty()) {
LOG.info("No errors found!");
} else {
LOG.warn("Found dead link(s):");
for (Path file : joined.keySet()) {
System.err.println(rootDirectory.relativize(file).toString());
joined.get(file).forEach(LOG::warn);
}
throw new AssertionError("Dead links detected");
}
}
private Map<Path, List<String>> joinFutures(Map<Path, List<Future<String>>> map) {
Map<Path, List<String>> joined = new HashMap<>();
for (Path p : map.keySet()) {
List<String> evaluatedResult = map.get(p).stream()
.map(f -> {
try {
return f.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
return null;
}
})
.filter(Objects::nonNull)
.sorted(Comparator.naturalOrder())
.collect(Collectors.toList());
if (!evaluatedResult.isEmpty()) {
joined.put(p, evaluatedResult);
}
}
return joined;
}
private void addDeadLink(Map<Path, List<Future<String>>> fileToDeadLinks, Path file, Future<String> line) {
fileToDeadLinks.computeIfAbsent(file, k -> new ArrayList<>()).add(line);
}
private Set<String> extractLinkTargets(List<Path> mdFiles) {
final Set<String> htmlPages = new HashSet<>();
for (Path mdFile : mdFiles) {
final String pageContent = fileToString(mdFile);
// extract the permalink header field
final Matcher permalinkMatcher = MD_HEADER_PERMALINK.matcher(pageContent);
if (!permalinkMatcher.find()) {
continue;
}
final String pageUrl = permalinkMatcher.group(1)
.replaceAll("^/+", ""); // remove the leading "/"
// add the root page
htmlPages.add(pageUrl);
// add all captions as anchors
final Matcher captionMatcher = MD_CAPTION.matcher(pageContent);
while (captionMatcher.find()) {
final String anchor = captionMatcher.group(1)
.toLowerCase(Locale.ROOT)
.replaceAll("[^a-z0-9_]+", "-") // replace all non-alphanumeric characters with dashes
.replaceAll("^-+|-+$", ""); // trim leading or trailing dashes
htmlPages.add(pageUrl + "#" + anchor);
}
}
return htmlPages;
}
private List<Path> listMdFiles(Path pagesDirectory) {
try (Stream<Path> stream = Files.walk(pagesDirectory)) {
return stream
.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith(".md"))
.collect(Collectors.toList());
} catch (IOException ex) {
throw new RuntimeException("error listing files in " + pagesDirectory, ex);
}
}
private String fileToString(Path mdFile) {
try (InputStream inputStream = Files.newInputStream(mdFile)) {
return IOUtil.readToString(inputStream, StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException("error reading " + mdFile, ex);
}
}
private CompletableFuture<Integer> getCachedFutureResponse(String url) {
if (urlResponseCache.containsKey(url)) {
LOG.info("response: HTTP {} (CACHED) on {}", urlResponseCache.get(url), url);
return urlResponseCache.get(url);
} else {
// process asynchronously
CompletableFuture<Integer> futureResponse = CompletableFuture.supplyAsync(() -> computeHttpResponse(url), executorService);
urlResponseCache.put(url, futureResponse);
return futureResponse;
}
}
private int computeHttpResponse(String url) {
try {
final HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
httpURLConnection.setRequestMethod("HEAD");
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setReadTimeout(15000);
httpURLConnection.connect();
final int responseCode = httpURLConnection.getResponseCode();
String response = "HTTP " + responseCode;
if (httpURLConnection.getHeaderField("Location") != null) {
response += ", Location: " + httpURLConnection.getHeaderField("Location");
}
LOG.debug("response: {} on {}", response, url);
// success (HTTP 2xx) or redirection (HTTP 3xx)
return responseCode;
} catch (IOException ex) {
LOG.debug("response: {} on {} : {}", ex.getClass().getName(), url, ex.getMessage());
return 599;
}
}
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Wrong arguments!");
System.err.println();
System.err.println("java " + DeadLinksChecker.class.getSimpleName() + " <project base directory>");
System.exit(1);
}
final Path rootDirectory = Paths.get(args[0]).resolve("..").toRealPath();
DeadLinksChecker deadLinksChecker = new DeadLinksChecker();
deadLinksChecker.checkDeadLinks(rootDirectory);
}
}
| 15,277 | 40.857534 | 138 | java |
pmd | pmd-master/pmd-doc/src/main/java/net/sourceforge/pmd/docs/SidebarGenerator.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.docs;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.lang3.SystemUtils;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.DumperOptions.FlowStyle;
import org.yaml.snakeyaml.DumperOptions.LineBreak;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.representer.Representer;
import net.sourceforge.pmd.RuleSet;
import net.sourceforge.pmd.lang.Language;
public class SidebarGenerator {
private static final String SIDEBAR_YML = "docs/_data/sidebars/pmd_sidebar.yml";
private final FileWriter writer;
private final Path sidebarPath;
public SidebarGenerator(FileWriter writer, Path basePath) {
this.writer = Objects.requireNonNull(writer, "A file writer must be provided");
this.sidebarPath = Objects.requireNonNull(basePath, "A base directory must be provided").resolve(SIDEBAR_YML);
}
@SuppressWarnings("unchecked")
private Map<String, Object> extractRuleReference(Map<String, Object> sidebar) {
List<Map<String, Object>> entries = (List<Map<String, Object>>) sidebar.get("entries");
Map<String, Object> entry = entries.get(0);
List<Map<String, Object>> folders = (List<Map<String, Object>>) entry.get("folders");
return folders.get(3);
}
public void generateSidebar(Map<Language, List<RuleSet>> sortedRulesets) throws IOException {
Map<String, Object> sidebar = loadSidebar();
Map<String, Object> ruleReference = extractRuleReference(sidebar);
ruleReference.put("folderitems", generateRuleReferenceSection(sortedRulesets));
writeSidebar(sidebar);
}
List<Map<String, Object>> generateRuleReferenceSection(Map<Language, List<RuleSet>> sortedRulesets) {
List<Map<String, Object>> newFolderItems = new ArrayList<>();
for (Map.Entry<Language, List<RuleSet>> entry : sortedRulesets.entrySet()) {
Map<String, Object> newFolderItem = new LinkedHashMap<>();
newFolderItem.put("title", null);
newFolderItem.put("output", "web, pdf");
Map<String, Object> subfolder = new LinkedHashMap<>();
newFolderItem.put("subfolders", Arrays.asList(subfolder));
subfolder.put("title", entry.getKey().getName() + " Rules");
subfolder.put("output", "web, pdf");
List<Map<String, Object>> subfolderitems = new ArrayList<>();
subfolder.put("subfolderitems", subfolderitems);
Map<String, Object> ruleIndexSubfolderItem = new LinkedHashMap<>();
ruleIndexSubfolderItem.put("title", "Index");
ruleIndexSubfolderItem.put("output", "web, pdf");
ruleIndexSubfolderItem.put("url", "/pmd_rules_" + entry.getKey().getTerseName() + ".html");
subfolderitems.add(ruleIndexSubfolderItem);
for (RuleSet ruleset : entry.getValue()) {
Map<String, Object> subfolderitem = new LinkedHashMap<>();
subfolderitem.put("title", ruleset.getName());
subfolderitem.put("output", "web, pdf");
subfolderitem.put("url", "/pmd_rules_" + entry.getKey().getTerseName() + "_" + RuleSetUtils.getRuleSetFilename(ruleset) + ".html");
subfolderitems.add(subfolderitem);
}
newFolderItems.add(newFolderItem);
}
return newFolderItems;
}
public Map<String, Object> loadSidebar() throws IOException {
try (Reader reader = Files.newBufferedReader(sidebarPath, StandardCharsets.UTF_8)) {
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
return yaml.load(reader);
}
}
public void writeSidebar(Map<String, Object> sidebar) throws IOException {
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(FlowStyle.BLOCK);
if (SystemUtils.IS_OS_WINDOWS) {
dumperOptions.setLineBreak(LineBreak.WIN);
}
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()), new Representer(dumperOptions), dumperOptions);
writer.write(sidebarPath, Arrays.asList(yaml.dump(sidebar)));
System.out.println("Generated " + sidebarPath);
}
}
| 4,693 | 42.06422 | 147 | java |
pmd | pmd-master/pmd-doc/src/main/java/net/sourceforge/pmd/docs/GenerateRuleDocsCmd.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.docs;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import net.sourceforge.pmd.RuleSet;
import net.sourceforge.pmd.RuleSetLoader;
import net.sourceforge.pmd.internal.util.IOUtil;
public final class GenerateRuleDocsCmd {
private GenerateRuleDocsCmd() {
// Utility class
}
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("One argument is required: The base directory of the module pmd-doc.");
System.exit(1);
}
long start = System.currentTimeMillis();
Path output = FileSystems.getDefault().getPath(args[0]).resolve("..").toAbsolutePath().normalize();
System.out.println("Generating docs into " + output);
// important: use a RuleSetFactory that includes all rules, e.g. deprecated rule references
List<RuleSet> registeredRuleSets = new RuleSetLoader().includeDeprecatedRuleReferences(true)
.getStandardRuleSets();
List<String> additionalRulesets = findAdditionalRulesets(output);
RuleDocGenerator generator = new RuleDocGenerator(new DefaultFileWriter(), output);
generator.generate(registeredRuleSets, additionalRulesets);
System.out.println("Generated docs in " + (System.currentTimeMillis() - start) + " ms");
}
static final Pattern ADDITIONAL_RULESET_PATTERN = Pattern.compile("^.+" + Pattern.quote(File.separator) + "pmd-\\w+"
+ Pattern.quote(IOUtil.normalizePath(File.separator + Paths.get("src", "main", "resources", "rulesets").toString()) + File.separator)
+ "\\w+" + Pattern.quote(File.separator) + "\\w+.xml$");
public static List<String> findAdditionalRulesets(Path basePath) {
try {
List<String> additionalRulesets = new ArrayList<>();
Files.walkFileTree(basePath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (ADDITIONAL_RULESET_PATTERN.matcher(file.toString()).matches()) {
additionalRulesets.add(file.toString());
}
return FileVisitResult.CONTINUE;
}
});
return additionalRulesets;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| 2,873 | 37.837838 | 145 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.