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 File: CompletionHandler.java    From netbeans with 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 #2
Source File: GroovyDeclarationFinder.java    From netbeans with 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 File: VariableScopeVisitor.java    From netbeans with 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 File: SynchronizedASTTransformation.java    From groovy with 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 File: GenericsUtils.java    From groovy with 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 File: BuildGradleParser.java    From synopsys-detect with 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 File: GroovyGradleParser.java    From size-analyzer with 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 File: GroovyHintsProvider.java    From netbeans with 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 #9
Source File: AstPath.java    From netbeans with 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 #10
Source File: AutoImplementASTTransformation.java    From groovy with 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 #11
Source File: GroovydocManager.java    From groovy with 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 #12
Source File: AstPath.java    From netbeans with 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 #13
Source File: GroovyInstantRenamer.java    From netbeans with 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 #14
Source File: GroovyDeclarationFinder.java    From netbeans with 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 #15
Source File: LazyASTTransformation.java    From groovy with 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 #16
Source File: OptimizingStatementWriter.java    From groovy with 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 #17
Source File: AutoFinalASTTransformation.java    From groovy with 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 File: FindAndroidVisitor.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
public static final boolean visit(File buildGradle) throws FileNotFoundException, IOException {
    AstBuilder builder = new AstBuilder();
    List<ASTNode> nodes = builder.buildFromString(IOUtils.toString(new FileInputStream(buildGradle), "UTF-8"));
    FindAndroidVisitor visitor = new FindAndroidVisitor();
    for (ASTNode node : nodes) {
        node.visit(visitor);
    }
    return visitor.androidProject;
}
 
Example #19
Source File: PositionConfigureUtils.java    From groovy with 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 #20
Source File: MethodInference.java    From netbeans with 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 #21
Source File: EqualsAndHashCodeASTTransformation.java    From groovy with 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 #22
Source File: ASTTransformationVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the annotation to the internal target list if a match is found.
 *
 * @param node the node to be processed
 */
public void visitAnnotations(final AnnotatedNode node) {
    super.visitAnnotations(node);
    for (AnnotationNode annotation : distinctAnnotations(node)) {
        if (transforms.containsKey(annotation)) {
            targetNodes.add(new ASTNode[]{annotation, node});
        }
    }
}
 
Example #23
Source File: BaseScriptASTTransformation.java    From groovy with 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 (!MY_TYPE.equals(node.getClassNode())) return;

    if (parent instanceof DeclarationExpression) {
        changeBaseScriptTypeFromDeclaration((DeclarationExpression) parent, node);
    } else if (parent instanceof ImportNode || parent instanceof PackageNode) {
        changeBaseScriptTypeFromPackageOrImport(source, parent, node);
    } else if (parent instanceof ClassNode) {
        changeBaseScriptTypeFromClass((ClassNode) parent, node);
    }
}
 
Example #24
Source File: DetectorTransform.java    From pushfish-android with 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 #25
Source File: AsmClassGenerator.java    From groovy with 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 #26
Source File: AstUtilTest.java    From powsybl-core with 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));
}
 
Example #27
Source File: CompletionItem.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public MetaMethodItem(Class clz, MetaMethod method, int anchorOffset, boolean isGDK, boolean nameOnly) {
    super(null, anchorOffset);
    this.method = method;
    this.isGDK = isGDK;
    this.nameOnly = nameOnly;

    // This is an artificial, new ElementHandle which has no real
    // equivalent in the AST. It's used to match the one passed to super.document()
    methodElement = new ASTMethod(new ASTNode(), clz, method, isGDK);
}
 
Example #28
Source File: CompletionContext.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private AstPath getPath(ParserResult parseResult, BaseDocument doc, int astOffset) {
    ASTNode root = ASTUtils.getRoot(parseResult);

    // in some cases we can not repair the code, therefore root == null
    // therefore we can not complete. See # 131317
    if (root == null) {
        return null;
    }
    return new AstPath(root, astOffset, doc);
}
 
Example #29
Source File: VerifierCodeVisitorTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void assertInvalidName(String name) {
    try {
        VerifierCodeVisitor.assertValidIdentifier(name, "variable name", new ASTNode());
        fail("Should have thrown exception due to invalid name: " + name);
    }
    catch (RuntimeParserException e) {
        System.out.println("Caught invalid exception: " + e);
    }
}
 
Example #30
Source File: AstPath.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public ASTNode leafParent() {
    if (path.size() < 2) {
        return null;
    } else {
        return path.get(path.size() - 2);
    }
}