org.codehaus.groovy.ast.ConstructorNode Java Examples
The following examples show how to use
org.codehaus.groovy.ast.ConstructorNode.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NullCheckASTTransformation.java From groovy with Apache License 2.0 | 6 votes |
@Override public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode anno = (AnnotationNode) nodes[0]; if (!NULL_CHECK_TYPE.equals(anno.getClassNode())) return; boolean includeGenerated = isIncludeGenerated(anno); if (parent instanceof ClassNode) { ClassNode cNode = (ClassNode) parent; if (!checkNotInterface(cNode, NULL_CHECK_NAME)) return; for (ConstructorNode cn : cNode.getDeclaredConstructors()) { adjustMethod(cn, includeGenerated); } for (MethodNode mn : cNode.getAllDeclaredMethods()) { adjustMethod(mn, includeGenerated); } } else if (parent instanceof MethodNode) { // handles constructor case too adjustMethod((MethodNode) parent, false); } }
Example #2
Source File: GroovyVirtualSourceProvider.java From netbeans with Apache License 2.0 | 6 votes |
private void genConstructor(ClassNode clazz, ConstructorNode constructorNode, PrintWriter out) { // <netbeans> if (constructorNode.isSynthetic()) { return; } // </netbeans> // printModifiers(out, constructorNode.getModifiers()); out.print("public "); // temporary hack out.print(clazz.getNameWithoutPackage()); printParams(constructorNode, out); ConstructorCallExpression constrCall = getConstructorCallExpression(constructorNode); if (constrCall == null || !constrCall.isSpecialCall()) { out.println(" {}"); } else { out.println(" {"); genSpecialConstructorArgs(out, constructorNode, constrCall); out.println("}"); } }
Example #3
Source File: GroovyVirtualSourceProvider.java From netbeans with Apache License 2.0 | 6 votes |
private ConstructorCallExpression getConstructorCallExpression( ConstructorNode constructorNode) { Statement code = constructorNode.getCode(); if (!(code instanceof BlockStatement)) { return null; } BlockStatement block = (BlockStatement) code; List<Statement> stats = block.getStatements(); if (stats == null || stats.isEmpty()) { return null; } Statement stat = stats.get(0); if (!(stat instanceof ExpressionStatement)) { return null; } Expression expr = ((ExpressionStatement) stat).getExpression(); if (!(expr instanceof ConstructorCallExpression)) { return null; } return (ConstructorCallExpression) expr; }
Example #4
Source File: GroovyVirtualSourceProvider.java From netbeans with Apache License 2.0 | 6 votes |
private Parameter[] selectAccessibleConstructorFromSuper(ConstructorNode node) { ClassNode type = node.getDeclaringClass(); ClassNode superType = type.getSuperClass(); boolean hadPrivateConstructor = false; for (ConstructorNode c : superType.getDeclaredConstructors()) { // Only look at things we can actually call if (c.isPublic() || c.isProtected()) { return c.getParameters(); } } // fall back for parameterless constructor if (superType.isPrimaryClassNode()) { return Parameter.EMPTY_ARRAY; } return null; }
Example #5
Source File: EnumCompletionVisitor.java From groovy with Apache License 2.0 | 6 votes |
/** * Add map and no-arg constructor or mirror those of the superclass (i.e. base enum). */ private static void addImplicitConstructors(ClassNode enumClass, boolean aic) { if (aic) { ClassNode sn = enumClass.getSuperClass(); List<ConstructorNode> sctors = new ArrayList<ConstructorNode>(sn.getDeclaredConstructors()); if (sctors.isEmpty()) { addMapConstructors(enumClass); } else { for (ConstructorNode constructorNode : sctors) { ConstructorNode init = new ConstructorNode(ACC_PUBLIC, constructorNode.getParameters(), ClassNode.EMPTY_ARRAY, new BlockStatement()); enumClass.addConstructor(init); } } } else { addMapConstructors(enumClass); } }
Example #6
Source File: Verifier.java From groovy with Apache License 2.0 | 6 votes |
protected void addInitialization(final ClassNode node) { boolean addSwapInit = moveOptimizedConstantsInitialization(node); for (ConstructorNode cn : node.getDeclaredConstructors()) { addInitialization(node, cn); } if (addSwapInit) { BytecodeSequence seq = new BytecodeSequence(new BytecodeInstruction() { @Override public void visit(MethodVisitor mv) { mv.visitMethodInsn(INVOKESTATIC, BytecodeHelper.getClassInternalName(node), SWAP_INIT, "()V", false); } }); List<Statement> swapCall = new ArrayList<>(1); swapCall.add(seq); node.addStaticInitializerStatements(swapCall, true); } }
Example #7
Source File: Verifier.java From groovy with Apache License 2.0 | 6 votes |
protected void addConstructor(Parameter[] newParams, ConstructorNode ctor, Statement code, ClassNode type) { ConstructorNode newConstructor = type.addConstructor(ctor.getModifiers(), newParams, ctor.getExceptions(), code); newConstructor.putNodeMetaData(DEFAULT_PARAMETER_GENERATED, Boolean.TRUE); markAsGenerated(type, newConstructor); // TODO: Copy annotations, etc.? // set anon. inner enclosing method reference code.visit(new CodeVisitorSupport() { @Override public void visitConstructorCallExpression(ConstructorCallExpression call) { if (call.isUsingAnonymousInnerClass()) { call.getType().setEnclosingMethod(newConstructor); } super.visitConstructorCallExpression(call); } }); }
Example #8
Source File: VariableScopeVisitor.java From netbeans with Apache License 2.0 | 6 votes |
@Override public void visitConstructorCallExpression(ConstructorCallExpression call) { // This might happened for constructor call with generics e.g. "new ArrayList<String>()" // In that case we want to highligt only in situation where the caret // is on "String" type, but not if the caret location is on ArrayList if (FindTypeUtils.isCaretOnClassNode(path, doc, cursorOffset)) { ClassNode findingNode = (ClassNode) FindTypeUtils.findCurrentNode(path, doc, cursorOffset); final String callName = ElementUtils.getNameWithoutPackage(call); final String findingNodeName = ElementUtils.getNameWithoutPackage(findingNode); if (!callName.equals(findingNodeName)) { addOccurrences(call.getType(), findingNode); } } else { if (leaf instanceof ConstructorNode) { ConstructorNode constructor = (ConstructorNode) leaf; if (Methods.isSameConstructor(constructor, call)) { occurrences.add(call); } } else if (leaf instanceof ConstructorCallExpression) { if (Methods.isSameConstuctor(call, (ConstructorCallExpression) leaf)) { occurrences.add(call); } } } super.visitConstructorCallExpression(call); }
Example #9
Source File: ClassCompletionVerifier.java From groovy with Apache License 2.0 | 6 votes |
private static String getRefDescriptor(ASTNode ref) { if (ref instanceof FieldNode) { FieldNode f = (FieldNode) ref; return "the field "+f.getName()+" "; } else if (ref instanceof PropertyNode) { PropertyNode p = (PropertyNode) ref; return "the property "+p.getName()+" "; } else if (ref instanceof ConstructorNode) { return "the constructor "+ref.getText()+" "; } else if (ref instanceof MethodNode) { return "the method "+ref.getText()+" "; } else if (ref instanceof ClassNode) { return "the super class "+ref+" "; } return "<unknown with class "+ref.getClass()+"> "; }
Example #10
Source File: FieldASTTransformation.java From groovy with Apache License 2.0 | 6 votes |
private void adjustConstructorAndFields(int skipIndex, ClassNode type) { List<ConstructorNode> constructors = type.getDeclaredConstructors(); if (constructors.size() == 1) { ConstructorNode constructor = constructors.get(0); Parameter[] params = constructor.getParameters(); Parameter[] newParams = new Parameter[params.length - 1]; int to = 0; for (int from = 0; from < params.length; from++) { if (from != skipIndex) { newParams[to++] = params[from]; } } type.removeConstructor(constructor); // code doesn't mention the removed param at this point, okay to leave as is addGeneratedConstructor(type, constructor.getModifiers(), newParams, constructor.getExceptions(), constructor.getCode()); type.removeField(variableName); } }
Example #11
Source File: JavaStubGenerator.java From groovy with Apache License 2.0 | 6 votes |
private static boolean noExceptionToAvoid(ConstructorNode fromStub, ConstructorNode fromSuper) { ClassNode[] superExceptions = fromSuper.getExceptions(); if (superExceptions==null || superExceptions.length==0) return true; ClassNode[] stubExceptions = fromStub.getExceptions(); if (stubExceptions==null || stubExceptions.length==0) return false; // if all remaining exceptions are used in the stub we are good outer: for (ClassNode superExc : superExceptions) { for (ClassNode stub : stubExceptions) { if (stub.isDerivedFrom(superExc)) continue outer; } // not found return false; } return true; }
Example #12
Source File: TemplateASTTransformer.java From groovy with Apache License 2.0 | 6 votes |
private void createConstructor(final ClassNode classNode) { Parameter[] params = new Parameter[]{ new Parameter(MarkupTemplateEngine.MARKUPTEMPLATEENGINE_CLASSNODE, "engine"), new Parameter(ClassHelper.MAP_TYPE.getPlainNodeReference(), "model"), new Parameter(ClassHelper.MAP_TYPE.getPlainNodeReference(), "modelTypes"), new Parameter(TEMPLATECONFIG_CLASSNODE, "tplConfig") }; List<Expression> vars = new LinkedList<Expression>(); for (Parameter param : params) { vars.add(new VariableExpression(param)); } ExpressionStatement body = new ExpressionStatement( new ConstructorCallExpression(ClassNode.SUPER, new ArgumentListExpression(vars))); ConstructorNode ctor = new ConstructorNode(Opcodes.ACC_PUBLIC, params, ClassNode.EMPTY_ARRAY, body); classNode.addConstructor(ctor); }
Example #13
Source File: NotYetImplementedASTTransformation.java From groovy with Apache License 2.0 | 6 votes |
public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotationNode anno = (AnnotationNode) nodes[0]; MethodNode methodNode = (MethodNode) nodes[1]; ClassNode exception = getMemberClassValue(anno, "exception"); if (exception == null) { exception = DEFAULT_THROW_TYPE; } ConstructorNode cons = exception.getDeclaredConstructor(new Parameter[]{new Parameter(ClassHelper.STRING_TYPE, "dummy")}); if (cons == null) { addError("Error during @NotYetImplemented processing: supplied exception " + exception.getNameWithoutPackage() + " doesn't have expected String constructor", methodNode); } if (methodNode.getCode() instanceof BlockStatement && !methodNode.getCode().isEmpty()) { // wrap code in try/catch with return for failure path followed by throws for success path TryCatchStatement tryCatchStatement = tryCatchS(methodNode.getCode()); tryCatchStatement.addCatch(catchS(param(CATCH_TYPE, "ignore"), ReturnStatement.RETURN_NULL_OR_VOID)); ThrowStatement throwStatement = throwS(ctorX(exception, args(constX("Method is marked with @NotYetImplemented but passes unexpectedly")))); methodNode.setCode(block(tryCatchStatement, throwStatement)); } }
Example #14
Source File: VisibilityUtils.java From groovy with Apache License 2.0 | 6 votes |
private static Visibility getVisForAnnotation(Class<? extends AnnotatedNode> clazz, AnnotationNode visAnno, String visId) { Map<String, Expression> visMembers = visAnno.getMembers(); if (visMembers == null) return Visibility.UNDEFINED; String id = getMemberStringValue(visAnno, "id", null); if ((id == null && visId != null) || (id != null && !id.equals(visId))) return Visibility.UNDEFINED; Visibility vis = null; if (clazz.equals(ConstructorNode.class)) { vis = getVisibility(visMembers.get("constructor")); } else if (clazz.equals(MethodNode.class)) { vis = getVisibility(visMembers.get("method")); } else if (clazz.equals(ClassNode.class)) { vis = getVisibility(visMembers.get("type")); } if (vis == null || vis == Visibility.UNDEFINED) { vis = getVisibility(visMembers.get("value")); } return vis; }
Example #15
Source File: InheritConstructorsASTTransformation.java From groovy with Apache License 2.0 | 6 votes |
private void processClass(ClassNode cNode, AnnotationNode node) { if (cNode.isInterface()) { addError("Error processing interface '" + cNode.getName() + "'. " + ANNOTATION + " only allowed for classes.", cNode); return; } boolean copyConstructorAnnotations = memberHasValue(node, "constructorAnnotations", true); boolean copyParameterAnnotations = memberHasValue(node, "parameterAnnotations", true); ClassNode sNode = cNode.getSuperClass(); List<AnnotationNode> superAnnotations = sNode.getAnnotations(INHERIT_CONSTRUCTORS_TYPE); if (superAnnotations.size() == 1) { // We need @InheritConstructors from parent classes processed first // so force that order here. The transformation is benign on an already // processed node so processing twice in any order won't matter bar // a very small time penalty. processClass(sNode, node); } for (ConstructorNode cn : sNode.getDeclaredConstructors()) { addConstructorUnlessAlreadyExisting(cNode, cn, copyConstructorAnnotations, copyParameterAnnotations); } }
Example #16
Source File: DummyClassGenerator.java From groovy with Apache License 2.0 | 5 votes |
public void visitConstructor(ConstructorNode node) { visitParameters(node, node.getParameters()); String methodType = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, node.getParameters()); mv = cv.visitMethod(node.getModifiers(), "<init>", methodType, null, null); mv.visitTypeInsn(NEW, "java/lang/RuntimeException"); mv.visitInsn(DUP); mv.visitLdcInsn("not intended for execution"); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/RuntimeException", "<init>", "(Ljava/lang/String;)V", false); mv.visitInsn(ATHROW); mv.visitMaxs(0, 0); }
Example #17
Source File: Verifier.java From groovy with Apache License 2.0 | 5 votes |
protected void addDefaultConstructor(ClassNode node) { if (!node.getDeclaredConstructors().isEmpty()) return; ConstructorNode constructor = new ConstructorNode(ACC_PUBLIC, new BlockStatement()); constructor.setHasNoRealSourcePosition(true); markAsGenerated(node, constructor); node.addConstructor(constructor); }
Example #18
Source File: InnerClassCompletionVisitor.java From groovy with Apache License 2.0 | 5 votes |
private String getUniqueName(Parameter[] params, ConstructorNode node) { String namePrefix = "$p"; outer: for (int i = 0; i < 100; i++) { namePrefix = namePrefix + "$"; for (Parameter p : params) { if (p.getName().equals(namePrefix)) continue outer; } return namePrefix; } addError("unable to find a unique prefix name for synthetic this reference in inner class constructor", node); return namePrefix; }
Example #19
Source File: InvocationWriter.java From groovy with Apache License 2.0 | 5 votes |
protected String prepareConstructorCall(final ConstructorNode cn) { String owner = BytecodeHelper.getClassInternalName(cn.getDeclaringClass()); MethodVisitor mv = controller.getMethodVisitor(); mv.visitTypeInsn(NEW, owner); mv.visitInsn(DUP); return owner; }
Example #20
Source File: DefaultStrategy.java From groovy with Apache License 2.0 | 5 votes |
private static MethodNode createBuildMethodForMethod(AnnotationNode anno, ClassNode buildee, MethodNode mNode, Parameter[] params) { String buildMethodName = getMemberStringValue(anno, "buildMethodName", "build"); final BlockStatement body = new BlockStatement(); ClassNode returnType; if (mNode instanceof ConstructorNode) { returnType = newClass(buildee); body.addStatement(returnS(ctorX(newClass(mNode.getDeclaringClass()), args(params)))); } else { body.addStatement(returnS(callX(newClass(mNode.getDeclaringClass()), mNode.getName(), args(params)))); returnType = newClass(mNode.getReturnType()); } return new MethodNode(buildMethodName, ACC_PUBLIC, returnType, NO_PARAMS, NO_EXCEPTIONS, body); }
Example #21
Source File: BuilderASTTransformation.java From groovy with Apache License 2.0 | 5 votes |
private boolean checkStatic(MethodNode mNode, String annotationName) { if (!mNode.isStatic() && !mNode.isStaticConstructor() && !(mNode instanceof ConstructorNode)) { addError("Error processing method '" + mNode.getName() + "'. " + annotationName + " not allowed for instance methods.", mNode); return false; } return true; }
Example #22
Source File: UnionTypeClassNode.java From groovy with Apache License 2.0 | 5 votes |
@Override public List<ConstructorNode> getDeclaredConstructors() { List<ConstructorNode> nodes = new LinkedList<ConstructorNode>(); for (ClassNode delegate : delegates) { nodes.addAll(delegate.getDeclaredConstructors()); } return nodes; }
Example #23
Source File: JavaStubGenerator.java From groovy with Apache License 2.0 | 5 votes |
private void printConstructors(PrintWriter out, ClassNode classNode) { @SuppressWarnings("unchecked") List<ConstructorNode> constrs = (List<ConstructorNode>) constructors.clone(); if (constrs != null) { constrs.addAll(classNode.getDeclaredConstructors()); for (ConstructorNode constr : constrs) { printConstructor(out, classNode, constr); } } }
Example #24
Source File: GroovyNodeToStringUtils.java From groovy-language-server with Apache License 2.0 | 5 votes |
public static String constructorToString(ConstructorNode constructorNode, ASTNodeVisitor ast) { StringBuilder builder = new StringBuilder(); builder.append(constructorNode.getDeclaringClass().getName()); builder.append("("); builder.append(parametersToString(constructorNode.getParameters(), ast)); builder.append(")"); return builder.toString(); }
Example #25
Source File: InheritConstructorsASTTransformation.java From groovy with Apache License 2.0 | 5 votes |
private void addConstructorUnlessAlreadyExisting(ClassNode classNode, ConstructorNode consNode, boolean copyConstructorAnnotations, boolean copyParameterAnnotations) { Parameter[] origParams = consNode.getParameters(); if (consNode.isPrivate()) return; Parameter[] params = new Parameter[origParams.length]; Map<String, ClassNode> genericsSpec = createGenericsSpec(classNode); extractSuperClassGenerics(classNode, classNode.getSuperClass(), genericsSpec); List<Expression> theArgs = buildParams(origParams, params, genericsSpec, copyParameterAnnotations); if (isExisting(classNode, params)) return; ConstructorNode added = addGeneratedConstructor(classNode, consNode.getModifiers(), params, consNode.getExceptions(), block(ctorSuperS(args(theArgs)))); if (copyConstructorAnnotations) { added.addAnnotations(copyAnnotatedNodeAnnotations(consNode, ANNOTATION, false)); } }
Example #26
Source File: InvocationWriter.java From groovy with Apache License 2.0 | 5 votes |
protected void finnishConstructorCall(final ConstructorNode cn, final String ownerDescriptor, final int argsToRemove) { String desc = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, cn.getParameters()); MethodVisitor mv = controller.getMethodVisitor(); mv.visitMethodInsn(INVOKESPECIAL, ownerDescriptor, "<init>", desc, false); controller.getOperandStack().remove(argsToRemove); controller.getOperandStack().push(cn.getDeclaringClass()); }
Example #27
Source File: InvocationWriter.java From groovy with Apache License 2.0 | 5 votes |
protected boolean writeAICCall(final ConstructorCallExpression call) { if (!call.isUsingAnonymousInnerClass()) return false; ConstructorNode cn = call.getType().getDeclaredConstructors().get(0); OperandStack os = controller.getOperandStack(); String ownerDescriptor = prepareConstructorCall(cn); List<Expression> args = makeArgumentList(call.getArguments()).getExpressions(); Parameter[] params = cn.getParameters(); // if a this appears as parameter here, then it should be // not static, unless we are in a static method. But since // ACG#visitVariableExpression does the opposite for this case, we // push here an explicit this. This should not have any negative effect // sine visiting a method call or property with implicit this will push // a new value for this again. controller.getCompileStack().pushImplicitThis(true); for (int i = 0, n = params.length; i < n; i += 1) { Parameter p = params[i]; Expression arg = args.get(i); if (arg instanceof VariableExpression) { VariableExpression var = (VariableExpression) arg; loadVariableWithReference(var); } else { arg.visit(controller.getAcg()); } os.doGroovyCast(p.getType()); } controller.getCompileStack().popImplicitThis(); finnishConstructorCall(cn, ownerDescriptor, args.size()); return true; }
Example #28
Source File: JavaStubGenerator.java From groovy with Apache License 2.0 | 5 votes |
private static Parameter[] selectAccessibleConstructorFromSuper(ConstructorNode node) { ClassNode type = node.getDeclaringClass(); ClassNode superType = type.getUnresolvedSuperClass(); Parameter[] bestMatch = null; for (ConstructorNode c : superType.getDeclaredConstructors()) { // Only look at things we can actually call if (!c.isPublic() && !c.isProtected()) continue; Parameter[] parameters = c.getParameters(); // workaround for GROOVY-5859: remove generic type info Parameter[] copy = new Parameter[parameters.length]; for (int i = 0; i < copy.length; i++) { Parameter orig = parameters[i]; copy[i] = new Parameter(orig.getOriginType().getPlainNodeReference(), orig.getName()); } if (noExceptionToAvoid(node,c)) return copy; if (bestMatch==null) bestMatch = copy; } if (bestMatch!=null) return bestMatch; // fall back for parameterless constructor if (superType.isPrimaryClassNode()) { return Parameter.EMPTY_ARRAY; } return null; }
Example #29
Source File: InvocationWriter.java From groovy with Apache License 2.0 | 5 votes |
private void visitSpecialConstructorCall(final ConstructorCallExpression call) { if (controller.getClosureWriter().addGeneratedClosureConstructorCall(call)) return; ClassNode callNode = controller.getClassNode(); if (call.isSuperCall()) callNode = callNode.getSuperClass(); List<ConstructorNode> constructors = sortConstructors(call, callNode); if (!makeDirectConstructorCall(constructors, call, callNode)) { makeMOPBasedConstructorCall(constructors, call, callNode); } }
Example #30
Source File: ClosureWriter.java From groovy with Apache License 2.0 | 5 votes |
protected ConstructorNode addConstructor(final ClosureExpression expression, final Parameter[] localVariableParams, final InnerClassNode answer, final BlockStatement block) { Parameter[] params = new Parameter[2 + localVariableParams.length]; params[0] = new Parameter(ClassHelper.OBJECT_TYPE, OUTER_INSTANCE); params[1] = new Parameter(ClassHelper.OBJECT_TYPE, THIS_OBJECT); System.arraycopy(localVariableParams, 0, params, 2, localVariableParams.length); ConstructorNode constructorNode = answer.addConstructor(ACC_PUBLIC, params, ClassNode.EMPTY_ARRAY, block); constructorNode.setSourcePosition(expression); return constructorNode; }