com.sun.source.tree.Scope Java Examples

The following examples show how to use com.sun.source.tree.Scope. 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: UtilitiesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testParseAndAttributeMultipleStatements2() throws Exception {
    prepareTest("test/Test.java", "package test; public class Test{}");

    Scope s = Utilities.constructScope(info, Collections.<String, TypeMirror>emptyMap());
    Tree result = Utilities.parseAndAttribute(info, "$type $name = $map.get($key); if ($name == null) { $map.put($key, $name = $init); }", s);

    assertTrue(result.getKind().name(), result.getKind() == Kind.BLOCK);

    String golden = "{" +
                    "    $$1$;" +
                    "    $type $name = $map.get($key);" +
                    "    if ($name == null) {" +
                    "        $map.put($key, $name = $init);" +
                    "    }" +
                    "    $$2$;\n" +
                    "}";
    assertEquals(golden.replaceAll("[ \n\r]+", " "), result.toString().replaceAll("[ \n\r]+", " "));
}
 
Example #2
Source File: JavadocCompletionQuery.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean isOfKindAndType(TypeMirror type, Element e, EnumSet<ElementKind> kinds, TypeMirror base, Scope scope, Trees trees, Types types) {
    if (type.getKind() != TypeKind.ERROR && kinds.contains(e.getKind())) {
        if (base == null)
            return true;
        if (types.isSubtype(type, base))
            return true;
    }
    if ((e.getKind().isClass() || e.getKind().isInterface()) && 
        (kinds.contains(ANNOTATION_TYPE) || kinds.contains(CLASS) || kinds.contains(ENUM) || kinds.contains(INTERFACE))) {
        DeclaredType dt = (DeclaredType)e.asType();
        for (Element ee : e.getEnclosedElements())
            if (trees.isAccessible(scope, ee, dt) && isOfKindAndType(ee.asType(), ee, kinds, base, scope, trees, types))
                return true;
    }
    return false;
}
 
Example #3
Source File: UtilitiesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testBrokenPlatform226678() throws Exception {
    prepareTest("test/Test.java", "package test; public class Test{}");

    JavaSource.create(ClasspathInfo.create(ClassPath.EMPTY, ClassPath.EMPTY, ClassPath.EMPTY), info.getFileObject()).runUserActionTask(new Task<CompilationController>() {
        @Override public void run(CompilationController parameter) throws Exception {
            parameter.toPhase(Phase.RESOLVED);
            info = parameter;
        }
    }, true);
    Scope s = Utilities.constructScope(info, Collections.<String, TypeMirror>emptyMap());
    String methodCode = "private int test(int i) { return i; }";
    Tree result = Utilities.parseAndAttribute(info, methodCode, s);

    assertEquals(Kind.METHOD, result.getKind());
    assertEquals(methodCode.replaceAll("[ \n\r]+", " "), result.toString().replaceAll("[ \n\r]+", " ").trim());
}
 
Example #4
Source File: UtilitiesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testParseAndAttributeMultipleClassMembers() throws Exception {
    prepareTest("test/Test.java", "package test; public class Test{}");

    Scope s = Utilities.constructScope(info, Collections.singletonMap("$1", info.getTreeUtilities().parseType("int", info.getTopLevelElements().get(0))));
    String code = "private int i; private int getI() { return i; } private void setI(int i) { this.i = i; }";
    Tree result = Utilities.parseAndAttribute(info, code, s);

    String golden = "class $ {\n" +
                    "    $$1$;\n" +
                    "    private int i;\n" +
                    "    private int getI() {\n" +
                    "        return i;\n" +
                    "    }\n" +
                    "    private void setI(int i) {\n" +
                    "        this.i = i;\n" +
                    "    }\n" +
                    "}";

    assertEquals(golden.replaceAll("[ \n\r]+", " "), result.toString().replaceAll("[ \n\r]+", " ").trim());
}
 
Example #5
Source File: TreeUtilitiesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testDisableAccessRightsCrash() throws Exception {
    ClassPath boot = ClassPathSupport.createClassPath(SourceUtilsTestUtil.getBootClassPath().toArray(new URL[0]));
    FileObject testFile = FileUtil.createData(FileUtil.createMemoryFileSystem().getRoot(), "Test.java");
    try (Writer w = new OutputStreamWriter(testFile.getOutputStream())) {
        w.append("public class Test {}");
    }
    JavaSource js = JavaSource.create(ClasspathInfo.create(boot, ClassPath.EMPTY, ClassPath.EMPTY), testFile);
    js.runUserActionTask(new Task<CompilationController>() {
        @Override
        public void run(CompilationController parameter) throws Exception {
            parameter.toPhase(Phase.RESOLVED);
            TreePath clazzPath = new TreePath(new TreePath(parameter.getCompilationUnit()),
                                              parameter.getCompilationUnit().getTypeDecls().get(0));
            Scope scope = parameter.getTrees().getScope(clazzPath);
            Scope disableScope = parameter.getTreeUtilities().toScopeWithDisabledAccessibilityChecks(scope);
            ExpressionTree et = parameter.getTreeUtilities().parseExpression("1 + 1", new SourcePositions[1]);
            parameter.getTreeUtilities().attributeTree(et, disableScope);
        }
    }, true);
}
 
Example #6
Source File: EqualsHashCodeGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static MethodTree createHashCodeMethod(WorkingCopy wc, Iterable<? extends VariableElement> hashCodeFields, Scope scope) {
    TreeMaker make = wc.getTreeMaker();
    Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC);        

    int startNumber = generatePrimeNumber(2, 10);
    int multiplyNumber = generatePrimeNumber(10, 100);
    List<StatementTree> statements = new ArrayList<>();
    //int hash = <startNumber>;
    statements.add(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "hash", make.PrimitiveType(TypeKind.INT), make.Literal(startNumber))); //NOI18N        
    for (VariableElement ve : hashCodeFields) {
        TypeMirror tm = ve.asType();
        ExpressionTree variableRead = prepareExpression(wc, HASH_CODE_PATTERNS, tm, ve, scope);
        statements.add(make.ExpressionStatement(make.Assignment(make.Identifier("hash"), make.Binary(Tree.Kind.PLUS, make.Binary(Tree.Kind.MULTIPLY, make.Literal(multiplyNumber), make.Identifier("hash")), variableRead)))); //NOI18N
    }
    statements.add(make.Return(make.Identifier("hash"))); //NOI18N        
    BlockTree body = make.Block(statements, false);
    ModifiersTree modifiers = prepareModifiers(wc, mods,make);
    
    return make.Method(modifiers, "hashCode", make.PrimitiveType(TypeKind.INT), Collections.<TypeParameterTree> emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), body, null); //NOI18N
}
 
Example #7
Source File: JavacTrees.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public boolean isAccessible(Scope scope, TypeElement type) {
    if (scope instanceof JavacScope && type instanceof ClassSymbol) {
        Env<AttrContext> env = ((JavacScope) scope).env;
        return resolve.isAccessible(env, (ClassSymbol)type, true);
    } else
        return false;
}
 
Example #8
Source File: UtilitiesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void DtestMultiStatementVarWithModifiers() throws Exception {
    prepareTest("test/Test.java", "package test; public class Test{}");

    Scope s = Utilities.constructScope(info, Collections.<String, TypeMirror>emptyMap());
    Tree result = Utilities.parseAndAttribute(info, "$mods$ $type $name; $name = $init;", s);

    assertTrue(result.getKind().name(), result.getKind() == Kind.BLOCK);

    String golden = "{ $$1$; $mods$$type $name; $name = $init; $$2$; }";
    assertEquals(golden.replaceAll("[ \n\r]+", " "), result.toString().replaceAll("[ \n\r]+", " "));
}
 
Example #9
Source File: UtilitiesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testParseAndAttributeExpressionStatement() throws Exception {
    prepareTest("test/Test.java", "package test; public class Test{}");

    Scope s = Utilities.constructScope(info, Collections.singletonMap("$1", info.getTreeUtilities().parseType("int", info.getTopLevelElements().get(0))));
    Tree result = Utilities.parseAndAttribute(info, "$1 = 1;", s);

    assertTrue(result.getKind().name(), result.getKind() == Kind.EXPRESSION_STATEMENT);
}
 
Example #10
Source File: CompletionFilter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Scope getScope(TreePath tp) {
    if (tp == null) {
        return null;
    }
    return delegate.getScope(tp);
}
 
Example #11
Source File: ScopeTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void verifyLambdaScopeCorrect(final String packageClause) throws Exception {
    JavacTool tool = JavacTool.create();
    JavaFileObject source = new SimpleJavaFileObject(URI.create("mem://Test.java"), Kind.SOURCE) {
        @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return packageClause + SOURCE_CODE;
        }
        @Override public boolean isNameCompatible(String simpleName, Kind kind) {
            return true;
        }
    };
    Iterable<? extends JavaFileObject> fos = Collections.singletonList(source);
    JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, fos);
    final Types types = JavacTypes.instance(((JavacTaskImpl) task).getContext());
    final Trees trees = Trees.instance(task);
    CompilationUnitTree cu = task.parse().iterator().next();

    task.analyze();

    new TreePathScanner<Void, Void>() {
        @Override public Void visitMemberSelect(MemberSelectTree node, Void p) {
            if (node.getIdentifier().contentEquals("correct")) {
                TypeMirror xType = trees.getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
                Scope scope = trees.getScope(getCurrentPath());
                for (Element l : scope.getLocalElements()) {
                    if (!l.getSimpleName().contentEquals("x")) continue;
                    if (!types.isSameType(xType, l.asType())) {
                        throw new IllegalStateException("Incorrect variable type in scope: " + l.asType() + "; should be: " + xType);
                    }
                }
            }
            return super.visitMemberSelect(node, p);
        }
    }.scan(cu, null);
}
 
Example #12
Source File: JavacTrees.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/** @see com.sun.tools.javadoc.ClassDocImpl#findConstructor */
MethodSymbol findConstructor(ClassSymbol tsym, List<Type> paramTypes) {
    for (com.sun.tools.javac.code.Scope.Entry e = tsym.members().lookup(names.init);
            e.scope != null; e = e.next()) {
        if (e.sym.kind == Kinds.MTH) {
            if (hasParameterTypes((MethodSymbol) e.sym, paramTypes)) {
                return (MethodSymbol) e.sym;
            }
        }
    }
    return null;
}
 
Example #13
Source File: JavacTrees.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/** @see com.sun.tools.javadoc.ClassDocImpl#findConstructor */
MethodSymbol findConstructor(ClassSymbol tsym, List<Type> paramTypes) {
    for (com.sun.tools.javac.code.Scope.Entry e = tsym.members().lookup(names.init);
            e.scope != null; e = e.next()) {
        if (e.sym.kind == Kinds.MTH) {
            if (hasParameterTypes((MethodSymbol) e.sym, paramTypes)) {
                return (MethodSymbol) e.sym;
            }
        }
    }
    return null;
}
 
Example #14
Source File: UtilitiesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testAnnotation() throws Exception {
    prepareTest("test/Test.java", "package test; public class Test{}");

    Scope s = Utilities.constructScope(info, Collections.<String, TypeMirror>emptyMap());
    Tree result = Utilities.parseAndAttribute(info, "@$annotation($args$)", s);

    assertTrue(result.getKind().name(), result.getKind() == Kind.ANNOTATION);

    String golden = "@$annotation(value = $args$)";
    assertEquals(golden.replaceAll("[ \n\r]+", " "), result.toString().replaceAll("[ \n\r]+", " "));
}
 
Example #15
Source File: UtilitiesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testParseAndAttributeMethodDeclarationWithMultiparameters() throws Exception {
    prepareTest("test/Test.java", "package test; public class Test{}");

    Scope s = Utilities.constructScope(info, Collections.<String, TypeMirror>emptyMap());
    Tree result = Utilities.parseAndAttribute(info, "public void t($params$) {}", s);

    assertTrue(result.getKind().name(), result.getKind() == Kind.METHOD);

    String golden = " public void t($params$) { }";
    assertEquals(golden.replaceAll("[ \n\r]+", " "), result.toString().replaceAll("[ \n\r]+", " "));
}
 
Example #16
Source File: ScopeTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void verifyLambdaScopeCorrect(final String packageClause) throws Exception {
    JavacTool tool = JavacTool.create();
    JavaFileObject source = new SimpleJavaFileObject(URI.create("mem://Test.java"), Kind.SOURCE) {
        @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return packageClause + SOURCE_CODE;
        }
        @Override public boolean isNameCompatible(String simpleName, Kind kind) {
            return true;
        }
    };
    Iterable<? extends JavaFileObject> fos = Collections.singletonList(source);
    JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, fos);
    final Types types = JavacTypes.instance(((JavacTaskImpl) task).getContext());
    final Trees trees = Trees.instance(task);
    CompilationUnitTree cu = task.parse().iterator().next();

    task.analyze();

    new TreePathScanner<Void, Void>() {
        @Override public Void visitMemberSelect(MemberSelectTree node, Void p) {
            if (node.getIdentifier().contentEquals("correct")) {
                TypeMirror xType = trees.getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
                Scope scope = trees.getScope(getCurrentPath());
                for (Element l : scope.getLocalElements()) {
                    if (!l.getSimpleName().contentEquals("x")) continue;
                    if (!types.isSameType(xType, l.asType())) {
                        throw new IllegalStateException("Incorrect variable type in scope: " + l.asType() + "; should be: " + xType);
                    }
                }
            }
            return super.visitMemberSelect(node, p);
        }
    }.scan(cu, null);
}
 
Example #17
Source File: JavacTrees.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public boolean isAccessible(Scope scope, TypeElement type) {
    if (scope instanceof JavacScope && type instanceof ClassSymbol) {
        Env<AttrContext> env = ((JavacScope) scope).env;
        return resolve.isAccessible(env, (ClassSymbol)type, true);
    } else
        return false;
}
 
Example #18
Source File: JavacTrees.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public boolean isAccessible(Scope scope, TypeElement type) {
    if (scope instanceof JavacScope && type instanceof ClassSymbol) {
        Env<AttrContext> env = ((JavacScope) scope).env;
        return resolve.isAccessible(env, (ClassSymbol)type, true);
    } else
        return false;
}
 
Example #19
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static TypeMirror attributeTree(JavacTaskImpl jti, Tree tree, Scope scope, 
            final List<Diagnostic<? extends JavaFileObject>> errors, @NullAllowed final Diagnostic.Kind filter) {
        Log log = Log.instance(jti.getContext());
        JavaFileObject prev = log.useSource(new DummyJFO());
        Enter enter = Enter.instance(jti.getContext());
        
        Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log) {
            private Diagnostic.Kind f = filter == null ? Diagnostic.Kind.ERROR : filter;
            @Override
            public void report(JCDiagnostic diag) {
                if (diag.getKind().compareTo(f) >= 0) {
                    errors.add(diag);
                }
            }            
        };
//        ArgumentAttr argumentAttr = ArgumentAttr.instance(jti.getContext());
//        ArgumentAttr.LocalCacheContext cacheContext = argumentAttr.withLocalCacheContext();
        try {
//            enter.shadowTypeEnvs(true);
            Attr attr = Attr.instance(jti.getContext());
            Env<AttrContext> env = ((JavacScope) scope).getEnv();
            if (tree instanceof JCTree.JCExpression) {
                return attr.attribExpr((JCTree) tree,env, Type.noType);
            }
            return attr.attribStat((JCTree) tree,env);
        } finally {
//            cacheContext.leave();
            log.useSource(prev);
            log.popDiagnosticHandler(discardHandler);
//            enter.shadowTypeEnvs(false);
        }
    }
 
Example #20
Source File: ScopeTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void verifyLambdaScopeCorrect(final String packageClause) throws Exception {
    JavacTool tool = JavacTool.create();
    JavaFileObject source = new SimpleJavaFileObject(URI.create("mem://Test.java"), Kind.SOURCE) {
        @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return packageClause + SOURCE_CODE;
        }
        @Override public boolean isNameCompatible(String simpleName, Kind kind) {
            return true;
        }
    };
    Iterable<? extends JavaFileObject> fos = Collections.singletonList(source);
    JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, fos);
    final Types types = JavacTypes.instance(((JavacTaskImpl) task).getContext());
    final Trees trees = Trees.instance(task);
    CompilationUnitTree cu = task.parse().iterator().next();

    task.analyze();

    new TreePathScanner<Void, Void>() {
        @Override public Void visitMemberSelect(MemberSelectTree node, Void p) {
            if (node.getIdentifier().contentEquals("correct")) {
                TypeMirror xType = trees.getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
                Scope scope = trees.getScope(getCurrentPath());
                for (Element l : scope.getLocalElements()) {
                    if (!l.getSimpleName().contentEquals("x")) continue;
                    if (!types.isSameType(xType, l.asType())) {
                        throw new IllegalStateException("Incorrect variable type in scope: " + l.asType() + "; should be: " + xType);
                    }
                }
            }
            return super.visitMemberSelect(node, p);
        }
    }.scan(cu, null);
}
 
Example #21
Source File: JavacTrees.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override @DefinedBy(Api.COMPILER_TREE)
public boolean isAccessible(Scope scope, TypeElement type) {
    if (scope instanceof JavacScope && type instanceof ClassSymbol) {
        Env<AttrContext> env = ((JavacScope) scope).env;
        return resolve.isAccessible(env, (ClassSymbol)type, true);
    } else
        return false;
}
 
Example #22
Source File: Hacks.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Scope constructScope(CompilationInfo info, String... importedClasses) {
    Collection<String> imports = new LinkedList<String>();

    for (String i : importedClasses) {
        imports.add("import " + i + ";\n");
    }

    return Utilities.constructScope(info, Collections.<String, TypeMirror>emptyMap(), imports);
}
 
Example #23
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Scope visitMethod(MethodTree node, CompilationInfo p) {
    if (node.getReturnType() == null) {
        return null;
    }
    return super.visitMethod(node, p);
}
 
Example #24
Source File: JavaProfilerSourceImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isOffsetValid(FileObject fo, final int offset) {
    final Boolean[] validated = new Boolean[1];

    JavaSource js = JavaSource.forFileObject(fo);
    
    if (js != null) {
        try {
            js.runUserActionTask(new CancellableTask<CompilationController>() {
                @Override
                public void cancel() {
                }

                public void run(CompilationController controller)
                        throws Exception {
                    controller.toPhase(JavaSource.Phase.RESOLVED);
                    validated[0] = false; // non-validated default

                    Scope sc = controller.getTreeUtilities().scopeFor(offset);

                    if (sc.getEnclosingClass() != null) {
                        validated[0] = true;
                    }

                }
            }, true);
        } catch (IOException ex) {
            ProfilerLogger.log(ex);
        }

    }

    return validated[0];
}
 
Example #25
Source File: JavacTrees.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public boolean isAccessible(Scope scope, TypeElement type) {
    if (scope instanceof JavacScope && type instanceof ClassSymbol) {
        Env<AttrContext> env = ((JavacScope) scope).env;
        return resolve.isAccessible(env, (ClassSymbol)type, true);
    } else
        return false;
}
 
Example #26
Source File: ChangeMethodReturnType.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<Fix> run(CompilationInfo info, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    TreePath parentPath = treePath.getParentPath();
    if (parentPath == null || parentPath.getLeaf().getKind() != Kind.RETURN) return null;
    
    TreePath method = null;
    TreePath tp = treePath;

    while (tp != null && !TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind())) {
        if (tp.getLeaf().getKind() == Kind.METHOD) {
            method = tp;
            break;
        }

        tp = tp.getParentPath();
    }

    if (method == null) return null;

    MethodTree mt = (MethodTree) tp.getLeaf();

    if (mt.getReturnType() == null) return null;

    TypeMirror targetType = purify(info, info.getTrees().getTypeMirror(treePath));

    if (targetType == null) return null;

    if (targetType.getKind() == TypeKind.EXECUTABLE) {
        String expression = info.getText().substring((int) info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), treePath.getLeaf()), (int) info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), treePath.getLeaf()));
        Scope s = info.getTrees().getScope(treePath);
        ExpressionTree expr = info.getTreeUtilities().parseExpression(expression, new SourcePositions[1]);

        targetType = purify(info, info.getTreeUtilities().attributeTree(expr, s));
    }

    if (targetType == null || targetType.getKind() == TypeKind.EXECUTABLE) return null;

    return Collections.singletonList(new FixImpl(info, method, TypeMirrorHandle.create(targetType), info.getTypeUtilities().getTypeName(targetType).toString()).toEditorFix());
}
 
Example #27
Source File: Hacks.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Scope constructScope(CompilationInfo info, String... importedClasses) {
    StringBuilder clazz = new StringBuilder();

    clazz.append("package $$;\n");

    for (String i : importedClasses) {
        clazz.append("import ").append(i).append(";\n");
    }

    clazz.append("public class $$scopeclass$").append(inc++).append("{");

    clazz.append("private void test() {\n");
    clazz.append("}\n");
    clazz.append("}\n");

    JavacTaskImpl jti = JavaSourceAccessor.getINSTANCE().getJavacTask(info);
    Context context = jti.getContext();

    JavaCompiler jc = JavaCompiler.instance(context);
    Log.instance(context).nerrors = 0;

    JavaFileObject jfo = FileObjects.memoryFileObject("$$", "$", new File("/tmp/t.java").toURI(), System.currentTimeMillis(), clazz.toString());

    try {
        CompilationUnitTree cut = ParserFactory.instance(context).newParser(jfo.getCharContent(true), true, true, true).parseCompilationUnit();

        jti.analyze(jti.enter(Collections.singletonList(cut)));

        return new ScannerImpl().scan(cut, info);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
        return null;
    } finally {
    }
}
 
Example #28
Source File: CompletionFilter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isAccessible(Scope scope, TypeElement te) {
    if (te == null || scope == null) {
        return false;
    }
    if (te.getQualifiedName().toString().startsWith("REPL.") && te.getNestingKind() == NestingKind.TOP_LEVEL) {
        return false;
    }
    return delegate.isAccessible(scope, te);
}
 
Example #29
Source File: AddJavaFXPropertyCodeGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void perform(FileObject file, JTextComponent pane, final AddFxPropertyConfig config, final Scope scope) {
    final int caretOffset = component.getCaretPosition();
    JavaSource js = JavaSource.forDocument(component.getDocument());
    if (js != null) {
        try {
            ModificationResult mr = js.runModificationTask(new Task<WorkingCopy>() {
                @Override
                public void run(WorkingCopy javac) throws IOException {
                    javac.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                    Element e = handle.resolve(javac);
                    TreePath path = e != null ? javac.getTrees().getPath(e) : javac.getTreeUtilities().pathFor(caretOffset);
                    path = getPathElementOfKind(TreeUtilities.CLASS_TREE_KINDS, path);
                    if (path == null) {
                        org.netbeans.editor.Utilities.setStatusBoldText(component, ERR_CannotFindOriginalClass());
                    } else {
                        ClassTree cls = (ClassTree) path.getLeaf();
                        AddJavaFXPropertyMaker maker = new AddJavaFXPropertyMaker(javac, scope, javac.getTreeMaker(), config);
                        List<Tree> members = maker.createMembers();
                        if(members != null) {
                            javac.rewrite(cls, GeneratorUtils.insertClassMembers(javac, cls, members, caretOffset));
                        }
                    }
                }
            });
            GeneratorUtils.guardedCommit(component, mr);
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
}
 
Example #30
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static TypeMirror attributeTree(JavacTaskImpl jti, Tree tree, Scope scope, final List<Diagnostic<? extends JavaFileObject>> errors) {
        Log log = Log.instance(jti.getContext());
        JavaFileObject prev = log.useSource(new DummyJFO());
        Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log) {
            @Override
            public void report(JCDiagnostic diag) {
                errors.add(diag);
            }            
        };
        NBResolve resolve = NBResolve.instance(jti.getContext());
        resolve.disableAccessibilityChecks();
//        Enter enter = Enter.instance(jti.getContext());
//        enter.shadowTypeEnvs(true);
//        ArgumentAttr argumentAttr = ArgumentAttr.instance(jti.getContext());
//        ArgumentAttr.LocalCacheContext cacheContext = argumentAttr.withLocalCacheContext();
        try {
            Attr attr = Attr.instance(jti.getContext());
            Env<AttrContext> env = ((JavacScope) scope).getEnv();
            if (tree instanceof JCExpression)
                return attr.attribExpr((JCTree) tree,env, Type.noType);
            return attr.attribStat((JCTree) tree,env);
        } finally {
//            cacheContext.leave();
            log.useSource(prev);
            log.popDiagnosticHandler(discardHandler);
            resolve.restoreAccessbilityChecks();
//            enter.shadowTypeEnvs(false);
        }
    }