Java Code Examples for com.sun.source.tree.ExpressionTree

The following examples show how to use com.sun.source.tree.ExpressionTree. These examples are extracted from open source projects. 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 Project: netbeans   Source File: ExtendsImplements.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    TreePath clazz = findClass(ctx.getPath());
    
    if (clazz == null) {
        //TODO: should not happen - warn?
        return ;
    }
    
    TreeMaker make = ctx.getWorkingCopy().getTreeMaker();
    ClassTree original = (ClassTree) clazz.getLeaf();
    ClassTree nue;
    
    if (extends2Implements) {
        nue = make.insertClassImplementsClause(make.setExtends(original, null), 0, ctx.getPath().getLeaf());
    } else {
        nue = make.setExtends(make.removeClassImplementsClause(original, ctx.getPath().getLeaf()), (ExpressionTree) ctx.getPath().getLeaf());
    }
    
    ctx.getWorkingCopy().rewrite(original, nue);
}
 
Example 2
Source Project: netbeans   Source File: MagicSurroundWithTryCatchFix.java    License: Apache License 2.0 6 votes vote down vote up
private static StatementTree createRethrowAsRuntimeExceptionStatement(WorkingCopy info, TreeMaker make, String name) {
    if (!ErrorFixesFakeHint.isRethrowAsRuntimeException(ErrorFixesFakeHint.getPreferences(info.getFileObject(), FixKind.SURROUND_WITH_TRY_CATCH))) {
        return null;
    }

    TypeElement runtimeException = info.getElements().getTypeElement("java.lang.RuntimeException");

    if (runtimeException == null) {
        return null;
    }

    ExpressionTree exceptionName = make.QualIdent(runtimeException);
    StatementTree result = make.Throw(make.NewClass(null, Collections.<ExpressionTree>emptyList(), exceptionName, Arrays.asList(make.Identifier(name)), null));

    info.tag(exceptionName, Utilities.TAG_SELECT);
    
    return result;
}
 
Example 3
Source Project: java-n-IDE-for-Android   Source File: Trees.java    License: Apache License 2.0 6 votes vote down vote up
/**
     * Returns the string name of an operator, including assignment and compound assignment.
     */
    static String operatorName(ExpressionTree expression) {
//        JCTree.Tag tag = ((JCTree) expression).getTag();
//        if (tag == JCTree.Tag.ASSIGN) {
//            return "=";
//        }
//        boolean assignOp = expression instanceof CompoundAssignmentTree;
//        if (assignOp) {
//            tag = tag.noAssignOp();
//        }
        int tag = ((JCTree) expression).getTag();
        if (tag == JCTree.ASSIGN) {
            return "=";
        }
        boolean assignOp = expression instanceof CompoundAssignmentTree;
        if (assignOp) {
//            tag = tag.noAssignOp();
            // TODO: 22-Jul-17  ?????
        }

        String name = new Pretty(/*writer*/ null, /*sourceOutput*/ true).operatorName(tag);
        return assignOp ? name + "=" : name;
    }
 
Example 4
Source Project: google-java-format   Source File: JavaInputAstVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private void visitPackage(
    ExpressionTree packageName, List<? extends AnnotationTree> packageAnnotations) {
  if (!packageAnnotations.isEmpty()) {
    for (AnnotationTree annotation : packageAnnotations) {
      builder.forcedBreak();
      scan(annotation, null);
    }
    builder.forcedBreak();
  }
  builder.open(plusFour);
  token("package");
  builder.space();
  visitName(packageName);
  builder.close();
  token(";");
}
 
Example 5
void visitVariables(
        List<VariableTree> fragments,
        DeclarationKind declarationKind,
        Direction annotationDirection) {
    if (fragments.size() == 1) {
        VariableTree fragment = fragments.get(0);
        declareOne(
                declarationKind,
                annotationDirection,
                Optional.of(fragment.getModifiers()),
                fragment.getType(),
                VarArgsOrNot.fromVariable(fragment),
                ImmutableList.<AnnotationTree>of(),
                fragment.getName(),
                "",
                "=",
                Optional.fromNullable(fragment.getInitializer()),
                Optional.of(";"),
                Optional.<ExpressionTree>absent(),
                Optional.fromNullable(variableFragmentDims(true, 0, fragment.getType())));

    } else {
        declareMany(fragments, annotationDirection);
    }
}
 
Example 6
Source Project: netbeans   Source File: AbstractTestGenerator.java    License: Apache License 2.0 6 votes vote down vote up
protected ClassTree generateStubTestMethod(ClassTree tstClass,
                                           String testMethodName,
                                           WorkingCopy workingCopy) {
    List<? extends Tree> tstMembersOrig = tstClass.getMembers();
    List<Tree> tstMembers = new ArrayList<Tree>(tstMembersOrig.size() + 4);
    tstMembers.addAll(tstMembersOrig);

    List<ExpressionTree> throwsList = Collections.emptyList();
    MethodTree method = composeNewTestMethod(
            STUB_TEST_NAME,
            generateStubTestMethodBody(workingCopy),
            throwsList,
            workingCopy);

    tstMembers.add(method);

    ClassTree newClass = workingCopy.getTreeMaker().Class(
            tstClass.getModifiers(),
            tstClass.getSimpleName(),
            tstClass.getTypeParameters(),
            tstClass.getExtendsClause(),
            (List<? extends ExpressionTree>) tstClass.getImplementsClause(),
            tstMembers);
    return newClass;
}
 
Example 7
Source Project: NullAway   Source File: NullAway.java    License: MIT License 6 votes vote down vote up
@Override
public Description matchSwitch(SwitchTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }

  ExpressionTree switchExpression = tree.getExpression();
  if (switchExpression instanceof ParenthesizedTree) {
    switchExpression = ((ParenthesizedTree) switchExpression).getExpression();
  }

  if (mayBeNullExpr(state, switchExpression)) {
    final String message =
        "switch expression " + state.getSourceForNode(switchExpression) + " is @Nullable";
    ErrorMessage errorMessage =
        new ErrorMessage(MessageTypes.SWITCH_EXPRESSION_NULLABLE, message);

    return errorBuilder.createErrorDescription(
        errorMessage, switchExpression, buildDescription(switchExpression), state);
  }

  return Description.NO_MATCH;
}
 
Example 8
Source Project: javaide   Source File: JavaInputAstVisitor.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void dotExpressionUpToArgs(ExpressionTree expression, Optional<BreakTag> tyargTag) {
    expression = getArrayBase(expression);
    switch (expression.getKind()) {
        case MEMBER_SELECT:
            MemberSelectTree fieldAccess = (MemberSelectTree) expression;
            visit(fieldAccess.getIdentifier());
            break;
        case METHOD_INVOCATION:
            MethodInvocationTree methodInvocation = (MethodInvocationTree) expression;
            if (!methodInvocation.getTypeArguments().isEmpty()) {
                builder.open(plusFour);
                addTypeArguments(methodInvocation.getTypeArguments(), ZERO);
                // TODO(jdd): Should indent the name -4.
                builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO, tyargTag);
                builder.close();
            }
            visit(getMethodName(methodInvocation));
            break;
        case IDENTIFIER:
            visit(((IdentifierTree) expression).getName());
            break;
        default:
            scan(expression, null);
            break;
    }
}
 
Example 9
Source Project: netbeans   Source File: EjbFacadeGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private ExpressionTree mimeTypeTree(TreeMaker maker, String mimeType) {
    String mediaTypeMember = null;
    if (mimeType.equals("application/xml")) { // NOI18N
        mediaTypeMember = "APPLICATION_XML"; // NOI18N
    } else if (mimeType.equals("application/json")) { // NOI18N
        mediaTypeMember = "APPLICATION_JSON"; // NOI18N
    } else if (mimeType.equals("text/plain")) { // NOI18N
        mediaTypeMember = "TEXT_PLAIN"; // NOI18N
    }
    ExpressionTree result;
    if (mediaTypeMember == null) {
        result = maker.Literal(mimeType);
    } else {
        // Use a field of MediaType class if possible
        ExpressionTree typeTree = maker.QualIdent("javax.ws.rs.core.MediaType"); // NOI18N
        result = maker.MemberSelect(typeTree, mediaTypeMember);
    }
    return result;
}
 
Example 10
Source Project: netbeans   Source File: PreconditionsChecker.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isIterbale(ExpressionTree expression) {
    TypeMirror tm = workingCopy.getTrees().getTypeMirror(TreePath.getPath(workingCopy.getCompilationUnit(), expression));
    if (!Utilities.isValidType(tm)) {
        return false;
    }
    if (tm.getKind() == TypeKind.ARRAY) {
        return false;
    } else {
        tm = workingCopy.getTypes().erasure(tm);
        TypeElement typeEl = workingCopy.getElements().getTypeElement("java.util.Collection");
        if (typeEl != null) {
            TypeMirror collection = typeEl.asType();
            collection = workingCopy.getTypes().erasure(collection);
            if (this.workingCopy.getTypes().isSubtype(tm, collection)) {
                return true;
            }
        }
    }

    return false;
}
 
Example 11
Source Project: netbeans   Source File: EqualsHashCodeGenerator.java    License: 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 12
Source Project: netbeans   Source File: AddCastFix.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    TypeMirror resolvedTargetType = targetType.resolve(ctx.getWorkingCopy());
    
    if (resolvedTargetType == null) {
        //cannot resolve anymore:
        return;
    }
    
    TreePath resolvedIdealTypeTree = idealTypeTree != null ? idealTypeTree.resolve(ctx.getWorkingCopy()) : null;
    
    TreeMaker make = ctx.getWorkingCopy().getTreeMaker();
    ExpressionTree toCast = (ExpressionTree) ctx.getPath().getLeaf();

    Class interf = toCast.getKind().asInterface();
    boolean wrapWithBrackets = interf == BinaryTree.class || interf == ConditionalExpressionTree.class;

    if (/*TODO: replace with JavaFixUtilities.requiresparenthesis*/wrapWithBrackets) {
        toCast = make.Parenthesized(toCast);
    }

    ExpressionTree cast = make.TypeCast(resolvedIdealTypeTree != null ? resolvedIdealTypeTree.getLeaf() : make.Type(resolvedTargetType), toCast);

    ctx.getWorkingCopy().rewrite(ctx.getPath().getLeaf(), cast);
}
 
Example 13
Source Project: netbeans   Source File: CodeGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private AnnotationTree computeAnnotationTree(AnnotationMirror am) {
    List<ExpressionTree> params = new LinkedList<ExpressionTree>();

    for (Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : am.getElementValues().entrySet()) {
        ExpressionTree val = createTreeForAnnotationValue(make, entry.getValue());

        if (val == null) {
            LOG.log(Level.WARNING, "Cannot create annotation for: {0}", entry.getValue());
            continue;
        }

        ExpressionTree vt = make.Assignment(make.Identifier(entry.getKey().getSimpleName()), val);

        params.add(vt);
    }

    return make.Annotation(make.Type(am.getAnnotationType()), params);
}
 
Example 14
Source Project: netbeans   Source File: MethodTest2.java    License: Apache License 2.0 6 votes vote down vote up
public Void visitMethod(MethodTree node, Object p) {
    super.visitMethod(node, p);
    if (method.equals(node)) {
        MethodTree njuMethod = make.Method(
                node.getModifiers(),
                node.getName().toString(),
                make.Identifier(newType),
                node.getTypeParameters(),
                node.getParameters(),
                node.getThrows(),
                node.getBody(),
                (ExpressionTree) node.getDefaultValue()
                );
        copy.rewrite(node, njuMethod);
        method = njuMethod;
    }
    return null;
}
 
Example 15
Source Project: netbeans   Source File: LoggerStringConcat.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    TreePath invocation = ctx.getPath();
    TreePath message    = FixImpl.this.message.resolve(wc);
    MethodInvocationTree mit = (MethodInvocationTree) invocation.getLeaf();
    ExpressionTree level = null;

    if (logMethodName != null) {
        String logMethodNameUpper = logMethodName.toUpperCase();
        VariableElement c = findConstant(wc, logMethodNameUpper);

        level = wc.getTreeMaker().QualIdent(c);
    } else {
        level = mit.getArguments().get(0);
    }

    rewrite(wc, level, mit, message);
}
 
Example 16
Source Project: netbeans   Source File: ToStringGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private static List<StatementTree> createToStringMethodBodyWithPlusOperator(TreeMaker make, String typeName, Iterable<? extends VariableElement> fields) {
    ExpressionTree exp = make.Literal(typeName + '{');
    boolean first = true;
    for (VariableElement variableElement : fields) {
        StringBuilder sb = new StringBuilder();
        if (!first) {
            sb.append(", ");
        }
        sb.append(variableElement.getSimpleName().toString()).append('=');
        exp = make.Binary(Tree.Kind.PLUS, exp, make.Literal(sb.toString()));
        exp = make.Binary(Tree.Kind.PLUS, exp, make.Identifier(variableElement.getSimpleName()));
        first = false;
    }
    StatementTree stat = make.Return(make.Binary(Tree.Kind.PLUS, exp, make.Literal('}'))); //NOI18N
    return Collections.singletonList(stat);
}
 
Example 17
Source Project: netbeans   Source File: EntityMethodGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public  MethodTree createEqualsMethod(String simpleClassName, List<VariableTree> fields) {
    StringBuilder body = new StringBuilder(50 + fields.size() * 30);
    body.append("{"); // NOI18N
    body.append("// TODO: Warning - this method won't work in the case the id fields are not set\n"); // NOI18N
    body.append("if (!(object instanceof "); // NOI18N
    body.append(simpleClassName + ")) {return false;}"); // NOI18N
    body.append(simpleClassName + " other = (" + simpleClassName + ")object;"); // NOI18N
    for (VariableTree field : fields) {
        body.append(createEqualsLineForField(field));
    }
    body.append("return true;"); // NOI18N
    body.append("}"); // NOI18N
    TreeMaker make = copy.getTreeMaker();
    // XXX Javadoc
    return make.Method(make.Modifiers(EnumSet.of(Modifier.PUBLIC),
            Collections.singletonList(genUtils.createAnnotation("java.lang.Override"))), "equals",
            make.PrimitiveType(TypeKind.BOOLEAN), Collections.<TypeParameterTree>emptyList(),
            Collections.singletonList(genUtils.createVariable(scope, "object", "java.lang.Object")),
            Collections.<ExpressionTree>emptyList(), body.toString(), null);
}
 
Example 18
Source Project: netbeans   Source File: SyncOnNonFinal.java    License: Apache License 2.0 5 votes vote down vote up
@TriggerTreeKind(Kind.SYNCHRONIZED)
public static ErrorDescription run(HintContext ctx) {
    ExpressionTree expression = ((SynchronizedTree) ctx.getPath().getLeaf()).getExpression();
    
    Element e = ctx.getInfo().getTrees().getElement(new TreePath(ctx.getPath(), expression));
    
    if (e == null || e.getKind() != ElementKind.FIELD || e.getModifiers().contains(Modifier.FINAL)) {
        return null;
    }
    
    String displayName = NbBundle.getMessage(SyncOnNonFinal.class, "ERR_SynchronizationOnNonFinalField");
    
    return ErrorDescriptionFactory.forTree(ctx, expression, displayName);
}
 
Example 19
Source Project: deptective   Source File: PackageReferenceValidator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onEnteringCompilationUnit(CompilationUnitTree tree) {
    ExpressionTree packageNameTree = tree.getPackageName();

    // TODO deal with default package
    if (packageNameTree == null) {
        return false;
    }

    String packageName = packageNameTree.toString();
    currentPackageName = packageName;

    try {
        currentComponent = allowedPackageDependencies.getComponentByPackage(packageName);

        if (currentComponent == null) {
            reportUnconfiguredPackageIfNeeded(tree, packageName);
        }
    }
    catch (PackageAssignedToMultipleComponentsException e) {
        log.report(
                ReportingPolicy.ERROR,
                DeptectiveMessages.PACKAGE_CONTAINED_IN_MULTIPLE_COMPONENTS,
                String.join(
                        ", ",
                        e.getMatchingComponents()
                                .stream()
                                .map(Component::getName)
                                .sorted()
                                .collect(Collectors.toList())
                ),
                packageName
        );

        createDotFile = false;
        return false;
    }

    return true;
}
 
Example 20
Source Project: javaide   Source File: Trees.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the simple name of a (possibly qualified) method invocation expression.
 */
static Name getMethodName(MethodInvocationTree methodInvocation) {
    ExpressionTree select = methodInvocation.getMethodSelect();
    return select instanceof MemberSelectTree
            ? ((MemberSelectTree) select).getIdentifier()
            : ((IdentifierTree) select).getName();
}
 
Example 21
Source Project: j2objc   Source File: TreeConverter.java    License: Apache License 2.0 5 votes vote down vote up
private TreeNode convertCase(CaseTree node, TreePath parent) {
  // Case statements are converted in convertSwitch().
  SwitchCase newNode = new SwitchCase();
  ExpressionTree expressionTree = node.getExpression();
  if (expressionTree != null) {
    newNode.setExpression((Expression) convert(expressionTree, getTreePath(parent, node)));
  } else {
    newNode.setIsDefault(true);
  }
  return newNode;
}
 
Example 22
Source Project: netbeans   Source File: JaxRsGenerationStrategy.java    License: Apache License 2.0 5 votes vote down vote up
@Override
MethodTree generateFormMethod( TreeMaker maker, WorkingCopy copy ) {
    String form = "javax.ws.rs.core.Form"; //NOI18N
    TypeElement mvMapEl = copy.getElements().getTypeElement(form);
    String mvType = mvMapEl==null?"javax.ws.rs.core.Form":"Form"; //NOI18N

    String body =
    "{"+ //NOI18N
        mvType+" form = new javax.ws.rs.core.Form();"+ //NOI18N
        "for (int i=0;i< paramNames.length;i++) {" + //NOI18N
        "    if (paramValues[i] != null) {"+ //NOI18N
        "        form = form.param(paramNames[i], paramValues[i]);"+ //NOI18N
        "    }"+ //NOI18N
        "}"+ //NOI18N
        "return form;"+ //NOI18N
    "}"; //NOI18N
    ModifiersTree methodModifier = maker.Modifiers(
            Collections.<Modifier>singleton(Modifier.PRIVATE));
    ExpressionTree returnTree =
            mvMapEl ==null ? 
                copy.getTreeMaker().Identifier("javax.ws.rs.core.Form"):    //NOI18N
                    copy.getTreeMaker().QualIdent(mvMapEl);
    List<VariableTree> paramList = new ArrayList<VariableTree>();
    ModifiersTree paramModifier = maker.Modifiers(Collections.<Modifier>emptySet());
    paramList.add(maker.Variable(paramModifier, "paramNames", maker.Identifier("String[]"), null)); //NOI18N
    paramList.add(maker.Variable(paramModifier, "paramValues", maker.Identifier("String[]"), null)); //NOI18N
    return maker.Method (
            methodModifier,
            "getQueryOrFormParams", //NOI18N
            returnTree,
            Collections.<TypeParameterTree>emptyList(),
            paramList,
            Collections.<ExpressionTree>emptyList(),
            body,
            null); //NOI18N
}
 
Example 23
Source Project: google-java-format   Source File: JavaInputAstVisitor.java    License: Apache License 2.0 5 votes vote down vote up
/** Lays out one or more array indices. Does not output the expression for the array itself. */
private void formatArrayIndices(Deque<ExpressionTree> indices) {
  if (indices.isEmpty()) {
    return;
  }
  builder.open(ZERO);
  do {
    token("[");
    builder.breakToFill();
    scan(indices.removeLast(), null);
    token("]");
  } while (!indices.isEmpty());
  builder.close();
}
 
Example 24
Source Project: netbeans   Source File: RemoveUnnecessary.java    License: Apache License 2.0 5 votes vote down vote up
private Object addExpressionStatement(ExpressionTree node, Object p) {
    if (mk != null) {
        statements.add(mk.ExpressionStatement(node));
    }
    remove = false;
    return null;
}
 
Example 25
/**
 * Formats a union type declaration in a catch clause.
 */
private void visitUnionType(VariableTree declaration) {
    UnionTypeTree type = (UnionTypeTree) declaration.getType();
    builder.open(ZERO);
    sync(declaration);
    visitAndBreakModifiers(
            declaration.getModifiers(), Direction.HORIZONTAL, Optional.<BreakTag>absent());
    List<? extends Tree> union = type.getTypeAlternatives();
    boolean first = true;
    for (int i = 0; i < union.size() - 1; i++) {
        if (!first) {
            builder.breakOp(" ");
            token("|");
            builder.space();
        } else {
            first = false;
        }
        scan(union.get(i), null);
    }
    builder.breakOp(" ");
    token("|");
    builder.space();
    Tree last = union.get(union.size() - 1);
    declareOne(
            DeclarationKind.NONE,
            Direction.HORIZONTAL,
            Optional.<ModifiersTree>absent(),
            last,
            VarArgsOrNot.NO, // VarArgsOrNot.valueOf(declaration.isVarargs()),
            ImmutableList.<AnnotationTree>of(), // declaration.varargsAnnotations(),
            declaration.getName(),
            "",
            // declaration.extraDimensions(),
            "=",
            Optional.fromNullable(declaration.getInitializer()),
            Optional.<String>absent(),
            Optional.<ExpressionTree>absent(),
            Optional.<TypeWithDims>absent());
    builder.close();
}
 
Example 26
Source Project: buck   Source File: ImportsTrackerTestHelper.java    License: Apache License 2.0 5 votes vote down vote up
private static void handleImport(Trees trees, ImportsTracker imports, TreePath importTreePath) {
  ImportTree importTree = (ImportTree) importTreePath.getLeaf();
  MemberSelectTree importedExpression = (MemberSelectTree) importTree.getQualifiedIdentifier();
  TreePath importedExpressionPath = new TreePath(importTreePath, importedExpression);
  Name simpleName = importedExpression.getIdentifier();
  boolean isStarImport = simpleName.contentEquals("*");

  if (!isStarImport && !importTree.isStatic()) {
    TypeElement importedType = (TypeElement) trees.getElement(importedExpressionPath);
    imports.importType(importedType, importedExpressionPath);
  } else {
    ExpressionTree containingElementExpression = importedExpression.getExpression();
    TreePath containingElementExpressionPath =
        new TreePath(importedExpressionPath, containingElementExpression);
    QualifiedNameable containingElement =
        (QualifiedNameable) trees.getElement(containingElementExpressionPath);

    if (importTree.isStatic()) {
      TypeElement containingType = (TypeElement) containingElement;
      if (isStarImport) {
        imports.importStaticMembers((TypeElement) containingElement);
      } else {
        imports.importStatic(containingType, simpleName);
      }
    } else {
      // Normal star import
      imports.importMembers(containingElement, containingElementExpressionPath);
    }
  }
}
 
Example 27
Source Project: netbeans   Source File: NCLOCVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object visitMethodInvocation(MethodInvocationTree node, Object p) {
    TreePath parentPath = getCurrentPath().getParentPath();
    if (parentPath != null) {
        Tree t = parentPath.getLeaf();
        // do not count invocations that are a part of expression (expression statement is counted already)
        if (!ExpressionTree.class.isAssignableFrom(t.getKind().asInterface()) &&
            !ExpressionStatementTree.class.isAssignableFrom(t.getKind().asInterface())) {
            statements++;
        }
    }
    return super.visitMethodInvocation(node, p);
}
 
Example 28
Source Project: netbeans   Source File: MethodTest2.java    License: Apache License 2.0 5 votes vote down vote up
public MethodTree makeMethod() {
    Set<Modifier> emptyModifs = Collections.emptySet();
    List<TypeParameterTree> emptyTpt= Collections.emptyList();
    List<VariableTree> emptyVt = Collections.emptyList();
    List<ExpressionTree> emptyEt = Collections.emptyList();
    return make.Method(
              make.Modifiers(emptyModifs),
              (CharSequence)"",
              (ExpressionTree) null,
              emptyTpt,
              emptyVt,
              emptyEt,
              (BlockTree) null,
              (ExpressionTree)null);                    
}
 
Example 29
Source Project: netbeans   Source File: Imports.java    License: Apache License 2.0 5 votes vote down vote up
private static List<TreePathHandle> getAllImportsOfKind(CompilationInfo ci, ImportHintKind kind) {
    //allow only default and samepackage
    assert (kind == ImportHintKind.DEFAULT_PACKAGE || kind == ImportHintKind.SAME_PACKAGE);

    CompilationUnitTree cut = ci.getCompilationUnit();
    TreePath topLevel = new TreePath(cut);
    List<TreePathHandle> result = new ArrayList<TreePathHandle>(3);

    List<? extends ImportTree> imports = cut.getImports();
    for (ImportTree it : imports) {
        if (it.isStatic()) {
            continue; // XXX
        }
        if (it.getQualifiedIdentifier() instanceof MemberSelectTree) {
            MemberSelectTree ms = (MemberSelectTree) it.getQualifiedIdentifier();
            if (kind == ImportHintKind.DEFAULT_PACKAGE) {
                if (ms.getExpression().toString().equals(DEFAULT_PACKAGE)) {
                    result.add(TreePathHandle.create(new TreePath(topLevel, it), ci));
                }
            }
            if (kind == ImportHintKind.SAME_PACKAGE) {
                ExpressionTree packageName = cut.getPackageName();
                if (packageName != null &&
                    ms.getExpression().toString().equals(packageName.toString())) {
                    result.add(TreePathHandle.create(new TreePath(topLevel, it), ci));
                }
            }
        }
    }
    return result;
}
 
Example 30
Source Project: google-java-format   Source File: Java14InputAstVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Void visitCase(CaseTree node, Void unused) {
  sync(node);
  markForPartialFormat();
  builder.forcedBreak();
  if (node.getExpressions().isEmpty()) {
    token("default", plusTwo);
  } else {
    token("case", plusTwo);
    builder.space();
    boolean first = true;
    for (ExpressionTree expression : node.getExpressions()) {
      if (!first) {
        token(",");
        builder.space();
      }
      scan(expression, null);
      first = false;
    }
  }
  switch (node.getCaseKind()) {
    case STATEMENT:
      token(":");
      builder.open(plusTwo);
      visitStatements(node.getStatements());
      builder.close();
      break;
    case RULE:
      builder.space();
      token("-");
      token(">");
      builder.space();
      scan(node.getBody(), null);
      builder.guessToken(";");
      break;
    default:
      throw new AssertionError(node.getCaseKind());
  }
  return null;
}