下面列出了org.eclipse.lsp4j.RenameParams#org.codehaus.groovy.ast.expr.ConstantExpression 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private Expression annotationValueToExpression (Object value) {
if (value == null || value instanceof String || value instanceof Number || value instanceof Character || value instanceof Boolean)
return new ConstantExpression(value);
if (value instanceof Class)
return new ClassExpression(ClassHelper.makeWithoutCaching((Class<?>)value));
if (value.getClass().isArray()) {
ListExpression elementExprs = new ListExpression();
int len = Array.getLength(value);
for (int i = 0; i != len; ++i)
elementExprs.addExpression(annotationValueToExpression(Array.get(value, i)));
return elementExprs;
}
return null;
}
private void visitAnnotationArrayElement(final Expression expr, final int arrayElementType, final AnnotationVisitor av) {
switch (arrayElementType) {
case 1:
AnnotationNode atAttr = (AnnotationNode) ((AnnotationConstantExpression) expr).getValue();
AnnotationVisitor av2 = av.visitAnnotation(null, BytecodeHelper.getTypeDescription(atAttr.getClassNode()));
visitAnnotationAttributes(atAttr, av2);
av2.visitEnd();
break;
case 2:
av.visit(null, ((ConstantExpression) expr).getValue());
break;
case 3:
av.visit(null, Type.getType(BytecodeHelper.getTypeDescription(expr.getType())));
break;
case 4:
PropertyExpression propExpr = (PropertyExpression) expr;
av.visitEnum(null,
BytecodeHelper.getTypeDescription(propExpr.getObjectExpression().getType()),
String.valueOf(((ConstantExpression) propExpr.getProperty()).getValue()));
break;
}
}
private static Statement createConstructorStatementGuarded(FieldNode fNode, Parameter namedArgsMap, List<String> knownImmutables, List<String> knownImmutableClasses, boolean shouldNullCheck) {
final Expression fieldExpr = propX(varX("this"), fNode.getName());
Expression param = getParam(fNode, namedArgsMap != null);
Statement assignStmt = assignS(fieldExpr, createCheckImmutable(fNode, param, knownImmutables, knownImmutableClasses));
assignStmt = ifElseS(
equalsNullX(param),
shouldNullCheck ? NullCheckASTTransformation.makeThrowStmt(fNode.getName()) : assignNullS(fieldExpr),
assignStmt);
Expression initExpr = fNode.getInitialValueExpression();
final Statement assignInit;
if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression) initExpr).isNullExpression())) {
assignInit = shouldNullCheck ? NullCheckASTTransformation.makeThrowStmt(fNode.getName()) : assignNullS(fieldExpr);
} else {
assignInit = assignS(fieldExpr, createCheckImmutable(fNode, initExpr, knownImmutables, knownImmutableClasses));
}
return assignFieldWithDefault(namedArgsMap, fNode, assignStmt, assignInit);
}
private boolean isEmpty(SourceUnit source) {
if (!source.getAST().getMethods().isEmpty()) {
return false;
}
List<Statement> statements = source.getAST().getStatementBlock().getStatements();
if (statements.size() > 1) {
return false;
}
if (statements.isEmpty()) {
return true;
}
Statement statement = statements.get(0);
if (statement instanceof ReturnStatement) {
ReturnStatement returnStatement = (ReturnStatement) statement;
if (returnStatement.getExpression() instanceof ConstantExpression) {
ConstantExpression constantExpression = (ConstantExpression) returnStatement.getExpression();
if (constantExpression.getValue() == null) {
return true;
}
}
}
return false;
}
public void visitField(FieldNode node) {
if (sameVariableName(leaf, node)) {
if (node.hasInitialExpression()){
Expression expression = node.getInitialExpression();
if (expression instanceof ConstantExpression
&& !expression.getText().equals("null")) { // NOI18N
guessedType = ((ConstantExpression) expression).getType();
} else if (expression instanceof ConstructorCallExpression) {
guessedType = ((ConstructorCallExpression) expression).getType();
} else if (expression instanceof MethodCallExpression) {
int newOffset = ASTUtils.getOffset(doc, expression.getLineNumber(), expression.getColumnNumber());
AstPath newPath = new AstPath(path.root(), newOffset, doc);
guessedType = MethodInference.findCallerType(expression, newPath, doc, newOffset);
}
}
}
}
@Override
public void visitArrayExpression(ArrayExpression visitedArray) {
final ClassNode visitedType = visitedArray.getElementType();
final String visitedName = ElementUtils.getTypeName(visitedType);
if (FindTypeUtils.isCaretOnClassNode(path, doc, cursorOffset)) {
ASTNode currentNode = FindTypeUtils.findCurrentNode(path, doc, cursorOffset);
addOccurrences(visitedType, (ClassNode) currentNode);
} else if (leaf instanceof Variable) {
String varName = removeParentheses(((Variable) leaf).getName());
if (varName.equals(visitedName)) {
occurrences.add(new FakeASTNode(visitedType, visitedName));
}
} else if (leaf instanceof ConstantExpression && leafParent instanceof PropertyExpression) {
if (visitedName.equals(((PropertyExpression) leafParent).getPropertyAsString())) {
occurrences.add(new FakeASTNode(visitedType, visitedName));
}
}
super.visitArrayExpression(visitedArray);
}
public static ClassNode resolveType(AstPath path, FileObject fo) {
final ASTNode leaf = path.leaf();
final ASTNode leafParent = path.leafParent();
if (leaf instanceof VariableExpression) {
return resolveType(path, (VariableExpression) leaf, fo);
}
if (leaf instanceof ConstantExpression) {
if (leafParent instanceof MethodCallExpression) {
return resolveMethodType(path, (MethodCallExpression) leafParent, fo);
}
if (leafParent instanceof PropertyExpression) {
return resolveVariableType(path, (PropertyExpression) leafParent, fo);
}
}
return null;
}
private Statement createConstructorStatementCollection(FieldNode fNode, Parameter namedArgsMap, boolean shouldNullCheck) {
final Expression fieldExpr = propX(varX("this"), fNode.getName());
ClassNode fieldType = fieldExpr.getType();
Expression param = getParam(fNode, namedArgsMap != null);
Statement assignStmt = ifElseS(
isInstanceOfX(param, CLONEABLE_TYPE),
assignS(fieldExpr, cloneCollectionExpr(cloneArrayOrCloneableExpr(param, fieldType), fieldType)),
assignS(fieldExpr, cloneCollectionExpr(param, fieldType)));
assignStmt = ifElseS(
equalsNullX(param),
shouldNullCheck ? NullCheckASTTransformation.makeThrowStmt(fNode.getName()) : assignNullS(fieldExpr),
assignStmt);
Expression initExpr = fNode.getInitialValueExpression();
final Statement assignInit;
if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression) initExpr).isNullExpression())) {
assignInit = shouldNullCheck ? NullCheckASTTransformation.makeThrowStmt(fNode.getName()) : assignNullS(fieldExpr);
} else {
assignInit = assignS(fieldExpr, cloneCollectionExpr(initExpr, fieldType));
}
return assignFieldWithDefault(namedArgsMap, fNode, assignStmt, assignInit);
}
@Override
protected boolean handleTargetMethodCallExpression(MethodCallExpression call) {
ClosureExpression closureExpression = getClosureArgument(call);
List<Expression> otherArgs = getNonClosureArguments(call);
String source = convertClosureToSource(closureExpression);
// parameter order is build(CompilePhase, boolean, String)
otherArgs.add(new ConstantExpression(source));
call.setArguments(new ArgumentListExpression(otherArgs));
call.setMethod(new ConstantExpression("buildFromBlock"));
call.setSpreadSafe(false);
call.setSafe(false);
call.setImplicitThis(false);
return false;
}
/**
* Attempts to call given macroMethod
* @param call MethodCallExpression before the transformation
* @param macroMethod a macro method candidate
* @param macroArguments arguments to pass to
* @return true if call succeeded and current call was transformed
*/
private boolean tryMacroMethod(MethodCallExpression call, ExtensionMethodNode macroMethod, Object[] macroArguments) {
Expression result = (Expression) InvokerHelper.invokeStaticMethod(
macroMethod.getExtensionMethodNode().getDeclaringClass().getTypeClass(),
macroMethod.getName(),
macroArguments
);
if (result == null) {
// Allow macro methods to return null as an indicator that they didn't match a method call
return false;
}
call.setObjectExpression(MACRO_STUB_INSTANCE);
call.setMethod(new ConstantExpression(MACRO_STUB_METHOD_NAME));
// TODO check that we reset everything here
call.setSpreadSafe(false);
call.setSafe(false);
call.setImplicitThis(false);
call.setArguments(result);
call.setGenericsTypes(GenericsType.EMPTY_ARRAY);
return true;
}
protected String getMethodName(final Expression message) {
String methodName = null;
if (message instanceof CastExpression) {
CastExpression msg = (CastExpression) message;
if (msg.getType() == ClassHelper.STRING_TYPE) {
final Expression methodExpr = msg.getExpression();
if (methodExpr instanceof ConstantExpression) {
methodName = methodExpr.getText();
}
}
}
if (methodName == null && message instanceof ConstantExpression) {
ConstantExpression constantExpression = (ConstantExpression) message;
methodName = constantExpression.getText();
}
return methodName;
}
private void attachGroovydocAnnotation(ASTNode node, String docCommentNodeText) {
if (!runtimeGroovydocEnabled) {
return;
}
if (!(node instanceof AnnotatedNode)) {
return;
}
if (!docCommentNodeText.startsWith(RUNTIME_GROOVYDOC_PREFIX)) {
return;
}
AnnotatedNode annotatedNode = (AnnotatedNode) node;
AnnotationNode annotationNode = new AnnotationNode(ClassHelper.make(Groovydoc.class));
annotationNode.addMember(VALUE, new ConstantExpression(docCommentNodeText));
annotatedNode.addAnnotation(annotationNode);
}
private void evaluateLogicalAndExpression(final BinaryExpression expression) {
AsmClassGenerator acg = controller.getAcg();
MethodVisitor mv = controller.getMethodVisitor();
OperandStack operandStack = controller.getOperandStack();
expression.getLeftExpression().visit(acg);
operandStack.doGroovyCast(ClassHelper.boolean_TYPE);
Label falseCase = operandStack.jump(IFEQ);
expression.getRightExpression().visit(acg);
operandStack.doGroovyCast(ClassHelper.boolean_TYPE);
operandStack.jump(IFEQ, falseCase);
ConstantExpression.PRIM_TRUE.visit(acg);
Label trueCase = new Label();
mv.visitJumpInsn(GOTO, trueCase);
mv.visitLabel(falseCase);
ConstantExpression.PRIM_FALSE.visit(acg);
mv.visitLabel(trueCase);
operandStack.remove(1); // have to remove 1 because of the GOTO
}
private Expression transformMapEntryExpression(MapEntryExpression me, ClassNode constructorCallType) {
Expression key = me.getKeyExpression();
Expression value = me.getValueExpression();
ModuleNode module = currentClass.getModule();
if (module != null && key instanceof ConstantExpression) {
Map<String, ImportNode> importNodes = module.getStaticImports();
if (importNodes.containsKey(key.getText())) {
ImportNode importNode = importNodes.get(key.getText());
if (importNode.getType().equals(constructorCallType)) {
String newKey = importNode.getFieldName();
return new MapEntryExpression(new ConstantExpression(newKey), value.transformExpression(this));
}
}
}
return me;
}
static void visitField(ErrorCollecting xform, AnnotationNode node, FieldNode fieldNode) {
final Expression soft = node.getMember("soft");
final Expression init = getInitExpr(xform, fieldNode);
String backingFieldName = "$" + fieldNode.getName();
fieldNode.rename(backingFieldName);
fieldNode.setModifiers(ACC_PRIVATE | ACC_SYNTHETIC | (fieldNode.getModifiers() & (~(ACC_PUBLIC | ACC_PROTECTED))));
PropertyNode pNode = fieldNode.getDeclaringClass().getProperty(backingFieldName);
if (pNode != null) {
fieldNode.getDeclaringClass().getProperties().remove(pNode);
}
if (soft instanceof ConstantExpression && ((ConstantExpression) soft).getValue().equals(true)) {
createSoft(fieldNode, init);
} else {
create(fieldNode, init);
// @Lazy not meaningful with primitive so convert to wrapper if needed
if (ClassHelper.isPrimitiveType(fieldNode.getType())) {
fieldNode.setType(ClassHelper.getWrapper(fieldNode.getType()));
}
}
}
private boolean isEmpty(SourceUnit source) {
if (!source.getAST().getMethods().isEmpty()) {
return false;
}
List<Statement> statements = source.getAST().getStatementBlock().getStatements();
if (statements.size() > 1) {
return false;
}
if (statements.isEmpty()) {
return true;
}
Statement statement = statements.get(0);
if (statement instanceof ReturnStatement) {
ReturnStatement returnStatement = (ReturnStatement) statement;
if (returnStatement.getExpression() instanceof ConstantExpression) {
ConstantExpression constantExpression = (ConstantExpression) returnStatement.getExpression();
if (constantExpression.getValue() == null) {
return true;
}
}
}
return false;
}
private MethodNode addSyntheticMethodForDGSM(MethodNode mn) {
Parameter[] parameters = removeFirstParameter(mn.getParameters());
ArgumentListExpression args = args(parameters);
args.getExpressions().add(0, ConstantExpression.NULL);
MethodNode syntheticMethodNode = controller.getClassNode().addSyntheticMethod(
"dgsm$$" + mn.getParameters()[0].getType().getName().replace(".", "$") + "$$" + mn.getName(),
Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC,
mn.getReturnType(),
parameters,
ClassNode.EMPTY_ARRAY,
block(
returnS(
callX(new ClassExpression(mn.getDeclaringClass()), mn.getName(), args)
)
)
);
syntheticMethodNode.addAnnotation(new AnnotationNode(GENERATED_TYPE));
syntheticMethodNode.addAnnotation(new AnnotationNode(COMPILE_STATIC_TYPE));
return syntheticMethodNode;
}
public void visitConstantExpression(ConstantExpression node) {
pushASTNode(node);
try {
super.visitConstantExpression(node);
} finally {
popASTNode();
}
}
private void addDependencyFromConstantExpression(final ConstantExpression constantExpression) {
final String dependencyString = constantExpression.getText();
final String[] pieces = dependencyString.split(":");
if (pieces.length == 3) {
final String group = pieces[0];
final String name = pieces[1];
final String version = pieces[2];
addDependency(group, name, version);
}
}
/** Handles a groovy BinaryExpression such as foo = true, or bar.baz.foo = true. */
@Override
public void visitBinaryExpression(BinaryExpression binaryExpression) {
if (!methodCallStack.isEmpty()) {
MethodCallExpression call = Iterables.getLast(methodCallStack);
String parent = call.getMethodAsString();
String parentParent = getParentParent();
Expression leftExpression = binaryExpression.getLeftExpression();
Expression rightExpression = binaryExpression.getRightExpression();
if (rightExpression instanceof ConstantExpression
&& (leftExpression instanceof PropertyExpression
|| leftExpression instanceof VariableExpression)) {
String value = rightExpression.getText();
String property = "";
if (leftExpression instanceof PropertyExpression) {
Expression leftPropertyExpression = ((PropertyExpression) leftExpression).getProperty();
if (!(leftPropertyExpression instanceof ConstantExpression)) {
return;
}
property = ((ConstantExpression) leftPropertyExpression).getText();
Expression leftObjectExpression =
((PropertyExpression) leftExpression).getObjectExpression();
parentParent = parent;
parent = getValidParentString(leftObjectExpression);
if (leftObjectExpression instanceof PropertyExpression) {
parentParent =
getValidParentString(
((PropertyExpression) leftObjectExpression).getObjectExpression());
}
} else {
property = ((VariableExpression) leftExpression).getName();
}
checkDslPropertyAssignment(
property, value, parent, parentParent, binaryExpression.getLineNumber());
}
}
super.visitBinaryExpression(binaryExpression);
}
public void visit(ASTNode[] nodes, SourceUnit source) {
if (nodes.length == 0 || !(nodes[0] instanceof ModuleNode)) {
source.getErrorCollector().addError(new SimpleMessage(
"internal error in DetectorTransform", source));
return;
}
ModuleNode module = (ModuleNode)nodes[0];
for (ClassNode clazz : (List<ClassNode>)module.getClasses()) {
FieldNode field = clazz.getField(VERSION_FIELD_NAME);
if (field != null) {
field.setInitialValueExpression(new ConstantExpression(ReleaseInfo.getVersion()));
break;
}
}
}
public static boolean isSameMethod(ExecutableElement javaMethod, MethodCallExpression methodCall) {
ConstantExpression methodName = (ConstantExpression) methodCall.getMethod();
if (javaMethod.getSimpleName().contentEquals(methodName.getText())) {
// not comparing parameter types for now, only their count
// is it even possible to make some check for parameter types?
if (getParameterCount(methodCall) == javaMethod.getParameters().size()) {
return true;
}
}
return false;
}
@Override
public void visitMethodCallExpression(final MethodCallExpression expression) {
if (expression.isImplicitThis() && expression.getMethod() instanceof ConstantExpression) {
ConstantExpression methodNameConstant = (ConstantExpression) expression.getMethod();
String methodName = methodNameConstant.getText();
if (methodName == null) {
throw new GroovyBugError("method name is null");
}
Variable variable = findVariableDeclaration(methodName);
if (variable != null && !(variable instanceof DynamicVariable)) {
checkVariableContextAccess(variable, expression);
}
if (variable instanceof VariableExpression || variable instanceof Parameter) {
VariableExpression object = new VariableExpression(variable);
object.setSourcePosition(methodNameConstant);
expression.setObjectExpression(object);
ConstantExpression method = new ConstantExpression("call");
method.setSourcePosition(methodNameConstant); // important for GROOVY-4344
expression.setImplicitThis(false);
expression.setMethod(method);
}
}
super.visitMethodCallExpression(expression);
}
@Override
public void visitGStringExpression(final GStringExpression expression) {
MethodVisitor mv = controller.getMethodVisitor();
mv.visitTypeInsn(NEW, "org/codehaus/groovy/runtime/GStringImpl");
mv.visitInsn(DUP);
int size = expression.getValues().size();
BytecodeHelper.pushConstant(mv, size);
mv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
for (int i = 0; i < size; i += 1) {
mv.visitInsn(DUP);
BytecodeHelper.pushConstant(mv, i);
expression.getValue(i).visit(this);
controller.getOperandStack().box();
mv.visitInsn(AASTORE);
}
controller.getOperandStack().remove(size);
List<ConstantExpression> strings = expression.getStrings();
size = strings.size();
BytecodeHelper.pushConstant(mv, size);
mv.visitTypeInsn(ANEWARRAY, "java/lang/String");
for (int i = 0; i < size; i += 1) {
mv.visitInsn(DUP);
BytecodeHelper.pushConstant(mv, i);
controller.getOperandStack().pushConstant(strings.get(i));
controller.getOperandStack().box();
mv.visitInsn(AASTORE);
}
controller.getOperandStack().remove(size);
mv.visitMethodInsn(INVOKESPECIAL, "org/codehaus/groovy/runtime/GStringImpl", "<init>", "([Ljava/lang/Object;[Ljava/lang/String;)V", false);
controller.getOperandStack().push(ClassHelper.GSTRING_TYPE);
}
@Override
public void visitConstantExpression(final ConstantExpression expression) {
proposals = Collections.emptyList();
final String fullyQualifiedType = getTypeFor(expression.getText(), inputs);
if (fullyQualifiedType != null && prefix.isEmpty()) {
proposals = getMethodProposals(contentAssistContext, context, inputs, prefix, expression.getText(), fullyQualifiedType);
}
}
private void checkForClassLoader(AnnotationNode node) {
Object val = node.getMember("systemClassLoader");
if (!(val instanceof ConstantExpression)) return;
Object systemClassLoaderObject = ((ConstantExpression)val).getValue();
if (!(systemClassLoaderObject instanceof Boolean)) return;
Boolean systemClassLoader = (Boolean) systemClassLoaderObject;
if (systemClassLoader) loader = ClassLoader.getSystemClassLoader();
}
@Override
public void visitMethod(MethodNode methodNode) {
VariableScope variableScope = methodNode.getVariableScope();
if (FindTypeUtils.isCaretOnClassNode(path, doc, cursorOffset)) {
addMethodOccurrences(methodNode, (ClassNode) FindTypeUtils.findCurrentNode(path, doc, cursorOffset));
} else {
if (leaf instanceof Variable) {
String name = ((Variable) leaf).getName();
// This check is here because we can have method parameter with the same
// name hidding property/field and we don't want to show occurences of these
if (variableScope != null && variableScope.getDeclaredVariable(name) != null) {
return;
}
} else if (leaf instanceof MethodNode) {
if (Methods.isSameMethod(methodNode, (MethodNode) leaf)) {
occurrences.add(methodNode);
}
} else if (leaf instanceof DeclarationExpression) {
VariableExpression variable = ((DeclarationExpression) leaf).getVariableExpression();
if (!variable.isDynamicTyped() && !methodNode.isDynamicReturnType()) {
addMethodOccurrences(methodNode, variable.getType());
}
} else if (leaf instanceof ConstantExpression && leafParent instanceof MethodCallExpression) {
MethodCallExpression methodCallExpression = (MethodCallExpression) leafParent;
if (Methods.isSameMethod(methodNode, methodCallExpression)) {
occurrences.add(methodNode);
}
}
}
super.visitMethod(methodNode);
}
private static int determineCommonArrayType(final List<Expression> values) {
Expression expr = values.get(0);
int arrayElementType = -1;
if (expr instanceof AnnotationConstantExpression) {
arrayElementType = 1;
} else if (expr instanceof ConstantExpression) {
arrayElementType = 2;
} else if (expr instanceof ClassExpression) {
arrayElementType = 3;
} else if (expr instanceof PropertyExpression) {
arrayElementType = 4;
}
return arrayElementType;
}
private void checkStringExceedingMaximumLength(ConstantExpression expression) {
Object value = expression.getValue();
if (value instanceof String) {
String s = (String) value;
if (s.length() > 65535) {
addError("String too long. The given string is " + s.length() + " Unicode code units long, but only a maximum of 65535 is allowed.", expression);
}
}
}
public void testScript() throws Exception {
Iterator<ASTNode> it = getPath("testfiles/GroovyScopeTestcase.groovy", "pri^ntln \"Starting testcase\"").iterator();
assertEquals(ConstantExpression.class, it.next().getClass());
assertEquals(MethodCallExpression.class, it.next().getClass());
assertEquals(ExpressionStatement.class, it.next().getClass());
assertEquals(BlockStatement.class, it.next().getClass());
assertEquals(MethodNode.class, it.next().getClass());
assertEquals(ClassNode.class, it.next().getClass());
assertEquals(ModuleNode.class, it.next().getClass());
assertFalse(it.hasNext());
}