Class StaticTypeCheckingVisitor
java.lang.Object
org.codehaus.groovy.ast.CodeVisitorSupport
org.codehaus.groovy.ast.ClassCodeVisitorSupport
org.codehaus.groovy.transform.stc.StaticTypeCheckingVisitor
- All Implemented Interfaces:
GroovyClassVisitor,GroovyCodeVisitor,ErrorCollecting
- Direct Known Subclasses:
StaticCompilationVisitor
The main class code visitor responsible for static type checking. It will perform various inspections like checking
assignment types, type inference, ... Eventually, class nodes may be annotated with inferred type information.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classCreates signature codecs for serialized type checking metadata.protected classMemoizes inferred variable types so they can be restored after temporary rewrites. -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected static final ClassNodeCachedCharSequencetype (GROOVY-9848: membership operator dispatch).static final MethodNodeCached zero-argumentClosure#call()method.static final MethodNodeCached single-argumentClosure#call(Object)method.static final MethodNodeCached varargsClosure#call(Object[])method.protected static final ClassNodeCachedClosureParamsannotation type.protected static final ExpressionConstant expression for the current signature protocol version.protected static final intCurrent encoding protocol for stored type-checking signatures.protected FieldNodeField currently being visited.protected PropertyNodeProperty currently being visited.protected static final ClassNodeCachedDelegatesToannotation type.protected static final ClassNodeCachedDelegatesTo.Targetannotation type.protected static final ClassNodeCachedDefaultGroovyMethodstype.protected static final List<MethodNode>Shared empty method list.protected static final ClassNodeCachedEnumerationtype.protected static final ObjectMetadata key used to store per-method error collectors.protected DefaultTypeCheckingExtensionComposite extension chain consulted during type checking.static final StatementEmpty statement reused for synthetic AST nodes.protected static final MethodNodeCachedClosure#getDelegate()method.protected static final MethodNodeCachedClosure#getOwner()method.protected static final MethodNodeCachedClosure#getThisObject()method.protected static final ClassNodeCachedIterabletype.protected static final ClassNodeDeprecated, for removal: This API element is subject to removal in a future version.protected static final ClassNodeCachedMap.Entrytype.protected static final ClassNodeCachedNamedParamannotation type.protected static final ClassNodeCachedNamedParamsannotation type.protected final ReturnAdderReturn adder used to normalize implicit and explicit returns.protected final ReturnAdder.ReturnStatementListenerprotected static final ClassNodeCachedTypeCheckedannotation type.protected static final ClassNode[]Type-checking annotations recognized by this visitor.protected static final ClassNodeCachedTypeChecked.TypeCheckingInfoannotation type.protected TypeCheckingContextMutable state for the current type-checking run. -
Constructor Summary
ConstructorsConstructorDescriptionStaticTypeCheckingVisitor(SourceUnit source, ClassNode classNode) Creates a static type-checking visitor for the supplied source and class. -
Method Summary
Modifier and TypeMethodDescriptionprotected voidaddAmbiguousErrorMessage(List<MethodNode> foundMethods, String name, ClassNode[] args, Expression expr) Reports that method resolution remained ambiguous after filtering.protected voidaddAssignmentError(ClassNode leftType, ClassNode rightType, Expression expression) Reports an incompatible assignment between the supplied types.protected voidReports that categories cannot be used under static type checking.protected voidaddClosureReturnType(ClassNode returnType) Records a non-void return type for the current enclosing closure.voidAdds an error message associated with an AST node to the source unit.protected voidaddNoMatchingMethodError(ClassNode receiver, String name, ClassNode[] args, ASTNode origin) Reports that no matching method or constructor could be found for the call.protected voidaddNoMatchingMethodError(ClassNode receiver, String name, ClassNode[] args, Expression exp) Reports that no matching method or constructor could be found for the call.protected voidaddReceivers(List<Receiver<String>> receivers, Collection<Receiver<String>> owners, boolean implicitThis) Adds candidate receivers derived from owner chains.protected voidaddStaticTypeError(String msg, ASTNode node) Reports a static type checking error for the supplied node.voidaddTypeCheckingExtension(TypeCheckingExtension extension) Adds a type-checking extension to the active extension chain.protected voidAddsTypeChecked.TypeCheckingInfometadata for an inferred method return type.protected voidaddUnsupportedPreOrPostfixExpressionError(Expression expression) Reports an unsupported prefix or postfix operation.protected voidafterSwitchCaseStatementsVisited(SwitchStatement statement) Hook method called after all case statements are visited, but before the default statement.protected voidHook method called after the switch condition expression is visited, but before case statements.protected booleanareCategoryMethodCalls(List<MethodNode> foundMethods, String name, ClassNode[] args) Indicates whether all candidates are category-style extension methods.protected booleancheckCast(ClassNode targetType, Expression source) Checks whether the source expression can be cast to the supplied target type.protected voidcheckClosureParameters(Expression callArguments, ClassNode receiver) Deprecated, for removal: This API element is subject to removal in a future version.protected voidRejects spread arguments where no target signature is available.protected voidcheckGroovyConstructorMap(Expression receiver, ClassNode receiverType, MapExpression mapExpression) Validates map-style constructor arguments against writable properties.protected MethodNodecheckGroovyStyleConstructor(ClassNode node, ClassNode[] arguments, ASTNode origin) Checks that a constructor style expression is valid regarding the number of arguments and the argument types.protected ClassNodecheckReturnType(ReturnStatement statement) Validates the current return statement against the enclosing closure or method.protected booleanexistsProperty(PropertyExpression pexp, boolean checkForReadOnly) Checks whether the property exists for the current access mode.protected booleanexistsProperty(PropertyExpression pexp, boolean readMode, ClassCodeVisitorSupport visitor) Checks whether a property exists on the receiver, or on any of the possible receiver classes (found in the temporary type information table)static StringextractPropertyNameFromMethodName(String prefix, String methodName) Given a method name and a prefix, returns the name of the property that should be looked up, following the java beans rules.protected ObjectextractTemporaryTypeInfoKey(Expression expression) Computes the key to use forTypeCheckingContext.temporaryIfBranchTypeInformation.protected static ClassNode[]extractTypesFromParameters(Parameter[] parameters) Extracts the declared types of the supplied parameters.protected ClassNodefindCurrentInstanceOfClass(Expression expression, ClassNode type) A helper method which determines which receiver class should be used in error messages when a field or attribute is not found.protected List<MethodNode>findMethod(ClassNode receiver, String name, ClassNode... args) Finds candidate methods matching the supplied receiver, name, and argument types.protected MethodNodefindMethodOrFail(Expression expr, ClassNode receiver, String name, ClassNode... args) Finds a matching method or reports a static type error when none is available.protected List<MethodNode>findMethodsWithGenerated(ClassNode receiver, String name) Returns methods defined for the specified receiver and adds "non-existing" methods that will be generated afterwards by the compiler; for example if a method is using default values and the class node is not compiled yet.protected static StringformatArgumentList(ClassNode[] nodes) Formats an argument-type list for diagnostics.protected ClassNode[]getArgumentTypes(ArgumentListExpression argumentList) Returns the inferred argument types for the supplied argument list.protected org.codehaus.groovy.transform.stc.DelegationMetadatagetDelegationMetadata(ClosureExpression expression) Returns delegation metadata attached to the supplied closure expression.protected static ClassNodeReturns the result type for grouped numeric operations such as addition.protected ClassNodegetInferredReturnType(ASTNode node) Returns the inferred return type of a closure or method, if stored on the AST node.protected ClassNodegetInferredReturnTypeFromWithClosureArgument(Expression callArguments) In the case of a Object.with { ...protected ClassNodeReturns the declared type of the left-hand side before any flow-based refinement.protected ClassNodegetResultType(ClassNode left, int op, ClassNode right, BinaryExpression expr) Computes the result type of a binary operation.protected SourceUnitProvides access to theSourceUnitfor error reporting during visitation.getTemporaryTypesForExpression(Expression expression) Returns temporary narrowed types recorded for the supplied expression.protected ClassNodeReturns the inferred type for the supplied AST node.protected ClassNode[]Returns array of type checking annotations.Returns the current type checking context.protected static booleanhasRHSIncompleteGenericTypeInfo(ClassNode inferredRightExpressionType) Deprecated, for removal: This API element is subject to removal in a future version.protected voidinferClosureParameterTypes(ClassNode receiver, Expression arguments, ClosureExpression expression, Parameter target, MethodNode method) Performs type inference on closure argument types whenever code like this is found:foo.collect { it.toUpperCase() }.protected ClassNodeinferComponentType(ClassNode receiverType, ClassNode subscriptType) Infers the component type addressed by subscript or iterator access.protected voidinferDiamondType(ConstructorCallExpression cce, ClassNode lType) Infers generic arguments for constructor calls that use the diamond operator.protected ClassNodeInfers the static type of a list literal.static ClassNodeinferLoopElementType(ClassNode collectionType) Returns the inferred loop element type given a loop collection type.protected ClassNodeInfers the static type of a map literal.protected ClassNodeinferRangeSliceType(ClassNode receiverType) GEP-20: probe the static return type ofrhs.getAt(IntRange)onreceiverType, so the rest binder can be typed against the actual slice type rather than a hard-codedList<T>.protected ClassNodeinferReturnTypeGenerics(ClassNode receiver, MethodNode method, Expression arguments) If a method call returns a parameterized type, then perform additional inference on the return type, so that the type gets actual type arguments.protected ClassNodeinferReturnTypeGenerics(ClassNode receiver, MethodNode method, Expression arguments, GenericsType[] explicitTypeHints) If a method call returns a parameterized type, then perform additional inference on the return type, so that the type gets actual type arguments.voidInitializes the registered type-checking extensions.protected static booleanisClassInnerClassOrEqualTo(ClassNode toBeChecked, ClassNode start) Indicates whetherstartistoBeCheckedor nested within it.protected static booleanisNullConstant(Expression expression) Indicates whether the expression is thenullconstant.protected booleanisSecondPassNeededForControlStructure(Map<VariableExpression, ClassNode> startTypes, Map<VariableExpression, List<ClassNode>> oldTracker) Indicates whether a second pass is needed after visiting a control structure.booleanisSkipMode(AnnotatedNode node) Indicates whether the annotated node is configured forTypeCheckingMode.SKIP.protected booleanTests if a node is an inner class node, and if it is, then checks if the enclosing method is skipped.protected static booleanisSuperExpression(Expression expression) Indicates whether the expression representssuper.protected static booleanisThisExpression(Expression expression) Indicates whether the expression representsthis.makeOwnerList(Expression objectExpression) Given an object expression (a message receiver expression), generate list of possible types.voidReplays deferred checks that require information collected during the first pass.protected Map<VariableExpression,ClassNode> popAssignmentTracking(Map<VariableExpression, List<ClassNode>> oldTracker) Pops the current assignment tracker and applies any merged types.protected static StringprettyPrintMethodList(List<MethodNode> nodes) Formats a method list for diagnostics.protected Map<VariableExpression,List<ClassNode>> Pushes a fresh assignment tracker and returns the previous tracker.protected voidpushInstanceOfTypeInfo(Expression objectExpression, Expression typeExpression) Stores information about types when [objectExpression instanceof typeExpression] is visited.protected voidrestoreVariableExpressionMetadata(Map<VariableExpression, Map<StaticTypesMarker, Object>> typesBeforeVisit) Restores variable-expression metadata saved before a closure visit.protected voidsaveVariableExpressionMetadata(Set<VariableExpression> closureSharedExpressions, Map<VariableExpression, Map<StaticTypesMarker, Object>> typesBeforeVisit) Saves variable-expression metadata that must survive closure re-visits.voidsetCompilationUnit(CompilationUnit compilationUnit) Associates the visitor with a compilation unit.voidsetMethodsToBeVisited(Set<MethodNode> methodsToBeVisited) Restricts type checking to the supplied method set.protected booleanshouldSkipClassNode(ClassNode node) Indicates whether the class should be skipped by this visitor.protected booleanIndicates whether the method should be skipped by this visitor.protected voidsilentlyVisitMethodNode(MethodNode directMethodCallCandidate) Visits a method call target, to infer the type.protected voidstartMethodInference(MethodNode node, ErrorCollector collector) Starts type inference for the supplied method using the supplied error collector.protected ClassNodestoreInferredReturnType(ASTNode node, ClassNode type) Stores the inferred return type of a closure or method.protected voidstoreTargetMethod(Expression call, MethodNode target) Stores the selected target method on the call expression.protected voidstoreType(Expression exp, ClassNode cn) Stores the inferred type for the supplied expression.protected voidtypeCheckAssignment(BinaryExpression assignmentExpression, Expression leftExpression, ClassNode leftExpressionType, Expression rightExpression, ClassNode rightExpressionType) Checks assignment compatibility and reports any associated type errors.protected voidtypeCheckClosureCall(Expression arguments, ClassNode[] argumentTypes, Parameter[] parameters) Validates closure calls against the signatures implied by the closure parameters.protected MethodNodetypeCheckMapConstructor(ConstructorCallExpression call, ClassNode receiver, Expression arguments) Selects and validates a synthetic map-style constructor target.protected booleantypeCheckMethodsWithGenericsOrFail(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod, Expression location) Validates a chosen method against its generic constraints and reports failures.voidvisitArrayExpression(ArrayExpression expression) Visits anArrayExpression, traversing element expressions and size expressions.voidvisitAttributeExpression(AttributeExpression expression) Visits anAttributeExpression, traversing the object and attribute name expressions.voidvisitBinaryExpression(BinaryExpression expression) Visits aBinaryExpression, traversing left and right operand expressions.voidVisits aBitwiseNegationExpression, traversing the operand expression.voidvisitCaseStatement(CaseStatement statement) Visits aCaseStatement, invoking the statement hook before parent traversal.voidvisitCastExpression(CastExpression expression) Visits aCastExpression, traversing the operand expression.voidvisitClass(ClassNode node) Visits aClassNode, processing its annotations, package, imports, contents, and object initializers.voidvisitClassExpression(ClassExpression expression) Visits aClassExpression.voidvisitClosureExpression(ClosureExpression expression) Visits aClosureExpressionwith annotation processing, traversing parameter annotations before delegating to parent traversal.voidVisits aConstructorNode, processing its annotations, parameter annotations, and code block.voidVisits aConstructorCallExpression, traversing its argument list.protected voidvisitConstructorOrMethod(MethodNode node, boolean isConstructor) Visits a constructor or method node (implementation detail for both visit methods).voidvisitExpressionStatement(ExpressionStatement statement) Visits anExpressionStatement, invoking the statement hook before parent traversal.voidvisitField(FieldNode node) Visits aFieldNode, processing its annotations and initial value expression if present.voidvisitForLoop(ForStatement forLoop) Visits aForStatement, invoking statement hooks and processing loop variable annotations.voidvisitIfElse(IfStatement ifElse) Visits anIfStatement, invoking the statement hook before parent traversal.voidvisitMethod(MethodNode node) Visits aMethodNode, processing its annotations, parameter annotations, and code block.protected voidvisitMethodCallArguments(ClassNode receiver, ArgumentListExpression arguments, boolean visitFunctors, MethodNode selectedMethod) Visits method-call arguments and defers functional arguments until a target is known.voidVisits aMethodCallExpression, traversing the object expression, method expression, and argument list.voidvisitMethodPointerExpression(MethodPointerExpression expression) Visits aMethodPointerExpression, traversing the object and method name expressions.voidvisitNotExpression(NotExpression expression) Visits aNotExpression, traversing the operand expression.protected voidVisits all object initializer statements in a class, typically static or instance initialization blocks.voidvisitPostfixExpression(PostfixExpression expression) Visits aPostfixExpression, traversing the operand expression.voidvisitPrefixExpression(PrefixExpression expression) Visits aPrefixExpression, traversing the operand expression.voidvisitProperty(PropertyNode node) Visits aPropertyNode, processing its annotations, initial value expression, and getter/setter blocks if present.voidvisitPropertyExpression(PropertyExpression expression) Visits aPropertyExpression, traversing the object and property name expressions.voidvisitRangeExpression(RangeExpression expression) Visits aRangeExpression, traversing from and to boundary expressions.voidvisitReturnStatement(ReturnStatement statement) Visits aReturnStatement, invoking the statement hook before parent traversal.voidVisits aStaticMethodCallExpression, traversing its argument list.voidvisitSwitch(SwitchStatement statement) Visits aSwitchStatement, invoking the statement hook before parent traversal.voidvisitTernaryExpression(TernaryExpression expression) Visits aTernaryExpression, traversing the condition, true-branch, and false-branch expressions.voidvisitTryCatchFinally(TryCatchStatement statement) Visits aTryCatchStatement, invoking the statement hook before parent traversal.voidvisitUnaryMinusExpression(UnaryMinusExpression expression) Visits aUnaryMinusExpression, traversing the operand expression.voidvisitUnaryPlusExpression(UnaryPlusExpression expression) Visits aUnaryPlusExpression, traversing the operand expression.voidVisits aVariableExpression.voidvisitWhileLoop(WhileStatement loop) Visits aWhileStatement, invoking statement hooks before parent traversal.protected static ClassNodewrapTypeIfNecessary(ClassNode type) Returns a wrapped type if, and only if, the provided class node is a primitive type.Methods inherited from class org.codehaus.groovy.ast.ClassCodeVisitorSupport
visitAnnotation, visitAnnotations, visitAnnotations, visitAssertStatement, visitBlockStatement, visitBreakStatement, visitCatchStatement, visitClassCodeContainer, visitContinueStatement, visitDeclarationExpression, visitDoWhileLoop, visitImports, visitPackage, visitStatement, visitStatementAnnotations, visitSynchronizedStatement, visitThrowStatementMethods inherited from class org.codehaus.groovy.ast.CodeVisitorSupport
visitArgumentlistExpression, visitBooleanExpression, visitBytecodeExpression, visitClosureListExpression, visitConstantExpression, visitEmptyStatement, visitFieldExpression, visitGStringExpression, visitLambdaExpression, visitListExpression, visitMapEntryExpression, visitMapExpression, visitMethodReferenceExpression, visitShortTernaryExpression, visitSpreadExpression, visitSpreadMapExpression, visitTupleExpressionMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface org.codehaus.groovy.ast.GroovyCodeVisitor
visit, visit, visitEmptyExpression, visitListOfExpressions
-
Field Details
-
ERROR_COLLECTOR
Metadata key used to store per-method error collectors. -
EMPTY_METHODNODE_LIST
Shared empty method list. -
TYPECHECKED_CLASSNODE
CachedTypeCheckedannotation type. -
TYPECHECKING_ANNOTATIONS
Type-checking annotations recognized by this visitor. -
TYPECHECKING_INFO_NODE
CachedTypeChecked.TypeCheckingInfoannotation type. -
DGM_CLASSNODE
CachedDefaultGroovyMethodstype. -
CURRENT_SIGNATURE_PROTOCOL_VERSION
protected static final int CURRENT_SIGNATURE_PROTOCOL_VERSIONCurrent encoding protocol for stored type-checking signatures.- See Also:
-
CURRENT_SIGNATURE_PROTOCOL
Constant expression for the current signature protocol version. -
GET_DELEGATE
CachedClosure#getDelegate()method. -
GET_OWNER
CachedClosure#getOwner()method. -
GET_THISOBJECT
CachedClosure#getThisObject()method. -
DELEGATES_TO
CachedDelegatesToannotation type. -
DELEGATES_TO_TARGET
CachedDelegatesTo.Targetannotation type. -
CLOSUREPARAMS_CLASSNODE
CachedClosureParamsannotation type. -
NAMED_PARAMS_CLASSNODE
CachedNamedParamsannotation type. -
NAMED_PARAM_CLASSNODE
CachedNamedParamannotation type. -
LINKEDHASHMAP_CLASSNODE
@Deprecated(forRemoval=true, since="4.0.0") protected static final ClassNode LINKEDHASHMAP_CLASSNODEDeprecated, for removal: This API element is subject to removal in a future version. -
ENUMERATION_TYPE
CachedEnumerationtype. -
CHAR_SEQUENCE_TYPE
CachedCharSequencetype (GROOVY-9848: membership operator dispatch). -
MAP_ENTRY_TYPE
CachedMap.Entrytype. -
ITERABLE_TYPE
CachedIterabletype. -
CLOSURE_CALL_NO_ARG
Cached zero-argumentClosure#call()method. -
CLOSURE_CALL_ONE_ARG
Cached single-argumentClosure#call(Object)method. -
CLOSURE_CALL_VARGS
Cached varargsClosure#call(Object[])method. -
GENERATED_EMPTY_STATEMENT
Empty statement reused for synthetic AST nodes. -
returnListener
-
returnAdder
Return adder used to normalize implicit and explicit returns. -
currentField
Field currently being visited. -
currentProperty
Property currently being visited. -
extension
Composite extension chain consulted during type checking. -
typeCheckingContext
Mutable state for the current type-checking run.
-
-
Constructor Details
-
StaticTypeCheckingVisitor
Creates a static type-checking visitor for the supplied source and class.
-
-
Method Details
-
setCompilationUnit
Associates the visitor with a compilation unit. -
getSourceUnit
Provides access to theSourceUnitfor error reporting during visitation. Implementations must override this method.- Specified by:
getSourceUnitin classClassCodeVisitorSupport- Returns:
- the source unit for this visitor
-
initialize
public void initialize()Initializes the registered type-checking extensions. -
getTypeCheckingAnnotations
Returns array of type checking annotations. Subclasses may override this method in order to provide additional types which must be looked up when checking if a method or a class node should be skipped.The default implementation returns
TypeChecked. -
getTypeCheckingContext
Returns the current type checking context. The context is used internally by the type checker during type checking to store various state data.- Returns:
- the type checking context
-
addTypeCheckingExtension
Adds a type-checking extension to the active extension chain. -
visitClass
Visits aClassNode, processing its annotations, package, imports, contents, and object initializers.- Specified by:
visitClassin interfaceGroovyClassVisitor- Overrides:
visitClassin classClassCodeVisitorSupport- Parameters:
node- the class node to visit
-
shouldSkipClassNode
Indicates whether the class should be skipped by this visitor. -
shouldSkipMethodNode
Indicates whether the method should be skipped by this visitor. -
isSkipMode
Indicates whether the annotated node is configured forTypeCheckingMode.SKIP. -
isSkippedInnerClass
Tests if a node is an inner class node, and if it is, then checks if the enclosing method is skipped.- Returns:
- true if the inner class node should be skipped
-
visitClassExpression
Visits aClassExpression. No traversal is performed as class expressions contain no child expressions.- Specified by:
visitClassExpressionin interfaceGroovyCodeVisitor- Overrides:
visitClassExpressionin classCodeVisitorSupport- Parameters:
expression- the class expression
-
visitVariableExpression
Visits aVariableExpression. No traversal is performed as variable expressions contain no child expressions.- Specified by:
visitVariableExpressionin interfaceGroovyCodeVisitor- Overrides:
visitVariableExpressionin classCodeVisitorSupport- Parameters:
vexp- the variable expression
-
visitPropertyExpression
Visits aPropertyExpression, traversing the object and property name expressions.- Specified by:
visitPropertyExpressionin interfaceGroovyCodeVisitor- Overrides:
visitPropertyExpressionin classCodeVisitorSupport- Parameters:
expression- the property expression
-
visitAttributeExpression
Visits anAttributeExpression, traversing the object and attribute name expressions.- Specified by:
visitAttributeExpressionin interfaceGroovyCodeVisitor- Overrides:
visitAttributeExpressionin classCodeVisitorSupport- Parameters:
expression- the attribute expression
-
visitRangeExpression
Visits aRangeExpression, traversing from and to boundary expressions.- Specified by:
visitRangeExpressionin interfaceGroovyCodeVisitor- Overrides:
visitRangeExpressionin classCodeVisitorSupport- Parameters:
expression- the range expression
-
visitNotExpression
Visits aNotExpression, traversing the operand expression.- Specified by:
visitNotExpressionin interfaceGroovyCodeVisitor- Overrides:
visitNotExpressionin classCodeVisitorSupport- Parameters:
expression- the not expression
-
visitBinaryExpression
Visits aBinaryExpression, traversing left and right operand expressions.- Specified by:
visitBinaryExpressionin interfaceGroovyCodeVisitor- Overrides:
visitBinaryExpressionin classCodeVisitorSupport- Parameters:
expression- the binary expression
-
getOriginalDeclarationType
Returns the declared type of the left-hand side before any flow-based refinement. -
inferDiamondType
Infers generic arguments for constructor calls that use the diamond operator. -
typeCheckAssignment
protected void typeCheckAssignment(BinaryExpression assignmentExpression, Expression leftExpression, ClassNode leftExpressionType, Expression rightExpression, ClassNode rightExpressionType) Checks assignment compatibility and reports any associated type errors. -
checkGroovyConstructorMap
protected void checkGroovyConstructorMap(Expression receiver, ClassNode receiverType, MapExpression mapExpression) Validates map-style constructor arguments against writable properties. -
hasRHSIncompleteGenericTypeInfo
@Deprecated(forRemoval=true, since="4.0.0") protected static boolean hasRHSIncompleteGenericTypeInfo(ClassNode inferredRightExpressionType) Deprecated, for removal: This API element is subject to removal in a future version.Indicates whether the inferred type still contains unresolved placeholder generics. -
checkGroovyStyleConstructor
protected MethodNode checkGroovyStyleConstructor(ClassNode node, ClassNode[] arguments, ASTNode origin) Checks that a constructor style expression is valid regarding the number of arguments and the argument types.- Parameters:
node- the class node for which we will try to find a matching constructorarguments- the constructor arguments
-
existsProperty
Checks whether the property exists for the current access mode. -
existsProperty
protected boolean existsProperty(PropertyExpression pexp, boolean readMode, ClassCodeVisitorSupport visitor) Checks whether a property exists on the receiver, or on any of the possible receiver classes (found in the temporary type information table)- Parameters:
pexp- a property expressionreadMode- if true, look for property read, else for property setvisitor- if not null, when the property node is found, visit it with the provided visitor- Returns:
- true if the property is defined in any of the possible receiver classes
-
visitProperty
Visits aPropertyNode, processing its annotations, initial value expression, and getter/setter blocks if present.- Specified by:
visitPropertyin interfaceGroovyClassVisitor- Overrides:
visitPropertyin classClassCodeVisitorSupport- Parameters:
node- the property node to visit
-
visitField
Visits aFieldNode, processing its annotations and initial value expression if present.- Specified by:
visitFieldin interfaceGroovyClassVisitor- Overrides:
visitFieldin classClassCodeVisitorSupport- Parameters:
node- the field node to visit
-
visitForLoop
Visits aForStatement, invoking statement hooks and processing loop variable annotations.- Specified by:
visitForLoopin interfaceGroovyCodeVisitor- Overrides:
visitForLoopin classClassCodeVisitorSupport- Parameters:
forLoop- the for statement to visit
-
inferLoopElementType
Returns the inferred loop element type given a loop collection type. Used, for example, to infer the element type of afor (e in list)loop.- Parameters:
collectionType- the type of the collection- Returns:
- the inferred component type
- See Also:
-
isSecondPassNeededForControlStructure
protected boolean isSecondPassNeededForControlStructure(Map<VariableExpression, ClassNode> startTypes, Map<VariableExpression, List<ClassNode>> oldTracker) Indicates whether a second pass is needed after visiting a control structure. -
visitWhileLoop
Visits aWhileStatement, invoking statement hooks before parent traversal.- Specified by:
visitWhileLoopin interfaceGroovyCodeVisitor- Overrides:
visitWhileLoopin classClassCodeVisitorSupport- Parameters:
loop- the while statement to visit
-
visitBitwiseNegationExpression
Visits aBitwiseNegationExpression, traversing the operand expression.- Specified by:
visitBitwiseNegationExpressionin interfaceGroovyCodeVisitor- Overrides:
visitBitwiseNegationExpressionin classCodeVisitorSupport- Parameters:
expression- the bitwise negation expression
-
visitUnaryPlusExpression
Visits aUnaryPlusExpression, traversing the operand expression.- Specified by:
visitUnaryPlusExpressionin interfaceGroovyCodeVisitor- Overrides:
visitUnaryPlusExpressionin classCodeVisitorSupport- Parameters:
expression- the unary plus expression
-
visitUnaryMinusExpression
Visits aUnaryMinusExpression, traversing the operand expression.- Specified by:
visitUnaryMinusExpressionin interfaceGroovyCodeVisitor- Overrides:
visitUnaryMinusExpressionin classCodeVisitorSupport- Parameters:
expression- the unary minus expression
-
visitPostfixExpression
Visits aPostfixExpression, traversing the operand expression.- Specified by:
visitPostfixExpressionin interfaceGroovyCodeVisitor- Overrides:
visitPostfixExpressionin classCodeVisitorSupport- Parameters:
expression- the postfix expression
-
visitPrefixExpression
Visits aPrefixExpression, traversing the operand expression.- Specified by:
visitPrefixExpressionin interfaceGroovyCodeVisitor- Overrides:
visitPrefixExpressionin classCodeVisitorSupport- Parameters:
expression- the prefix expression
-
visitExpressionStatement
Visits anExpressionStatement, invoking the statement hook before parent traversal.- Specified by:
visitExpressionStatementin interfaceGroovyCodeVisitor- Overrides:
visitExpressionStatementin classClassCodeVisitorSupport- Parameters:
statement- the expression statement to visit
-
visitReturnStatement
Visits aReturnStatement, invoking the statement hook before parent traversal.- Specified by:
visitReturnStatementin interfaceGroovyCodeVisitor- Overrides:
visitReturnStatementin classClassCodeVisitorSupport- Parameters:
statement- the return statement to visit
-
checkReturnType
Validates the current return statement against the enclosing closure or method. -
addClosureReturnType
Records a non-void return type for the current enclosing closure. -
visitConstructorCallExpression
Visits aConstructorCallExpression, traversing its argument list.- Specified by:
visitConstructorCallExpressionin interfaceGroovyCodeVisitor- Overrides:
visitConstructorCallExpressionin classCodeVisitorSupport- Parameters:
call- the constructor call expression
-
typeCheckMapConstructor
protected MethodNode typeCheckMapConstructor(ConstructorCallExpression call, ClassNode receiver, Expression arguments) Selects and validates a synthetic map-style constructor target. -
getArgumentTypes
Returns the inferred argument types for the supplied argument list. -
visitClosureExpression
Visits aClosureExpressionwith annotation processing, traversing parameter annotations before delegating to parent traversal.- Specified by:
visitClosureExpressionin interfaceGroovyCodeVisitor- Overrides:
visitClosureExpressionin classClassCodeVisitorSupport- Parameters:
expression- the closure expression to visit
-
visitMethodPointerExpression
Visits aMethodPointerExpression, traversing the object and method name expressions.- Specified by:
visitMethodPointerExpressionin interfaceGroovyCodeVisitor- Overrides:
visitMethodPointerExpressionin classCodeVisitorSupport- Parameters:
expression- the method pointer expression
-
getDelegationMetadata
protected org.codehaus.groovy.transform.stc.DelegationMetadata getDelegationMetadata(ClosureExpression expression) Returns delegation metadata attached to the supplied closure expression. -
restoreVariableExpressionMetadata
protected void restoreVariableExpressionMetadata(Map<VariableExpression, Map<StaticTypesMarker, Object>> typesBeforeVisit) Restores variable-expression metadata saved before a closure visit. -
saveVariableExpressionMetadata
protected void saveVariableExpressionMetadata(Set<VariableExpression> closureSharedExpressions, Map<VariableExpression, Map<StaticTypesMarker, Object>> typesBeforeVisit) Saves variable-expression metadata that must survive closure re-visits. -
visitConstructor
Visits aConstructorNode, processing its annotations, parameter annotations, and code block.- Specified by:
visitConstructorin interfaceGroovyClassVisitor- Overrides:
visitConstructorin classClassCodeVisitorSupport- Parameters:
node- the constructor node to visit
-
visitMethod
Visits aMethodNode, processing its annotations, parameter annotations, and code block.- Specified by:
visitMethodin interfaceGroovyClassVisitor- Overrides:
visitMethodin classClassCodeVisitorSupport- Parameters:
node- the method node to visit
-
startMethodInference
Starts type inference for the supplied method using the supplied error collector. -
visitConstructorOrMethod
Visits a constructor or method node (implementation detail for both visit methods). Processes the node's annotations, all parameter annotations, and code block.- Overrides:
visitConstructorOrMethodin classClassCodeVisitorSupport- Parameters:
node- the method or constructor nodeisConstructor- true if node is a constructor, false if it is a method
-
visitObjectInitializerStatements
Visits all object initializer statements in a class, typically static or instance initialization blocks.- Overrides:
visitObjectInitializerStatementsin classClassCodeVisitorSupport- Parameters:
node- the class node containing initializer statements
-
addTypeCheckingInfoAnnotation
AddsTypeChecked.TypeCheckingInfometadata for an inferred method return type. -
visitStaticMethodCallExpression
Visits aStaticMethodCallExpression, traversing its argument list.- Specified by:
visitStaticMethodCallExpressionin interfaceGroovyCodeVisitor- Overrides:
visitStaticMethodCallExpressionin classCodeVisitorSupport- Parameters:
call- the static method call expression
-
checkClosureParameters
@Deprecated(forRemoval=true, since="2.5.0") protected void checkClosureParameters(Expression callArguments, ClassNode receiver) Deprecated, for removal: This API element is subject to removal in a future version.this method is unused, replaced withDelegatesToinference. -
silentlyVisitMethodNode
Visits a method call target, to infer the type. Don't report errors right away, that will be done by a later visitMethod call. -
visitMethodCallArguments
protected void visitMethodCallArguments(ClassNode receiver, ArgumentListExpression arguments, boolean visitFunctors, MethodNode selectedMethod) Visits method-call arguments and defers functional arguments until a target is known. -
inferClosureParameterTypes
protected void inferClosureParameterTypes(ClassNode receiver, Expression arguments, ClosureExpression expression, Parameter target, MethodNode method) Performs type inference on closure argument types whenever code like this is found:foo.collect { it.toUpperCase() }.In this case the type checker tries to find if the
collectmethod has itsClosureargument annotated withClosureParams. If so, then additional type inference can be performed and the type ofitmay be inferred.- Parameters:
receiver-arguments-expression- closure or lambda expression for which the argument types should be inferredtarget- parameter which may provideClosureParamsannotation or SAM typemethod- method that declarestarget
-
addReceivers
protected void addReceivers(List<Receiver<String>> receivers, Collection<Receiver<String>> owners, boolean implicitThis) Adds candidate receivers derived from owner chains. -
visitMethodCallExpression
Visits aMethodCallExpression, traversing the object expression, method expression, and argument list.- Specified by:
visitMethodCallExpressionin interfaceGroovyCodeVisitor- Overrides:
visitMethodCallExpressionin classCodeVisitorSupport- Parameters:
call- the method call expression
-
getInferredReturnTypeFromWithClosureArgument
In the case of a Object.with { ... } call, this method is supposed to retrieve the inferred closure return type.- Parameters:
callArguments- the argument list from the Object#with(Closure) call, i.e. a single closure expression- Returns:
- the inferred closure return type or null
-
makeOwnerList
Given an object expression (a message receiver expression), generate list of possible types.- Parameters:
objectExpression- the message receiver- Returns:
- types and qualifiers of the receiver
-
checkForbiddenSpreadArgument
Rejects spread arguments where no target signature is available. -
storeTargetMethod
Stores the selected target method on the call expression. -
typeCheckClosureCall
protected void typeCheckClosureCall(Expression arguments, ClassNode[] argumentTypes, Parameter[] parameters) Validates closure calls against the signatures implied by the closure parameters. -
visitIfElse
Visits anIfStatement, invoking the statement hook before parent traversal.- Specified by:
visitIfElsein interfaceGroovyCodeVisitor- Overrides:
visitIfElsein classClassCodeVisitorSupport- Parameters:
ifElse- the if statement to visit
-
visitSwitch
Visits aSwitchStatement, invoking the statement hook before parent traversal.- Specified by:
visitSwitchin interfaceGroovyCodeVisitor- Overrides:
visitSwitchin classClassCodeVisitorSupport- Parameters:
statement- the switch statement to visit
-
afterSwitchConditionExpressionVisited
Hook method called after the switch condition expression is visited, but before case statements. Subclasses may override to perform processing between condition and cases.- Overrides:
afterSwitchConditionExpressionVisitedin classCodeVisitorSupport- Parameters:
statement- the switch statement being visited
-
afterSwitchCaseStatementsVisited
Hook method called after all case statements are visited, but before the default statement. Subclasses may override to perform processing between cases and default.- Overrides:
afterSwitchCaseStatementsVisitedin classCodeVisitorSupport- Parameters:
statement- the switch statement being visited
-
visitCaseStatement
Visits aCaseStatement, invoking the statement hook before parent traversal.- Specified by:
visitCaseStatementin interfaceGroovyCodeVisitor- Overrides:
visitCaseStatementin classClassCodeVisitorSupport- Parameters:
statement- the case statement to visit
-
pushAssignmentTracking
Pushes a fresh assignment tracker and returns the previous tracker. -
popAssignmentTracking
protected Map<VariableExpression,ClassNode> popAssignmentTracking(Map<VariableExpression, List<ClassNode>> oldTracker) Pops the current assignment tracker and applies any merged types. -
visitArrayExpression
Visits anArrayExpression, traversing element expressions and size expressions.- Specified by:
visitArrayExpressionin interfaceGroovyCodeVisitor- Overrides:
visitArrayExpressionin classCodeVisitorSupport- Parameters:
expression- the array expression
-
visitCastExpression
Visits aCastExpression, traversing the operand expression.- Specified by:
visitCastExpressionin interfaceGroovyCodeVisitor- Overrides:
visitCastExpressionin classCodeVisitorSupport- Parameters:
expression- the cast expression
-
checkCast
Checks whether the source expression can be cast to the supplied target type. -
visitTernaryExpression
Visits aTernaryExpression, traversing the condition, true-branch, and false-branch expressions.- Specified by:
visitTernaryExpressionin interfaceGroovyCodeVisitor- Overrides:
visitTernaryExpressionin classCodeVisitorSupport- Parameters:
expression- the ternary expression
-
visitTryCatchFinally
Visits aTryCatchStatement, invoking the statement hook before parent traversal.- Specified by:
visitTryCatchFinallyin interfaceGroovyCodeVisitor- Overrides:
visitTryCatchFinallyin classClassCodeVisitorSupport- Parameters:
statement- the try-catch statement to visit
-
storeType
Stores the inferred type for the supplied expression. -
getResultType
Computes the result type of a binary operation. -
getGroupOperationResultType
Returns the result type for grouped numeric operations such as addition. -
inferRangeSliceType
GEP-20: probe the static return type ofrhs.getAt(IntRange)onreceiverType, so the rest binder can be typed against the actual slice type rather than a hard-codedList<T>. Returns the resolved slice type (e.g.Stringfor a String receiver,BitSetfor a BitSet receiver, the user-declared return type for custom classes), ornullif the receiver has no resolvablegetAt(IntRange).Mirrors
inferComponentType(org.codehaus.groovy.ast.ClassNode, org.codehaus.groovy.ast.ClassNode)but for the IntRange overload. Method resolution runs under a swallowed error collector so a missing overload doesn't surface as a static-type error. -
inferComponentType
Infers the component type addressed by subscript or iterator access. -
findMethodOrFail
protected MethodNode findMethodOrFail(Expression expr, ClassNode receiver, String name, ClassNode... args) Finds a matching method or reports a static type error when none is available. -
prettyPrintMethodList
Formats a method list for diagnostics. -
areCategoryMethodCalls
protected boolean areCategoryMethodCalls(List<MethodNode> foundMethods, String name, ClassNode[] args) Indicates whether all candidates are category-style extension methods. -
findMethodsWithGenerated
Returns methods defined for the specified receiver and adds "non-existing" methods that will be generated afterwards by the compiler; for example if a method is using default values and the class node is not compiled yet.- Parameters:
receiver- the type to search for methodsname- the name of the methods to return- Returns:
- the methods that are defined on the receiver completed with stubs for future methods
-
findMethod
Finds candidate methods matching the supplied receiver, name, and argument types. -
extractPropertyNameFromMethodName
Given a method name and a prefix, returns the name of the property that should be looked up, following the java beans rules. For example, "getName" would return "name", while "getFullName" would return "fullName". If the prefix is not found, returns null.- Parameters:
prefix- the method name prefix ("get", "is", "set", ...)methodName- the method name- Returns:
- a property name if the prefix is found and the method matches the java beans rules, null otherwise
-
getType
Returns the inferred type for the supplied AST node. -
storeInferredReturnType
Stores the inferred return type of a closure or method. We are using a separate key to store inferred return type because the inferred type of a closure isClosure, which is different from the inferred type of the code of the closure.- Parameters:
node- aClosureExpressionorMethodNodetype- the inferred return type of the code- Returns:
- The old value of the inferred type.
-
getInferredReturnType
Returns the inferred return type of a closure or method, if stored on the AST node. This method doesn't perform any type inference by itself.- Parameters:
node- aClosureExpressionorMethodNode- Returns:
- The expected return type.
-
isNullConstant
Indicates whether the expression is thenullconstant. -
isThisExpression
Indicates whether the expression representsthis. -
isSuperExpression
Indicates whether the expression representssuper. -
inferListExpressionType
Infers the static type of a list literal. -
inferMapExpressionType
Infers the static type of a map literal. -
inferReturnTypeGenerics
protected ClassNode inferReturnTypeGenerics(ClassNode receiver, MethodNode method, Expression arguments) If a method call returns a parameterized type, then perform additional inference on the return type, so that the type gets actual type arguments. For example, the methodArrays.asList(T...)is parameterized withT, which can be deduced type arguments or call arguments.- Parameters:
method- the method nodearguments- the method call argumentsreceiver- the object expression type
-
inferReturnTypeGenerics
protected ClassNode inferReturnTypeGenerics(ClassNode receiver, MethodNode method, Expression arguments, GenericsType[] explicitTypeHints) If a method call returns a parameterized type, then perform additional inference on the return type, so that the type gets actual type arguments. For example, the methodArrays.asList(T...)is parameterized withT, which can be deduced type arguments or call arguments.- Parameters:
method- the method nodearguments- the method call argumentsreceiver- the object expression typeexplicitTypeHints- type arguments (optional), for exampleCollections.<String>emptyList()
-
typeCheckMethodsWithGenericsOrFail
protected boolean typeCheckMethodsWithGenericsOrFail(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod, Expression location) Validates a chosen method against its generic constraints and reports failures. -
formatArgumentList
Formats an argument-type list for diagnostics. -
addError
Adds an error message associated with an AST node to the source unit. Errors are accumulated and reported after visitation completes.- Specified by:
addErrorin interfaceErrorCollecting- Overrides:
addErrorin classClassCodeVisitorSupport- Parameters:
msg- the error message to reportnode- the AST node associated with the error location- See Also:
-
addStaticTypeError
Reports a static type checking error for the supplied node. -
addNoMatchingMethodError
protected void addNoMatchingMethodError(ClassNode receiver, String name, ClassNode[] args, Expression exp) Reports that no matching method or constructor could be found for the call. -
addNoMatchingMethodError
protected void addNoMatchingMethodError(ClassNode receiver, String name, ClassNode[] args, ASTNode origin) Reports that no matching method or constructor could be found for the call. -
addAmbiguousErrorMessage
protected void addAmbiguousErrorMessage(List<MethodNode> foundMethods, String name, ClassNode[] args, Expression expr) Reports that method resolution remained ambiguous after filtering. -
addCategoryMethodCallError
Reports that categories cannot be used under static type checking. -
addAssignmentError
Reports an incompatible assignment between the supplied types. -
addUnsupportedPreOrPostfixExpressionError
Reports an unsupported prefix or postfix operation. -
setMethodsToBeVisited
Restricts type checking to the supplied method set. -
performSecondPass
public void performSecondPass()Replays deferred checks that require information collected during the first pass. -
extractTypesFromParameters
Extracts the declared types of the supplied parameters. -
wrapTypeIfNecessary
Returns a wrapped type if, and only if, the provided class node is a primitive type. This method differs fromClassHelper.getWrapper(org.codehaus.groovy.ast.ClassNode)as it will return the same instance if the provided type is not a generic type.- Returns:
- the wrapped type
-
isClassInnerClassOrEqualTo
Indicates whetherstartistoBeCheckedor nested within it. -
pushInstanceOfTypeInfo
Stores information about types when [objectExpression instanceof typeExpression] is visited.- Parameters:
objectExpression- the expression to be checked against instanceoftypeExpression- the expression which represents the target type
-
extractTemporaryTypeInfoKey
Computes the key to use forTypeCheckingContext.temporaryIfBranchTypeInformation. -
findCurrentInstanceOfClass
A helper method which determines which receiver class should be used in error messages when a field or attribute is not found. The returned type class depends on whether we have temporary type information available (due to instanceof checks) and whether there is a single candidate in that case.- Parameters:
expression- the expression for which an unknown field has been foundtype- the type of the expression (used as fallback type)- Returns:
- if temporary information is available and there's only one type, returns the temporary type class otherwise falls back to the provided type class.
-
getTemporaryTypesForExpression
Returns temporary narrowed types recorded for the supplied expression.
-
DelegatesToinference.