org.codehaus.groovy.ast.ASTNode Java Examples

The following examples show how to use org.codehaus.groovy.ast.ASTNode. 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 Project: netbeans   Author: apache   File: GroovyInstantRenamer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean isRenameAllowed(ParserResult info, int caretOffset, String[] explanationRetValue) {
    LOG.log(Level.FINEST, "isRenameAllowed()"); //NOI18N

    final AstPath path = getPathUnderCaret(ASTUtils.getParseResult(info), caretOffset);

    if (path != null) {
        final ASTNode closest = path.leaf();
        if (closest instanceof Variable) {
            final BaseDocument doc = LexUtilities.getDocument(ASTUtils.getParseResult(info), false);
            if (!FindTypeUtils.isCaretOnClassNode(path, doc, caretOffset)) {
                return true;
            } else {
                explanationRetValue[0] = NbBundle.getMessage(GroovyInstantRenamer.class, "NoInstantRenameOnClassNode");
                return false;
            }
        } else {
            explanationRetValue[0] = NbBundle.getMessage(GroovyInstantRenamer.class, "OnlyRenameLocalVars");
            return false;
        }
    }

    return false;
}
 
Example #2
Source Project: netbeans   Author: apache   File: GroovyDeclarationFinder.java    License: Apache License 2.0 6 votes vote down vote up
private DeclarationLocation getClassDeclaration(GroovyParserResult info, Set<IndexedClass> classes,
        AstPath path, ASTNode closest, GroovyIndex index, BaseDocument doc) {
    final IndexedClass candidate =
        findBestClassMatch(classes, path, closest, index);

    if (candidate != null) {
        IndexedElement com = candidate;
        ASTNode node = ASTUtils.getForeignNode(com);

        DeclarationLocation loc = new DeclarationLocation(com.getFileObject(),
            ASTUtils.getOffset(doc, node.getLineNumber(), node.getColumnNumber()), com);

        return loc;
    }

    return DeclarationLocation.NONE;
}
 
Example #3
Source Project: netbeans   Author: apache   File: VariableScopeVisitor.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source Project: groovy   Author: apache   File: SynchronizedASTTransformation.java    License: Apache License 2.0 6 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    init(nodes, source);
    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    AnnotationNode node = (AnnotationNode) nodes[0];
    if (!MY_TYPE.equals(node.getClassNode())) return;
    String value = getMemberStringValue(node, "value");

    if (parent instanceof MethodNode) {
        MethodNode mNode = (MethodNode) parent;
        if (mNode.isAbstract()) {
            addError("Error during " + MY_TYPE_NAME + " processing: annotation not allowed on abstract method '" + mNode.getName() + "'", mNode);
            return;
        }
        ClassNode cNode = mNode.getDeclaringClass();
        String lockExpr = determineLock(value, cNode, mNode);
        if (lockExpr == null) return;
        Statement origCode = mNode.getCode();
        Statement newCode = new SynchronizedStatement(varX(lockExpr), origCode);
        mNode.setCode(newCode);
    }
}
 
Example #5
Source Project: groovy   Author: apache   File: GenericsUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static ClassNode[] parseClassNodesFromString(final String option, final SourceUnit sourceUnit, final CompilationUnit compilationUnit, final MethodNode mn, final ASTNode usage) {
    try {
        ModuleNode moduleNode = ParserPlugin.buildAST("Dummy<" + option + "> dummy;", compilationUnit.getConfiguration(), compilationUnit.getClassLoader(), null);
        DeclarationExpression dummyDeclaration = (DeclarationExpression) ((ExpressionStatement) moduleNode.getStatementBlock().getStatements().get(0)).getExpression();

        // the returned node is DummyNode<Param1, Param2, Param3, ...)
        ClassNode dummyNode = dummyDeclaration.getLeftExpression().getType();
        GenericsType[] dummyNodeGenericsTypes = dummyNode.getGenericsTypes();
        if (dummyNodeGenericsTypes == null) {
            return null;
        }
        ClassNode[] signature = new ClassNode[dummyNodeGenericsTypes.length];
        for (int i = 0, n = dummyNodeGenericsTypes.length; i < n; i += 1) {
            final GenericsType genericsType = dummyNodeGenericsTypes[i];
            signature[i] = resolveClassNode(sourceUnit, compilationUnit, mn, usage, genericsType.getType());
        }
        return signature;
    } catch (Exception | LinkageError e) {
        sourceUnit.addError(new IncorrectTypeHintException(mn, e, usage.getLineNumber(), usage.getColumnNumber()));
    }
    return null;
}
 
Example #6
Source Project: synopsys-detect   Author: blackducksoftware   File: BuildGradleParser.java    License: Apache License 2.0 6 votes vote down vote up
public Optional<DependencyGraph> parse(final InputStream inputStream) {
    final MutableDependencyGraph dependencyGraph = new MutableMapDependencyGraph();

    try {
        final String sourceContents = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        final AstBuilder astBuilder = new AstBuilder();
        final List<ASTNode> nodes = astBuilder.buildFromString(sourceContents);

        final DependenciesVisitor dependenciesVisitor = new DependenciesVisitor(externalIdFactory);
        for (final ASTNode node : nodes) {
            node.visit(dependenciesVisitor);
        }

        final List<Dependency> dependencies = dependenciesVisitor.getDependencies();
        dependencyGraph.addChildrenToRoot(dependencies);

        return Optional.of(dependencyGraph);
    } catch (final IOException e) {
        logger.error("Could not get the build file contents: " + e.getMessage());
    }

    return Optional.empty();
}
 
Example #7
Source Project: size-analyzer   Author: android   File: GroovyGradleParser.java    License: Apache License 2.0 6 votes vote down vote up
public static GradleContext.Builder parseGradleBuildFile(
    String content,
    int defaultMinSdkVersion,
    @Nullable AndroidPluginVersion defaultAndroidPluginVersion) {
  // We need to have an abstract syntax tree, which is what the conversion phase produces,
  // Anything more will try to semantically understand the groovy code.
  List<ASTNode> astNodes = new AstBuilder().buildFromString(CompilePhase.CONVERSION, content);
  GroovyGradleParser parser =
      new GroovyGradleParser(content, defaultMinSdkVersion, defaultAndroidPluginVersion);

  for (ASTNode node : astNodes) {
    if (node instanceof ClassNode) {
      // class nodes do not implement the visit method, and will throw a runtime exception.
      continue;
    }
    node.visit(parser);
  }
  return parser.getGradleContextBuilder();
}
 
Example #8
Source Project: netbeans   Author: apache   File: AstPath.java    License: Apache License 2.0 6 votes vote down vote up
public AstPath(ASTNode root, int caretOffset, BaseDocument document) {
    try {
        // make sure offset is not higher than document length, see #138353
        int length = document.getLength();
        int offset = length == 0 ? 0 : caretOffset + 1;
        if (length > 0 && offset >= length) {
            offset = length - 1;
        }
        Scanner scanner = new Scanner(document.getText(0, offset));
        int line = 0;
        String lineText = "";
        while (scanner.hasNextLine()) {
            lineText = scanner.nextLine();
            line++;
        }
        int column = lineText.length();

        this.lineNumber = line;
        this.columnNumber = column;

        findPathTo(root, line, column);
    } catch (BadLocationException ble) {
        Exceptions.printStackTrace(ble);
    }
}
 
Example #9
Source Project: netbeans   Author: apache   File: GroovyHintsProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void computeSelectionHints(HintsManager manager, RuleContext context, List<Hint> result, int start, int end) {
    cancelled = false;
    ParserResult parserResult = context.parserResult;
    if (parserResult == null) {
        return;
    }
    
    ASTNode root = ASTUtils.getRoot(parserResult);

    if (root == null) {
        return;
    }
    @SuppressWarnings("unchecked")
    List<GroovySelectionRule> hints = (List)manager.getSelectionHints();

    if (hints.isEmpty()) {
        return;
    }
    
    if (isCancelled()) {
        return;
    }
    
    applyRules(context, hints, start, end, result);
}
 
Example #10
Source Project: netbeans   Author: apache   File: AstPath.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private List<ASTNode> find(ASTNode node, int line, int column) {
    
    assert line >=0 : "line number was negative: " + line;
    assert column >=0 : "column number was negative: " + column;
    assert node != null : "ASTNode should not be null";
    assert node instanceof ModuleNode : "ASTNode must be a ModuleNode";
    
    ModuleNode moduleNode = (ModuleNode) node;
    PathFinderVisitor pathFinder = new PathFinderVisitor(moduleNode.getContext(), line, column);

    for (ClassNode classNode : moduleNode.getClasses()) {
        pathFinder.visitClass(classNode);
    }

    for (MethodNode methodNode : moduleNode.getMethods()) {
        pathFinder.visitMethod(methodNode);
    }

    return pathFinder.getPath();
}
 
Example #11
Source Project: groovy   Author: apache   File: AutoImplementASTTransformation.java    License: Apache License 2.0 6 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    init(nodes, source);
    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    AnnotationNode anno = (AnnotationNode) nodes[0];
    if (!MY_TYPE.equals(anno.getClassNode())) return;

    if (parent instanceof ClassNode) {
        ClassNode cNode = (ClassNode) parent;
        if (!checkNotInterface(cNode, MY_TYPE_NAME)) return;
        ClassNode exception = getMemberClassValue(anno, "exception");
        if (exception != null && Undefined.isUndefinedException(exception)) {
            exception = null;
        }
        String message = getMemberStringValue(anno, "message");
        Expression code = anno.getMember("code");
        if (code != null && !(code instanceof ClosureExpression)) {
            addError("Expected closure value for annotation parameter 'code'. Found " + code, cNode);
            return;
        }
        createMethods(cNode, exception, message, (ClosureExpression) code);
        if (code != null) {
            anno.setMember("code", new ClosureExpression(Parameter.EMPTY_ARRAY, EmptyStatement.INSTANCE));
        }
    }
}
 
Example #12
Source Project: groovy   Author: apache   File: GroovydocManager.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #13
Source Project: netbeans   Author: apache   File: CompletionHandler.java    License: Apache License 2.0 6 votes vote down vote up
private static void printASTNodeInformation(String description, ASTNode node) {

        LOG.log(Level.FINEST, "--------------------------------------------------------");
        LOG.log(Level.FINEST, "{0}", description);

        if (node == null) {
            LOG.log(Level.FINEST, "node == null");
        } else {
            LOG.log(Level.FINEST, "Node.getText()  : {0}", node.getText());
            LOG.log(Level.FINEST, "Node.toString() : {0}", node.toString());
            LOG.log(Level.FINEST, "Node.getClass() : {0}", node.getClass());
            LOG.log(Level.FINEST, "Node.hashCode() : {0}", node.hashCode());


            if (node instanceof ModuleNode) {
                LOG.log(Level.FINEST, "ModuleNode.getClasses() : {0}", ((ModuleNode) node).getClasses());
                LOG.log(Level.FINEST, "SourceUnit.getName() : {0}", ((ModuleNode) node).getContext().getName());
            }
        }

        LOG.log(Level.FINEST, "--------------------------------------------------------");
    }
 
Example #14
Source Project: groovy   Author: apache   File: AsmClassGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public void onLineNumber(final ASTNode statement, final String message) {
    if (statement == null || statement instanceof BlockStatement) return;

    currentASTNode = statement;
    int line = statement.getLineNumber();
    if (line < 0 || (!ASM_DEBUG && line == controller.getLineNumber())) return;

    controller.setLineNumber(line);
    MethodVisitor mv = controller.getMethodVisitor();
    if (mv != null) {
        Label l = new Label();
        mv.visitLabel(l);
        mv.visitLineNumber(line, l);
    }
}
 
Example #15
Source Project: netbeans   Author: apache   File: MethodInference.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tries to infer correct {@link ClassNode} representing type of the caller for
 * the given expression. Typically the given parameter is instance of {@link MethodCallExpression}
 * and in that case the return type of the method call is returned.<br/><br/>
 * 
 * The method also handles method chain and in such case the return type of the
 * last method call should be return.
 * 
 * @param expression
 * @return class type of the caller if found, {@code null} otherwise
 */
@CheckForNull
public static ClassNode findCallerType(@NonNull ASTNode expression, @NonNull AstPath path, BaseDocument baseDocument, int offset) {
    // In case if the method call is chained with another method call
    // For example: someInteger.toString().^
    if (expression instanceof MethodCallExpression) {
        MethodCallExpression methodCall = (MethodCallExpression) expression;

        ClassNode callerType = findCallerType(methodCall.getObjectExpression(), path, baseDocument, offset);
        if (callerType != null) {
            return findReturnTypeFor(callerType, methodCall.getMethodAsString(), methodCall.getArguments(), path, false, baseDocument, offset);
        }
    }

    // In case if the method call is directly on a variable
    if (expression instanceof VariableExpression) {
        int newOffset = ASTUtils.getOffset(baseDocument, expression.getLineNumber(), expression.getColumnNumber());
        AstPath newPath = new AstPath(path.root(), newOffset, baseDocument);
        TypeInferenceVisitor tiv = new TypeInferenceVisitor(((ModuleNode)path.root()).getContext(), newPath, baseDocument, newOffset);
        tiv.collect();
        return tiv.getGuessedType();

        }
    if (expression instanceof ConstantExpression) {
        return ((ConstantExpression) expression).getType();
    }
    if (expression instanceof ClassExpression) {
        return ClassHelper.make(((ClassExpression) expression).getType().getName());
    }

    if (expression instanceof StaticMethodCallExpression) {
        StaticMethodCallExpression staticMethodCall = (StaticMethodCallExpression) expression;

        return findReturnTypeFor(staticMethodCall.getOwnerType(), staticMethodCall.getMethod(), staticMethodCall.getArguments(), path, true, baseDocument, offset);
    }
    return null;
}
 
Example #16
Source Project: groovy   Author: apache   File: PositionConfigureUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static <T extends ASTNode> T configureAST(T astNode, GroovyParser.GroovyParserRuleContext ctx, ASTNode stop) {
    Token start = ctx.getStart();

    astNode.setLineNumber(start.getLine());
    astNode.setColumnNumber(start.getCharPositionInLine() + 1);

    if (asBoolean(stop)) {
        astNode.setLastLineNumber(stop.getLastLineNumber());
        astNode.setLastColumnNumber(stop.getLastColumnNumber());
    } else {
        configureEndPosition(astNode, start);
    }

    return astNode;
}
 
Example #17
Source Project: groovy   Author: apache   File: AutoFinalASTTransformation.java    License: Apache License 2.0 5 votes vote down vote up
private void process(ASTNode[] nodes, final ClassCodeVisitorSupport visitor) {
    candidate = (AnnotatedNode) nodes[1];
    AnnotationNode node = (AnnotationNode) nodes[0];
    if (!MY_TYPE.equals(node.getClassNode())) return;

    if (candidate instanceof ClassNode) {
        processClass((ClassNode) candidate, visitor);
    } else if (candidate instanceof MethodNode) {
        processConstructorOrMethod((MethodNode) candidate, visitor);
    } else if (candidate instanceof FieldNode) {
        processField((FieldNode) candidate, visitor);
    } else if (candidate instanceof DeclarationExpression) {
        processLocalVariable((DeclarationExpression) candidate, visitor);
    }
}
 
Example #18
Source Project: groovy   Author: apache   File: ResolveVisitor.java    License: Apache License 2.0 5 votes vote down vote up
private void resolveOrFail(final ClassNode type, final String msg, final ASTNode node) {
    if (resolve(type)) return;
    if (resolveToInner(type)) return;
    if (resolveToOuterNested(type)) return;

    addError("unable to resolve class " + type.toString(false) + msg, node);
}
 
Example #19
Source Project: groovy   Author: apache   File: ReadWriteLockASTTransformation.java    License: Apache License 2.0 5 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    init(nodes, source);
    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    AnnotationNode node = (AnnotationNode) nodes[0];
    final boolean isWriteLock;
    if (READ_LOCK_TYPE.equals(node.getClassNode())) {
        isWriteLock = false;
    } else if (WRITE_LOCK_TYPE.equals(node.getClassNode())) {
        isWriteLock = true;
    } else {
        throw new GroovyBugError("Internal error: expecting [" + READ_LOCK_TYPE.getName() + ", " + WRITE_LOCK_TYPE.getName() + "]" + " but got: " + node.getClassNode().getName());
    }

    String myTypeName = "@" + node.getClassNode().getNameWithoutPackage();

    String value = getMemberStringValue(node, "value");

    if (parent instanceof MethodNode) {
        MethodNode mNode = (MethodNode) parent;
        ClassNode cNode = mNode.getDeclaringClass();
        FieldNode lockExpr = determineLock(value, cNode, mNode.isStatic(), myTypeName);
        if (lockExpr == null) return;

        // get lock type
        final MethodCallExpression lockType = callX(varX(lockExpr), isWriteLock ? "writeLock" : "readLock");
        lockType.setImplicitThis(false);

        MethodCallExpression acquireLock = callX(lockType, "lock");
        acquireLock.setImplicitThis(false);

        MethodCallExpression releaseLock = callX(lockType, "unlock");
        releaseLock.setImplicitThis(false);

        Statement originalCode = mNode.getCode();

        mNode.setCode(block(
                stmt(acquireLock),
                new TryCatchStatement(originalCode, stmt(releaseLock))));
    }
}
 
Example #20
Source Project: netbeans   Author: apache   File: GroovyDeclarationFinder.java    License: Apache License 2.0 5 votes vote down vote up
IndexedMethod findBestMethodMatch(String name, Set<IndexedMethod> methodSet,
    BaseDocument doc, int astOffset, int lexOffset, AstPath path, ASTNode call, GroovyIndex index) {
    // Make sure that the best fit method actually has a corresponding valid source location
    // and parse tree

    Set<IndexedMethod> methods = new HashSet<IndexedMethod>(methodSet);

    while (!methods.isEmpty()) {
        IndexedMethod method =
            findBestMethodMatchHelper(name, methods, doc, astOffset, lexOffset, path, call, index);
        ASTNode node = method == null ? null : ASTUtils.getForeignNode(method);

        if (node != null) {
            return method;
        }

        if (!methods.contains(method)) {
            // Avoid infinite loop when we somehow don't find the node for
            // the best method and we keep trying it
            methods.remove(methods.iterator().next());
        } else {
            methods.remove(method);
        }
    }

    // Dynamic methods that don't have source (such as the TableDefinition methods "binary", "boolean", etc.
    if (methodSet.size() > 0) {
        return methodSet.iterator().next();
    }

    return null;
}
 
Example #21
Source Project: groovy   Author: apache   File: LazyASTTransformation.java    License: Apache License 2.0 5 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    init(nodes, source);
    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    AnnotationNode node = (AnnotationNode) nodes[0];

    if (parent instanceof FieldNode) {
        final FieldNode fieldNode = (FieldNode) parent;
        visitField(this, node, fieldNode);
    }
}
 
Example #22
Source Project: groovy   Author: apache   File: OptimizingStatementWriter.java    License: Apache License 2.0 5 votes vote down vote up
private FastPathData writeGuards(final StatementMeta meta, final ASTNode node) {
    if (fastPathBlocked || controller.isFastPath() || meta == null || !meta.optimize) return null;

    controller.getAcg().onLineNumber(node, null);

    MethodVisitor mv = controller.getMethodVisitor();
    FastPathData fastPathData = new FastPathData();
    Label slowPath = new Label();

    for (int i = 0, n = guards.length; i < n; i += 1) {
        if (meta.involvedTypes[i]) {
            guards[i].call(mv);
            mv.visitJumpInsn(IFEQ, slowPath);
        }
    }

    // meta class check with boolean holder
    MethodNode mn = controller.getMethodNode();
    if (mn != null) {
        mv.visitFieldInsn(GETSTATIC, controller.getInternalClassName(), Verifier.STATIC_METACLASS_BOOL, "Z");
        mv.visitJumpInsn(IFNE, slowPath);
    }

    // standard metaclass check
    disabledStandardMetaClass.call(mv);
    mv.visitJumpInsn(IFNE, slowPath);

    // other guards here
    mv.visitJumpInsn(GOTO, fastPathData.pathStart);
    mv.visitLabel(slowPath);

    return fastPathData;
}
 
Example #23
Source Project: groovy-language-server   Author: prominic   File: ASTNodeVisitor.java    License: Apache License 2.0 5 votes vote down vote up
public List<ASTNode> getNodes() {
	List<ASTNode> result = new ArrayList<>();
	for (List<ASTNode> nodes : nodesByURI.values()) {
		result.addAll(nodes);
	}
	return result;
}
 
Example #24
Source Project: groovy   Author: apache   File: BindableASTTransformation.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Handles the bulk of the processing, mostly delegating to other methods.
 *
 * @param nodes   the ast nodes
 * @param source  the source unit for the nodes
 */
public void visit(ASTNode[] nodes, SourceUnit source) {
    if (!(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) {
        throw new RuntimeException("Internal error: wrong types: $node.class / $parent.class");
    }
    AnnotationNode node = (AnnotationNode) nodes[0];
    AnnotatedNode parent = (AnnotatedNode) nodes[1];

    if (VetoableASTTransformation.hasVetoableAnnotation(parent)) {
        // VetoableASTTransformation will handle both @Bindable and @Vetoable
        return;
    }

    ClassNode declaringClass = parent.getDeclaringClass();
    if (parent instanceof FieldNode) {
        if ((((FieldNode) parent).getModifiers() & Opcodes.ACC_FINAL) != 0) {
            source.getErrorCollector().addErrorAndContinue("@groovy.beans.Bindable cannot annotate a final property.", node, source);
        }

        if (VetoableASTTransformation.hasVetoableAnnotation(parent.getDeclaringClass())) {
            // VetoableASTTransformation will handle both @Bindable and @Vetoable
            return;
        }
        addListenerToProperty(source, node, declaringClass, (FieldNode) parent);
    } else if (parent instanceof ClassNode) {
        addListenerToClass(source, (ClassNode) parent);
    }
}
 
Example #25
Source Project: groovy-language-server   Author: prominic   File: ASTNodeVisitor.java    License: Apache License 2.0 5 votes vote down vote up
public ASTNode getParent(ASTNode child) {
	if (child == null) {
		return null;
	}
	ASTNodeLookupData data = lookup.get(new ASTLookupKey(child));
	if (data == null) {
		return null;
	}
	return data.parent;
}
 
Example #26
Source Project: groovy   Author: apache   File: PackageScopeASTTransformation.java    License: Apache License 2.0 5 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    init(nodes, source);
    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    AnnotationNode node = (AnnotationNode) nodes[0];
    boolean legacyMode = LEGACY_TYPE_NAME.equals(node.getClassNode().getName());
    if (!MY_TYPE.equals(node.getClassNode()) && !legacyMode) return;

    Expression value = node.getMember("value");
    if (parent instanceof ClassNode) {
        List<groovy.transform.PackageScopeTarget> targets;
        if (value == null) targets = Collections.singletonList(legacyMode ? PackageScopeTarget.FIELDS : PackageScopeTarget.CLASS);
        else targets = determineTargets(value);
        visitClassNode((ClassNode) parent, targets);
        parent.getAnnotations();
    } else {
        if (value != null) {
            addError("Error during " + MY_TYPE_NAME
                    + " processing: " + TARGET_CLASS_NAME + " only allowed at class level.", parent);
            return;
        }
        if (parent instanceof MethodNode) {
            visitMethodNode((MethodNode) parent);
        } else if (parent instanceof FieldNode) {
            visitFieldNode((FieldNode) parent);
        }
    }
}
 
Example #27
Source Project: groovy-language-server   Author: prominic   File: GroovyASTUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static ASTNode getEnclosingNodeOfType(ASTNode offsetNode, Class<? extends ASTNode> nodeType,
        ASTNodeVisitor astVisitor) {
    ASTNode current = offsetNode;
    while (current != null) {
        if (nodeType.isInstance(current)) {
            return current;
        }
        current = astVisitor.getParent(current);
    }
    return null;
}
 
Example #28
Source Project: groovy   Author: apache   File: EqualsAndHashCodeASTTransformation.java    License: Apache License 2.0 5 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    init(nodes, source);
    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    AnnotationNode anno = (AnnotationNode) nodes[0];
    if (!MY_TYPE.equals(anno.getClassNode())) return;

    if (parent instanceof ClassNode) {
        ClassNode cNode = (ClassNode) parent;
        if (!checkNotInterface(cNode, MY_TYPE_NAME)) return;
        boolean callSuper = memberHasValue(anno, "callSuper", true);
        boolean cacheHashCode = memberHasValue(anno, "cache", true);
        boolean useCanEqual = !memberHasValue(anno, "useCanEqual", false);
        if (callSuper && cNode.getSuperClass().getName().equals("java.lang.Object")) {
            addError("Error during " + MY_TYPE_NAME + " processing: callSuper=true but '" + cNode.getName() + "' has no super class.", anno);
        }
        boolean includeFields = memberHasValue(anno, "includeFields", true);
        List<String> excludes = getMemberStringList(anno, "excludes");
        List<String> includes = getMemberStringList(anno, "includes");
        final boolean allNames = memberHasValue(anno, "allNames", true);
        final boolean allProperties = memberHasValue(anno, "allProperties", true);
        if (!checkIncludeExcludeUndefinedAware(anno, excludes, includes, MY_TYPE_NAME)) return;
        if (!checkPropertyList(cNode, includes, "includes", anno, MY_TYPE_NAME, includeFields)) return;
        if (!checkPropertyList(cNode, excludes, "excludes", anno, MY_TYPE_NAME, includeFields)) return;
        createHashCode(cNode, cacheHashCode, includeFields, callSuper, excludes, includes, allNames, allProperties);
        createEquals(cNode, includeFields, callSuper, useCanEqual, excludes, includes, allNames, allProperties);
    }
}
 
Example #29
Source Project: pushfish-android   Author: PushFish   File: DetectorTransform.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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;
    }
  }
}
 
Example #30
Source Project: powsybl-core   Author: powsybl   File: AstUtilTest.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void visit(ASTNode[] astNodes, SourceUnit sourceUnit) {
    ModuleNode ast = sourceUnit.getAST();
    BlockStatement blockStatement = ast.getStatementBlock();
    String ref = "this.print('hello')\n"; // AstNodeToScriptVisitor has hardcoded \n
    assertEquals(ref, AstUtil.toString(blockStatement));
}