Class StaticTypeCheckingVisitor

All Implemented Interfaces:
GroovyClassVisitor, GroovyCodeVisitor, ErrorCollecting
Direct Known Subclasses:
StaticCompilationVisitor

public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport
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.
  • Field Details

    • ERROR_COLLECTOR

      protected static final Object ERROR_COLLECTOR
      Metadata key used to store per-method error collectors.
    • EMPTY_METHODNODE_LIST

      protected static final List<MethodNode> EMPTY_METHODNODE_LIST
      Shared empty method list.
    • TYPECHECKED_CLASSNODE

      protected static final ClassNode TYPECHECKED_CLASSNODE
      Cached TypeChecked annotation type.
    • TYPECHECKING_ANNOTATIONS

      protected static final ClassNode[] TYPECHECKING_ANNOTATIONS
      Type-checking annotations recognized by this visitor.
    • TYPECHECKING_INFO_NODE

      protected static final ClassNode TYPECHECKING_INFO_NODE
      Cached TypeChecked.TypeCheckingInfo annotation type.
    • DGM_CLASSNODE

      protected static final ClassNode DGM_CLASSNODE
    • CURRENT_SIGNATURE_PROTOCOL_VERSION

      protected static final int CURRENT_SIGNATURE_PROTOCOL_VERSION
      Current encoding protocol for stored type-checking signatures.
      See Also:
    • CURRENT_SIGNATURE_PROTOCOL

      protected static final Expression CURRENT_SIGNATURE_PROTOCOL
      Constant expression for the current signature protocol version.
    • GET_DELEGATE

      protected static final MethodNode GET_DELEGATE
      Cached Closure#getDelegate() method.
    • GET_OWNER

      protected static final MethodNode GET_OWNER
      Cached Closure#getOwner() method.
    • GET_THISOBJECT

      protected static final MethodNode GET_THISOBJECT
      Cached Closure#getThisObject() method.
    • DELEGATES_TO

      protected static final ClassNode DELEGATES_TO
      Cached DelegatesTo annotation type.
    • DELEGATES_TO_TARGET

      protected static final ClassNode DELEGATES_TO_TARGET
      Cached DelegatesTo.Target annotation type.
    • CLOSUREPARAMS_CLASSNODE

      protected static final ClassNode CLOSUREPARAMS_CLASSNODE
      Cached ClosureParams annotation type.
    • NAMED_PARAMS_CLASSNODE

      protected static final ClassNode NAMED_PARAMS_CLASSNODE
      Cached NamedParams annotation type.
    • NAMED_PARAM_CLASSNODE

      protected static final ClassNode NAMED_PARAM_CLASSNODE
      Cached NamedParam annotation type.
    • LINKEDHASHMAP_CLASSNODE

      @Deprecated(forRemoval=true, since="4.0.0") protected static final ClassNode LINKEDHASHMAP_CLASSNODE
      Deprecated, for removal: This API element is subject to removal in a future version.
    • ENUMERATION_TYPE

      protected static final ClassNode ENUMERATION_TYPE
      Cached Enumeration type.
    • CHAR_SEQUENCE_TYPE

      protected static final ClassNode CHAR_SEQUENCE_TYPE
      Cached CharSequence type (GROOVY-9848: membership operator dispatch).
    • MAP_ENTRY_TYPE

      protected static final ClassNode MAP_ENTRY_TYPE
      Cached Map.Entry type.
    • ITERABLE_TYPE

      protected static final ClassNode ITERABLE_TYPE
      Cached Iterable type.
    • CLOSURE_CALL_NO_ARG

      public static final MethodNode CLOSURE_CALL_NO_ARG
      Cached zero-argument Closure#call() method.
    • CLOSURE_CALL_ONE_ARG

      public static final MethodNode CLOSURE_CALL_ONE_ARG
      Cached single-argument Closure#call(Object) method.
    • CLOSURE_CALL_VARGS

      public static final MethodNode CLOSURE_CALL_VARGS
      Cached varargs Closure#call(Object[]) method.
    • GENERATED_EMPTY_STATEMENT

      public static final Statement GENERATED_EMPTY_STATEMENT
      Empty statement reused for synthetic AST nodes.
    • returnListener

      protected final ReturnAdder.ReturnStatementListener returnListener
    • returnAdder

      protected final ReturnAdder returnAdder
      Return adder used to normalize implicit and explicit returns.
    • currentField

      protected FieldNode currentField
      Field currently being visited.
    • currentProperty

      protected PropertyNode currentProperty
      Property currently being visited.
    • extension

      protected DefaultTypeCheckingExtension extension
      Composite extension chain consulted during type checking.
    • typeCheckingContext

      protected TypeCheckingContext typeCheckingContext
      Mutable state for the current type-checking run.
  • Constructor Details

    • StaticTypeCheckingVisitor

      public StaticTypeCheckingVisitor(SourceUnit source, ClassNode classNode)
      Creates a static type-checking visitor for the supplied source and class.
  • Method Details

    • setCompilationUnit

      public void setCompilationUnit(CompilationUnit compilationUnit)
      Associates the visitor with a compilation unit.
    • getSourceUnit

      protected SourceUnit getSourceUnit()
      Provides access to the SourceUnit for error reporting during visitation. Implementations must override this method.
      Specified by:
      getSourceUnit in class ClassCodeVisitorSupport
      Returns:
      the source unit for this visitor
    • initialize

      public void initialize()
      Initializes the registered type-checking extensions.
    • getTypeCheckingAnnotations

      protected ClassNode[] 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

      public TypeCheckingContext 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

      public void addTypeCheckingExtension(TypeCheckingExtension extension)
      Adds a type-checking extension to the active extension chain.
    • visitClass

      public void visitClass(ClassNode node)
      Visits a ClassNode, processing its annotations, package, imports, contents, and object initializers.
      Specified by:
      visitClass in interface GroovyClassVisitor
      Overrides:
      visitClass in class ClassCodeVisitorSupport
      Parameters:
      node - the class node to visit
    • shouldSkipClassNode

      protected boolean shouldSkipClassNode(ClassNode node)
      Indicates whether the class should be skipped by this visitor.
    • shouldSkipMethodNode

      protected boolean shouldSkipMethodNode(MethodNode node)
      Indicates whether the method should be skipped by this visitor.
    • isSkipMode

      public boolean isSkipMode(AnnotatedNode node)
      Indicates whether the annotated node is configured for TypeCheckingMode.SKIP.
    • isSkippedInnerClass

      protected boolean isSkippedInnerClass(AnnotatedNode node)
      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

      public void visitClassExpression(ClassExpression expression)
      Visits a ClassExpression. No traversal is performed as class expressions contain no child expressions.
      Specified by:
      visitClassExpression in interface GroovyCodeVisitor
      Overrides:
      visitClassExpression in class CodeVisitorSupport
      Parameters:
      expression - the class expression
    • visitVariableExpression

      public void visitVariableExpression(VariableExpression vexp)
      Visits a VariableExpression. No traversal is performed as variable expressions contain no child expressions.
      Specified by:
      visitVariableExpression in interface GroovyCodeVisitor
      Overrides:
      visitVariableExpression in class CodeVisitorSupport
      Parameters:
      vexp - the variable expression
    • visitPropertyExpression

      public void visitPropertyExpression(PropertyExpression expression)
      Visits a PropertyExpression, traversing the object and property name expressions.
      Specified by:
      visitPropertyExpression in interface GroovyCodeVisitor
      Overrides:
      visitPropertyExpression in class CodeVisitorSupport
      Parameters:
      expression - the property expression
    • visitAttributeExpression

      public void visitAttributeExpression(AttributeExpression expression)
      Visits an AttributeExpression, traversing the object and attribute name expressions.
      Specified by:
      visitAttributeExpression in interface GroovyCodeVisitor
      Overrides:
      visitAttributeExpression in class CodeVisitorSupport
      Parameters:
      expression - the attribute expression
    • visitRangeExpression

      public void visitRangeExpression(RangeExpression expression)
      Visits a RangeExpression, traversing from and to boundary expressions.
      Specified by:
      visitRangeExpression in interface GroovyCodeVisitor
      Overrides:
      visitRangeExpression in class CodeVisitorSupport
      Parameters:
      expression - the range expression
    • visitNotExpression

      public void visitNotExpression(NotExpression expression)
      Visits a NotExpression, traversing the operand expression.
      Specified by:
      visitNotExpression in interface GroovyCodeVisitor
      Overrides:
      visitNotExpression in class CodeVisitorSupport
      Parameters:
      expression - the not expression
    • visitBinaryExpression

      public void visitBinaryExpression(BinaryExpression expression)
      Visits a BinaryExpression, traversing left and right operand expressions.
      Specified by:
      visitBinaryExpression in interface GroovyCodeVisitor
      Overrides:
      visitBinaryExpression in class CodeVisitorSupport
      Parameters:
      expression - the binary expression
    • getOriginalDeclarationType

      protected ClassNode getOriginalDeclarationType(Expression lhs)
      Returns the declared type of the left-hand side before any flow-based refinement.
    • inferDiamondType

      protected void inferDiamondType(ConstructorCallExpression cce, ClassNode lType)
      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 constructor
      arguments - the constructor arguments
    • existsProperty

      protected boolean existsProperty(PropertyExpression pexp, boolean checkForReadOnly)
      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 expression
      readMode - if true, look for property read, else for property set
      visitor - 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

      public void visitProperty(PropertyNode node)
      Visits a PropertyNode, processing its annotations, initial value expression, and getter/setter blocks if present.
      Specified by:
      visitProperty in interface GroovyClassVisitor
      Overrides:
      visitProperty in class ClassCodeVisitorSupport
      Parameters:
      node - the property node to visit
    • visitField

      public void visitField(FieldNode node)
      Visits a FieldNode, processing its annotations and initial value expression if present.
      Specified by:
      visitField in interface GroovyClassVisitor
      Overrides:
      visitField in class ClassCodeVisitorSupport
      Parameters:
      node - the field node to visit
    • visitForLoop

      public void visitForLoop(ForStatement forLoop)
      Visits a ForStatement, invoking statement hooks and processing loop variable annotations.
      Specified by:
      visitForLoop in interface GroovyCodeVisitor
      Overrides:
      visitForLoop in class ClassCodeVisitorSupport
      Parameters:
      forLoop - the for statement to visit
    • inferLoopElementType

      public static ClassNode inferLoopElementType(ClassNode collectionType)
      Returns the inferred loop element type given a loop collection type. Used, for example, to infer the element type of a for (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

      public void visitWhileLoop(WhileStatement loop)
      Visits a WhileStatement, invoking statement hooks before parent traversal.
      Specified by:
      visitWhileLoop in interface GroovyCodeVisitor
      Overrides:
      visitWhileLoop in class ClassCodeVisitorSupport
      Parameters:
      loop - the while statement to visit
    • visitBitwiseNegationExpression

      public void visitBitwiseNegationExpression(BitwiseNegationExpression expression)
      Visits a BitwiseNegationExpression, traversing the operand expression.
      Specified by:
      visitBitwiseNegationExpression in interface GroovyCodeVisitor
      Overrides:
      visitBitwiseNegationExpression in class CodeVisitorSupport
      Parameters:
      expression - the bitwise negation expression
    • visitUnaryPlusExpression

      public void visitUnaryPlusExpression(UnaryPlusExpression expression)
      Visits a UnaryPlusExpression, traversing the operand expression.
      Specified by:
      visitUnaryPlusExpression in interface GroovyCodeVisitor
      Overrides:
      visitUnaryPlusExpression in class CodeVisitorSupport
      Parameters:
      expression - the unary plus expression
    • visitUnaryMinusExpression

      public void visitUnaryMinusExpression(UnaryMinusExpression expression)
      Visits a UnaryMinusExpression, traversing the operand expression.
      Specified by:
      visitUnaryMinusExpression in interface GroovyCodeVisitor
      Overrides:
      visitUnaryMinusExpression in class CodeVisitorSupport
      Parameters:
      expression - the unary minus expression
    • visitPostfixExpression

      public void visitPostfixExpression(PostfixExpression expression)
      Visits a PostfixExpression, traversing the operand expression.
      Specified by:
      visitPostfixExpression in interface GroovyCodeVisitor
      Overrides:
      visitPostfixExpression in class CodeVisitorSupport
      Parameters:
      expression - the postfix expression
    • visitPrefixExpression

      public void visitPrefixExpression(PrefixExpression expression)
      Visits a PrefixExpression, traversing the operand expression.
      Specified by:
      visitPrefixExpression in interface GroovyCodeVisitor
      Overrides:
      visitPrefixExpression in class CodeVisitorSupport
      Parameters:
      expression - the prefix expression
    • visitExpressionStatement

      public void visitExpressionStatement(ExpressionStatement statement)
      Visits an ExpressionStatement, invoking the statement hook before parent traversal.
      Specified by:
      visitExpressionStatement in interface GroovyCodeVisitor
      Overrides:
      visitExpressionStatement in class ClassCodeVisitorSupport
      Parameters:
      statement - the expression statement to visit
    • visitReturnStatement

      public void visitReturnStatement(ReturnStatement statement)
      Visits a ReturnStatement, invoking the statement hook before parent traversal.
      Specified by:
      visitReturnStatement in interface GroovyCodeVisitor
      Overrides:
      visitReturnStatement in class ClassCodeVisitorSupport
      Parameters:
      statement - the return statement to visit
    • checkReturnType

      protected ClassNode checkReturnType(ReturnStatement statement)
      Validates the current return statement against the enclosing closure or method.
    • addClosureReturnType

      protected void addClosureReturnType(ClassNode returnType)
      Records a non-void return type for the current enclosing closure.
    • visitConstructorCallExpression

      public void visitConstructorCallExpression(ConstructorCallExpression call)
      Visits a ConstructorCallExpression, traversing its argument list.
      Specified by:
      visitConstructorCallExpression in interface GroovyCodeVisitor
      Overrides:
      visitConstructorCallExpression in class CodeVisitorSupport
      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

      protected ClassNode[] getArgumentTypes(ArgumentListExpression argumentList)
      Returns the inferred argument types for the supplied argument list.
    • visitClosureExpression

      public void visitClosureExpression(ClosureExpression expression)
      Visits a ClosureExpression with annotation processing, traversing parameter annotations before delegating to parent traversal.
      Specified by:
      visitClosureExpression in interface GroovyCodeVisitor
      Overrides:
      visitClosureExpression in class ClassCodeVisitorSupport
      Parameters:
      expression - the closure expression to visit
    • visitMethodPointerExpression

      public void visitMethodPointerExpression(MethodPointerExpression expression)
      Visits a MethodPointerExpression, traversing the object and method name expressions.
      Specified by:
      visitMethodPointerExpression in interface GroovyCodeVisitor
      Overrides:
      visitMethodPointerExpression in class CodeVisitorSupport
      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

      public void visitConstructor(ConstructorNode node)
      Visits a ConstructorNode, processing its annotations, parameter annotations, and code block.
      Specified by:
      visitConstructor in interface GroovyClassVisitor
      Overrides:
      visitConstructor in class ClassCodeVisitorSupport
      Parameters:
      node - the constructor node to visit
    • visitMethod

      public void visitMethod(MethodNode node)
      Visits a MethodNode, processing its annotations, parameter annotations, and code block.
      Specified by:
      visitMethod in interface GroovyClassVisitor
      Overrides:
      visitMethod in class ClassCodeVisitorSupport
      Parameters:
      node - the method node to visit
    • startMethodInference

      protected void startMethodInference(MethodNode node, ErrorCollector collector)
      Starts type inference for the supplied method using the supplied error collector.
    • visitConstructorOrMethod

      protected void visitConstructorOrMethod(MethodNode node, boolean isConstructor)
      Visits a constructor or method node (implementation detail for both visit methods). Processes the node's annotations, all parameter annotations, and code block.
      Overrides:
      visitConstructorOrMethod in class ClassCodeVisitorSupport
      Parameters:
      node - the method or constructor node
      isConstructor - true if node is a constructor, false if it is a method
    • visitObjectInitializerStatements

      protected void visitObjectInitializerStatements(ClassNode node)
      Visits all object initializer statements in a class, typically static or instance initialization blocks.
      Overrides:
      visitObjectInitializerStatements in class ClassCodeVisitorSupport
      Parameters:
      node - the class node containing initializer statements
    • addTypeCheckingInfoAnnotation

      protected void addTypeCheckingInfoAnnotation(MethodNode node)
      Adds TypeChecked.TypeCheckingInfo metadata for an inferred method return type.
    • visitStaticMethodCallExpression

      public void visitStaticMethodCallExpression(StaticMethodCallExpression call)
      Visits a StaticMethodCallExpression, traversing its argument list.
      Specified by:
      visitStaticMethodCallExpression in interface GroovyCodeVisitor
      Overrides:
      visitStaticMethodCallExpression in class CodeVisitorSupport
      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 with DelegatesTo inference.
    • silentlyVisitMethodNode

      protected void silentlyVisitMethodNode(MethodNode directMethodCallCandidate)
      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 collect method has its Closure argument annotated with ClosureParams. If so, then additional type inference can be performed and the type of it may be inferred.

      Parameters:
      receiver -
      arguments -
      expression - closure or lambda expression for which the argument types should be inferred
      target - parameter which may provide ClosureParams annotation or SAM type
      method - method that declares target
    • addReceivers

      protected void addReceivers(List<Receiver<String>> receivers, Collection<Receiver<String>> owners, boolean implicitThis)
      Adds candidate receivers derived from owner chains.
    • visitMethodCallExpression

      public void visitMethodCallExpression(MethodCallExpression call)
      Visits a MethodCallExpression, traversing the object expression, method expression, and argument list.
      Specified by:
      visitMethodCallExpression in interface GroovyCodeVisitor
      Overrides:
      visitMethodCallExpression in class CodeVisitorSupport
      Parameters:
      call - the method call expression
    • getInferredReturnTypeFromWithClosureArgument

      protected ClassNode getInferredReturnTypeFromWithClosureArgument(Expression callArguments)
      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

      protected List<Receiver<String>> makeOwnerList(Expression objectExpression)
      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

      protected void checkForbiddenSpreadArgument(ArgumentListExpression arguments)
      Rejects spread arguments where no target signature is available.
    • storeTargetMethod

      protected void storeTargetMethod(Expression call, MethodNode target)
      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

      public void visitIfElse(IfStatement ifElse)
      Visits an IfStatement, invoking the statement hook before parent traversal.
      Specified by:
      visitIfElse in interface GroovyCodeVisitor
      Overrides:
      visitIfElse in class ClassCodeVisitorSupport
      Parameters:
      ifElse - the if statement to visit
    • visitSwitch

      public void visitSwitch(SwitchStatement statement)
      Visits a SwitchStatement, invoking the statement hook before parent traversal.
      Specified by:
      visitSwitch in interface GroovyCodeVisitor
      Overrides:
      visitSwitch in class ClassCodeVisitorSupport
      Parameters:
      statement - the switch statement to visit
    • afterSwitchConditionExpressionVisited

      protected void afterSwitchConditionExpressionVisited(SwitchStatement statement)
      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:
      afterSwitchConditionExpressionVisited in class CodeVisitorSupport
      Parameters:
      statement - the switch statement being visited
    • afterSwitchCaseStatementsVisited

      protected void afterSwitchCaseStatementsVisited(SwitchStatement statement)
      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:
      afterSwitchCaseStatementsVisited in class CodeVisitorSupport
      Parameters:
      statement - the switch statement being visited
    • visitCaseStatement

      public void visitCaseStatement(CaseStatement statement)
      Visits a CaseStatement, invoking the statement hook before parent traversal.
      Specified by:
      visitCaseStatement in interface GroovyCodeVisitor
      Overrides:
      visitCaseStatement in class ClassCodeVisitorSupport
      Parameters:
      statement - the case statement to visit
    • pushAssignmentTracking

      protected Map<VariableExpression,List<ClassNode>> 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

      public void visitArrayExpression(ArrayExpression expression)
      Visits an ArrayExpression, traversing element expressions and size expressions.
      Specified by:
      visitArrayExpression in interface GroovyCodeVisitor
      Overrides:
      visitArrayExpression in class CodeVisitorSupport
      Parameters:
      expression - the array expression
    • visitCastExpression

      public void visitCastExpression(CastExpression expression)
      Visits a CastExpression, traversing the operand expression.
      Specified by:
      visitCastExpression in interface GroovyCodeVisitor
      Overrides:
      visitCastExpression in class CodeVisitorSupport
      Parameters:
      expression - the cast expression
    • checkCast

      protected boolean checkCast(ClassNode targetType, Expression source)
      Checks whether the source expression can be cast to the supplied target type.
    • visitTernaryExpression

      public void visitTernaryExpression(TernaryExpression expression)
      Visits a TernaryExpression, traversing the condition, true-branch, and false-branch expressions.
      Specified by:
      visitTernaryExpression in interface GroovyCodeVisitor
      Overrides:
      visitTernaryExpression in class CodeVisitorSupport
      Parameters:
      expression - the ternary expression
    • visitTryCatchFinally

      public void visitTryCatchFinally(TryCatchStatement statement)
      Visits a TryCatchStatement, invoking the statement hook before parent traversal.
      Specified by:
      visitTryCatchFinally in interface GroovyCodeVisitor
      Overrides:
      visitTryCatchFinally in class ClassCodeVisitorSupport
      Parameters:
      statement - the try-catch statement to visit
    • storeType

      protected void storeType(Expression exp, ClassNode cn)
      Stores the inferred type for the supplied expression.
    • getResultType

      protected ClassNode getResultType(ClassNode left, int op, ClassNode right, BinaryExpression expr)
      Computes the result type of a binary operation.
    • getGroupOperationResultType

      protected static ClassNode getGroupOperationResultType(ClassNode a, ClassNode b)
      Returns the result type for grouped numeric operations such as addition.
    • inferRangeSliceType

      protected ClassNode inferRangeSliceType(ClassNode receiverType)
      GEP-20: probe the static return type of rhs.getAt(IntRange) on receiverType, so the rest binder can be typed against the actual slice type rather than a hard-coded List<T>. Returns the resolved slice type (e.g. String for a String receiver, BitSet for a BitSet receiver, the user-declared return type for custom classes), or null if the receiver has no resolvable getAt(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

      protected ClassNode inferComponentType(ClassNode receiverType, ClassNode subscriptType)
      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

      protected static String prettyPrintMethodList(List<MethodNode> nodes)
      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

      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.
      Parameters:
      receiver - the type to search for methods
      name - the name of the methods to return
      Returns:
      the methods that are defined on the receiver completed with stubs for future methods
    • findMethod

      protected List<MethodNode> findMethod(ClassNode receiver, String name, ClassNode... args)
      Finds candidate methods matching the supplied receiver, name, and argument types.
    • extractPropertyNameFromMethodName

      public static String extractPropertyNameFromMethodName(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. 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

      protected ClassNode getType(ASTNode node)
      Returns the inferred type for the supplied AST node.
    • storeInferredReturnType

      protected ClassNode storeInferredReturnType(ASTNode node, ClassNode type)
      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 is Closure, which is different from the inferred type of the code of the closure.
      Parameters:
      node - a ClosureExpression or MethodNode
      type - the inferred return type of the code
      Returns:
      The old value of the inferred type.
    • getInferredReturnType

      protected ClassNode getInferredReturnType(ASTNode node)
      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 - a ClosureExpression or MethodNode
      Returns:
      The expected return type.
    • isNullConstant

      protected static boolean isNullConstant(Expression expression)
      Indicates whether the expression is the null constant.
    • isThisExpression

      protected static boolean isThisExpression(Expression expression)
      Indicates whether the expression represents this.
    • isSuperExpression

      protected static boolean isSuperExpression(Expression expression)
      Indicates whether the expression represents super.
    • inferListExpressionType

      protected ClassNode inferListExpressionType(ListExpression list)
      Infers the static type of a list literal.
    • inferMapExpressionType

      protected ClassNode inferMapExpressionType(MapExpression map)
      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 method Arrays.asList(T...) is parameterized with T, which can be deduced type arguments or call arguments.
      Parameters:
      method - the method node
      arguments - the method call arguments
      receiver - 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 method Arrays.asList(T...) is parameterized with T, which can be deduced type arguments or call arguments.
      Parameters:
      method - the method node
      arguments - the method call arguments
      receiver - the object expression type
      explicitTypeHints - type arguments (optional), for example Collections.<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

      protected static String formatArgumentList(ClassNode[] nodes)
      Formats an argument-type list for diagnostics.
    • addError

      public void addError(String msg, ASTNode node)
      Adds an error message associated with an AST node to the source unit. Errors are accumulated and reported after visitation completes.
      Specified by:
      addError in interface ErrorCollecting
      Overrides:
      addError in class ClassCodeVisitorSupport
      Parameters:
      msg - the error message to report
      node - the AST node associated with the error location
      See Also:
    • addStaticTypeError

      protected void addStaticTypeError(String msg, ASTNode node)
      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

      protected void addCategoryMethodCallError(Expression call)
      Reports that categories cannot be used under static type checking.
    • addAssignmentError

      protected void addAssignmentError(ClassNode leftType, ClassNode rightType, Expression expression)
      Reports an incompatible assignment between the supplied types.
    • addUnsupportedPreOrPostfixExpressionError

      protected void addUnsupportedPreOrPostfixExpressionError(Expression expression)
      Reports an unsupported prefix or postfix operation.
    • setMethodsToBeVisited

      public void setMethodsToBeVisited(Set<MethodNode> methodsToBeVisited)
      Restricts type checking to the supplied method set.
    • performSecondPass

      public void performSecondPass()
      Replays deferred checks that require information collected during the first pass.
    • extractTypesFromParameters

      protected static ClassNode[] extractTypesFromParameters(Parameter[] parameters)
      Extracts the declared types of the supplied parameters.
    • wrapTypeIfNecessary

      protected static ClassNode wrapTypeIfNecessary(ClassNode type)
      Returns a wrapped type if, and only if, the provided class node is a primitive type. This method differs from ClassHelper.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

      protected static boolean isClassInnerClassOrEqualTo(ClassNode toBeChecked, ClassNode start)
      Indicates whether start is toBeChecked or nested within it.
    • pushInstanceOfTypeInfo

      protected void pushInstanceOfTypeInfo(Expression objectExpression, Expression typeExpression)
      Stores information about types when [objectExpression instanceof typeExpression] is visited.
      Parameters:
      objectExpression - the expression to be checked against instanceof
      typeExpression - the expression which represents the target type
    • extractTemporaryTypeInfoKey

      protected Object extractTemporaryTypeInfoKey(Expression expression)
    • findCurrentInstanceOfClass

      protected ClassNode findCurrentInstanceOfClass(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. 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 found
      type - 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

      protected List<ClassNode> getTemporaryTypesForExpression(Expression expression)
      Returns temporary narrowed types recorded for the supplied expression.