Package org.codehaus.groovy.ast.tools
Class GeneralUtils
java.lang.Object
org.codehaus.groovy.ast.tools.GeneralUtils
Handy methods when working with the Groovy AST. Provides factory methods for creating
common AST nodes and utility methods for expression and statement construction.
This utility class offers shorthand methods (often with abbreviated names) for building AST structures:
- Statement constructors:
block(),expr(),assign(),ret(), etc. - Expression constructors:
var(),constX(),classX(),cast(), etc. - Operator expressions:
binX(),andX(),orX(),cmp(), etc. - Collection literals:
list(),map(),tuple(),array(), etc. - Method calls:
call(),invokeMethod(),staticCall(), etc.
Common patterns use abbreviated names like X suffix for expression factories
(e.g., varX() for VariableExpression) and S suffix for statement factories
(e.g., blockS() for BlockStatement).
Null Handling: Most methods handle null gracefully, often returning empty or no-op structures rather than throwing exceptions.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic enumRepresents the compile-time constant value of a boolean loop-condition or branch expression. -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final TokenAST logical AND operator token ("&&").static final TokenAST assignment operator token ("=").static final TokenAST compare-to operator token ("<=>").static final TokenAST equality operator token ("==").static final TokenAST greater-than-or-equal operator token (">=").static final TokenAST greater-than operator token (">").static final TokenAST instanceof keyword token.static final TokenAST less-than-or-equal operator token ("<=").static final TokenAST less-than operator token ("<").static final TokenAST subtraction operator token ("-").static final TokenAST inequality operator token ("!=").static final TokenAST non-identity operator token ("!==").static final TokenAST logical OR operator token ("||").static final TokenAST addition operator token ("+"). -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic BinaryExpressionandX(Expression lhv, Expression rhv) Creates a binary expression with the AND operator joining two expressions.static ArgumentListExpressionCreates an ArgumentListExpression from variable names, converting each to a VariableExpression.static ArgumentListExpressionargs(List<Expression> expressions) Creates an ArgumentListExpression from a list of expressions.static ArgumentListExpressionargs(Expression... expressions) Creates an ArgumentListExpression from individual expression arguments.static ArgumentListExpressionCreates an ArgumentListExpression from parameter nodes, extracting their names as variable references.static ArrayExpressionarrayX(ClassNode elementType, List<Expression> initExpressions) Creates an ArrayExpression for the given element type and initial value expressions.static ArrayExpressionarrayX(ClassNode elementType, List<Expression> initExpressions, List<Expression> sizeExpressions) Creates an ArrayExpression for the given element type, dimensions, and initial values.static StatementassignNullS(Expression target) Creates a statement that assigns a null/empty value to the target expression.static StatementassignS(Expression target, Expression value) Creates an assignment statement for the supplied target and value.static ExpressionassignX(Expression target, Expression value) Creates an assignment expression usingASSIGN.static CastExpressionasX(ClassNode type, Expression expression) Creates a CastExpression converting the given expression to the specified type.static AttributeExpressionattrX(Expression owner, String attribute) static AttributeExpressionattrX(Expression owner, Expression attribute) Creates an attribute access expression.static ExpressionattrX$$bridge(Expression owner, Expression attribute) Deprecated.static BinaryExpressionbinX(Expression left, Token token, Expression right) Creates a binary expression from operands and an operator token.static BlockStatementCreates a block statement from statements and optional scope.static BlockStatementblock(VariableScope scope, List<Statement> stmts) Creates a block statement from statements and optional scope.static BlockStatementblock(VariableScope scope, Statement... stmts) Creates a block statement from statements and optional scope.static BooleanExpressionboolX(Expression expr) Wraps an expression in aBooleanExpression.static BytecodeExpressionCreates a customBytecodeExpression.static BytecodeExpressionCreates a customBytecodeExpression.static MethodCallExpressioncallSuperX(String methodName) Creates a method call expression onsuper.static MethodCallExpressioncallSuperX(String methodName, Expression args) Creates a method call expression onsuper.static MethodCallExpressionCreates a method call expression onthis.static MethodCallExpressioncallThisX(String methodName, Expression args) Creates a method call expression onthis.static StaticMethodCallExpressionCreates a method call expression.static StaticMethodCallExpressioncallX(ClassNode receiver, String methodName, Expression args) Creates a method call expression.static MethodCallExpressioncallX(Expression receiver, String methodName) Creates a method call expression.static MethodCallExpressioncallX(Expression receiver, String methodName, Expression args) Creates a method call expression.static MethodCallExpressioncallX(Expression receiver, Expression method, Expression args) Creates a method call expression.static CaseStatementcaseS(Expression expression, Statement code) Creates a switch-case statement.static CastExpressioncastX(ClassNode type, Expression expression) Creates a cast expression.static CastExpressioncastX(ClassNode type, Expression expression, boolean ignoreAutoboxing) Creates a cast expression.static CatchStatementCreates a catch statement.static ListExpressionclassList2args(List<String> args) Converts class-name strings into class-literal expressions.static ClassExpressionCreates a class literal expression.static ClassExpressionCreates a class literal expression.static Parameter[]cloneParams(Parameter[] parameters) Clones parameter metadata as newParameterinstances with original type and name.static ClosureExpressionCreates a closure expression.static ClosureExpressionCreates a closure expression.static BinaryExpressioncmpX(Expression lhv, Expression rhv) Builds a binary expression that compares two values.static GeneralUtils.ConditionValueconstantBooleanValue(Expression expression) Returns the compile-time constant boolean value of a loop condition expression.static ConstantExpressionCreates a constant expression.static ConstantExpressionCreates a constant expression.static StringconvertASTToSource(ReaderSource readerSource, ASTNode expression) Converts an expression into the String source.static voidcopyAnnotatedNodeAnnotations(AnnotatedNode annotatedNode, List<AnnotationNode> copied, List<AnnotationNode> notCopied) Copies all candidateAnnotations with retention policyRetentionPolicy.RUNTIMEandRetentionPolicy.CLASS.static voidcopyAnnotatedNodeAnnotations(AnnotatedNode annotatedNode, List<AnnotationNode> copied, List<AnnotationNode> notCopied, boolean includeGenerated) Copies all candidateAnnotations with retention policyRetentionPolicy.RUNTIMEandRetentionPolicy.CLASS.static booleanCopies closure statements into a block and rewrites a leadingsuper(...)call when present.static StatementBuilds default constructor-assignment logic for a field and matching argument.static StatementCreates asuper(...)constructor call statement.static StatementctorSuperS(Expression args) Creates asuper(...)constructor call statement.static ConstructorCallExpressionCreates asuper(...)constructor call expression.static ConstructorCallExpressionctorSuperX(Expression args) Creates asuper(...)constructor call expression.static StatementCreates athis(...)constructor call statement.static StatementctorThisS(Expression args) Creates athis(...)constructor call statement.static ConstructorCallExpressionCreates athis(...)constructor call expression.static ConstructorCallExpressionctorThisX(Expression args) Creates athis(...)constructor call expression.static ConstructorCallExpressionCreates a constructor call expression.static ConstructorCallExpressionctorX(ClassNode type, Expression args) Creates a constructor call expression.static StatementdeclS(Expression target, Expression init) Creates a variable declaration statement.static DeclarationExpressiondeclX(Expression target, Expression init) Creates a variable declaration expression.static ConstantExpressiondefaultValueX(ClassNode type) Returns a constant expression with the default value for the given type (i.e.,falsefor boolean,0for numbers ornull).static ElvisOperatorExpressionelvisX(Expression base, Expression otherwise) Creates an Elvis operator expression.static MapEntryExpressionentryX(Expression key, Expression value) Creates a map entry expression.static BooleanExpressionequalsNullX(Expression expr) Creates a null-equality test expression.static BinaryExpressioneqX(Expression left, Expression right) Creates an equality comparison expression.static FieldExpressionCreates a field expression.static FieldExpressionCreates a field expression.static ExpressionCreates an expression that resolves an entry from script args.static MethodNodefindDeclaredMethod(ClassNode cNode, String name, int argsCount) Finds the first declared method with the specified name and arity.static ForStatementforS(Parameter variable, Expression collectionExpression, Statement loopS) Creates a for-loop statement.static List<MethodNode>getAllMethods(ClassNode type) Collects methods declared on a class and its super classes.static List<PropertyNode>getAllProperties(Set<String> names, ClassNode cNode, boolean includeProperties, boolean includeFields, boolean includePseudoGetters, boolean includePseudoSetters, boolean traverseSuperClasses, boolean skipReadonly) Collects properties according to the supplied inclusion flags.static List<PropertyNode>getAllProperties(Set<String> names, ClassNode origType, ClassNode cNode, boolean includeProperties, boolean includeFields, boolean includePseudoGetters, boolean includePseudoSetters, boolean traverseSuperClasses, boolean skipReadonly) Collects properties according to the supplied inclusion flags.static List<PropertyNode>getAllProperties(Set<String> names, ClassNode origType, ClassNode cNode, boolean includeProperties, boolean includeFields, boolean includePseudoGetters, boolean includePseudoSetters, boolean traverseSuperClasses, boolean skipReadonly, boolean reverse, boolean allNames, boolean includeStatic) Collects properties according to the supplied inclusion flags.static List<PropertyNode>getAllProperties(ClassNode type) Collects properties according to the supplied inclusion flags.static StringgetGetterName(String name) WARNING: Avoid this method unless just the name is available.static StringgetGetterName(String name, Class<?> type) WARNING: Avoid this method unless just the name and type are available.static StringgetGetterName(PropertyNode pNode) Generally preferred to usePropertyNode.getGetterNameOrDefault()directly.Collects names of instance fields that are not exposed as properties.Collects instance fields that are not exposed as properties.static List<PropertyNode>getInstanceProperties(ClassNode cNode) Collects instance (non-static) properties.Collects backing fields for instance properties.Collects names of instance properties.Collects interfaces implemented directly or transitively.static StringgetSetterName(String name) Computes the JavaBean setter name for a property.Collects inherited instance fields that are not properties.getSuperPropertyFields(ClassNode cNode) Collects inherited property backing fields.static ExpressiongetterThisX(ClassNode annotatedNode, PropertyNode pNode) This method is similar topropX(Expression, Expression)but will make sure that if the property being accessed is defined inside the classnode provided as a parameter, then a getter call is generated instead of a field access.static ExpressiongetterX(ClassNode annotatedNode, Expression receiver, PropertyNode pNode) This method is similar topropX(Expression, Expression)but will make sure that if the property being accessed is defined inside the classnode provided as a parameter, then a getter call is generated instead of a field access.static BinaryExpressiongeX(Expression lhv, Expression rhv) Creates a greater-than-or-equal comparison expression.static BinaryExpressiongtX(Expression lhv, Expression rhv) Creates a greater-than comparison expression.static BinaryExpressionhasClassX(Expression instance, ClassNode cNode) Creates an expression testing whetherinstance.getClass()equals the supplied class.static booleanhasDeclaredMethod(ClassNode cNode, String name, int argsCount) Checks whether a class declares a method with the specified name and arity.static BinaryExpressionhasEqualFieldX(FieldNode fNode, Expression other) Creates an equality comparison against another object's field value.static BinaryExpressionhasEqualPropertyX(ClassNode cNode, PropertyNode pNode, VariableExpression other) Creates an equality comparison against another object's property value.static BinaryExpressionhasEqualPropertyX(PropertyNode pNode, Expression other) Deprecated.static BooleanExpressionhasSameFieldX(FieldNode fNode, Expression other) Creates an identity comparison against another object's field value.static BooleanExpressionhasSamePropertyX(PropertyNode pNode, Expression other) Creates an identity comparison against another object's property value.static IfStatementifElseS(Expression cond, Statement thenStmt, Statement elseStmt) Creates an if/else statement.static StatementifElseS$$bridge(Expression cond, Statement thenStmt, Statement elseStmt) Deprecated.static IfStatementifS(Expression cond, Expression trueExpr) Creates an if statement with an empty else branch.static IfStatementifS(Expression cond, Statement trueStmt) Creates an if statement with an empty else branch.static StatementifS$$bridge(Expression cond, Expression trueExpr) Deprecated.static StatementifS$$bridge(Expression cond, Statement trueStmt) Deprecated.static ExpressionindexX(Expression target, Expression value) Creates an index access expression.static booleaninSamePackage(Class<?> first, Class<?> second) Checks whether two classes belong to the same package.static booleaninSamePackage(ClassNode first, ClassNode second) Checks whether two classes belong to the same package.static booleanisDefaultVisibility(int modifiers) Checks whether modifier bits indicate package-private visibility.static booleanisEmptyStatement(Statement statement) Returnstrueif the given statement is effectively empty — i.e.static BooleanExpressionisInstanceOfX(Expression expr, ClassNode type) Creates aninstanceoftest expression.static BooleanExpressionisNullOrInstanceOfX(Expression expr, ClassNode type) static BooleanExpressionisNullX(Expression expr) Alias forequalsNullX(Expression)static BooleanExpressionisOneX(Expression expr) Creates an equality test against numeric one.static booleanisOrImplements(ClassNode type, ClassNode interfaceType) Checks whether a type equals or implements an interface type.static BooleanExpressionisTrueX(Expression argExpr) Creates an equality test againstBoolean.TRUE.static BooleanExpressionisZeroX(Expression expr) Creates an equality test against numeric zero.static LambdaExpressionBuilds a lambda expressionstatic LambdaExpressionBuilds a lambda expression with no parametersstatic BinaryExpressionleX(Expression lhv, Expression rhv) Creates a less-than-or-equal comparison expression.static ListExpressionConverts values into a constant-based list expression.static ListExpressionlistX(List<Expression> args) Creates a list expression.static VariableExpressionCreates a local variable expression and marks it as the accessed variable.static VariableExpressionCreates a local variable expression and marks it as the accessed variable.static BinaryExpressionltX(Expression lhv, Expression rhv) Creates a less-than comparison expression.static StringDeprecated.use MethodNodeUtils#methodDescriptorWithoutReturnType(MethodNode) insteadstatic MapEntryExpressionmapEntryX(String key, Expression valueExpr) Creates a map entry expression.static MapEntryExpressionmapEntryX(Expression keyExpr, Expression valueExpr) Creates a map entry expression.static MapExpressionmapX()Creates a map expression.static MapExpressionmapX(List<MapEntryExpression> expressions) Creates a map expression.static booleanmaybeFallsThrough(Statement statement) Determines whether execution may continue past the supplied statement.static booleanmaybeFallsThroughToNextSwitchCase(Statement statement, SwitchStatement switchStatement) Indicates whether switch-case code may fall through into the next case body.static booleanmayReachLoopCondition(LoopingStatement statement) Indicates whether execution of a loop body may reach the loop's condition/update step.static BinaryExpressionminusX(Expression lhv, Expression rhv) Creates a subtraction expression.static BinaryExpressionneX(Expression lhv, Expression rhv) Creates an inequality comparison expression.static BinaryExpressionnotIdenticalX(Expression lhv, Expression rhv) Creates a non-identity comparison expression.static BooleanExpressionnotNullX(Expression expr) Creates a non-null test expression.static NotExpressionnotX(Expression expr) Creates a logical NOT expression.static ConstantExpressionnullX()Creates anullconstant expression.static BinaryExpressionorX(Expression lhv, Expression rhv) Creates a logical OR expression.static ParameterCreates a parameter node.static Parameterparam(ClassNode type, String name, Expression initialExpression) Creates a parameter node.static Parameter[]Returns the input parameters orParameter.EMPTY_ARRAYwhen input isnull.static BinaryExpressionplusX(Expression lhv, Expression rhv) Creates an addition expression.static PropertyExpressionpropX(Expression owner, String property) Creates a property access expression.static PropertyExpressionpropX(Expression owner, Expression property) Creates a property access expression.static PropertyExpressionpropX(Expression owner, Expression property, boolean safe) Creates a property access expression.static ExpressionpropX$$bridge(Expression owner, String property) Deprecated.static ExpressionpropX$$bridge(Expression owner, Expression property) Deprecated.static StatementreturnS(Expression expr) Creates a return statement.static StatementsafeExpression(Expression fieldExpr, Expression expression) Creates a null-guarded statement sequence.static BooleanExpressionsameX(Expression self, Expression other) Creates an identity test expression using Groovy'sismethod.static SpreadExpressionspreadX(Expression expr) Creates a spread expression.static Statementstmt(Expression expr) Wraps an expression in anExpressionStatement.static SwitchStatementswitchS(Expression expr) Creates a switch statement.static SwitchStatementswitchS(Expression expr, List<CaseStatement> caseStatements, Statement defaultStatement) Creates a switch statement.static SwitchStatementswitchS(Expression expr, Statement defaultStatement) Creates a switch statement.static TernaryExpressionternaryX(Expression cond, Expression trueExpr, Expression elseExpr) Creates a ternary expression.static PropertyExpressionCreates a property expression onthiswith configurable implicit-this behavior.static ThrowStatementthrowS(Expression expr) Creates a throw statement.static TryCatchStatementCreates a try/catch/finally statement.static TryCatchStatementCreates a try/catch/finally statement.static TryCatchStatementtryCatchS(Statement tryStatement, Statement finallyStatement, CatchStatement... catchStatements) Creates a try/catch/finally statement.static VariableExpressionCreates a variable expression.static VariableExpressionCreates a variable expression.static VariableExpressionCreates a variable expression.
-
Field Details
-
ASSIGN
AST assignment operator token ("="). -
CMP
AST compare-to operator token ("<=>"). -
EQ
AST equality operator token ("=="). -
NE
AST inequality operator token ("!="). -
NOT_IDENTICAL
AST non-identity operator token ("!=="). -
GE
AST greater-than-or-equal operator token (">="). -
GT
AST greater-than operator token (">"). -
LE
AST less-than-or-equal operator token ("<="). -
LT
AST less-than operator token ("<"). -
AND
AST logical AND operator token ("&&"). -
OR
AST logical OR operator token ("||"). -
INSTANCEOF
AST instanceof keyword token. -
MINUS
AST subtraction operator token ("-"). -
PLUS
AST addition operator token ("+").
-
-
Constructor Details
-
GeneralUtils
public GeneralUtils()
-
-
Method Details
-
andX
Creates a binary expression with the AND operator joining two expressions.- Parameters:
lhv- the left-hand-side operandrhv- the right-hand-side operand- Returns:
- a BinaryExpression with AND operator
- See Also:
-
args
Creates an ArgumentListExpression from individual expression arguments.- Parameters:
expressions- the argument expressions (may be empty)- Returns:
- an ArgumentListExpression containing the arguments
-
args
Creates an ArgumentListExpression from a list of expressions.- Parameters:
expressions- the list of argument expressions (may be empty)- Returns:
- an ArgumentListExpression containing the arguments
-
args
Creates an ArgumentListExpression from parameter nodes, extracting their names as variable references.- Parameters:
parameters- the parameter nodes- Returns:
- an ArgumentListExpression with variable expressions for each parameter
-
args
Creates an ArgumentListExpression from variable names, converting each to a VariableExpression.- Parameters:
names- the variable names (non-null strings)- Returns:
- an ArgumentListExpression with variable expressions for each name
-
arrayX
Creates an ArrayExpression for the given element type and initial value expressions.- Parameters:
elementType- theClassNoderepresenting the array element typeinitExpressions- the expressions providing initial array values- Returns:
- an ArrayExpression with the given element type and values
-
arrayX
public static ArrayExpression arrayX(ClassNode elementType, List<Expression> initExpressions, List<Expression> sizeExpressions) Creates an ArrayExpression for the given element type, dimensions, and initial values.- Parameters:
elementType- theClassNoderepresenting the array element typeinitExpressions- the expressions providing initial array valuessizeExpressions- the expressions providing array dimensions- Returns:
- an ArrayExpression with the given element type, dimensions, and values
-
asX
Creates a CastExpression converting the given expression to the specified type.- Parameters:
type- theClassNodeto cast toexpression- the expression to cast- Returns:
- a CastExpression with the given type and expression
-
assignNullS
Creates a statement that assigns a null/empty value to the target expression. Used to clear or reset variable values.- Parameters:
target- the expression to assign to- Returns:
- an ExpressionStatement assigning null to the target
-
assignS
Creates an assignment statement for the supplied target and value.- Parameters:
target- the assignment target expressionvalue- the value expression- Returns:
- the resulting Statement
-
assignX
Creates an assignment expression usingASSIGN.- Parameters:
target- the assignment target expressionvalue- the value expression- Returns:
- the resulting Expression
-
attrX
- Since:
- 5.0.0
-
attrX
Creates an attribute access expression.- Parameters:
owner- the owner expressionattribute- the attribute expression- Returns:
- the resulting AttributeExpression
-
attrX$$bridge
Deprecated.Deprecated compatibility bridge forattrX(Expression, Expression).- Parameters:
owner- the owner expressionattribute- the attribute expression- Returns:
- the resulting Expression
-
binX
Creates a binary expression from operands and an operator token.- Parameters:
left- the left-hand operandtoken- the operator tokenright- the right-hand operand- Returns:
- the resulting BinaryExpression
-
block
Creates a block statement from statements and optional scope.- Parameters:
scope- the variable scope for the blockstmts- the statements to include in the block- Returns:
- the resulting BlockStatement
-
block
Creates a block statement from statements and optional scope.- Parameters:
scope- the variable scope for the blockstmts- the statements to include in the block- Returns:
- the resulting BlockStatement
-
block
Creates a block statement from statements and optional scope.- Parameters:
stmts- the statements to include in the block- Returns:
- the resulting BlockStatement
-
boolX
Wraps an expression in aBooleanExpression.- Parameters:
expr- the expression- Returns:
- the resulting BooleanExpression
-
bytecodeX
Creates a customBytecodeExpression.- Parameters:
writer- the bytecode writer callback- Returns:
- the resulting BytecodeExpression
-
bytecodeX
public static BytecodeExpression bytecodeX(ClassNode type, Consumer<org.objectweb.asm.MethodVisitor> writer) Creates a customBytecodeExpression.- Parameters:
type- the target typewriter- the bytecode writer callback- Returns:
- the resulting BytecodeExpression
-
callSuperX
Creates a method call expression onsuper.- Parameters:
methodName- the method name- Returns:
- the resulting MethodCallExpression
-
callSuperX
Creates a method call expression onsuper.- Parameters:
methodName- the method nameargs- the argument expression(s)- Returns:
- the resulting MethodCallExpression
-
callThisX
Creates a method call expression onthis.- Parameters:
methodName- the method name- Returns:
- the resulting MethodCallExpression
-
callThisX
Creates a method call expression onthis.- Parameters:
methodName- the method nameargs- the argument expression(s)- Returns:
- the resulting MethodCallExpression
-
callX
Creates a method call expression.- Parameters:
receiver- the call receivermethodName- the method name- Returns:
- the resulting MethodCallExpression
-
callX
Creates a method call expression.- Parameters:
receiver- the call receivermethodName- the method nameargs- the argument expression(s)- Returns:
- the resulting MethodCallExpression
-
callX
Creates a method call expression.- Parameters:
receiver- the call receivermethod- the method expressionargs- the argument expression(s)- Returns:
- the resulting MethodCallExpression
-
callX
Creates a method call expression.- Parameters:
receiver- the call receivermethodName- the method name- Returns:
- the resulting StaticMethodCallExpression
-
callX
public static StaticMethodCallExpression callX(ClassNode receiver, String methodName, Expression args) Creates a method call expression.- Parameters:
receiver- the call receivermethodName- the method nameargs- the argument expression(s)- Returns:
- the resulting StaticMethodCallExpression
-
caseS
Creates a switch-case statement.- Parameters:
expression- the expressioncode- the statement body- Returns:
- the resulting CaseStatement
-
castX
Creates a cast expression.- Parameters:
type- the target typeexpression- the expression- Returns:
- the resulting CastExpression
-
castX
Creates a cast expression.- Parameters:
type- the target typeexpression- the expressionignoreAutoboxing- whether autoboxing should be ignored- Returns:
- the resulting CastExpression
-
catchS
Creates a catch statement.- Parameters:
variable- the loop or catch parametercode- the statement body- Returns:
- the resulting CatchStatement
-
classX
Creates a class literal expression.- Parameters:
clazz- the class reference- Returns:
- the resulting ClassExpression
-
classX
Creates a class literal expression.- Parameters:
clazz- the class reference- Returns:
- the resulting ClassExpression
-
closureX
Creates a closure expression.- Parameters:
params- the parameter arraycode- the statement body- Returns:
- the resulting ClosureExpression
-
closureX
Creates a closure expression.- Parameters:
code- the statement body- Returns:
- the resulting ClosureExpression
-
lambdaX
Builds a lambda expression- Parameters:
params- lambda parameterscode- lambda code- Returns:
- the lambda expression
-
lambdaX
Builds a lambda expression with no parameters- Parameters:
code- lambda code- Returns:
- the lambda expression
-
cmpX
Builds a binary expression that compares two values.- Parameters:
lhv- expression for the value to compare fromrhv- expression for the value to compare to- Returns:
- the expression comparing two values
-
constX
Creates a constant expression.- Parameters:
val- the val- Returns:
- the resulting ConstantExpression
-
constX
Creates a constant expression.- Parameters:
val- the valkeepPrimitive- whether primitive-wrapper constants should be preserved- Returns:
- the resulting ConstantExpression
-
ctorX
Creates a constructor call expression.- Parameters:
type- the target typeargs- the argument expression(s)- Returns:
- the resulting ConstructorCallExpression
-
ctorX
Creates a constructor call expression.- Parameters:
type- the target type- Returns:
- the resulting ConstructorCallExpression
-
ctorSuperS
Creates asuper(...)constructor call statement.- Parameters:
args- the argument expression(s)- Returns:
- the resulting Statement
-
ctorSuperX
Creates asuper(...)constructor call expression.- Parameters:
args- the argument expression(s)- Returns:
- the resulting ConstructorCallExpression
-
ctorThisS
Creates athis(...)constructor call statement.- Parameters:
args- the argument expression(s)- Returns:
- the resulting Statement
-
ctorThisX
Creates athis(...)constructor call expression.- Parameters:
args- the argument expression(s)- Returns:
- the resulting ConstructorCallExpression
-
ctorSuperS
Creates asuper(...)constructor call statement.- Returns:
- the resulting Statement
-
ctorSuperX
Creates asuper(...)constructor call expression.- Returns:
- the resulting ConstructorCallExpression
-
ctorThisS
Creates athis(...)constructor call statement.- Returns:
- the resulting Statement
-
ctorThisX
Creates athis(...)constructor call expression.- Returns:
- the resulting ConstructorCallExpression
-
declS
Creates a variable declaration statement.- Parameters:
target- the assignment target expressioninit- the initializer expression- Returns:
- the resulting Statement
-
declX
Creates a variable declaration expression.- Parameters:
target- the assignment target expressioninit- the initializer expression- Returns:
- the resulting DeclarationExpression
-
defaultValueX
Returns a constant expression with the default value for the given type (i.e.,falsefor boolean,0for numbers ornull).- Since:
- 4.0.0
-
elvisX
Creates an Elvis operator expression.- Parameters:
base- the base expressionotherwise- the fallback expression- Returns:
- the resulting ElvisOperatorExpression
-
entryX
Creates a map entry expression.- Parameters:
key- the key expressionvalue- the value expression- Returns:
- the resulting MapEntryExpression
-
eqX
Creates an equality comparison expression.- Parameters:
left- the left-hand operandright- the right-hand operand- Returns:
- the resulting BinaryExpression
-
equalsNullX
Creates a null-equality test expression.- Parameters:
expr- the expression- Returns:
- the resulting BooleanExpression
-
fieldX
Creates a field expression.- Parameters:
fieldNode- the fieldNode- Returns:
- the resulting FieldExpression
-
fieldX
Creates a field expression.- Parameters:
owner- the owner expressionfieldName- the field name- Returns:
- the resulting FieldExpression
-
findArg
Creates an expression that resolves an entry from script args.- Parameters:
argName- the argument name- Returns:
- the resulting Expression
-
forS
public static ForStatement forS(Parameter variable, Expression collectionExpression, Statement loopS) Creates a for-loop statement.- Parameters:
variable- the loop or catch parametercollectionExpression- the collection expressionloopS- the loop body statement- Returns:
- the resulting ForStatement
-
getAllMethods
Collects methods declared on a class and its super classes.- Parameters:
type- the target type- Returns:
- the resulting List
-
getAllProperties
Collects properties according to the supplied inclusion flags.- Parameters:
type- the target type- Returns:
- the resulting List
-
getInstanceNonPropertyFields
Collects instance fields that are not exposed as properties.- Parameters:
cNode- the class node- Returns:
- the resulting List
-
getInstanceNonPropertyFieldNames
Collects names of instance fields that are not exposed as properties.- Parameters:
cNode- the class node- Returns:
- the resulting List
-
getInstanceProperties
Collects instance (non-static) properties.- Parameters:
cNode- the class node- Returns:
- the resulting List
-
getInstancePropertyNames
Collects names of instance properties.- Parameters:
cNode- the class node- Returns:
- the resulting List
-
getInstancePropertyFields
Collects backing fields for instance properties.- Parameters:
cNode- the class node- Returns:
- the resulting List
-
getInterfacesAndSuperInterfaces
Collects interfaces implemented directly or transitively.- Parameters:
cNode- the class node- Returns:
- the resulting Set
-
getSuperNonPropertyFields
Collects inherited instance fields that are not properties.- Parameters:
cNode- the class node- Returns:
- the resulting List
-
getSuperPropertyFields
Collects inherited property backing fields.- Parameters:
cNode- the class node- Returns:
- the resulting List
-
getAllProperties
public static List<PropertyNode> getAllProperties(Set<String> names, ClassNode cNode, boolean includeProperties, boolean includeFields, boolean includePseudoGetters, boolean includePseudoSetters, boolean traverseSuperClasses, boolean skipReadonly) Collects properties according to the supplied inclusion flags.- Parameters:
names- the set tracking already-added property namescNode- the class nodeincludeProperties- whether declared properties are includedincludeFields- whether fields are exposed as propertiesincludePseudoGetters- whether pseudo-getter properties are includedincludePseudoSetters- whether pseudo-setter properties are includedtraverseSuperClasses- whether super classes are traversedskipReadonly- whether read-only initialized fields are excluded- Returns:
- the resulting List
-
getAllProperties
public static List<PropertyNode> getAllProperties(Set<String> names, ClassNode origType, ClassNode cNode, boolean includeProperties, boolean includeFields, boolean includePseudoGetters, boolean includePseudoSetters, boolean traverseSuperClasses, boolean skipReadonly) Collects properties according to the supplied inclusion flags.- Parameters:
names- the set tracking already-added property namesorigType- the original class node used for pseudo-property resolutioncNode- the class nodeincludeProperties- whether declared properties are includedincludeFields- whether fields are exposed as propertiesincludePseudoGetters- whether pseudo-getter properties are includedincludePseudoSetters- whether pseudo-setter properties are includedtraverseSuperClasses- whether super classes are traversedskipReadonly- whether read-only initialized fields are excluded- Returns:
- the resulting List
-
getAllProperties
public static List<PropertyNode> getAllProperties(Set<String> names, ClassNode origType, ClassNode cNode, boolean includeProperties, boolean includeFields, boolean includePseudoGetters, boolean includePseudoSetters, boolean traverseSuperClasses, boolean skipReadonly, boolean reverse, boolean allNames, boolean includeStatic) Collects properties according to the supplied inclusion flags.- Parameters:
names- the set tracking already-added property namesorigType- the original class node used for pseudo-property resolutioncNode- the class nodeincludeProperties- whether declared properties are includedincludeFields- whether fields are exposed as propertiesincludePseudoGetters- whether pseudo-getter properties are includedincludePseudoSetters- whether pseudo-setter properties are includedtraverseSuperClasses- whether super classes are traversedskipReadonly- whether read-only initialized fields are excludedreverse- whether superclass traversal order is reversedallNames- whether special/internal field names are includedincludeStatic- whether static members are included- Returns:
- the resulting List
-
getterThisX
This method is similar topropX(Expression, Expression)but will make sure that if the property being accessed is defined inside the classnode provided as a parameter, then a getter call is generated instead of a field access.- Parameters:
annotatedNode- the class node where the property node is accessed frompNode- the property being accessed- Returns:
- a method call expression or a property expression
-
getterX
This method is similar topropX(Expression, Expression)but will make sure that if the property being accessed is defined inside the classnode provided as a parameter, then a getter call is generated instead of a field access.- Parameters:
annotatedNode- the class node where the property node is accessed fromreceiver- the object having the propertypNode- the property being accessed- Returns:
- a method call expression or a property expression
-
geX
Creates a greater-than-or-equal comparison expression.- Parameters:
lhv- the left-hand operandrhv- the right-hand operand- Returns:
- the resulting BinaryExpression
-
gtX
Creates a greater-than comparison expression.- Parameters:
lhv- the left-hand operandrhv- the right-hand operand- Returns:
- the resulting BinaryExpression
-
hasClassX
Creates an expression testing whetherinstance.getClass()equals the supplied class.- Parameters:
instance- the instance expressioncNode- the class node- Returns:
- the resulting BinaryExpression
-
hasEqualFieldX
Creates an equality comparison against another object's field value.- Parameters:
fNode- the field nodeother- the other object/value expression- Returns:
- the resulting BinaryExpression
-
hasEqualPropertyX
public static BinaryExpression hasEqualPropertyX(ClassNode cNode, PropertyNode pNode, VariableExpression other) Creates an equality comparison against another object's property value.- Parameters:
cNode- the class nodepNode- the property nodeother- the other object/value expression- Returns:
- the resulting BinaryExpression
-
hasEqualPropertyX
Deprecated.Creates an equality comparison against another object's property value.- Parameters:
pNode- the property nodeother- the other object/value expression- Returns:
- the resulting BinaryExpression
-
hasSameFieldX
Creates an identity comparison against another object's field value.- Parameters:
fNode- the field nodeother- the other object/value expression- Returns:
- the resulting BooleanExpression
-
hasSamePropertyX
Creates an identity comparison against another object's property value.- Parameters:
pNode- the property nodeother- the other object/value expression- Returns:
- the resulting BooleanExpression
-
ifElseS$$bridge
@Deprecated public static Statement ifElseS$$bridge(Expression cond, Statement thenStmt, Statement elseStmt) Deprecated.Deprecated compatibility bridge forifElseS(Expression, Statement, Statement).- Parameters:
cond- the condition expressionthenStmt- the true-branch statementelseStmt- the false-branch statement- Returns:
- the resulting Statement
-
ifElseS
Creates an if/else statement.- Parameters:
cond- the condition expressionthenStmt- the true-branch statementelseStmt- the false-branch statement- Returns:
- the resulting IfStatement
-
ifS$$bridge
Deprecated.Deprecated compatibility bridge for theifSoverloads.- Parameters:
cond- the condition expressiontrueExpr- the true-branch expression- Returns:
- the resulting Statement
-
ifS
Creates an if statement with an empty else branch.- Parameters:
cond- the condition expressiontrueExpr- the true-branch expression- Returns:
- the resulting IfStatement
-
ifS$$bridge
Deprecated.Deprecated compatibility bridge for theifSoverloads.- Parameters:
cond- the condition expressiontrueStmt- the true-branch statement- Returns:
- the resulting Statement
-
ifS
Creates an if statement with an empty else branch.- Parameters:
cond- the condition expressiontrueStmt- the true-branch statement- Returns:
- the resulting IfStatement
-
indexX
Creates an index access expression.- Parameters:
target- the assignment target expressionvalue- the value expression- Returns:
- the resulting Expression
-
isInstanceOfX
Creates aninstanceoftest expression.- Parameters:
expr- the expressiontype- the target type- Returns:
- the resulting BooleanExpression
-
isNullOrInstanceOfX
- Since:
- 4.0.8
-
isNullX
Alias forequalsNullX(Expression) -
isOneX
Creates an equality test against numeric one.- Parameters:
expr- the expression- Returns:
- the resulting BooleanExpression
-
isTrueX
Creates an equality test againstBoolean.TRUE.- Parameters:
argExpr- the argument expression- Returns:
- the resulting BooleanExpression
-
isZeroX
Creates an equality test against numeric zero.- Parameters:
expr- the expression- Returns:
- the resulting BooleanExpression
-
listX
Creates a list expression.- Parameters:
args- the argument expression(s)- Returns:
- the resulting ListExpression
-
list2args
Converts values into a constant-based list expression.- Parameters:
args- the argument expression(s)- Returns:
- the resulting ListExpression
-
classList2args
Converts class-name strings into class-literal expressions.- Parameters:
args- the argument expression(s)- Returns:
- the resulting ListExpression
-
localVarX
Creates a local variable expression and marks it as the accessed variable.- Parameters:
name- the property name- Returns:
- the resulting VariableExpression
-
localVarX
Creates a local variable expression and marks it as the accessed variable.- Parameters:
name- the property nametype- the target type- Returns:
- the resulting VariableExpression
-
leX
Creates a less-than-or-equal comparison expression.- Parameters:
lhv- the left-hand operandrhv- the right-hand operand- Returns:
- the resulting BinaryExpression
-
ltX
Creates a less-than comparison expression.- Parameters:
lhv- the left-hand operandrhv- the right-hand operand- Returns:
- the resulting BinaryExpression
-
mapEntryX
Creates a map entry expression.- Parameters:
keyExpr- the map-entry key expressionvalueExpr- the map-entry value expression- Returns:
- the resulting MapEntryExpression
-
mapEntryX
Creates a map entry expression.- Parameters:
key- the key expressionvalueExpr- the map-entry value expression- Returns:
- the resulting MapEntryExpression
-
mapX
Creates a map expression.- Returns:
- the resulting MapExpression
-
mapX
Creates a map expression.- Parameters:
expressions- the map-entry expressions- Returns:
- the resulting MapExpression
-
minusX
Creates a subtraction expression.- Parameters:
lhv- the left-hand operandrhv- the right-hand operand- Returns:
- the resulting BinaryExpression
-
neX
Creates an inequality comparison expression.- Parameters:
lhv- the left-hand operandrhv- the right-hand operand- Returns:
- the resulting BinaryExpression
-
notIdenticalX
Creates a non-identity comparison expression.- Parameters:
lhv- the left-hand operandrhv- the right-hand operand- Returns:
- the resulting BinaryExpression
-
notNullX
Creates a non-null test expression.- Parameters:
expr- the expression- Returns:
- the resulting BooleanExpression
-
notX
Creates a logical NOT expression.- Parameters:
expr- the expression- Returns:
- the resulting NotExpression
-
nullX
Creates anullconstant expression.- Returns:
- the resulting ConstantExpression
-
orX
Creates a logical OR expression.- Parameters:
lhv- the left-hand operandrhv- the right-hand operand- Returns:
- the resulting BinaryExpression
-
param
Creates a parameter node.- Parameters:
type- the target typename- the property name- Returns:
- the resulting Parameter
-
param
Creates a parameter node.- Parameters:
type- the target typename- the property nameinitialExpression- the initial expression for the parameter- Returns:
- the resulting Parameter
-
params
Returns the input parameters orParameter.EMPTY_ARRAYwhen input isnull.- Parameters:
params- the parameter array- Returns:
- the resulting Parameter[]
-
plusX
Creates an addition expression.- Parameters:
lhv- the left-hand operandrhv- the right-hand operand- Returns:
- the resulting BinaryExpression
-
propX
Creates a property access expression.- Parameters:
owner- the owner expressionproperty- the property name/expression- Returns:
- the resulting PropertyExpression
-
propX$$bridge
Deprecated.Deprecated compatibility bridge for thepropXoverloads.- Parameters:
owner- the owner expressionproperty- the property name/expression- Returns:
- the resulting Expression
-
propX
Creates a property access expression.- Parameters:
owner- the owner expressionproperty- the property name/expression- Returns:
- the resulting PropertyExpression
-
propX$$bridge
Deprecated.Deprecated compatibility bridge for thepropXoverloads.- Parameters:
owner- the owner expressionproperty- the property name/expression- Returns:
- the resulting Expression
-
propX
Creates a property access expression.- Parameters:
owner- the owner expressionproperty- the property name/expressionsafe- whether safe-navigation is enabled- Returns:
- the resulting PropertyExpression
-
returnS
Creates a return statement.- Parameters:
expr- the expression- Returns:
- the resulting Statement
-
safeExpression
Creates a null-guarded statement sequence.- Parameters:
fieldExpr- the field expression used in the guardexpression- the expression- Returns:
- the resulting Statement
-
sameX
Creates an identity test expression using Groovy'sismethod.- Parameters:
self- the left-hand expressionother- the other object/value expression- Returns:
- the resulting BooleanExpression
-
stmt
Wraps an expression in anExpressionStatement.- Parameters:
expr- the expression- Returns:
- the resulting Statement
-
spreadX
Creates a spread expression.- Parameters:
expr- the expression- Returns:
- the resulting SpreadExpression
-
switchS
Creates a switch statement.- Parameters:
expr- the expression- Returns:
- the resulting SwitchStatement
-
switchS
Creates a switch statement.- Parameters:
expr- the expressiondefaultStatement- the default branch statement- Returns:
- the resulting SwitchStatement
-
switchS
public static SwitchStatement switchS(Expression expr, List<CaseStatement> caseStatements, Statement defaultStatement) Creates a switch statement.- Parameters:
expr- the expressioncaseStatements- the case statementsdefaultStatement- the default branch statement- Returns:
- the resulting SwitchStatement
-
ternaryX
Creates a ternary expression.- Parameters:
cond- the condition expressiontrueExpr- the true-branch expressionelseExpr- the false-branch expression- Returns:
- the resulting TernaryExpression
-
thisPropX
Creates a property expression onthiswith configurable implicit-this behavior.- Parameters:
implicit- whether the receiver is implicit thisproperty- the property name/expression- Returns:
- the resulting PropertyExpression
-
throwS
Creates a throw statement.- Parameters:
expr- the expression- Returns:
- the resulting ThrowStatement
-
tryCatchS
Creates a try/catch/finally statement.- Parameters:
tryStatement- the try-block statement- Returns:
- the resulting TryCatchStatement
-
tryCatchS
Creates a try/catch/finally statement.- Parameters:
tryStatement- the try-block statementfinallyStatement- the finally-block statement- Returns:
- the resulting TryCatchStatement
-
tryCatchS
public static TryCatchStatement tryCatchS(Statement tryStatement, Statement finallyStatement, CatchStatement... catchStatements) Creates a try/catch/finally statement.- Parameters:
tryStatement- the try-block statementfinallyStatement- the finally-block statementcatchStatements- the catch statements- Returns:
- the resulting TryCatchStatement
-
varX
Creates a variable expression.- Parameters:
name- the property name- Returns:
- the resulting VariableExpression
-
varX
Creates a variable expression.- Parameters:
variable- the loop or catch parameter- Returns:
- the resulting VariableExpression
-
varX
Creates a variable expression.- Parameters:
name- the property nametype- the target type- Returns:
- the resulting VariableExpression
-
cloneParams
Clones parameter metadata as newParameterinstances with original type and name.- Parameters:
parameters- the parameters to clone- Returns:
- the resulting Parameter[]
-
copyAnnotatedNodeAnnotations
public static void copyAnnotatedNodeAnnotations(AnnotatedNode annotatedNode, List<AnnotationNode> copied, List<AnnotationNode> notCopied) Copies all candidateAnnotations with retention policyRetentionPolicy.RUNTIMEandRetentionPolicy.CLASS.Annotations with
GeneratedClosuremembers are not supported at present. -
copyAnnotatedNodeAnnotations
public static void copyAnnotatedNodeAnnotations(AnnotatedNode annotatedNode, List<AnnotationNode> copied, List<AnnotationNode> notCopied, boolean includeGenerated) Copies all candidateAnnotations with retention policyRetentionPolicy.RUNTIMEandRetentionPolicy.CLASS.Generatedannotations will be copied ifincludeGeneratedis true.Annotations with
GeneratedClosuremembers are not supported at present. -
createConstructorStatementDefault
Builds default constructor-assignment logic for a field and matching argument.- Parameters:
fNode- the field node- Returns:
- the resulting Statement
-
getGetterName
Generally preferred to usePropertyNode.getGetterNameOrDefault()directly. -
getGetterName
WARNING: Avoid this method unless just the name and type are available. UsegetGetterName(PropertyNode)if the propertyNode is available. -
getGetterName
WARNING: Avoid this method unless just the name is available. UsegetGetterName(PropertyNode)if the propertyNode is available. UsegetGetterName(String, Class)if the type is available. -
getSetterName
Computes the JavaBean setter name for a property.- Parameters:
name- the property name- Returns:
- the resulting String
-
convertASTToSource
public static String convertASTToSource(ReaderSource readerSource, ASTNode expression) throws Exception Converts an expression into the String source. Only some specific expressions like closure expression support this.- Parameters:
readerSource- a sourceexpression- an expression. Can't be null- Returns:
- the source the closure was created from
- Throws:
IllegalArgumentException- when expression is nullException- when closure can't be read from source
-
copyStatementsWithSuperAdjustment
Copies closure statements into a block and rewrites a leadingsuper(...)call when present.- Parameters:
pre- the closure containing statements to copybody- the destination block- Returns:
- true if a leading super call was rewritten; false otherwise
-
hasDeclaredMethod
Checks whether a class declares a method with the specified name and arity.- Parameters:
cNode- the class nodename- the property nameargsCount- the expected argument count- Returns:
- true if a matching declared method exists; false otherwise
-
findDeclaredMethod
Finds the first declared method with the specified name and arity.- Parameters:
cNode- the class nodename- the property nameargsCount- the expected argument count- Returns:
- the matching method node, or
nullif not found
-
inSamePackage
Checks whether two classes belong to the same package.- Parameters:
first- the first class/typesecond- the second class/type- Returns:
- true if both classes are in the same package; false otherwise
-
inSamePackage
Checks whether two classes belong to the same package.- Parameters:
first- the first class/typesecond- the second class/type- Returns:
- true if both classes are in the same package; false otherwise
-
isDefaultVisibility
public static boolean isDefaultVisibility(int modifiers) Checks whether modifier bits indicate package-private visibility.- Parameters:
modifiers- the modifier bit mask- Returns:
- true if no public/protected/private visibility flag is set; false otherwise
-
isOrImplements
Checks whether a type equals or implements an interface type.- Parameters:
type- the target typeinterfaceType- the interface to test against- Returns:
- true if the type equals or implements the interface type; false otherwise
-
makeDescriptorWithoutReturnType
Deprecated.use MethodNodeUtils#methodDescriptorWithoutReturnType(MethodNode) instead -
maybeFallsThrough
Determines whether execution may continue past the supplied statement.- Parameters:
statement- the statement to analyze- Returns:
- true if execution may continue after the statement; false otherwise
-
isEmptyStatement
Returnstrueif the given statement is effectively empty — i.e. it isnull, anEmptyStatement, or aBlockStatementwhose every nested statement is itself empty (recursively). This is subtly different fromStatement.isEmpty(), which only checks whether aBlockStatementhas zero entries, not whether those entries are all empty. -
constantBooleanValue
Returns the compile-time constant boolean value of a loop condition expression. Handles nestedBooleanExpression/NotExpressionwrappers and an absent (empty) condition, which is alwaystrue(e.g.for(;;)). ReturnsGeneralUtils.ConditionValue.UNKNOWNwhen the value cannot be determined statically. -
maybeFallsThroughToNextSwitchCase
public static boolean maybeFallsThroughToNextSwitchCase(Statement statement, SwitchStatement switchStatement) Indicates whether switch-case code may fall through into the next case body. -
mayReachLoopCondition
Indicates whether execution of a loop body may reach the loop's condition/update step.
-