com.sun.source.tree.ModuleTree Java Examples

The following examples show how to use com.sun.source.tree.ModuleTree. 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: GoToSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static TreePath adjustPathForModuleName(TreePath path) {
    TreePath tp = path;
    while (tp != null && (tp.getLeaf().getKind() == Kind.IDENTIFIER || tp.getLeaf().getKind() == Kind.MEMBER_SELECT)) {
        Tree parent = tp.getParentPath().getLeaf();
        if (parent.getKind() == Kind.MODULE && ((ModuleTree)parent).getName() == tp.getLeaf()) {
            return tp.getParentPath();
        }
        if (parent.getKind() == Kind.REQUIRES && ((RequiresTree)parent).getModuleName() == tp.getLeaf()
                || parent.getKind() == Kind.EXPORTS && ((ExportsTree)parent).getModuleNames() != null && ((ExportsTree)parent).getModuleNames().contains(tp.getLeaf())
                || parent.getKind() == Kind.OPENS && ((OpensTree)parent).getModuleNames() != null && ((OpensTree)parent).getModuleNames().contains(tp.getLeaf())) {
            return tp;
        }
        tp = tp.getParentPath();
    }
    return path;
}
 
Example #2
Source File: ModuleClassPaths.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@NonNull
private static Set<URL> collectRequiredModules(
        @NonNull final ModuleElement module,
        @NullAllowed final ModuleTree moduleTree,
        final boolean transitive,
        final boolean includeTopLevel,
        @NonNull final Map<String,List<URL>> modulesByName) {
    final Set<URL> res = new HashSet<>();
    final Set<ModuleElement> seen = new HashSet<>();
    if (includeTopLevel) {
        final List<URL> moduleLocs = modulesByName.get(module.getQualifiedName().toString());
        if (moduleLocs != null) {
            res.addAll(moduleLocs);
        }
    }
    collectRequiredModulesImpl(module, moduleTree, transitive, !includeTopLevel, modulesByName, seen, res);
    return res;
}
 
Example #3
Source File: ElementScanningTask.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Context visitModule(ModuleTree node, Void p) {
    final ModuleElement module = (ModuleElement) trees.getElement(getCurrentPath());
    if (module != null) {
        ctx.pos.put(module, this.sourcePositions.getStartPosition(cu, node));
        final List<? extends ModuleElement.Directive> de = module.getDirectives();
        final List<? extends DirectiveTree> dt = node.getDirectives();
        for (int i = 0, j = 0; i < de.size() ; i++) {
            if (isImportant(de.get(i))) {
                ctx.directives.put(de.get(i), dt.get(j));
                ctx.pos.put(de.get(i), this.sourcePositions.getStartPosition(cu, dt.get(j)));
                j += 1;
            }
        }
    }
    return super.visitModule(node, p);
}
 
Example #4
Source File: ModuleNames.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@CheckForNull
public static String parseModuleName(
        @NonNull final FileObject moduleInfo) {
    final JavacTaskImpl jt = JavacParser.createJavacTask(
            new ClasspathInfo.Builder(ClassPath.EMPTY).build(),
            null,
            "1.3",  //min sl to prevent validateSourceLevel warning
            null,
            null,
            null,
            null,
            null,
            Collections.singletonList(FileObjects.fileObjectFileObject(
                moduleInfo,
                moduleInfo.getParent(),
                null,
                FileEncodingQuery.getEncoding(moduleInfo))));
        final CompilationUnitTree cu =  jt.parse().iterator().next();
        final List<? extends Tree> typeDecls = cu.getTypeDecls();
        if (!typeDecls.isEmpty()) {
            final Tree typeDecl = typeDecls.get(0);
            if (typeDecl.getKind() == Tree.Kind.MODULE) {
                return ((ModuleTree)typeDecl).getName().toString();
            }
        }
    return null;
}
 
Example #5
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitModule(ModuleTree node, Void unused) {
  for (AnnotationTree annotation : node.getAnnotations()) {
    scan(annotation, null);
    builder.forcedBreak();
  }
  if (node.getModuleType() == ModuleTree.ModuleKind.OPEN) {
    token("open");
    builder.space();
  }
  token("module");
  builder.space();
  scan(node.getName(), null);
  builder.space();
  if (node.getDirectives().isEmpty()) {
    tokenBreakTrailingComment("{", plusTwo);
    builder.blankLineWanted(BlankLineWanted.NO);
    token("}", plusTwo);
  } else {
    builder.open(plusTwo);
    token("{");
    builder.forcedBreak();
    Optional<Tree.Kind> previousDirective = Optional.empty();
    for (DirectiveTree directiveTree : node.getDirectives()) {
      markForPartialFormat();
      builder.blankLineWanted(
          previousDirective.map(k -> !k.equals(directiveTree.getKind())).orElse(false)
              ? BlankLineWanted.YES
              : BlankLineWanted.NO);
      builder.forcedBreak();
      scan(directiveTree, null);
      previousDirective = Optional.of(directiveTree.getKind());
    }
    builder.close();
    builder.forcedBreak();
    token("}");
  }
  return null;
}
 
Example #6
Source File: JavacModuleParser.java    From pro with GNU General Public License v3.0 5 votes vote down vote up
public void visitModule(ModuleTree node, TreeVisitor<?, ?> visitor) {
  var name = qualifiedString(node.getName());
  var flags = node.getModuleType() == ModuleKind.OPEN? ACC_OPEN: 0;
  
  mv = moduleClassVisitor.visitModule(name, flags, null);
  
  node.getDirectives().forEach(n -> accept(visitor, n));
}
 
Example #7
Source File: JavacModuleParser.java    From pro with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("static-method")
public void visitCompilationUnit(CompilationUnitTree node, TreeVisitor<?, ?> visitor) {
  for(var directive: node.getTypeDecls()) {
    if (!(directive instanceof ModuleTree)) {  // skip unnecessary nodes: imports, etc
      continue;
    }
    accept(visitor, directive);
  }
}
 
Example #8
Source File: CodeGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Tree visitModule(ModuleElement e, Void p) {
    ModifiersTree mods = make.Modifiers(e.getModifiers());
    ModuleTree.ModuleKind kind = wc.getElementUtilities().isOpen(e) ? ModuleTree.ModuleKind.OPEN : ModuleTree.ModuleKind.STRONG;
    List<DirectiveTree> directives = new LinkedList<>();
    for (ModuleElement.Directive directive : e.getDirectives()) {
        switch(directive.getKind()) {
            case EXPORTS:
                ModuleElement.ExportsDirective expDirective = (ModuleElement.ExportsDirective)directive;
                directives.add(make.Exports(make.QualIdent(expDirective.getPackage()), constructModuleList(expDirective.getTargetModules())));
                break;
            case OPENS:
                ModuleElement.OpensDirective opensDirective = (ModuleElement.OpensDirective)directive;
                directives.add(make.Opens(make.QualIdent(opensDirective.getPackage()), constructModuleList(opensDirective.getTargetModules())));
                break;
            case PROVIDES:
                ModuleElement.ProvidesDirective provDirective = (ModuleElement.ProvidesDirective)directive;
                directives.add(make.Provides(make.QualIdent(provDirective.getService()), constructTypeList(provDirective.getImplementations())));
                break;
            case REQUIRES:
                ModuleElement.RequiresDirective reqDirective = (ModuleElement.RequiresDirective)directive;
                directives.add(make.Requires(reqDirective.isTransitive(), reqDirective.isStatic(), make.QualIdent(reqDirective.getDependency().getQualifiedName().toString())));
                break;
            case USES:
                ModuleElement.UsesDirective usesDirective = (ModuleElement.UsesDirective)directive;
                directives.add(make.Uses(make.QualIdent(usesDirective.getService())));
                break;
        }
    }
    return addDeprecated(e, make.Module(mods, kind, make.QualIdent(e.getQualifiedName().toString()), directives));
}
 
Example #9
Source File: JavaDocumentationTask.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private TreePath refinePath(final TreePath path) {
    TreePath tp = path;
    Tree last = null;
    while(tp != null) {
        if (tp.getLeaf().getKind() == Tree.Kind.MODULE && ((ModuleTree)tp.getLeaf()).getName() == last) {
            return tp;
        }
        last = tp.getLeaf();
        tp = tp.getParentPath();
    }
    return path;
}
 
Example #10
Source File: TreeNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitModule(ModuleTree tree, List<Node> d) {
    List<Node> below = new ArrayList<Node>();
    
    addCorrespondingElement(below);
    addCorrespondingType(below);
    addCorrespondingComments(below);
    super.visitModule(tree, below);
    
    d.add(new TreeNode(info, getCurrentPath(), below));
    return null;
}
 
Example #11
Source File: ModuleInfoAccessibilityQueryImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NonNull
private static Set<FileObject> readExports(
    @NonNull final FileObject moduleInfo,
    @NonNull final Set<FileObject> roots) {
    final Set<FileObject> exports = new HashSet<>();
    final JavaSource src = JavaSource.forFileObject(moduleInfo);
    if (src != null) {
        try {
            src.runUserActionTask((cc) -> {
                cc.toPhase(JavaSource.Phase.RESOLVED);
                final CompilationUnitTree cu = cc.getCompilationUnit();
                if (cu.getTypeDecls().size() == 1 && cu.getTypeDecls().get(0) instanceof ModuleTree) {
                    final ModuleTree mt = (ModuleTree) cu.getTypeDecls().get(0);
                    final ModuleElement me = (ModuleElement) cc.getTrees().getElement(TreePath.getPath(cu, mt));
                    if (me != null) {
                        for (ModuleElement.Directive directive : me.getDirectives()) {
                            if (directive.getKind() == ModuleElement.DirectiveKind.EXPORTS) {
                                final ModuleElement.ExportsDirective export = (ModuleElement.ExportsDirective) directive;
                                final String pkgName = export.getPackage().getQualifiedName().toString();
                                exports.addAll(findPackage(pkgName, roots));
                            }
                        }
                    }
                }
            }, true);
        } catch (IOException ioe) {
            Exceptions.printStackTrace(ioe);
        }
    }
    return exports;
}
 
Example #12
Source File: UnitTestsCompilerOptionsQueryImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@CheckForNull
private static String getModuleName(@NonNull final FileObject moduleInfo) {
    try {
        final String[] res = new String[1];
        final JavaSource src = JavaSource.forFileObject(moduleInfo);
        if (src != null) {
            src.runUserActionTask((cc) -> {
                cc.toPhase(JavaSource.Phase.PARSED);
                final CompilationUnitTree cu = cc.getCompilationUnit();
                for (Tree decl : cu.getTypeDecls()) {
                    if (decl.getKind().name().equals("MODULE")) {
                        res[0] = ((ModuleTree)decl).getName().toString();
                        break;
                    }
                }
            }, true);
        }
        return res[0];
    } catch (IOException ioe) {
        LOG.log(
                Level.WARNING,
                "Cannot read module declaration in: {0} due to: {1}",   //NOI18N
                new Object[]{
                    FileUtil.getFileDisplayName(moduleInfo),
                    ioe.getMessage()
                });
        return null;
    }
}
 
Example #13
Source File: ModuleInfoSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void addRequires(FileObject moduleInfo, List<String> newModules) {
    final JavaSource src = JavaSource.forFileObject(moduleInfo);
    if (src == null) {
        return;
    }

    Set<String> declaredModuleNames = getDeclaredModules(src);
    Set<String> requiredModuleNames = new LinkedHashSet<>();
    for (String  name : newModules) {
        if (name != null && !declaredModuleNames.contains(name)) {
            requiredModuleNames.add(name);
        }
    }

    log("To be addded modules:", requiredModuleNames); // NOI18N
    if (!requiredModuleNames.isEmpty()) {
        final Set<String> mNames = requiredModuleNames;
        try {
            src.runModificationTask((WorkingCopy copy) -> {
                copy.toPhase(JavaSource.Phase.RESOLVED);
                TreeMaker tm = copy.getTreeMaker();
                ModuleTree modle = (ModuleTree) copy.getCompilationUnit().getTypeDecls().get(0);
                ModuleTree newModle = modle;
                for (String mName : mNames) {
                    newModle = tm.addModuleDirective(newModle, tm.Requires(false, false, tm.QualIdent(mName)));
                }
                copy.rewrite(modle, newModle);
            }).commit();
        } catch (IOException ex) {
            LOG.log(Level.WARNING, null, ex);
        }
    }
}
 
Example #14
Source File: TreeDuplicator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Tree visitModule(ModuleTree tree, Void p) {
    ModuleTree n = make.Module(make.Modifiers(0, tree.getAnnotations()), tree.getModuleType(), tree.getName(), tree.getDirectives());
    model.setType(n, model.getType(tree));
    comments.copyComments(tree, n);
    model.setPos(n, model.getPos(tree));
    return n;
}
 
Example #15
Source File: NewJavaFileWizardIterator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void addRequires(FileObject createdFile, Set<String> requiredModuleNames) throws IOException {
    if (requiredModuleNames == null) {
        requiredModuleNames = new LinkedHashSet<>();
        ClassPath modulePath = ClassPath.getClassPath(createdFile, JavaClassPathConstants.MODULE_COMPILE_PATH);
        for (FileObject root : modulePath.getRoots()) {
            String name = SourceUtils.getModuleName(root.toURL(), true);
            if (name != null) {
                requiredModuleNames.add(name);
            }
        }
    }
    if (!requiredModuleNames.isEmpty()) {
        final JavaSource src = JavaSource.forFileObject(createdFile);
        if (src != null) {
            final Set<String> mNames = requiredModuleNames;
            src.runModificationTask((WorkingCopy copy) -> {
                copy.toPhase(JavaSource.Phase.RESOLVED);
                TreeMaker tm = copy.getTreeMaker();
                ModuleTree modle = (ModuleTree) copy.getCompilationUnit().getTypeDecls().get(0);
                ModuleTree newModle = modle;
                for (String mName : mNames) {
                    newModle = tm.addModuleDirective(newModle, tm.Requires(false, false, tm.QualIdent(mName)));
                }
                copy.rewrite(modle, newModle);
            }).commit();
        }
    }
}
 
Example #16
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public List<? extends TypeMirror> visitModule(ModuleTree node, Object p) {
    return null;
}
 
Example #17
Source File: JavaSourceUtilImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@CheckForNull
public abstract ModuleTree parseModule() throws IOException;
 
Example #18
Source File: JavaSourceUtilImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@CheckForNull
public abstract ModuleElement resolveModule(@NonNull ModuleTree moduleTree) throws IOException;
 
Example #19
Source File: CanInterpretVisitor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Boolean visitModule(ModuleTree node, EvaluationContext p) {
    return Boolean.FALSE;
}
 
Example #20
Source File: DocLint.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override @DefinedBy(Api.COMPILER_TREE)
public Void visitModule(ModuleTree tree, Void ignore) {
    visitDecl(tree, null);
    return super.visitModule(tree, ignore);
}
 
Example #21
Source File: VeryPretty.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
   public void visitModuleDef(JCModuleDecl tree) {
toLeftMargin();
       printAnnotations(tree.mods.annotations);
       if (tree.getModuleType() == ModuleTree.ModuleKind.OPEN) {
           print("open ");
       }
       print("module ");
       print(fullName(tree.qualId));
int old = cs.indentTopLevelClassMembers() ? indent() : out.leftMargin;
int bcol = old;
       switch(cs.getModuleDeclBracePlacement()) {
       case NEW_LINE:
           newline();
           toColExactly(old);
           break;
       case NEW_LINE_HALF_INDENTED:
           newline();
    bcol += (indentSize >> 1);
           toColExactly(bcol);
           break;
       case NEW_LINE_INDENTED:
           newline();
    bcol = out.leftMargin;
           toColExactly(bcol);
           break;
       }
       if (cs.spaceBeforeModuleDeclLeftBrace())
           needSpace();
print('{');
       printInnerCommentsAsTrailing(tree, true);
if (!tree.directives.isEmpty()) {
    blankLines(cs.getBlankLinesAfterModuleHeader());
           boolean firstDirective = true;
           for (JCTree t : tree.directives) {
               printStat(t, true, firstDirective, true, true, false);
               firstDirective = false;
           }
    blankLines(cs.getBlankLinesBeforeModuleClosingBrace());
       } else {
           printEmptyBlockComments(tree, false);
       }
       toColExactly(bcol);
undent(old);
print('}');
   }
 
Example #22
Source File: ModuleUtilities.java    From netbeans with Apache License 2.0 2 votes vote down vote up
/**
 * Parses ModuleElement from the module-info.java file represented by the JavaSource.
 * 
 * @param javaSource JavaSource representing module-info.java file to be parsed
 * @return {@link ModuleElement} of the given module
 * @throws IOException if the module-info.java does not exist or cannot be parsed. 
 */
@CheckForNull
public ModuleTree parseModule() throws IOException {
    return init() ? handle.parseModule() : null;
}
 
Example #23
Source File: ModuleUtilities.java    From netbeans with Apache License 2.0 2 votes vote down vote up
/**
 * Resolves a {@link ModuleTree} into the {@link ModuleElement}.
 * @param moduleTree the {@link ModuleTree} to resolve.
 * @return the resolved {@link ModuleElement} or null
 * @throws IOException in case of IO error.
 * @since 1.49
 */
@CheckForNull
public ModuleElement resolveModule(@NonNull final ModuleTree moduleTree) throws IOException {
    return init() ? handle.resolveModule(moduleTree) : null;
}