Java 类javax.lang.model.element.Name 实例源码

项目:incubator-netbeans    文件:Analyzer.java   
@NbBundle.Messages({"# {0} - @param name", "UNKNOWN_TYPEPARAM_DESC=Unknown @param: {0}",
                    "# {0} - @param name", "DUPLICATE_PARAM_DESC=Duplicate @param name: {0}"})
private void checkParamDeclared(ParamTree tree, List<? extends Element> list,
        DocTreePathHandle dtph, int start, int end, List<ErrorDescription> errors) {
    Name name = tree.getName().getName();
    boolean found = false;
    for (Element e: list) {
        if(ctx.isCanceled()) { return; }
        if (name.equals(e.getSimpleName())) {
            if(!foundParams.add(e)) {
                errors.add(ErrorDescriptionFactory.forSpan(ctx, start, end, DUPLICATE_PARAM_DESC(name), new RemoveTagFix(dtph, "@param").toEditorFix())); // NOI18N
            }
            found = true;
        }
    }
    if (!found) {
        errors.add(ErrorDescriptionFactory.forSpan(ctx, start, end, UNKNOWN_TYPEPARAM_DESC(name), new RemoveTagFix(dtph, "@param").toEditorFix())); //NOI18N
    }
}
项目:incubator-netbeans    文件:JavaSourceHelper.java   
public static boolean isInjectionTarget(CompilationController controller, TypeElement typeElement) {
    FileObject fo = controller.getFileObject();
    Project project = FileOwnerQuery.getOwner(fo);
    if (ElementKind.INTERFACE != typeElement.getKind()) {
        List<? extends AnnotationMirror> annotations = typeElement.getAnnotationMirrors();
        boolean found = false;

        for (AnnotationMirror m : annotations) {
            Name qualifiedName = ((TypeElement) m.getAnnotationType().asElement()).getQualifiedName();
            if (qualifiedName.contentEquals("javax.jws.WebService")) {
                //NOI18N
                found = true;
                break;
            }
            if (qualifiedName.contentEquals("javax.jws.WebServiceProvider")) {
                //NOI18N
                found = true;
                break;
            }
        }
        if (found) {
            return true;
        }
    }
    return false;
}
项目:javaide    文件:JavaInputAstVisitor.java   
/**
 * Helper method for import declarations, names, and qualified names.
 */
private void visitName(Tree node) {
    Deque<Name> stack = new ArrayDeque<>();
    for (; node instanceof MemberSelectTree; node = ((MemberSelectTree) node).getExpression()) {
        stack.addFirst(((MemberSelectTree) node).getIdentifier());
    }
    stack.addFirst(((IdentifierTree) node).getName());
    boolean first = true;
    for (Name name : stack) {
        if (!first) {
            token(".");
        }
        token(name.toString());
        first = false;
    }
}
项目:incubator-netbeans    文件:Analyzer.java   
@Override
public Void visitDocComment(DocCommentTree node, List<ErrorDescription> errors) {
    DocTreePath currentDocPath = getCurrentPath();
    Void value = super.visitDocComment(node, errors);
    DocSourcePositions sp = (DocSourcePositions) javac.getTrees().getSourcePositions();

    while (!tagStack.isEmpty()) {
        StartElementTree startTree = tagStack.pop();
        Name tagName = startTree.getName();
        HtmlTag tag = HtmlTag.get(tagName);
        if (tag.endKind == HtmlTag.EndKind.REQUIRED) {
            int s = (int) sp.getStartPosition(javac.getCompilationUnit(), currentDocPath.getDocComment(), startTree);
            int e = (int) sp.getEndPosition(javac.getCompilationUnit(), currentDocPath.getDocComment(), startTree);
            errors.add(ErrorDescriptionFactory.forSpan(ctx, s, e, TAG_START_UNMATCHED(tagName)));
        }
    }
    return value;
}
项目:jdoocsoup    文件:DataClassBuilderDescriptorTest.java   
@Before
public void before() {
    mockedDataClassBuilderAnnotation = mock(DataClassBuilder.class);
    mockedProcessingEnv = mock(ProcessingEnvironment.class);
    mockedTypeElement = mock(TypeElement.class);

    when(mockedDataClassBuilderAnnotation.name()).thenReturn("");
    when(mockedTypeElement.getAnnotation(DataClassBuilder.class)).thenReturn(mockedDataClassBuilderAnnotation);

    mockedElementUtils = mock(Elements.class);
    when(mockedProcessingEnv.getElementUtils()).thenReturn(mockedElementUtils);

    PackageElement mockedPackageElement = mock(PackageElement.class);
    when(mockedElementUtils.getPackageOf(any(Element.class))).thenReturn(mockedPackageElement);

    Name mockedQualifiedName = mock(Name.class);
    when(mockedPackageElement.getQualifiedName()).thenReturn(mockedQualifiedName);
    when(mockedQualifiedName.toString()).thenReturn("eu.rsulkowski.test");

    dataClassBuilderDescriptor = new DataClassBuilderDescriptor(mockedProcessingEnv, mockedTypeElement);
}
项目:openjdk-jdk10    文件:HtmlDocletWriter.java   
boolean ignoreNonInlineTag(DocTree dtree) {
    Name name = null;
    if (dtree.getKind() == Kind.START_ELEMENT) {
        StartElementTree setree = (StartElementTree)dtree;
        name = setree.getName();
    } else if (dtree.getKind() == Kind.END_ELEMENT) {
        EndElementTree eetree = (EndElementTree)dtree;
        name = eetree.getName();
    }

    if (name != null) {
        com.sun.tools.doclint.HtmlTag htmlTag = com.sun.tools.doclint.HtmlTag.get(name);
        if (htmlTag != null &&
                htmlTag.blockType != com.sun.tools.doclint.HtmlTag.BlockType.INLINE) {
            return true;
        }
    }
    return false;
}
项目:openjdk-jdk10    文件:DocCommentTester.java   
@Override
    void check(TreePath path, Name name) throws Exception {
        String raw = trees.getDocComment(path);
        String normRaw = normalize(raw);

        StringWriter out = new StringWriter();
        DocPretty dp = new DocPretty(out);
        dp.print(trees.getDocCommentTree(path));
        String pretty = out.toString();

        if (!pretty.equals(normRaw)) {
            error("mismatch");
            System.err.println("*** expected:");
            System.err.println(normRaw.replace(" ", "_"));
            System.err.println("*** found:");
            System.err.println(pretty.replace(" ", "_"));
//            throw new Error();
        }
    }
项目:incubator-netbeans    文件:ProspectiveOperation.java   
private Set<Name> getAvailableVariables() {
    if (this.availableVariables == null) {
        PreconditionsChecker.VariablesVisitor treeVariableVisitor = new PreconditionsChecker.VariablesVisitor(new TreePath(this.workingCopy.getCompilationUnit()));
        if (this.correspondingTree.getKind() == Tree.Kind.VARIABLE) {
            treeVariableVisitor.scan(((VariableTree) correspondingTree).getInitializer(), this.workingCopy.getTrees());
            this.availableVariables = buildAvailables(treeVariableVisitor);
            this.availableVariables.add(((VariableTree) correspondingTree).getName());
        } else {
            treeVariableVisitor.scan(correspondingTree, this.workingCopy.getTrees());
            this.availableVariables = buildAvailables(treeVariableVisitor);
        }
    }
    //If the operation is a filter, then it only makes available what it gets
    //if needed is empty, it can pull anything needed from upstream.
    if (this.opType == OperationType.FILTER) {
        return this.getNeededVariables();
    }
    return this.availableVariables;
}
项目:incubator-netbeans    文件:IfToSwitchSupport.java   
private Set<Name> declaredVariables(TreePath where) {
    Set<Name> result = new HashSet<Name>();
    Iterable<? extends Tree> statements;

    if (where.getLeaf().getKind() == Tree.Kind.BLOCK) {
        statements = ((BlockTree) where.getLeaf()).getStatements();
    } else {
        statements = Collections.singletonList(where.getLeaf());
    }

    for (Tree t : statements) {
        if (t.getKind() == Tree.Kind.VARIABLE) {
            result.add(((VariableTree) t).getName());
        }
    }

    return result;
}
项目:openjdk-jdk10    文件:Checker.java   
private void validateHtml4Attrs(AttributeTree tree, Name name, AttrKind k) {
    switch (k) {
        case ALL:
        case HTML4:
            break;

        case INVALID:
            env.messages.error(HTML, tree, "dc.attr.unknown", name);
            break;

        case OBSOLETE:
            env.messages.warning(ACCESSIBILITY, tree, "dc.attr.obsolete", name);
            break;

        case USE_CSS:
            env.messages.warning(ACCESSIBILITY, tree, "dc.attr.obsolete.use.css", name);
            break;

        case HTML5:
            env.messages.error(HTML, tree, "dc.attr.not.supported.html4", name);
            break;
    }
}
项目:incubator-netbeans    文件:Utilities.java   
public static String target2String(TypeElement target) {
    final Name qualifiedName = target.getQualifiedName(); //#130759
    if (qualifiedName == null) {
        Logger.getLogger(Utilities.class.getName()).warning("Target qualified name could not be resolved."); //NOI18N
        return ""; //NOI18N
    } else {
        String qnString = qualifiedName.toString();
        if (qnString.length() == 0) {
            //probably an anonymous class
            qnString = target.asType().toString();
        }

        try {
            qnString = XMLUtil.toElementContent(qnString);
        } catch (CharConversionException ex) {
            Logger.getLogger(Utilities.class.getName()).log(Level.FINE, null, ex);
        }

        return qnString;
    }
}
项目:GitHub    文件:ProcessorUtil.java   
/**
 * Returns a safe String to use in a Javadoc that will function in a link.
 *
 * <p>This method exists because by Javadoc doesn't handle type parameters({@literal <T>}
 * in {@literal RequestOptions<T>} for example).
 */
private TypeName getJavadocSafeName(Element element) {
  Types typeUtils = processingEnv.getTypeUtils();
  TypeMirror type = element.asType();
  if (typeUtils.asElement(type) == null) {
    // If there is no Element, it's a primitive and can't have additional types, so we're done.
    return ClassName.get(element.asType());
  }
  Name simpleName = typeUtils.asElement(type).getSimpleName();
  return ClassName.bestGuess(simpleName.toString());
}
项目:openjdk-jdk10    文件:DocCommentTester.java   
void check(TreePath path, Name name) {
    StringWriter out = new StringWriter();
    DocCommentTree dc = trees.getDocCommentTree(path);
    printer.print(dc, out);
    out.flush();
    String found = out.toString().replace(NEWLINE, "\n");

    /*
     * Look for the first block comment after the first occurrence
     * of name, noting that, block comments with BI_MARKER may
     * very well be present.
     */
    int start = test.useBreakIterator
            ? source.indexOf("\n/*\n" + BI_MARKER + "\n", findName(source, name))
            : source.indexOf("\n/*\n", findName(source, name));
    int end = source.indexOf("\n*/\n", start);
    int startlen = start + (test.useBreakIterator ? BI_MARKER.length() + 1 : 0) + 4;
    String expect = source.substring(startlen, end + 1);
    if (!found.equals(expect)) {
        if (test.useBreakIterator) {
            System.err.println("Using BreakIterator");
        }
        System.err.println("Expect:\n" + expect);
        System.err.println("Found:\n" + found);
        error("AST mismatch for " + name);
    }
}
项目:auto-value-node    文件:AutoValueNodeExtension.java   
private MethodSpec generateNodeMethod(Name superName, String packageName) {
    return MethodSpec.methodBuilder("node") //
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL) //
            .returns(ClassName.get(packageName, "Node_" + superName))
            .addCode("return new Node_$L(this);\n", superName)
            .build();
}
项目:OpenJSharp    文件:LLNI.java   
protected final boolean needLongName(ExecutableElement method,
                                     TypeElement clazz) {
    Name methodName = method.getSimpleName();
    for (ExecutableElement memberMethod: methods) {
        if ((memberMethod != method) &&
            memberMethod.getModifiers().contains(Modifier.NATIVE) &&
                (methodName.equals(memberMethod.getSimpleName())))
            return true;
    }
    return false;
}
项目:Pogamut3    文件:ClassCrawler.java   
/**
 * Extract {@link PrimitiveData} information about the class.
 *
 * @param classFQN
 * @param annotation
 * @return
 */
private PrimitiveData getInfo(String classFQN, TypeElement classType, AnnotationMirror annotation) {
    String name = null;
    String description = null;
    List<String> tags = Collections.EMPTY_LIST;

    for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotation.getElementValues().entrySet()) {
        // name
        Name entryName = entry.getKey().getSimpleName();
        AnnotationValue entryValue = entry.getValue();
        if (entryName.contentEquals("name")) {
            name = getAnnotationValue(String.class, classFQN, "name", entryValue);
        } else if (entryName.contentEquals("description")) {
            description = getAnnotationValue(String.class, classFQN, "description", entryValue);
        } else if (entryName.contentEquals("tags")) {
            List<AnnotationValue> tagList = getAnnotationValue(List.class, classFQN, "tags", entryValue);
            if (tagList != null) {
                tags = new ArrayList<String>(tagList.size());
                for (AnnotationValue tagValue : tagList) {
                    String tag = getAnnotationValue(String.class, classFQN, "tags", tagValue);
                    if (tag != null) {
                        tags.add(tag);
                    }
                }
            }
        }
    }
    Set<ParamInfo> primitiveParams = getAnnotatedParams(classType);

    return new PrimitiveData(classFQN, name, description, tags.toArray(new String[tags.size()]), primitiveParams);
}
项目:jtsgen    文件:TypeScriptModelTest.java   
private TSType createTsType(final String canonicalName) {
    final TypeElement mockedTypeElement = mock(TypeElement.class);
    final Name mockedName = mock(Name.class);
    when(mockedName.toString()).thenReturn(canonicalName);
    when(mockedTypeElement.getQualifiedName()).thenReturn(mockedName);
    return TSInterfaceBuilder.of(mockedTypeElement).withNamespace(StringUtils.untill(canonicalName)).withName(StringUtils.lastOf(canonicalName));
}
项目:incubator-netbeans    文件:TestGenerator.java   
/**
 * Checks that the given annotation is of type
 * <code>{@value #ANN_SUITE}.{@value #ANN_SUITE_MEMBERS}</code>
 * and contains the given list of classes as (the only) argument,
 * in the same order.
 * 
 * @param  annMirror  annotation to be checked
 * @param  suiteMembers  list of fully qualified class names denoting
 *                       content of the test suite
 * @return  {@code true} if the annotation meets the described criteria,
 *          {@code false} otherwise
 */
private boolean checkSuiteMembersAnnotation(AnnotationMirror annMirror,
                                            List<String> suiteMembers,
                                            WorkingCopy workingCopy) {
    Map<? extends ExecutableElement,? extends AnnotationValue> annParams
            = annMirror.getElementValues();

    if (annParams.size() != 1) {
        return false;
    }

    AnnotationValue annValue = annParams.values().iterator().next();
    Object value = annValue.getValue();
    if (value instanceof java.util.List) {
        List<? extends AnnotationValue> items
                = (List<? extends AnnotationValue>) value;

        if (items.size() != suiteMembers.size()) {
            return false;
        }

        Types types = workingCopy.getTypes();
        Iterator<String> suiteMembersIt = suiteMembers.iterator();
        for (AnnotationValue item : items) {
            Name suiteMemberName = getAnnotationValueClassName(item, types);
            if (suiteMemberName == null) {
                return false;
            }
            if (!suiteMemberName.contentEquals(suiteMembersIt.next())) {
                return false;
            }
        }
        return true;
    }

    return false;
}
项目:auto-value-variant    文件:AutoValueVariantExtension.java   
private static MethodSpec generateVariantOrEqual(Name superName, TypeName parameterName) {
    return MethodSpec.methodBuilder("likeOrEqual") //
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL) //
            .returns(TypeName.BOOLEAN)
            .addParameter(parameterName, "other")
            .addCode("return likeOrEqual(other, \"\");\n")
            .build();
}
项目:incubator-netbeans    文件:ElementOverlay.java   
private Element createElement(ASTService ast, Elements elements, String name, Element original, ModuleElement modle) {
    Element el = elementCache.get(name);

    if (el == null) {
        if (original != null) {
            if (original.getKind().isClass() || original.getKind().isInterface()) {
                elementCache.put(name, el = new TypeElementWrapper(ast, elements, (TypeElement) original));
                return el;
            }
            if (original.getKind() == ElementKind.PACKAGE) {
                elementCache.put(name, el = new PackageElementWrapper(ast, elements, (PackageElement) original));
                return el;
            }

            return original;
        }

        int lastDot = name.lastIndexOf('.');
        Name simpleName = elements.getName(name.substring(lastDot + 1));
        Name fqnName = elements.getName(name);

        if (classes.containsKey(name)) {
            Element parent = lastDot > 0 ? resolve(ast, elements, name.substring(0, lastDot), modle) : elements.getPackageElement("");

            elementCache.put(name, el = new FakeTypeElement(ast, elements, simpleName, fqnName, name, parent, classes.get(name), modle));
        } else if (packages.contains(name)) {
            elementCache.put(name, el = new FakePackageElement(ast, elements, fqnName, name, simpleName, modle));
        } else {
            return null;//XXX: handling of this null in callers!
        }
    }

    return el;
}
项目:incubator-netbeans    文件:ElementOverlay.java   
public FakeTypeElement(ASTService ast, Elements elements, Name simpleName, Name fqn, String fqnString, Element parent, Set<Modifier> mods, ModuleElement modle) {
    this.ast = ast;
    this.elements = elements;
    this.simpleName = simpleName;
    this.fqn = fqn;
    this.fqnString = fqnString;
    this.parent = parent;
    this.mods = mods;
    this.modle = modle;
}
项目:openjdk-jdk10    文件:DocCommentTester.java   
@Override
void check(TreePath path, Name name) throws Exception {
    JavaFileObject fo = path.getCompilationUnit().getSourceFile();
    final CharSequence cs = fo.getCharContent(true);

    final DCDocComment dc = (DCDocComment) trees.getDocCommentTree(path);
    DCTree t = (DCTree) trees.getDocCommentTree(path);

    DocTreeScanner scanner = new DocTreeScanner<Void,Void>() {
        @Override
        public Void scan(DocTree node, Void ignore) {
            if (node != null) {
                try {
                    String expect = getExpectText(node);
                    long pos = ((DCTree) node).getSourcePosition(dc);
                    String found = getFoundText(cs, (int) pos, expect.length());
                    if (!found.equals(expect)) {
                        System.err.println("expect: " + expect);
                        System.err.println("found:  " + found);
                        error("mismatch");
                    }

                } catch (StringIndexOutOfBoundsException e) {
                    error(node.getClass() + ": " + e.toString());
                        e.printStackTrace();
                }
            }
            return super.scan(node, ignore);
        }
    };

    scanner.scan(t, null);
}
项目:auto-value-variant    文件:AutoValueVariantExtension.java   
private static MethodSpec generateVariantOfInGroup(Name superName, TypeName parameterName) {
    return MethodSpec.methodBuilder("like") //
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL) //
            .returns(TypeName.BOOLEAN)
            .addParameter(parameterName, "other")
            .addParameter(String.class, "group")
            .addCode("return group != null ")
            .addCode("\n  && other != null")
            .addCode("\n  && other instanceof $L", superName)
            .addCode("\n  && groupFieldsEqual(($L) other, group) && !equals(other);\n", superName)
            .build();
}
项目:CommandsMap    文件:CommandMapGenerator.java   
private String twoParameterBody(ExecutableElement element, String className) {
    Name methodName = element.getSimpleName();
    String typeCastOne = element.getParameters().get(0).asType().toString();
    String typeCastTwo = element.getParameters().get(1).asType().toString();
    return bodyPrefix(methodName, className)
            + "((" + typeCastOne + ")o1, (" + typeCastTwo + ")o2)" + END_LINE +
            bodyPostfix(methodName, className);
}
项目:incubator-netbeans    文件:FQN2Files.java   
public boolean check(final Name fqn, final JavaFileObject jfo) {
    String value = props.getProperty(fqn.toString());
    try {
        return value != null && !value.equals(jfo.toUri().toURL().toExternalForm());
    } catch (MalformedURLException ex) {
        Exceptions.printStackTrace(ex);
        return false;
    }
}
项目:incubator-netbeans    文件:JUnit4TestGenerator.java   
/**
 * Returns fully qualified class name of a class given to an annotation
 * as (the only) argument.
 * 
 * @param  annValue  annotation value
 * @return  fully qualified name of a class represented by the given
 *          annotation value, or {@code null} if the annotation value
 *          does not represent a class
 */
private Name getAnnotationValueClassName(AnnotationValue annValue,
                                         Types types) {
    Object value = annValue.getValue();
    if (value instanceof TypeMirror) {
        TypeMirror typeMirror = (TypeMirror) value;
        Element typeElement = types.asElement(typeMirror);
        if (typeElement.getKind() == ElementKind.CLASS) {
            return ((TypeElement) typeElement).getQualifiedName();
        }
    }
    return null;
}
项目:gwt-jackson-apt    文件:SerializerGenerator.java   
public String generate(TypeMirror beanType, String packageName, Name beanName) {
    String generatedClassName = Type.serializerName(packageName, beanName.toString());
    if (!TypeRegistry.containsSerializer(beanType.toString())) {
        try {
            new AptSerializerBuilder(beanType, ObjectMapperProcessor.filer)
                    .generate(beanName, packageName);
            TypeRegistry.registerSerializer(beanType.toString(), ClassName.bestGuess(generatedClassName));
        } catch (IOException e) {
            throw new SerializerGenerationFailedException(beanType.toString());
        }
    }
    return generatedClassName;
}
项目:incubator-netbeans    文件:DependencyCollector.java   
private void addDependency(TypeMirror t) {
    Collection<DeclaredType> declaredTypes = new ArrayList<DeclaredType>(7);
    DeclaredTypeCollector.INSTANCE.visit(t, declaredTypes);
    for (DeclaredType dt : declaredTypes) {
        TypeElement te = (TypeElement)dt.asElement();

        if (outermostClass != null ) {
            TypeElement outermost = info.getElementUtilities().outermostTypeElement(te);
            if (outermost == outermostClass) {
                return;
            }
        }

        Name qn = ((TypeElement) dt.asElement()).getQualifiedName();
        if (qn.length() > 5) {
            if (qn.subSequence(0, 4).equals("java")) { // NOI18N
                // java. or javax.
                if (qn.charAt(4) == '.' || (qn.length() > 6 && qn.charAt(4) == 'x' && qn.charAt(5) == '.')) {
                    if (ignoreJavaLibraries) {
                        return;
                    }
                }
            }
        }
        if (!ignoreQNames.contains(qn)) {
            seenQNames.add(qn);
        }
    }
}
项目:incubator-netbeans    文件:TreeLoader.java   
@Override
public void enhance(Context context, FQN2Files fqn2Files) {
    if (fqn2Files == null)
        return;
    context.put(DuplicateClassChecker.class, new DuplicateClassChecker() {
        @Override
        public boolean check(Name name, JavaFileObject jfo) {
            return fqn2Files.check(name, jfo);
        }
    });
}
项目:javaide    文件:JavaInputAstVisitor.java   
private boolean fillFirstArgument(
        ExpressionTree e,
        List<ExpressionTree> items,
        Indent indent) {
    // is there a trailing dereference?
    if (items.size() < 2) {
        return false;
    }
    // don't special-case calls nested inside expressions
    if (e.getKind() != METHOD_INVOCATION) {
        return false;
    }
    MethodInvocationTree methodInvocation = (MethodInvocationTree) e;
    Name name = getMethodName(methodInvocation);
    if (!(methodInvocation.getMethodSelect() instanceof IdentifierTree)
            || name.length() > 4
            || !methodInvocation.getTypeArguments().isEmpty()
            || methodInvocation.getArguments().size() != 1) {
        return false;
    }
    builder.open(ZERO);
    builder.open(indent);
    visit(name);
    token("(");
    ExpressionTree arg = getOnlyElement(methodInvocation.getArguments());
    scan(arg, null);
    builder.close();
    token(")");
    builder.close();
    return true;
}
项目:openjdk-jdk10    文件:LLNI.java   
protected final boolean needLongName(ExecutableElement method,
                                     TypeElement clazz) {
    Name methodName = method.getSimpleName();
    for (ExecutableElement memberMethod: methods) {
        if ((memberMethod != method) &&
            memberMethod.getModifiers().contains(Modifier.NATIVE) &&
                (methodName.equals(memberMethod.getSimpleName())))
            return true;
    }
    return false;
}
项目:incubator-netbeans    文件:ProspectiveOperation.java   
private Set<Name> buildNeeded(PreconditionsChecker.VariablesVisitor treeVariableVisitor) {
    Set<Name> allVariablesUsedInCurrentOp = treeVariableVisitor.getAllLocalVariablesUsed();
    //Remove the ones also declared in the current block.
    allVariablesUsedInCurrentOp.removeAll(treeVariableVisitor.getInnervariables());
    //Keeps the ones that are local to the loop. These are the ones that need to be passed around
    //in a pipe-like fashion.
    allVariablesUsedInCurrentOp.retainAll(this.innerLoopVariables);
    return allVariablesUsedInCurrentOp;
}
项目:incubator-netbeans    文件:ProspectiveOperation.java   
private void beautifyVariable(Tree currentTree, Set<Name> needed) {
    VariableTree varTree = (VariableTree) currentTree;
    if (needed.contains(varTree.getName())) {
        this.correspondingTree = varTree.getInitializer() != null
                ? treeMaker.ExpressionStatement(varTree.getInitializer())
                : null;
    } else {

        this.correspondingTree = this.addReturn(castToStatementTree(currentTree), getOneFromSet(needed));
    }
}
项目:incubator-netbeans    文件:EvaluatorVisitor.java   
@Override
public Mirror visitContinue(ContinueTree arg0, EvaluationContext evaluationContext) {
    Name label = arg0.getLabel();
    if (label != null) {
        Assert.error(arg0, "unsupported");
        return null;
    }
    return new Continue();
}
项目:incubator-netbeans    文件:ProspectiveOperation.java   
private static void beautify(List<ProspectiveOperation> ls) {
    for ( int i = ls.size() - 1; i > 0; i--) {
        ProspectiveOperation current = ls.get(i - 1);
        ProspectiveOperation next = ls.get(i);
        Set<Name> needed = next.getNeededVariables();
        current.beautify(needed);
    }
    for (Iterator<ProspectiveOperation> it = ls.iterator(); it.hasNext();) {
        if (it.next().correspondingTree == null)
            it.remove();
    }
}
项目:openjdk-jdk10    文件:MethodSubstitutionVerifier.java   
private TypeMirror[] originalSignature(TypeElement originalType, ExecutableElement method, AnnotationMirror annotation, boolean isStatic) {
    AnnotationValue signatureValue = findAnnotationValue(annotation, ORIGINAL_SIGNATURE);
    String signatureString = resolveAnnotationValue(String.class, signatureValue);
    List<TypeMirror> parameters = new ArrayList<>();
    if (signatureString.equals(ORIGINAL_SIGNATURE_DEFAULT)) {
        for (int i = 0; i < method.getParameters().size(); i++) {
            parameters.add(method.getParameters().get(i).asType());
        }
        if (!isStatic) {
            if (parameters.isEmpty()) {
                env.getMessager().printMessage(Kind.ERROR, "Method signature must be a static method with the 'this' object as its first parameter", method, annotation);
                return null;
            } else {
                TypeMirror thisParam = parameters.remove(0);
                if (!isSubtype(originalType.asType(), thisParam)) {
                    Name thisName = method.getParameters().get(0).getSimpleName();
                    env.getMessager().printMessage(Kind.ERROR, String.format("The type of %s must assignable from %s", thisName, originalType), method, annotation);
                }
            }
        }
        parameters.add(0, method.getReturnType());
    } else {
        try {
            APHotSpotSignature signature = new APHotSpotSignature(signatureString);
            parameters.add(signature.getReturnType(env));
            for (int i = 0; i < signature.getParameterCount(false); i++) {
                parameters.add(signature.getParameterType(env, i));
            }
        } catch (Exception e) {
            /*
             * That's not good practice and should be changed after APHotSpotSignature has
             * received a cleanup.
             */
            env.getMessager().printMessage(Kind.ERROR, String.format("Parsing the signature failed: %s", e.getMessage() != null ? e.getMessage() : e.toString()), method, annotation,
                            signatureValue);
            return null;
        }
    }
    return parameters.toArray(new TypeMirror[parameters.size()]);
}
项目:incubator-netbeans    文件:ProspectiveOperation.java   
public Set<Name> getNeededVariables() {
    if (neededVariables == null) {
        if (this.opType == OperationType.REDUCE) {
            return new HashSet<Name>();
        }
        PreconditionsChecker.VariablesVisitor treeVariableVisitor = new PreconditionsChecker.VariablesVisitor(new TreePath(this.workingCopy.getCompilationUnit()));
        if (this.correspondingTree.getKind() == Tree.Kind.VARIABLE) {
            treeVariableVisitor.scan(((VariableTree) correspondingTree).getInitializer(), this.workingCopy.getTrees());
        } else {
            treeVariableVisitor.scan(correspondingTree, this.workingCopy.getTrees());
        }
        this.neededVariables = buildNeeded(treeVariableVisitor);
    }
    return this.neededVariables;
}
项目:incubator-netbeans    文件:UtilityClass.java   
private static boolean isUtilityClass(CompilationInfo compilationInfo, Element clazz) {
    if (clazz.getKind() != ElementKind.CLASS) {
        return false;
    }

    TypeMirror supr = ((TypeElement) clazz).getSuperclass();
    if (supr == null) {
        return false;
    }
    Element superElem = compilationInfo.getTypes().asElement(supr);
    if (superElem instanceof TypeElement) {
        Name superName = compilationInfo.getElements().getBinaryName((TypeElement) superElem);
        if (superName != null && !superName.contentEquals("java.lang.Object")) {
            return false;
        }
    }

    int cnt = 0;
    for (Element m : clazz.getEnclosedElements()) {
        if (m.getKind() == ElementKind.METHOD && isMainMethod(((ExecutableElement) m))) return false;
        if (m.getKind() == ElementKind.METHOD || m.getKind() == ElementKind.FIELD) {
            if (!m.getModifiers().contains(Modifier.STATIC)) return false;
            cnt++;
        }
    }

    return cnt > 0;
}
项目:incubator-netbeans    文件:IntroduceHint.java   
/**
 * Crates method formal parameters, following code style conventions.
 * The trees in 'statements' will be rewritten to use the new identifiers.
 * 
 * @param copy working copy
 * @param parameters variables to turn into parameters
 * @param statements trees that should refer to parameters
 * @return 
 */
static List<VariableTree> createVariables(WorkingCopy copy, List<VariableElement> parameters, 
        TreePath targetParent,
        List<TreePath> statements) {
    final TreeMaker make = copy.getTreeMaker();
    List<VariableTree> formalArguments = new LinkedList<VariableTree>();
    CodeStyle cs = CodeStyle.getDefault(copy.getFileObject());

    String prefix = cs.getParameterNamePrefix();
    String suffix = cs.getParameterNameSuffix(); 
    Map<VariableElement, CharSequence> renamedVariables = new HashMap<VariableElement, CharSequence>();
    Set<Name> changedNames = new HashSet<Name>();
    for (VariableElement p : parameters) {
        TypeMirror tm = p.asType();
        Tree type = make.Type(tm);
        Name formalArgName = p.getSimpleName();
        Set<Modifier> formalArgMods = EnumSet.noneOf(Modifier.class);

        if (p.getModifiers().contains(Modifier.FINAL)) {
            formalArgMods.add(Modifier.FINAL);
        }
        String strippedName = Utilities.stripVariableName(cs, p);
        CharSequence codeStyleName = Utilities.guessName(copy, strippedName, targetParent, prefix, suffix, p.getKind() == ElementKind.PARAMETER);
        if (!formalArgName.contentEquals(codeStyleName)) {
            renamedVariables.put(p, codeStyleName);
            changedNames.add(formalArgName);
        } else {
            codeStyleName = formalArgName;
        }
        formalArguments.add(make.Variable(make.Modifiers(formalArgMods), codeStyleName, type, null));
    }
    if (!changedNames.isEmpty()) {
        VariableRenamer renamer = new VariableRenamer(copy, renamedVariables, changedNames);
        for (TreePath stPath : statements) {
            renamer.scan(stPath, null);
        }
    }
    return formalArguments;
}
项目:incubator-netbeans    文件:LayerBuilderTest.java   
public void testOriginatingElementComments() throws Exception {
    b = new LayerBuilder(doc, new Element() {
        public @Override ElementKind getKind() {
            return ElementKind.OTHER;
        }
        public @Override String toString() {
            return "originating.Type";
        }
        public @Override TypeMirror asType() {return null;}
        public @Override List<? extends AnnotationMirror> getAnnotationMirrors() {return null;}
        public @Override <A extends Annotation> A getAnnotation(Class<A> annotationType) {return null;}
        public @Override Set<Modifier> getModifiers() {return null;}
        public @Override Name getSimpleName() {return null;}
        public @Override Element getEnclosingElement() {return null;}
        public @Override List<? extends Element> getEnclosedElements() {return null;}
        public @Override <R, P> R accept(ElementVisitor<R, P> v, P p) {return null;}
        @Override
        public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationType) {
            return (A[]) Array.newInstance(annotationType, 0);
        }
    }, null);
    b.folder("f").write();
    assertEquals("<filesystem><folder name='f'><!--originating.Type--></folder></filesystem>", dump());
    // #180154: do not repeat after an incremental build
    b.folder("f").write();
    assertEquals("<filesystem><folder name='f'><!--originating.Type--></folder></filesystem>", dump());
}