org.codehaus.groovy.ast.ModuleNode Java Examples
The following examples show how to use
org.codehaus.groovy.ast.ModuleNode.
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: FixImportsAction.java From netbeans with Apache License 2.0 | 6 votes |
@Override public void run(ResultIterator resultIterator) throws Exception { GroovyParserResult result = ASTUtils.getParseResult(resultIterator.getParserResult()); if (result != null) { ModuleNode rootModule = ASTUtils.getRoot(result); if (rootModule != null) { packageName = rootModule.getPackageName(); } ErrorCollector errorCollector = result.getErrorCollector(); if (errorCollector == null) { return; } List errors = errorCollector.getErrors(); if (errors == null) { return; } collectMissingImports(errors); } }
Example #2
Source File: PowsyblDslAstTransformation.java From powsybl-core with Mozilla Public License 2.0 | 6 votes |
protected void visit(SourceUnit sourceUnit, ClassCodeExpressionTransformer transformer) { LOGGER.trace("Apply AST transformation"); ModuleNode ast = sourceUnit.getAST(); BlockStatement blockStatement = ast.getStatementBlock(); if (DEBUG) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(AstUtil.toString(blockStatement)); } } List<MethodNode> methods = ast.getMethods(); for (MethodNode methodNode : methods) { methodNode.getCode().visit(transformer); } blockStatement.visit(transformer); if (DEBUG) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(AstUtil.toString(blockStatement)); } } }
Example #3
Source File: StaticImportVisitor.java From groovy with Apache License 2.0 | 6 votes |
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; }
Example #4
Source File: GroovyASTUtils.java From groovy-language-server with Apache License 2.0 | 6 votes |
public static Range findAddImportRange(ASTNode offsetNode, ASTNodeVisitor astVisitor) { ModuleNode moduleNode = (ModuleNode) GroovyASTUtils.getEnclosingNodeOfType(offsetNode, ModuleNode.class, astVisitor); if (moduleNode == null) { return new Range(new Position(0, 0), new Position(0, 0)); } ASTNode afterNode = null; if (afterNode == null) { List<ImportNode> importNodes = moduleNode.getImports(); if (importNodes.size() > 0) { afterNode = importNodes.get(importNodes.size() - 1); } } if (afterNode == null) { afterNode = moduleNode.getPackage(); } if (afterNode == null) { return new Range(new Position(0, 0), new Position(0, 0)); } Range nodeRange = GroovyLanguageServerUtils.astNodeToRange(afterNode); Position position = new Position(nodeRange.getEnd().getLine() + 1, 0); return new Range(position, position); }
Example #5
Source File: SourceUnit.java From groovy with Apache License 2.0 | 6 votes |
public ModuleNode buildAST() { if (null != this.ast) { return this.ast; } try { this.ast = parserPlugin.buildAST(this, this.classLoader, this.cst); this.ast.setDescription(this.name); } catch (SyntaxException e) { if (this.ast == null) { // Create a dummy ModuleNode to represent a failed parse - in case a later phase attempts to use the ast this.ast = new ModuleNode(this); } getErrorCollector().addError(new SyntaxErrorMessage(e, this)); } return this.ast; }
Example #6
Source File: TestMethodUtilTest.java From netbeans with Apache License 2.0 | 6 votes |
private ModuleNode createGroovyModuleNode() { final CompilerConfiguration conf = new CompilerConfiguration(); conf.setTargetDirectory(compileDir); final CompilationUnit cu = new CompilationUnit( new GroovyClassLoader( getClass().getClassLoader() ) ); cu.configure(conf); final SourceUnit sn = cu.addSource("AGroovyClass.groovy", groovyScript.toString()); try { cu.compile(); } catch (Exception e) { //this groovy compile bit didn't work when running tests //but did work when debugging them, so odd, but the AST is in //place either way, and is all we need for this this.log(e.getMessage()); } final ModuleNode mn = sn.getAST(); return mn; }
Example #7
Source File: TestMethodUtil.java From netbeans with Apache License 2.0 | 6 votes |
/** * Given a root {@link ModuleNode ModuleNode}, finds and returns the * {@link ClassNode ClassNode} for the given line and column. It is possible * in some situations for this to be null. * * @param root the root ModuleNode * @param line the line * @param col the column * @return the ClassNode for the line and column (cursor) */ public static ClassNode getClassNodeForLineAndColumn(final ModuleNode root, final int line, final int col) { ClassNode ret = null; if (root != null) { final List<ClassNode> classes = root.getClasses(); for (ClassNode cn : classes) { if (isBetweenLinesAndColumns(cn.getLineNumber(), cn.getColumnNumber(), cn.getLastLineNumber(), cn.getLastColumnNumber(), line, col)) { return cn; } } } return ret; }
Example #8
Source File: ImportCustomizer.java From groovy with Apache License 2.0 | 6 votes |
@Override public void call(final SourceUnit source, final GeneratorContext context, final ClassNode classNode) { ModuleNode ast = source.getAST(); // GROOVY-8399: apply import customizations only once per module if (!classNode.getName().equals(ast.getMainClassName())) return; for (Import anImport : imports) { switch (anImport.type) { case regular: ast.addImport(anImport.alias, anImport.classNode); break; case staticImport: ast.addStaticImport(anImport.classNode, anImport.field, anImport.alias); break; case staticStar: ast.addStaticStarImport(anImport.alias, anImport.classNode); break; case star: ast.addStarImport(anImport.star); break; } } }
Example #9
Source File: TestMethodUtil.java From netbeans with Apache License 2.0 | 6 votes |
/** * Gets the Groovy AST ModuleNode associated with the given Source result. * This is currently done with reflection due to the dependency graph of * "Groovy Support" and "Groovy Editor". This is hopefully just temporary * until the modules can be refactored into a better DAG. * * @param r the Result to extract from * @return the ModuleNode if the Result is in fact a "GroovyParserResult", * the sources have been parsed, and the {@link ModuleNode ModuleNode} has * been set. If not set or the wrong "Result" time, then null will be * returned. */ public static ModuleNode extractModuleNode(final Result r) { //below line long to show up properly in enumerations //TODO TestMethodUtil.extractModuleNode refactor "Groovy Support" and "Groovy Editor" to have a better DAG to remove need to use reflection to extract Groovy ModuleNode ModuleNode ret = null; try { //no need to test result type as it will have the method or it won't //and this makes it easier to test final Method getRE = r.getClass().getMethod(GPR_GET_ROOT_ELEMENT); final Object astRoot = getRE.invoke(r); if (astRoot != null) { final Method getMN = astRoot.getClass().getMethod(AST_GET_MODULE_NODE); final ModuleNode lmn = ModuleNode.class.cast(getMN.invoke(astRoot)); ret = lmn; } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { //push it up to the NB caller throw new RuntimeException("The given result doesn't appear to come from parsing a Groovy file.", e); } return ret; }
Example #10
Source File: FindMethodUsagesVisitor.java From netbeans with Apache License 2.0 | 6 votes |
public FindMethodUsagesVisitor(ModuleNode moduleNode, RefactoringElement refactoringElement) { super(moduleNode); assert (refactoringElement instanceof MethodRefactoringElement) : "It was: " + refactoringElement.getClass().getSimpleName(); this.element = (MethodRefactoringElement) refactoringElement; this.methodType = element.getMethodTypeName(); this.methodName = element.getName(); this.methodParams = element.getMethodParameters(); ClasspathInfo cpInfo = GroovyProjectUtil.getClasspathInfoFor(element.getFileObject()); ClassPath cp = cpInfo.getClassPath(ClasspathInfo.PathKind.SOURCE); this.index = GroovyIndex.get(Arrays.asList(cp.getRoots())); // Find all methods with the same name and the same method type final Set<IndexedMethod> possibleMethods = index.getMethods(methodName, methodType, QuerySupport.Kind.EXACT); for (IndexedMethod indexedMethod : possibleMethods) { final boolean sameName = methodName.equals(indexedMethod.getName()); final boolean sameParameters = Methods.isSameList(methodParams, indexedMethod.getParameterTypes()); // Find the exact method we are looking for if (sameName && sameParameters) { this.method = indexedMethod; } } }
Example #11
Source File: FindTypeUsagesVisitor.java From netbeans with Apache License 2.0 | 6 votes |
@Override public void visitImports(ModuleNode node) { for (ImportNode importNode : node.getImports()) { final ClassNode importType = importNode.getType(); if (!importNode.isStar()) { // ImportNode itself doesn't contain line/column information, so we need set them manually importNode.setLineNumber(importType.getLineNumber()); importNode.setColumnNumber(importType.getColumnNumber()); importNode.setLastLineNumber(importType.getLastLineNumber()); importNode.setLastColumnNumber(importType.getLastColumnNumber()); if (isEquals(importNode)) { usages.add(new ASTUtils.FakeASTNode(importNode, importNode.getClassName())); } } } super.visitImports(node); }
Example #12
Source File: GenericsUtils.java From groovy with Apache License 2.0 | 6 votes |
private static ClassNode resolveClassNode(final SourceUnit sourceUnit, final CompilationUnit compilationUnit, final MethodNode mn, final ASTNode usage, final ClassNode parsedNode) { ClassNode dummyClass = new ClassNode("dummy", 0, ClassHelper.OBJECT_TYPE); dummyClass.setModule(new ModuleNode(sourceUnit)); dummyClass.setGenericsTypes(mn.getDeclaringClass().getGenericsTypes()); MethodNode dummyMN = new MethodNode( "dummy", 0, parsedNode, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, EmptyStatement.INSTANCE ); dummyMN.setGenericsTypes(mn.getGenericsTypes()); dummyClass.addMethod(dummyMN); ResolveVisitor visitor = new ResolveVisitor(compilationUnit) { @Override public void addError(final String msg, final ASTNode expr) { sourceUnit.addError(new IncorrectTypeHintException(mn, msg, usage.getLineNumber(), usage.getColumnNumber())); } }; visitor.startResolving(dummyClass, sourceUnit); return dummyMN.getReturnType(); }
Example #13
Source File: CompletionHandler.java From netbeans with Apache License 2.0 | 6 votes |
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 File: GroovyTypeAnalyzer.java From netbeans with Apache License 2.0 | 6 votes |
public Set<ClassNode> getTypes(AstPath path, int astOffset) { ASTNode caller = path.leaf(); if (caller instanceof VariableExpression) { ModuleNode moduleNode = (ModuleNode) path.root(); TypeInferenceVisitor typeVisitor = new TypeInferenceVisitor(moduleNode.getContext(), path, document, astOffset); typeVisitor.collect(); ClassNode guessedType = typeVisitor.getGuessedType(); if (guessedType != null) { return Collections.singleton(guessedType); } } if (caller instanceof MethodCallExpression) { return Collections.singleton(MethodInference.findCallerType(caller, path, document, astOffset)); } return Collections.emptySet(); }
Example #15
Source File: JavaAwareCompilationUnit.java From groovy with Apache License 2.0 | 6 votes |
@Override public void gotoPhase(final int phase) throws CompilationFailedException { super.gotoPhase(phase); // compile Java and clean up if (phase == Phases.SEMANTIC_ANALYSIS && !javaSources.isEmpty()) { for (ModuleNode module : getAST().getModules()) { module.setImportsResolved(false); } try { addJavaCompilationUnits(stubGenerator.getJavaStubCompilationUnitSet()); // add java stubs JavaCompiler compiler = compilerFactory.createCompiler(configuration); compiler.compile(javaSources, this); } finally { if (!keepStubs) stubGenerator.clean(); javaSources.clear(); } } }
Example #16
Source File: GroovyInstantRenamer.java From netbeans with Apache License 2.0 | 6 votes |
private AstPath getPathUnderCaret(GroovyParserResult info, int caretOffset) { ModuleNode rootNode = ASTUtils.getRoot(info); if (rootNode == null) { return null; } int astOffset = ASTUtils.getAstOffset(info, caretOffset); if (astOffset == -1) { return null; } BaseDocument document = LexUtilities.getDocument(info, false); if (document == null) { LOG.log(Level.FINEST, "Could not get BaseDocument. It's null"); //NOI18N return null; } return new AstPath(rootNode, astOffset, document); }
Example #17
Source File: GenericsUtils.java From groovy with Apache License 2.0 | 6 votes |
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 #18
Source File: DetectorTransform.java From Pushjet-Android with BSD 2-Clause "Simplified" License | 5 votes |
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 #19
Source File: GroovyDocParser.java From groovy with Apache License 2.0 | 5 votes |
private Map<String, GroovyClassDoc> parseGroovy(String packagePath, String file, String src) throws RuntimeException { CompilerConfiguration config = new CompilerConfiguration(); config.getOptimizationOptions().put(CompilerConfiguration.GROOVYDOC, true); CompilationUnit compUnit = new CompilationUnit(config); SourceUnit unit = new SourceUnit(file, src, config, null, new ErrorCollector(config)); compUnit.addSource(unit); compUnit.compile(Phases.CONVERSION); ModuleNode root = unit.getAST(); GroovydocVisitor visitor = new GroovydocVisitor(unit, packagePath, links); visitor.visitClass(root.getClasses().get(0)); return visitor.getGroovyClassDocs(); }
Example #20
Source File: FindVariableUsages.java From netbeans with Apache License 2.0 | 5 votes |
public FindVariableUsagesVisitor(ModuleNode moduleNode) { super(moduleNode); assert (element instanceof VariableRefactoringElement) : "Expected VariableRefactoringElement but it was: " + element.getClass().getSimpleName(); // NOI18N final VariableRefactoringElement varElement = (VariableRefactoringElement) element; this.variableType = varElement.getVariableTypeName(); this.variableName = varElement.getVariableName(); }
Example #21
Source File: FindAllUsages.java From netbeans with Apache License 2.0 | 5 votes |
@Override protected List<AbstractFindUsagesVisitor> getVisitors(ModuleNode moduleNode, String defClass) { List<AbstractFindUsagesVisitor> visitors = new ArrayList<AbstractFindUsagesVisitor>(); visitors.add(new FindTypeUsagesVisitor(moduleNode, defClass)); visitors.add(new FindConstructorUsagesVisitor(moduleNode, element)); visitors.add(new FindClassDeclarationVisitor(moduleNode, defClass)); return visitors; }
Example #22
Source File: FindPossibleMethods.java From netbeans with Apache License 2.0 | 5 votes |
@Override public void run(ResultIterator resultIterator) throws Exception { final GroovyParserResult result = ASTUtils.getParseResult(resultIterator.getParserResult()); final ModuleNode moduleNode = result.getRootElement().getModuleNode(); methods.addAll(new MethodCollector(moduleNode, fqn, methodName).collectMethods()); }
Example #23
Source File: TestMethodUtil.java From netbeans with Apache License 2.0 | 5 votes |
public static SingleMethod getTestMethod(final Document doc, final int cursor) { final AtomicReference<SingleMethod> sm = new AtomicReference<>(); if (doc != null) { Source s = Source.create(doc); try { ParserManager.parseWhenScanFinished(Collections.<Source>singleton(s), new UserTask() { @Override public void run(ResultIterator rit) throws Exception { Result r = rit.getParserResult(); //0:line, 1:column final int[] lc = getLineAndColumn(doc.getText(0, doc.getLength()), cursor); final int line = lc[0]; final int col = lc[1]; final ModuleNode root = extractModuleNode(r); final ClassNode cn = getClassNodeForLineAndColumn(root, line, col); final MethodNode mn = getMethodNodeForLineAndColumn(cn, line, col); if (mn != null) { final SingleMethod lsm = new SingleMethod(s.getFileObject(), mn.getName()); sm.set(lsm); } } }); } catch (ParseException e) { throw new RuntimeException(e); } } return sm.get(); }
Example #24
Source File: AbstractFindUsages.java From netbeans with Apache License 2.0 | 5 votes |
@Override public void run(ResultIterator resultIterator) throws Exception { final GroovyParserResult result = ASTUtils.getParseResult(resultIterator.getParserResult()); final ModuleNode moduleNode = result.getRootElement().getModuleNode(); final BaseDocument doc = GroovyProjectUtil.getDocument(result, fo); for (AbstractFindUsagesVisitor visitor : getVisitors(moduleNode, defClass)) { for (ASTNode node : visitor.findUsages()) { if (node.getLineNumber() != -1 && node.getColumnNumber() != -1) { usages.add(new FindUsagesElement(new ClassRefactoringElement(fo, node), doc)); } } } Collections.sort(usages); }
Example #25
Source File: AstPathTest.java From netbeans with Apache License 2.0 | 5 votes |
private AstPath getPath(String relFilePath, final String caretLine) throws Exception { FileObject f = getTestFile(relFilePath); Source source = Source.create(f); final AstPath[] ret = new AstPath[1]; final CountDownLatch latch = new CountDownLatch(1); ParserManager.parse(Collections.singleton(source), new UserTask() { public @Override void run(ResultIterator resultIterator) throws Exception { GroovyParserResult result = ASTUtils.getParseResult(resultIterator.getParserResult()); String text = result.getSnapshot().getText().toString(); int caretDelta = caretLine.indexOf('^'); assertTrue(caretDelta != -1); String realCaretLine = caretLine.substring(0, caretDelta) + caretLine.substring(caretDelta + 1); int lineOffset = text.indexOf(realCaretLine); assertTrue(lineOffset != -1); int caretOffset = lineOffset + caretDelta; ModuleNode moduleNode = result.getRootElement().getModuleNode(); ret[0] = new AstPath(moduleNode, caretOffset, (BaseDocument) result.getSnapshot().getSource().getDocument(true)); latch.countDown(); } }); latch.await(); return ret[0]; }
Example #26
Source File: ASTNodeVisitor.java From groovy-language-server with Apache License 2.0 | 5 votes |
public void visitSourceUnit(SourceUnit unit) { sourceUnit = unit; URI uri = sourceUnit.getSource().getURI(); nodesByURI.put(uri, new ArrayList<>()); classNodesByURI.put(uri, new ArrayList<>()); stack.clear(); ModuleNode moduleNode = unit.getAST(); if (moduleNode != null) { visitModule(moduleNode); } sourceUnit = null; stack.clear(); }
Example #27
Source File: ParserPlugin.java From groovy with Apache License 2.0 | 5 votes |
static ModuleNode buildAST(CharSequence sourceText, CompilerConfiguration config, GroovyClassLoader loader, ErrorCollector errors) throws CompilationFailedException { SourceUnit sourceUnit = new SourceUnit("Script" + System.nanoTime() + ".groovy", sourceText.toString(), config, loader, errors); sourceUnit.parse(); sourceUnit.completePhase(); sourceUnit.nextPhase(); sourceUnit.convert(); return sourceUnit.getAST(); }
Example #28
Source File: ConstraintInputIndexerTest.java From bonita-studio with GNU General Public License v2.0 | 5 votes |
@Test public void should_run_ignore_invalid_module_node() throws Exception { when(groovyCompilationUnit.getModuleNode()).thenReturn(new ModuleNode(SourceUnit.create("unitName", ""))); final ContractInput input = ProcessFactory.eINSTANCE.createContractInput(); input.setName("name"); availableInputs.add(input); assertThat(indexer.run(null).isOK()).isTrue(); assertThat(indexer.getReferencedInputs()).isEmpty(); }
Example #29
Source File: ValidationCodeVisitorSupport.java From bonita-studio with GNU General Public License v2.0 | 5 votes |
public ValidationCodeVisitorSupport(final IValidationContext context, final Expression expression, final ModuleNode node) { dependenciesName = retrieveDependenciesList(expression); okStatus = context.createSuccessStatus(); errorStatus = new MultiStatus(ValidationPlugin.PLUGIN_ID, IStatus.OK, "", null); this.context = context; for (final MethodNode method : node.getMethods()) { declaredMethodsSignature.add(new MethodSignature(method.getName(), method.getParameters().length)); } }
Example #30
Source File: VariableScopeVisitor.java From netbeans with Apache License 2.0 | 5 votes |
@Override public void visitImports(ModuleNode node) { if (FindTypeUtils.isCaretOnClassNode(path, doc, cursorOffset)) { for (ImportNode importNode : node.getImports()) { addOccurrences(importNode.getType(), (ClassNode) FindTypeUtils.findCurrentNode(path, doc, cursorOffset)); } } else { // #233954 if (leaf instanceof ConstantExpression && leafParent instanceof MethodCallExpression) { addAliasOccurrences(node, ((MethodCallExpression) leafParent).getMethodAsString()); } // #234000 if (leaf instanceof VariableExpression) { addAliasOccurrences(node, ((VariableExpression) leaf).getName()); } // For both: #233954 and #234000 if (leaf instanceof BlockStatement) { for (Map.Entry<String, ImportNode> entry : node.getStaticImports().entrySet()) { OffsetRange range = ASTUtils.getNextIdentifierByName(doc, entry.getKey(), cursorOffset); if (range.containsInclusive(cursorOffset)) { occurrences.add(new FakeASTNode(entry.getValue().getType(), entry.getKey())); } } } } super.visitImports(node); }