Java Code Examples for com.sun.source.tree.VariableTree#getType()

The following examples show how to use com.sun.source.tree.VariableTree#getType() . 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: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
private void visitToDeclare(
        DeclarationKind kind,
        Direction annotationsDirection,
        VariableTree node,
        Optional<ExpressionTree> initializer,
        String equals,
        Optional<String> trailing) {
    sync(node);
    boolean varargs = VarArgsOrNot.fromVariable(node).isYes();
    List<? extends AnnotationTree> varargsAnnotations = ImmutableList.of();
    Tree type = node.getType();
    declareOne(
            kind,
            annotationsDirection,
            Optional.of(node.getModifiers()),
            type,
            VarArgsOrNot.valueOf(varargs),
            varargsAnnotations,
            node.getName(),
            "",
            equals,
            initializer,
            trailing,
            Optional.<ExpressionTree>absent(),
            Optional.<TypeWithDims>absent());
}
 
Example 2
Source File: TreeBackedExecutableElement.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public TypeMirror getReceiverType() {
  if (receiverType == null) {
    TreePath methodTreePath = getTreePath();
    TreePath receiverParameterPath = null;
    Tree receiverTypeTree = null;
    if (methodTreePath != null && tree != null) {
      VariableTree receiverParameterTree = tree.getReceiverParameter();
      if (receiverParameterTree != null) {
        receiverParameterPath = new TreePath(methodTreePath, receiverParameterTree);
        receiverTypeTree = receiverParameterTree.getType();
      }
    }
    receiverType =
        getCanonicalizer()
            .getCanonicalType(
                underlyingElement.getReceiverType(), receiverParameterPath, receiverTypeTree);
  }
  return receiverType;
}
 
Example 3
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
private void visitToDeclare(
        DeclarationKind kind,
        Direction annotationsDirection,
        VariableTree node,
        Optional<ExpressionTree> initializer,
        String equals,
        Optional<String> trailing) {
    sync(node);
    boolean varargs = VarArgsOrNot.fromVariable(node).isYes();
    List<? extends AnnotationTree> varargsAnnotations = ImmutableList.of();
    Tree type = node.getType();
    declareOne(
            kind,
            annotationsDirection,
            Optional.of(node.getModifiers()),
            type,
            VarArgsOrNot.valueOf(varargs),
            varargsAnnotations,
            node.getName(),
            "",
            equals,
            initializer,
            trailing,
            Optional.<ExpressionTree>absent(),
            Optional.<TypeWithDims>absent());
}
 
Example 4
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * 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 5
Source File: TreeBackedTypeResolutionSimulatorTest.java    From buck with Apache License 2.0 5 votes vote down vote up
private TreeBackedResolvedType resolveFieldType() {
  TypeElement fooElement = elements.getTypeElement("Foo");
  VariableElement field = ElementFilter.fieldsIn(fooElement.getEnclosedElements()).get(0);
  TreePath fieldTreePath = trees.getPath(field);
  VariableTree fieldTree = (VariableTree) fieldTreePath.getLeaf();
  TreePath typeTreePath = new TreePath(fieldTreePath, fieldTree.getType());

  CompilationUnitTree compilationUnit = typeTreePath.getCompilationUnit();
  TreeBackedTypeResolutionSimulator resolver =
      new TreeBackedTypeResolutionSimulator(elements, trees, compilationUnit);
  resolver.setImports(
      ImportsTrackerTestHelper.loadImports(elements, types, trees, compilationUnit));

  return resolver.resolve(typeTreePath);
}
 
Example 6
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
private void visitToDeclare(
    DeclarationKind kind,
    Direction annotationsDirection,
    VariableTree node,
    Optional<ExpressionTree> initializer,
    String equals,
    Optional<String> trailing) {
  sync(node);
  Optional<TypeWithDims> typeWithDims;
  Tree type;
  if (node.getType() != null) {
    TypeWithDims extractedDims = DimensionHelpers.extractDims(node.getType(), SortedDims.YES);
    typeWithDims = Optional.of(extractedDims);
    type = extractedDims.node;
  } else {
    typeWithDims = Optional.empty();
    type = null;
  }
  declareOne(
      kind,
      annotationsDirection,
      Optional.of(node.getModifiers()),
      type,
      node.getName(),
      "",
      equals,
      initializer,
      trailing,
      /* receiverExpression= */ Optional.empty(),
      typeWithDims);
}
 
Example 7
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
/** 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,
      /* declarationAnnotationBreak= */ Optional.empty());
  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,
      /* modifiers= */ Optional.empty(),
      last,
      /* name= */ declaration.getName(),
      /* op= */ "",
      "=",
      Optional.ofNullable(declaration.getInitializer()),
      /* trailing= */ Optional.empty(),
      /* receiverExpression= */ Optional.empty(),
      /* typeWithDims= */ Optional.empty());
  builder.close();
}
 
Example 8
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 9
Source File: Lambda.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Hint(displayName="#DN_addExplicitLambdaParameters", description="#DESC_addExplicitLambdaParameters", category="suggestions", hintKind=Hint.Kind.ACTION)
@Messages({
    "DN_addExplicitLambdaParameters=Convert Lambda to Use Explicit Parameter Types",
    "DESC_addExplicitLambdaParameters=Converts lambdas to use explicit parameter types",
    "ERR_addExplicitLambdaParameters=",
    "FIX_addExplicitLambdaParameters=Use explicit parameter types"
})
@TriggerTreeKind(Kind.LAMBDA_EXPRESSION)
public static ErrorDescription explicitParameterTypes(HintContext ctx) {
    LambdaExpressionTree let = (LambdaExpressionTree) ctx.getPath().getLeaf();

    if (ctx.getInfo().getTreeUtilities().hasError(let)) {
        return null;
    }

    boolean hasSyntheticParameterName = false;
    
    for (VariableTree var : let.getParameters()) {
        hasSyntheticParameterName |= var.getType() == null || ctx.getInfo().getTreeUtilities().isSynthetic(TreePath.getPath(ctx.getPath(), var.getType()));
    }
    
    if (!hasSyntheticParameterName) {
        return null;
    }
    
    return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_addExplicitLambdaParameters(), new AddExplicitLambdaParameterTypes(ctx.getInfo(), ctx.getPath()).toEditorFix());
}
 
Example 10
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<? extends TypeMirror> visitVariable(VariableTree node, Object p) {
    if (theExpression == null) {
        if (node.getInitializer() == null) {
            return null;
        }
        initExpression(node.getInitializer());
    }
    if (theExpression.getLeaf() == node.getInitializer()) {
        // the expression must be assiganble to the variable.
        this.expectedTree = new TreePath(getCurrentPath(), node.getType());
        return Collections.singletonList(info.getTrees().getTypeMirror(getCurrentPath()));
    }
    return null;
}
 
Example 11
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static List<? extends TypeMirror> computeVariableDeclaration(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    VariableTree vt = (VariableTree) parent.getLeaf();
    
    if (vt.getInitializer() == error) {
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return Collections.singletonList(info.getTrees().getTypeMirror(new TreePath(parent, vt.getType())));
    }
    
    TreePath context = parent.getParentPath();
    if (vt.getType() != error || context == null) {
        return null;
    }

    switch (context.getLeaf().getKind()) {
        case ENHANCED_FOR_LOOP:
            ExpressionTree iterableTree = ((EnhancedForLoopTree) context.getLeaf()).getExpression();
            TreePath iterablePath = new TreePath(context, iterableTree);
            TypeMirror type = getIterableGenericType(info, iterablePath);
            types.add(ElementKind.LOCAL_VARIABLE);
            return Collections.singletonList(type);
        default:
            types.add(ElementKind.CLASS);
            return Collections.<TypeMirror>emptyList();
    }
}
 
Example 12
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static List<? extends TypeMirror> computeVariableDeclaration(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    VariableTree vt = (VariableTree) parent.getLeaf();
    
    if (vt.getInitializer() == error) {
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return Collections.singletonList(info.getTrees().getTypeMirror(new TreePath(parent, vt.getType())));
    }
    
    TreePath context = parent.getParentPath();
    if (vt.getType() != error || context == null) {
        return null;
    }

    switch (context.getLeaf().getKind()) {
        case ENHANCED_FOR_LOOP:
            ExpressionTree iterableTree = ((EnhancedForLoopTree) context.getLeaf()).getExpression();
            TreePath iterablePath = new TreePath(context, iterableTree);
            TypeMirror type = getIterableGenericType(info, iterablePath);
            types.add(ElementKind.LOCAL_VARIABLE);
            return Collections.singletonList(type);
        default:
            types.add(ElementKind.CLASS);
            return Collections.<TypeMirror>emptyList();
    }
}
 
Example 13
Source File: ReplaceConstructorWithBuilderUI.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private ReplaceConstructorWithBuilderUI(TreePathHandle constructor, CompilationInfo info) {
    this.refactoring = new ReplaceConstructorWithBuilderRefactoring(constructor);
    ExecutableElement contructorElement = (ExecutableElement) constructor.resolveElement(info);
    this.name = contructorElement.getSimpleName().toString();
    MethodTree constTree = (MethodTree) constructor.resolve(info).getLeaf();
    paramaterNames = new ArrayList<String>();
    parameterTypes = new ArrayList<String>();
    parameterTypeVars = new ArrayList<Boolean>();
    boolean varargs = contructorElement.isVarArgs();
    List<? extends VariableElement> parameterElements = contructorElement.getParameters();
    List<? extends VariableTree> parameters = constTree.getParameters();
    for (int i = 0; i < parameters.size(); i++) {
        VariableTree var = parameters.get(i);
        paramaterNames.add(var.getName().toString());
        String type = contructorElement.getParameters().get(i).asType().toString();
        if(varargs && i+1 == parameters.size()) {
            if(var.getType().getKind() == Tree.Kind.ARRAY_TYPE) {
                ArrayTypeTree att = (ArrayTypeTree) var.getType();
                type = att.getType().toString();
                type += "..."; //NOI18N
            }
        }
        parameterTypes.add(type);
        parameterTypeVars.add(parameterElements.get(i).asType().getKind() == TypeKind.TYPEVAR);
    }
    TypeElement typeEl = (TypeElement) contructorElement.getEnclosingElement();
    if(typeEl.getNestingKind() != NestingKind.TOP_LEVEL) {
        PackageElement packageOf = info.getElements().getPackageOf(typeEl);
        builderFQN = packageOf.toString() + "." + typeEl.getSimpleName().toString();
    } else {
        builderFQN = typeEl.getQualifiedName().toString();
    }
    buildMethodName = "create" + typeEl.getSimpleName();
}
 
Example 14
Source File: EntityMethodGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String createEqualsLineForField(VariableTree field) {
    Name fieldName = field.getName();
    Tree fieldType = field.getType();
    if (fieldType.getKind() == Tree.Kind.PRIMITIVE_TYPE) {
        return "if (this." + fieldName + " != other." + fieldName + ") return false;"; // NOI18N
    }
    return "if ((this." + fieldName + " == null && other." + fieldName + " != null) || " + "(this." + fieldName +
            " != null && !this." + fieldName + ".equals(other." + fieldName + "))) return false;"; // NOI18N
}
 
Example 15
Source File: EntityMethodGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String createHashCodeLineForField(VariableTree field) {
    Name fieldName = field.getName();
    Tree fieldType = field.getType();
    if (fieldType.getKind() == Tree.Kind.PRIMITIVE_TYPE) {
        if (((PrimitiveTypeTree) fieldType).getPrimitiveTypeKind() == TypeKind.BOOLEAN) {
            return "hash += (" + fieldName + " ? 1 : 0"; // NOI18N
        }
        return "hash += (int)" + fieldName + ";"; // NOI18N
    }
    return "hash += (" + fieldName + " != null ? " + fieldName + ".hashCode() : 0);"; // NOI18N
}
 
Example 16
Source File: SnakeYAMLMojo.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
private static void addPropertyParametersIfNeeded(VariableTree node, Type type, String propName) {
    if (node.getType().getKind() == Tree.Kind.PARAMETERIZED_TYPE) {
        ParameterizedTypeTree pTree = (ParameterizedTypeTree) node.getType();

        List<String> parameterTypeNames = pTree.getTypeArguments().stream()
                .filter(argTree -> argTree.getKind() == Tree.Kind.IDENTIFIER)
                .map(argTree -> ((IdentifierTree) argTree).getName().toString())
                .collect(Collectors.toList());
        type.propertyParameter(propName, parameterTypeNames);
    }
}
 
Example 17
Source File: ComputeImports.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
        public Void visitVariable(VariableTree tree, Map<String, Object> p) {
            scan(tree.getModifiers(), p);
            
            if (tree.getType() != null && tree.getType().getKind() == Kind.IDENTIFIER) {
                p.put("request", null);
            }
            
            scan(tree.getType(), p, true);
            
            Union2<String, DeclaredType> leftSide = (Union2<String, DeclaredType>) p.remove("result");
            
            p.remove("request");
            
            Union2<String, DeclaredType> rightSide = null;
            
            if (leftSide != null && tree.getInitializer() != null) {
                Element el = info.getTrees().getElement(new TreePath(getCurrentPath(),tree.getInitializer()));
                TypeMirror rightType = el != null ? el.asType() : null;
                
//                System.err.println("rightType = " + rightType );
//                System.err.println("tree.getInitializer()=" + tree.getInitializer());
//                System.err.println("rightType.getKind()=" + rightType.getKind());
//                System.err.println("INVALID_TYPES.contains(rightType.getKind())=" + INVALID_TYPES.contains(rightType.getKind()));
                if (rightType != null && rightType.getKind() == TypeKind.DECLARED) {
                    rightSide = Union2.<String, DeclaredType>createSecond((DeclaredType) rightType);
                } else {
                    if (tree.getInitializer().getKind() == Kind.NEW_CLASS || tree.getInitializer().getKind() == Kind.NEW_ARRAY) {
                        p.put("request", null);
                    }
                }
            }
            
            scan(tree.getInitializer(), p);
            
            rightSide = rightSide == null ? (Union2<String, DeclaredType>) p.remove("result") : rightSide;
            
            p.remove("result");
            
//            System.err.println("rightSide = " + rightSide );
            
            p.remove("request");
            
            if (leftSide != null && rightSide != null) {
                if (!(leftSide instanceof TypeMirror) || !(rightSide instanceof TypeMirror)) {
                    hints.add(new TypeHint(leftSide, rightSide));
                }
            }
            
            return null;
        }
 
Example 18
Source File: CompilerTask.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void run(CompilationController controller) throws IOException {
    controller.toPhase(Phase.ELEMENTS_RESOLVED);
    CompilationUnitTree cut = controller.getCompilationUnit();

    TypeElement thisTypeEl = SourceUtils.getPublicTopLevelElement(controller);
    if (thisTypeEl != null) {
        ClassTree javaClass = controller.getTrees().getTree(thisTypeEl);
        // find if class is Injection Target
        generateWsRefInjection[0] = InjectionTargetQuery.isInjectionTarget(
                controller, thisTypeEl);
        if (generateWsRefInjection[0]) {
            // issue 126014 : check if J2EE Container supports EJBs (e.g. Tomcat 6 doesn't)
            Project project = FileOwnerQuery.getOwner(controller.getFileObject());
            generateWsRefInjection[0] = JaxWsUtils.isEjbSupported(project);
        }

        insertServiceDef[0] = !generateWsRefInjection[0];
        if (isServletClass(controller, thisTypeEl)) {
            // PENDING Need to compute pronter name from the method
            printerName[0] = "out"; //NOI18N
            argumentInitPart[0] = fixNamesInInitializationPart(argumentInitPart[0]);
            argumentDeclPart[0] = fixNamesInDeclarationPart(argumentDeclPart[0]);
            fixNamesMethodParams( paramNames );
        }
        // compute the service field name
        if (generateWsRefInjection[0]) {
            Set<String> serviceFieldNames = new HashSet<String>();
            boolean injectionExists = false;
            int memberOrder = 0;
            for (Tree member : javaClass.getMembers()) {
                // for the first inner class in top level
                ++memberOrder;
                if (VARIABLE == member.getKind()) {
                    // get variable type
                    VariableTree var = (VariableTree) member;
                    Tree typeTree = var.getType();
                    TreePath typeTreePath = controller.getTrees().
                        getPath(cut, typeTree);
                    TypeElement typeEl = (TypeElement) controller.getTrees().
                        getElement(typeTreePath);
                    if (typeEl != null) {
                        String variableType = typeEl.getQualifiedName().toString();
                        if (serviceJavaName.equals(variableType)) {
                            serviceFName[0] = var.getName().toString();
                            generateWsRefInjection[0] = false;
                            injectionExists = true;
                            break;
                        }
                    }
                    serviceFieldNames.add(var.getName().toString());
                }
            }
            if (!injectionExists) {
                serviceFName[0] = findProperServiceFieldName(serviceFieldNames);
            }
        }
    }
}
 
Example 19
Source File: JaxWsCodeGenerator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
        public void run(CompilationController controller) throws IOException {
            controller.toPhase(Phase.ELEMENTS_RESOLVED);
            CompilationUnitTree cut = controller.getCompilationUnit();

            TypeElement thisTypeEl = SourceUtils.getPublicTopLevelElement(controller);
            if (thisTypeEl != null) {
                ClassTree javaClass = controller.getTrees().getTree(thisTypeEl);
                // find if class is Injection Target
                generateWsRefInjection[0] = InjectionTargetQuery.isInjectionTarget(controller, thisTypeEl);
//                if (generateWsRefInjection[0]) {
//                    // issue 126014 : check if J2EE Container supports EJBs (e.g. Tomcat 6 doesn't)
//                    Project project = FileOwnerQuery.getOwner(controller.getFileObject());
//                    generateWsRefInjection[0] = JaxWsUtils.isEjbSupported(project);
//                }

                insertServiceDef[0] = !generateWsRefInjection[0];
                if (isServletClass(controller, thisTypeEl)) {
                    // PENDING Need to compute pronter name from the method
                    printerName[0] = "out"; //NOI18N
                    argumentInitPart[0] = fixNamesInInitializationPart(argumentInitPart[0]);
                    argumentDeclPart[0] = fixNamesInDeclarationPart(argumentDeclPart[0]);
                }
                // compute the service field name
                if (generateWsRefInjection[0]) {
                    Set<String> serviceFieldNames = new HashSet<String>();
                    boolean injectionExists = false;
                    int memberOrder = 0;
                    for (Tree member : javaClass.getMembers()) {
                        // for the first inner class in top level
                        ++memberOrder;
                        if (VARIABLE == member.getKind()) {
                            // get variable type
                            VariableTree var = (VariableTree) member;
                            Tree typeTree = var.getType();
                            TreePath typeTreePath = controller.getTrees().getPath(cut, typeTree);
                            TypeElement typeEl = (TypeElement) controller.getTrees().getElement(typeTreePath);
                            if (typeEl != null) {
                                String variableType = typeEl.getQualifiedName().toString();
                                if (serviceJavaName.equals(variableType)) {
                                    serviceFName[0] = var.getName().toString();
                                    generateWsRefInjection[0] = false;
                                    injectionExists = true;
                                    break;
                                }
                            }
                            serviceFieldNames.add(var.getName().toString());
                        }
                    }
                    if (!injectionExists) {
                        serviceFName[0] = findProperServiceFieldName(serviceFieldNames);
                    }
                }
            }
        }
 
Example 20
Source File: Eval.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private List<Snippet> processVariables(String userSource, List<? extends Tree> units, String compileSource, ParseTask pt) {
    List<Snippet> snippets = new ArrayList<>();
    TreeDissector dis = TreeDissector.createByFirstClass(pt);
    for (Tree unitTree : units) {
        VariableTree vt = (VariableTree) unitTree;
        String name = vt.getName().toString();
        String typeName = EvalPretty.prettyExpr((JCTree) vt.getType(), false);
        Tree baseType = vt.getType();
        TreeDependencyScanner tds = new TreeDependencyScanner();
        tds.scan(baseType); // Not dependent on initializer
        StringBuilder sbBrackets = new StringBuilder();
        while (baseType instanceof ArrayTypeTree) {
            //TODO handle annotations too
            baseType = ((ArrayTypeTree) baseType).getType();
            sbBrackets.append("[]");
        }
        Range rtype = dis.treeToRange(baseType);
        Range runit = dis.treeToRange(vt);
        runit = new Range(runit.begin, runit.end - 1);
        ExpressionTree it = vt.getInitializer();
        Range rinit = null;
        int nameMax = runit.end - 1;
        SubKind subkind;
        if (it != null) {
            subkind = SubKind.VAR_DECLARATION_WITH_INITIALIZER_SUBKIND;
            rinit = dis.treeToRange(it);
            nameMax = rinit.begin - 1;
        } else {
            subkind = SubKind.VAR_DECLARATION_SUBKIND;
        }
        int nameStart = compileSource.lastIndexOf(name, nameMax);
        if (nameStart < 0) {
            throw new AssertionError("Name '" + name + "' not found");
        }
        int nameEnd = nameStart + name.length();
        Range rname = new Range(nameStart, nameEnd);
        Wrap guts = Wrap.varWrap(compileSource, rtype, sbBrackets.toString(), rname, rinit);
        DiagList modDiag = modifierDiagnostics(vt.getModifiers(), dis, true);
        Snippet snip = new VarSnippet(state.keyMap.keyForVariable(name), userSource, guts,
                name, subkind, typeName,
                tds.declareReferences(), modDiag);
        snippets.add(snip);
    }
    return snippets;
}