use of org.codehaus.groovy.syntax.Token in project groovy by apache.
the class BinaryExpression method newInitializationExpression.
/**
* Creates variable initialization expression in which the specified expression
* is written into the specified variable name.
*/
public static BinaryExpression newInitializationExpression(String variable, ClassNode type, Expression rhs) {
VariableExpression lhs = new VariableExpression(variable);
if (type != null) {
lhs.setType(type);
}
Token operator = Token.newPlaceholder(Types.ASSIGN);
return new BinaryExpression(lhs, operator, rhs);
}
use of org.codehaus.groovy.syntax.Token in project groovy by apache.
the class NAryOperationRewriter method transformPrefixExpression.
private Expression transformPrefixExpression(final PrefixExpression exp) {
if (isInternalFieldAccess(exp.getExpression())) {
Token operation = exp.getOperation();
sourceUnit.addError(new SyntaxException("Prefix expressions on trait fields/properties are not supported in traits.", operation.getStartLine(), operation.getStartColumn()));
return exp;
} else {
return super.transform(exp);
}
}
use of org.codehaus.groovy.syntax.Token in project groovy by apache.
the class EnumVisitor method addInit.
private void addInit(ClassNode enumClass, FieldNode minValue, FieldNode maxValue, FieldNode values, boolean isAic) {
// constructor helper
// This method is used instead of calling the constructor as
// calling the constructor may require a table with MetaClass
// selecting the constructor for each enum value. So instead we
// use this method to have a central point for constructor selection
// and only one table. The whole construction is needed because
// Reflection forbids access to the enum constructor.
// code:
// def $INIT(Object[] para) {
// return this(*para)
// }
ClassNode enumRef = enumClass.getPlainNodeReference();
Parameter[] parameter = new Parameter[] { new Parameter(ClassHelper.OBJECT_TYPE.makeArray(), "para") };
MethodNode initMethod = new MethodNode("$INIT", PUBLIC_FS | Opcodes.ACC_SYNTHETIC, enumRef, parameter, ClassNode.EMPTY_ARRAY, null);
initMethod.setSynthetic(true);
ConstructorCallExpression cce = new ConstructorCallExpression(ClassNode.THIS, new ArgumentListExpression(new SpreadExpression(new VariableExpression("para"))));
BlockStatement code = new BlockStatement();
code.addStatement(new ReturnStatement(cce));
initMethod.setCode(code);
enumClass.addMethod(initMethod);
// static init
List<FieldNode> fields = enumClass.getFields();
List<Expression> arrayInit = new ArrayList<Expression>();
int value = -1;
Token assign = Token.newSymbol(Types.ASSIGN, -1, -1);
List<Statement> block = new ArrayList<Statement>();
FieldNode tempMin = null;
FieldNode tempMax = null;
for (FieldNode field : fields) {
if ((field.getModifiers() & Opcodes.ACC_ENUM) == 0)
continue;
value++;
if (tempMin == null)
tempMin = field;
tempMax = field;
ClassNode enumBase = enumClass;
ArgumentListExpression args = new ArgumentListExpression();
args.addExpression(new ConstantExpression(field.getName()));
args.addExpression(new ConstantExpression(value));
if (field.getInitialExpression() == null) {
if ((enumClass.getModifiers() & Opcodes.ACC_ABSTRACT) != 0) {
addError(field, "The enum constant " + field.getName() + " must override abstract methods from " + enumBase.getName() + ".");
continue;
}
} else {
ListExpression oldArgs = (ListExpression) field.getInitialExpression();
List<MapEntryExpression> savedMapEntries = new ArrayList<MapEntryExpression>();
for (Expression exp : oldArgs.getExpressions()) {
if (exp instanceof MapEntryExpression) {
savedMapEntries.add((MapEntryExpression) exp);
continue;
}
InnerClassNode inner = null;
if (exp instanceof ClassExpression) {
ClassExpression clazzExp = (ClassExpression) exp;
ClassNode ref = clazzExp.getType();
if (ref instanceof EnumConstantClassNode) {
inner = (InnerClassNode) ref;
}
}
if (inner != null) {
List<MethodNode> baseMethods = enumBase.getMethods();
for (MethodNode methodNode : baseMethods) {
if (!methodNode.isAbstract())
continue;
MethodNode enumConstMethod = inner.getMethod(methodNode.getName(), methodNode.getParameters());
if (enumConstMethod == null || (enumConstMethod.getModifiers() & Opcodes.ACC_ABSTRACT) != 0) {
addError(field, "Can't have an abstract method in enum constant " + field.getName() + ". Implement method '" + methodNode.getTypeDescriptor() + "'.");
}
}
if (inner.getVariableScope() == null) {
enumBase = inner;
/*
* GROOVY-3985: Remove the final modifier from $INIT method in this case
* so that subclasses of enum generated for enum constants (aic) can provide
* their own $INIT method
*/
initMethod.setModifiers(initMethod.getModifiers() & ~Opcodes.ACC_FINAL);
continue;
}
}
args.addExpression(exp);
}
if (!savedMapEntries.isEmpty()) {
args.getExpressions().add(2, new MapExpression(savedMapEntries));
}
}
field.setInitialValueExpression(null);
block.add(new ExpressionStatement(new BinaryExpression(new FieldExpression(field), assign, new StaticMethodCallExpression(enumBase, "$INIT", args))));
arrayInit.add(new FieldExpression(field));
}
if (!isAic) {
if (tempMin != null) {
block.add(new ExpressionStatement(new BinaryExpression(new FieldExpression(minValue), assign, new FieldExpression(tempMin))));
block.add(new ExpressionStatement(new BinaryExpression(new FieldExpression(maxValue), assign, new FieldExpression(tempMax))));
enumClass.addField(minValue);
enumClass.addField(maxValue);
}
block.add(new ExpressionStatement(new BinaryExpression(new FieldExpression(values), assign, new ArrayExpression(enumClass, arrayInit))));
enumClass.addField(values);
}
enumClass.addStaticInitializerStatements(block, true);
}
use of org.codehaus.groovy.syntax.Token in project groovy by apache.
the class EnumVisitor method addMethods.
private static void addMethods(ClassNode enumClass, FieldNode values) {
List<MethodNode> methods = enumClass.getMethods();
boolean hasNext = false;
boolean hasPrevious = false;
for (MethodNode m : methods) {
if (m.getName().equals("next") && m.getParameters().length == 0)
hasNext = true;
if (m.getName().equals("previous") && m.getParameters().length == 0)
hasPrevious = true;
if (hasNext && hasPrevious)
break;
}
ClassNode enumRef = enumClass.getPlainNodeReference();
{
// create values() method
MethodNode valuesMethod = new MethodNode("values", PUBLIC_FS, enumRef.makeArray(), Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null);
valuesMethod.setSynthetic(true);
BlockStatement code = new BlockStatement();
MethodCallExpression cloneCall = new MethodCallExpression(new FieldExpression(values), "clone", MethodCallExpression.NO_ARGUMENTS);
cloneCall.setMethodTarget(values.getType().getMethod("clone", Parameter.EMPTY_ARRAY));
code.addStatement(new ReturnStatement(cloneCall));
valuesMethod.setCode(code);
enumClass.addMethod(valuesMethod);
}
if (!hasNext) {
// create next() method, code:
// Day next() {
// int ordinal = ordinal().next()
// if (ordinal >= values().size()) ordinal = 0
// return values()[ordinal]
// }
Token assign = Token.newSymbol(Types.ASSIGN, -1, -1);
Token ge = Token.newSymbol(Types.COMPARE_GREATER_THAN_EQUAL, -1, -1);
MethodNode nextMethod = new MethodNode("next", Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, enumRef, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null);
nextMethod.setSynthetic(true);
BlockStatement code = new BlockStatement();
BlockStatement ifStatement = new BlockStatement();
ifStatement.addStatement(new ExpressionStatement(new BinaryExpression(new VariableExpression("ordinal"), assign, new ConstantExpression(0))));
code.addStatement(new ExpressionStatement(new DeclarationExpression(new VariableExpression("ordinal"), assign, new MethodCallExpression(new MethodCallExpression(VariableExpression.THIS_EXPRESSION, "ordinal", MethodCallExpression.NO_ARGUMENTS), "next", MethodCallExpression.NO_ARGUMENTS))));
code.addStatement(new IfStatement(new BooleanExpression(new BinaryExpression(new VariableExpression("ordinal"), ge, new MethodCallExpression(new FieldExpression(values), "size", MethodCallExpression.NO_ARGUMENTS))), ifStatement, EmptyStatement.INSTANCE));
code.addStatement(new ReturnStatement(new MethodCallExpression(new FieldExpression(values), "getAt", new VariableExpression("ordinal"))));
nextMethod.setCode(code);
enumClass.addMethod(nextMethod);
}
if (!hasPrevious) {
// create previous() method, code:
// Day previous() {
// int ordinal = ordinal().previous()
// if (ordinal < 0) ordinal = values().size() - 1
// return values()[ordinal]
// }
Token assign = Token.newSymbol(Types.ASSIGN, -1, -1);
Token lt = Token.newSymbol(Types.COMPARE_LESS_THAN, -1, -1);
MethodNode nextMethod = new MethodNode("previous", Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, enumRef, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null);
nextMethod.setSynthetic(true);
BlockStatement code = new BlockStatement();
BlockStatement ifStatement = new BlockStatement();
ifStatement.addStatement(new ExpressionStatement(new BinaryExpression(new VariableExpression("ordinal"), assign, new MethodCallExpression(new MethodCallExpression(new FieldExpression(values), "size", MethodCallExpression.NO_ARGUMENTS), "minus", new ConstantExpression(1)))));
code.addStatement(new ExpressionStatement(new DeclarationExpression(new VariableExpression("ordinal"), assign, new MethodCallExpression(new MethodCallExpression(VariableExpression.THIS_EXPRESSION, "ordinal", MethodCallExpression.NO_ARGUMENTS), "previous", MethodCallExpression.NO_ARGUMENTS))));
code.addStatement(new IfStatement(new BooleanExpression(new BinaryExpression(new VariableExpression("ordinal"), lt, new ConstantExpression(0))), ifStatement, EmptyStatement.INSTANCE));
code.addStatement(new ReturnStatement(new MethodCallExpression(new FieldExpression(values), "getAt", new VariableExpression("ordinal"))));
nextMethod.setCode(code);
enumClass.addMethod(nextMethod);
}
{
// create valueOf
Parameter stringParameter = new Parameter(ClassHelper.STRING_TYPE, "name");
MethodNode valueOfMethod = new MethodNode("valueOf", PS, enumRef, new Parameter[] { stringParameter }, ClassNode.EMPTY_ARRAY, null);
ArgumentListExpression callArguments = new ArgumentListExpression();
callArguments.addExpression(new ClassExpression(enumClass));
callArguments.addExpression(new VariableExpression("name"));
BlockStatement code = new BlockStatement();
code.addStatement(new ReturnStatement(new MethodCallExpression(new ClassExpression(ClassHelper.Enum_Type), "valueOf", callArguments)));
valueOfMethod.setCode(code);
valueOfMethod.setSynthetic(true);
enumClass.addMethod(valueOfMethod);
}
}
use of org.codehaus.groovy.syntax.Token in project groovy by apache.
the class BinaryExpressionTransformer method transformBinaryExpression.
Expression transformBinaryExpression(final BinaryExpression bin) {
if (bin instanceof DeclarationExpression) {
Expression optimized = transformDeclarationExpression(bin);
if (optimized != null) {
return optimized;
}
}
Object[] list = bin.getNodeMetaData(BINARY_EXP_TARGET);
Token operation = bin.getOperation();
int operationType = operation.getType();
Expression rightExpression = bin.getRightExpression();
Expression leftExpression = bin.getLeftExpression();
if (bin instanceof DeclarationExpression && leftExpression instanceof VariableExpression) {
ClassNode declarationType = ((VariableExpression) leftExpression).getOriginType();
if (rightExpression instanceof ConstantExpression) {
ClassNode unwrapper = ClassHelper.getUnwrapper(declarationType);
ClassNode wrapper = ClassHelper.getWrapper(declarationType);
if (!rightExpression.getType().equals(declarationType) && wrapper.isDerivedFrom(ClassHelper.Number_TYPE) && WideningCategories.isDoubleCategory(unwrapper)) {
ConstantExpression constant = (ConstantExpression) rightExpression;
if (constant.getValue() != null) {
return optimizeConstantInitialization(bin, operation, constant, leftExpression, declarationType);
}
}
}
}
if (operationType == Types.EQUAL && leftExpression instanceof PropertyExpression) {
MethodNode directMCT = leftExpression.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET);
if (directMCT != null) {
return transformPropertyAssignmentToSetterCall((PropertyExpression) leftExpression, rightExpression, directMCT);
}
}
if (operationType == Types.COMPARE_EQUAL || operationType == Types.COMPARE_NOT_EQUAL) {
// let's check if one of the operands is the null constant
CompareToNullExpression compareToNullExpression = null;
if (isNullConstant(leftExpression)) {
compareToNullExpression = new CompareToNullExpression(staticCompilationTransformer.transform(rightExpression), operationType == Types.COMPARE_EQUAL);
} else if (isNullConstant(rightExpression)) {
compareToNullExpression = new CompareToNullExpression(staticCompilationTransformer.transform(leftExpression), operationType == Types.COMPARE_EQUAL);
}
if (compareToNullExpression != null) {
compareToNullExpression.setSourcePosition(bin);
return compareToNullExpression;
}
} else if (operationType == Types.KEYWORD_IN) {
return convertInOperatorToTernary(bin, rightExpression, leftExpression);
}
if (list != null) {
if (operationType == Types.COMPARE_TO) {
StaticTypesTypeChooser typeChooser = staticCompilationTransformer.getTypeChooser();
ClassNode classNode = staticCompilationTransformer.getClassNode();
ClassNode leftType = typeChooser.resolveType(leftExpression, classNode);
if (leftType.implementsInterface(ClassHelper.COMPARABLE_TYPE)) {
ClassNode rightType = typeChooser.resolveType(rightExpression, classNode);
if (rightType.implementsInterface(ClassHelper.COMPARABLE_TYPE)) {
Expression left = staticCompilationTransformer.transform(leftExpression);
Expression right = staticCompilationTransformer.transform(rightExpression);
MethodCallExpression call = new MethodCallExpression(left, "compareTo", new ArgumentListExpression(right));
call.setImplicitThis(false);
call.setMethodTarget(COMPARE_TO_METHOD);
call.setSourcePosition(bin);
CompareIdentityExpression compareIdentity = new CompareIdentityExpression(left, right);
compareIdentity.putNodeMetaData(StaticTypesMarker.INFERRED_RETURN_TYPE, ClassHelper.boolean_TYPE);
TernaryExpression result = new TernaryExpression(// a==b
new BooleanExpression(compareIdentity), CONSTANT_ZERO, new TernaryExpression(// a==null
new BooleanExpression(new CompareToNullExpression(left, true)), CONSTANT_MINUS_ONE, new TernaryExpression(// b==null
new BooleanExpression(new CompareToNullExpression(right, true)), CONSTANT_ONE, call)));
compareIdentity.putNodeMetaData(StaticTypesMarker.INFERRED_RETURN_TYPE, ClassHelper.int_TYPE);
result.putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, ClassHelper.int_TYPE);
TernaryExpression expr = (TernaryExpression) result.getFalseExpression();
expr.putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, ClassHelper.int_TYPE);
expr.getFalseExpression().putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, ClassHelper.int_TYPE);
return result;
}
}
}
boolean isAssignment = StaticTypeCheckingSupport.isAssignment(operationType);
MethodCallExpression call;
MethodNode node = (MethodNode) list[0];
String name = (String) list[1];
Expression left = staticCompilationTransformer.transform(leftExpression);
Expression right = staticCompilationTransformer.transform(rightExpression);
BinaryExpression optimized = tryOptimizeCharComparison(left, right, bin);
if (optimized != null) {
optimized.removeNodeMetaData(BINARY_EXP_TARGET);
return transformBinaryExpression(optimized);
}
call = new MethodCallExpression(left, name, new ArgumentListExpression(right));
call.setImplicitThis(false);
call.setMethodTarget(node);
MethodNode adapter = StaticCompilationTransformer.BYTECODE_BINARY_ADAPTERS.get(operationType);
if (adapter != null) {
ClassExpression sba = new ClassExpression(StaticCompilationTransformer.BYTECODE_ADAPTER_CLASS);
// replace with compareEquals
call = new MethodCallExpression(sba, "compareEquals", new ArgumentListExpression(left, right));
call.setMethodTarget(adapter);
call.setImplicitThis(false);
}
call.setSourcePosition(bin);
if (!isAssignment)
return call;
// the method represents the operation type only, and we must add an assignment
return new BinaryExpression(left, Token.newSymbol("=", operation.getStartLine(), operation.getStartColumn()), call);
}
if (bin.getOperation().getType() == Types.EQUAL && leftExpression instanceof TupleExpression && rightExpression instanceof ListExpression) {
// multiple assignment
ListOfExpressionsExpression cle = new ListOfExpressionsExpression();
boolean isDeclaration = bin instanceof DeclarationExpression;
List<Expression> leftExpressions = ((TupleExpression) leftExpression).getExpressions();
List<Expression> rightExpressions = ((ListExpression) rightExpression).getExpressions();
Iterator<Expression> leftIt = leftExpressions.iterator();
Iterator<Expression> rightIt = rightExpressions.iterator();
if (isDeclaration) {
while (leftIt.hasNext()) {
Expression left = leftIt.next();
if (rightIt.hasNext()) {
Expression right = rightIt.next();
BinaryExpression bexp = new DeclarationExpression(left, bin.getOperation(), right);
bexp.setSourcePosition(right);
cle.addExpression(bexp);
}
}
} else {
// (next, result) = [ result, next+result ]
// -->
// def tmp1 = result
// def tmp2 = next+result
// next = tmp1
// result = tmp2
int size = rightExpressions.size();
List<Expression> tmpAssignments = new ArrayList<Expression>(size);
List<Expression> finalAssignments = new ArrayList<Expression>(size);
for (int i = 0; i < Math.min(size, leftExpressions.size()); i++) {
Expression left = leftIt.next();
Expression right = rightIt.next();
VariableExpression tmpVar = new VariableExpression("$tmpVar$" + tmpVarCounter++);
BinaryExpression bexp = new DeclarationExpression(tmpVar, bin.getOperation(), right);
bexp.setSourcePosition(right);
tmpAssignments.add(bexp);
bexp = new BinaryExpression(left, bin.getOperation(), new VariableExpression(tmpVar));
bexp.setSourcePosition(left);
finalAssignments.add(bexp);
}
for (Expression tmpAssignment : tmpAssignments) {
cle.addExpression(tmpAssignment);
}
for (Expression finalAssignment : finalAssignments) {
cle.addExpression(finalAssignment);
}
}
return staticCompilationTransformer.transform(cle);
}
return staticCompilationTransformer.superTransform(bin);
}
Aggregations