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

The following examples show how to use com.sun.source.tree.VariableTree. 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: besu   Source File: PrivateStaticFinalLoggers.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Description matchVariable(final VariableTree tree, final VisitorState state) {
  final Symbol.VarSymbol sym = ASTHelpers.getSymbol(tree);
  if (sym == null || sym.getKind() != ElementKind.FIELD) {
    return NO_MATCH;
  }
  if (sym.getModifiers()
      .containsAll(List.of(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL))) {
    return NO_MATCH;
  }
  if (!isSubtype(
      getType(tree), state.getTypeFromString("org.apache.logging.log4j.Logger"), state)) {
    return NO_MATCH;
  }
  return buildDescription(tree)
      .addFix(addModifiers(tree, state, Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL))
      .build();
}
 
Example 2
Source Project: netbeans   Source File: GeneratorUtilities.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a setter method for a field.
 *
 * @param clazz the class to create the setter within
 * @param field field to create setter for
 * @return the setter method
 * @since 0.20
 */
public MethodTree createSetter(ClassTree clazz, VariableTree field) {
    assert clazz != null && field != null;
    TreeMaker make = copy.getTreeMaker();
    Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC);
    boolean isStatic = field.getModifiers().getFlags().contains(Modifier.STATIC);
    if (isStatic)
        mods.add(Modifier.STATIC);
    CharSequence name = field.getName();
    assert name.length() > 0;
    CodeStyle cs = DiffContext.getCodeStyle(copy);
    String propName = removeFieldPrefixSuffix(field, cs);
    String setterName = CodeStyleUtils.computeSetterName(field.getName(), isStatic, cs);
    String paramName = addParamPrefixSuffix(propName, cs);
    List<VariableTree> params = Collections.singletonList(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), paramName, field.getType(), null));
    BlockTree body = make.Block(Collections.singletonList(make.ExpressionStatement(make.Assignment(make.MemberSelect(isStatic? make.Identifier(clazz.getSimpleName()) : make.Identifier("this"), name), make.Identifier(paramName)))), false); //NOI18N
    return make.Method(make.Modifiers(mods), setterName, make.Type(copy.getTypes().getNoType(TypeKind.VOID)), Collections.<TypeParameterTree>emptyList(), params, Collections.<ExpressionTree>emptyList(), body, null);
}
 
Example 3
Source Project: netbeans   Source File: FieldTest1.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * copy the initialization 'new String("NetBeers")' to 'new String()'.
 * It tests only change in expression, no expression swap.
 */
public void testFieldChangeInInitValue() throws IOException {
    System.err.println("testFieldChangeInInitValue");
    process(
        new Transformer<Void, Object>() {
            public Void visitVariable(VariableTree node, Object p) {
                super.visitVariable(node, p);
                if ("initialValueReplacer".contentEquals(node.getName())) {
                    if (Tree.Kind.NEW_CLASS.equals(node.getInitializer().getKind())) {
                        NewClassTree nct = (NewClassTree) node.getInitializer();
                        NewClassTree njuNct = make.NewClass(
                                nct.getEnclosingExpression(), 
                                (List<ExpressionTree>) nct.getTypeArguments(),
                                nct.getIdentifier(),
                                Collections.singletonList(make.Literal("NetBeans")),
                                nct.getClassBody()
                        );
                        copy.rewrite(nct, njuNct);
                    }
                }
                return null;
            }
        }
    );
    assertFiles("testFieldChangeInInitValue.pass");
}
 
Example 4
Source Project: netbeans   Source File: JavaSourceHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static ClassTree addConstructor(WorkingCopy copy, ClassTree tree, Modifier[] modifiers, String[] parameters, Object[] paramTypes, String bodyText, String comment) {
    TreeMaker maker = copy.getTreeMaker();
    ModifiersTree modifiersTree = createModifiersTree(copy, modifiers, null, null);
    ModifiersTree paramModTree = maker.Modifiers(Collections.<Modifier>emptySet());
    List<VariableTree> paramTrees = new ArrayList<VariableTree>();

    if (parameters != null) {
        for (int i = 0; i < parameters.length; i++) {
            paramTrees.add(maker.Variable(paramModTree, parameters[i], createTypeTree(copy, paramTypes[i]), null));
        }
    }

    MethodTree methodTree = maker.Constructor(modifiersTree, Collections.<TypeParameterTree>emptyList(), paramTrees, Collections.<ExpressionTree>emptyList(), bodyText);

    if (comment != null) {
        maker.addComment(methodTree, createJavaDocComment(comment), true);
    }

    return maker.addClassMember(tree, methodTree);
}
 
Example 5
Source Project: netbeans   Source File: Tiny.java    License: Apache License 2.0 6 votes vote down vote up
@Hint(displayName = "#DN_CanBeFinal", description = "#DESC_CanBeFinal", category="thread", suppressWarnings="FieldMayBeFinal")
@TriggerTreeKind(Kind.VARIABLE)
public static ErrorDescription canBeFinal(HintContext ctx) {
    Element ve = ctx.getInfo().getTrees().getElement(ctx.getPath());
    
    if (ve == null || ve.getKind() != ElementKind.FIELD || ve.getModifiers().contains(Modifier.FINAL) || /*TODO: the point of volatile?*/ve.getModifiers().contains(Modifier.VOLATILE)) return null;
    
    //we can't say much currently about non-private fields:
    if (!ve.getModifiers().contains(Modifier.PRIVATE)) return null;
    
    FlowResult flow = Flow.assignmentsForUse(ctx);
    
    if (flow == null || ctx.isCanceled()) return null;
    
    if (flow.getFinalCandidates().contains(ve)) {
        VariableTree vt = (VariableTree) ctx.getPath().getLeaf();
        Fix fix = null;
        if (flow.getFieldInitConstructors(ve).size() <= 1) {
            fix = FixFactory.addModifiersFix(ctx.getInfo(), new TreePath(ctx.getPath(), vt.getModifiers()), EnumSet.of(Modifier.FINAL), Bundle.FIX_CanBeFinal(ve.getSimpleName().toString()));
        }
        return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_CanBeFinal(ve.getSimpleName().toString()), fix);
    }
    
    return null;
}
 
Example 6
Source Project: netbeans   Source File: GenerationUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Inserts the given fields in the given class after any fields already existing
 * in the class (if any, otherwise the fields are inserted at the beginning
 * of the class).
 *
 * @param  classTree the class to add fields to; cannot be null.
 * @param  fieldTrees the fields to be added; cannot be null.
 * @return the class containing the new fields; never null.
 */
public ClassTree addClassFields(ClassTree classTree, List<? extends VariableTree> fieldTrees) {
    Parameters.notNull("classTree", classTree); // NOI18N
    Parameters.notNull("fieldTrees", fieldTrees); // NOI18N

    int firstNonFieldIndex = 0;
    Iterator<? extends Tree> memberTrees = classTree.getMembers().iterator();
    while (memberTrees.hasNext() && memberTrees.next().getKind() == Tree.Kind.VARIABLE) {
        firstNonFieldIndex++;
    }
    TreeMaker make = getTreeMaker();
    ClassTree newClassTree = classTree;
    for (VariableTree fieldTree : fieldTrees) {
        newClassTree = make.insertClassMember(newClassTree, firstNonFieldIndex, fieldTree);
        firstNonFieldIndex++;
    }
    return newClassTree;
}
 
Example 7
private void visitEnumConstantDeclaration(VariableTree enumConstant) {
    for (AnnotationTree annotation : enumConstant.getModifiers().getAnnotations()) {
        scan(annotation, null);
        builder.forcedBreak();
    }
    visit(enumConstant.getName());
    NewClassTree init = ((NewClassTree) enumConstant.getInitializer());
    if (init.getArguments().isEmpty()) {
        builder.guessToken("(");
        builder.guessToken(")");
    } else {
        addArguments(init.getArguments(), plusFour);
    }
    if (init.getClassBody() != null) {
        addBodyDeclarations(
                init.getClassBody().getMembers(), BracesOrNot.YES, FirstDeclarationsOrNot.YES);
    }
}
 
Example 8
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 9
Source Project: netbeans   Source File: ConstantNameHint.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean checkZeroSizeArray(CompilationInfo info, TreePath val) {
    if (val.getLeaf().getKind() != Tree.Kind.VARIABLE) {
        return false;
    }
    VariableTree vt = (VariableTree)val.getLeaf();
    ExpressionTree xpr = vt.getInitializer();
    if (xpr == null) {
        return false;
    }
    if (xpr.getKind() == Tree.Kind.NEW_ARRAY) {
        NewArrayTree nat = (NewArrayTree)xpr;
        List<? extends ExpressionTree> dims = nat.getDimensions();
        if (dims != null && !dims.isEmpty()) {
            Object size = ArithmeticUtilities.compute(info, 
                    new TreePath(
                        new TreePath(val, xpr),
                        dims.get(dims.size() -1)), 
                    true);
            return ArithmeticUtilities.isRealValue(size) && Integer.valueOf(0).equals(size);
        } else {
            return nat.getInitializers() != null && nat.getInitializers().isEmpty();
        }
    }
    return false;
}
 
Example 10
Source Project: netbeans   Source File: JavaSourceHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static ClassTree addConstructor(WorkingCopy copy, ClassTree tree, Modifier[] modifiers, String[] parameters, Object[] paramTypes, String bodyText, String comment) {
    TreeMaker maker = copy.getTreeMaker();
    ModifiersTree modifiersTree = createModifiersTree(copy, modifiers, null, null);
    ModifiersTree paramModTree = maker.Modifiers(Collections.<Modifier>emptySet());
    List<VariableTree> paramTrees = new ArrayList<VariableTree>();

    if (parameters != null) {
        for (int i = 0; i < parameters.length; i++) {
            paramTrees.add(maker.Variable(paramModTree, parameters[i], createTypeTree(copy, paramTypes[i]), null));
        }
    }

    MethodTree methodTree = maker.Constructor(modifiersTree, Collections.<TypeParameterTree>emptyList(), paramTrees, Collections.<ExpressionTree>emptyList(), bodyText);

    if (comment != null) {
        maker.addComment(methodTree, createJavaDocComment(comment), true);
    }

    return maker.addClassMember(tree, methodTree);
}
 
Example 11
Source Project: google-java-format   Source File: JavaInputAstVisitor.java    License: Apache License 2.0 6 votes vote down vote up
protected void visitStatements(List<? extends StatementTree> statements) {
  boolean first = true;
  PeekingIterator<StatementTree> it = Iterators.peekingIterator(statements.iterator());
  dropEmptyDeclarations();
  while (it.hasNext()) {
    StatementTree tree = it.next();
    builder.forcedBreak();
    if (!first) {
      builder.blankLineWanted(BlankLineWanted.PRESERVE);
    }
    markForPartialFormat();
    first = false;
    List<VariableTree> fragments = variableFragments(it, tree);
    if (!fragments.isEmpty()) {
      visitVariables(
          fragments,
          DeclarationKind.NONE,
          canLocalHaveHorizontalAnnotations(fragments.get(0).getModifiers()));
    } else {
      scan(tree, null);
    }
  }
}
 
Example 12
Source Project: EasyMPermission   Source File: TreeMirrorMaker.java    License: MIT License 6 votes vote down vote up
@Override public JCTree visitVariable(VariableTree node, Void p) {
	JCVariableDecl original = node instanceof JCVariableDecl ? (JCVariableDecl) node : null;
	JCVariableDecl copy = (JCVariableDecl) super.visitVariable(node, p);
	if (original == null) return copy;
	
	copy.sym = original.sym;
	if (copy.sym != null) copy.type = original.type;
	if (copy.type != null) {
		boolean wipeSymAndType = copy.type.isErroneous();
		if (!wipeSymAndType) {
			TypeTag typeTag = TypeTag.typeTag(copy.type);
			wipeSymAndType = (CTC_NONE.equals(typeTag) || CTC_ERROR.equals(typeTag) || CTC_UNKNOWN.equals(typeTag) || CTC_UNDETVAR.equals(typeTag));
		}
		
		if (wipeSymAndType) {
			copy.sym = null;
			copy.type = null;
		}
	}
	
	return copy;
}
 
Example 13
Source Project: netbeans   Source File: FieldTest1.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Change whole initial value expression to literal 78.
 */
public void testFieldInitialValue() throws IOException {
    System.err.println("testFieldInitialValue");
    process(
        new Transformer<Void, Object>() {
            public Void visitVariable(VariableTree node, Object p) {
                super.visitVariable(node, p);
                if ("initialValueChanger".contentEquals(node.getName())) {
                    copy.rewrite(node.getInitializer(), make.Literal(Long.valueOf(78)));
                }
                return null;
            }
        }
    );
    assertFiles("testFieldInitialValue.pass");
}
 
Example 14
Source Project: netbeans   Source File: Utilities.java    License: Apache License 2.0 6 votes vote down vote up
private static void addAnnotation(WorkingCopy workingCopy, 
        Element element, String annotationName) throws IOException 
 {
    ModifiersTree oldTree = null;
    if (element instanceof TypeElement) {
        oldTree = workingCopy.getTrees().getTree((TypeElement) element).
            getModifiers();
    } else if (element instanceof ExecutableElement) {
        oldTree = workingCopy.getTrees().getTree((ExecutableElement) element).
            getModifiers();
    } else if (element instanceof VariableElement) {
        oldTree = ((VariableTree) workingCopy.getTrees().getTree(element)).
            getModifiers();
    }
    if (oldTree == null) {
        return;
    }
    TreeMaker make = workingCopy.getTreeMaker();
    AnnotationTree annotationTree = make.Annotation(make.QualIdent(annotationName), 
            Collections.<ExpressionTree>emptyList());
    ModifiersTree newTree = make.addModifiersAnnotation(oldTree, annotationTree);
    workingCopy.rewrite(oldTree, newTree);
}
 
Example 15
Source Project: netbeans   Source File: GenerationUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Inserts the given fields in the given class after any fields already existing
 * in the class (if any, otherwise the fields are inserted at the beginning
 * of the class).
 *
 * @param  classTree the class to add fields to; cannot be null.
 * @param  fieldTrees the fields to be added; cannot be null.
 * @return the class containing the new fields; never null.
 */
public ClassTree addClassFields(ClassTree classTree, List fieldTrees) {
    Parameters.notNull("classTree", classTree); // NOI18N
    Parameters.notNull("fieldTrees", fieldTrees); // NOI18N

    int firstNonFieldIndex = 0;
    Iterator<? extends Tree> memberTrees = classTree.getMembers().iterator();
    while (memberTrees.hasNext() && memberTrees.next().getKind() == Tree.Kind.VARIABLE) {
        firstNonFieldIndex++;
    }
    TreeMaker make = getTreeMaker();
    ClassTree newClassTree = classTree;
    for (int i=0; i < fieldTrees.size(); i++ ) {
        VariableTree fieldTree =  (VariableTree)fieldTrees.get(i);        
        newClassTree = make.insertClassMember(newClassTree, firstNonFieldIndex, fieldTree);
        firstNonFieldIndex++;
    }
    return newClassTree;
}
 
Example 16
Source Project: openjdk-jdk9   Source File: JavacParserTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
void testNewClassWithEnclosing() throws IOException {

    final String theString = "Test.this.new d()";
    String code = "package test; class Test { " +
            "class d {} private void method() { " +
            "Object o = " + theString + "; } }";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
            null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    SourcePositions pos = Trees.instance(ct).getSourcePositions();

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    ExpressionTree est =
            ((VariableTree) ((MethodTree) clazz.getMembers().get(1)).getBody().getStatements().get(0)).getInitializer();

    final int spos = code.indexOf(theString);
    final int epos = spos + theString.length();
    assertEquals("testNewClassWithEnclosing",
            spos, pos.getStartPosition(cut, est));
    assertEquals("testNewClassWithEnclosing",
            epos, pos.getEndPosition(cut, est));
}
 
Example 17
/**
 * Gets the variable tree representing the first field of the given type in
 * our class.
 *
 * @param fieldTypeFqn the fully qualified name of the field's type.
 * @return the variable tree or null if no matching field was found.
 */
protected VariableTree getField(final String fieldTypeFqn){
    
    Parameters.notEmpty("fieldTypeFqn", fieldTypeFqn); //NOI18N
    
    for (Tree member : getClassTree().getMembers()){
        if (Tree.Kind.VARIABLE == member.getKind()){
            VariableTree variable = (VariableTree) member;
            TreePath path = getWorkingCopy().getTrees().getPath(getWorkingCopy().getCompilationUnit(), variable);
            TypeMirror variableType = getWorkingCopy().getTrees().getTypeMirror(path);
            if (fieldTypeFqn.equals(variableType.toString())){
                return variable;
            }
            
        }
    }
    return null;
}
 
Example 18
Source Project: netbeans   Source File: ConvertToLambdaConverter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Tree visitVariable(VariableTree variableDeclTree, Trees trees) {
    //check for shadowed variable
    if (isNameAlreadyUsed(variableDeclTree.getName())) {
        TreePath path = getCurrentPath();

        CharSequence newName = getUniqueName(variableDeclTree.getName());

        Element el = trees.getElement(path);
        if (el != null) {
            originalToNewName.put(el, newName);
        }

        VariableTree newTree = copy.getTreeMaker()
                .Variable(variableDeclTree.getModifiers(), newName, variableDeclTree.getType(), variableDeclTree.getInitializer());
        copy.rewrite(variableDeclTree, newTree);
    }

    return super.visitVariable(variableDeclTree, trees);
}
 
Example 19
Source Project: netbeans   Source File: EntityMethodGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public MethodTree createHashCodeMethod(List<VariableTree> fields) {
    StringBuilder body = new StringBuilder(20 + fields.size() * 30);
    body.append("{"); // NOI18N
    body.append("int hash = 0;"); // NOI18N
    for (VariableTree field : fields) {
        body.append(createHashCodeLineForField(field));
    }
    body.append("return hash;"); // 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"))), "hashCode",
            make.PrimitiveType(TypeKind.INT), Collections.<TypeParameterTree>emptyList(),
            Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), body.toString(), null);
}
 
Example 20
Source Project: j2objc   Source File: TreeConverter.java    License: Apache License 2.0 6 votes vote down vote up
private TreeNode convertMethodDeclaration(MethodTree node, TreePath parent) {
  TreePath path = getTreePath(parent, node);
  ExecutableElement element = (ExecutableElement) getElement(path);
  MethodDeclaration newNode = new MethodDeclaration();

  // JCMethodDecl's preferred diagnostic position is the beginning of the method name.
  int methodStartPosition = ((JCMethodDecl) node).pos().getPreferredPosition();

  int length =
      ElementUtil.isConstructor(element)
          ? element.toString().indexOf('(')
          : node.getName().length();

  Name name = Name.newName(null /* qualifier */, element);
  name.setPosition(new SourcePosition(methodStartPosition, length));

  convertBodyDeclaration(node, parent, node.getModifiers(), newNode);
  for (VariableTree param : node.getParameters()) {
    newNode.addParameter((SingleVariableDeclaration) convert(param, path));
  }
  return newNode
      .setIsConstructor(ElementUtil.isConstructor(element))
      .setExecutableElement(element)
      .setBody((Block) convert(node.getBody(), path))
      .setName(name);
}
 
Example 21
Source Project: openjdk-jdk9   Source File: JavacParserTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVarPos() throws IOException {

    final String code = "package t; class Test { " +
            "{ java.io.InputStream in = null; } }";

    CompilationUnitTree cut = getCompilationUnitTree(code);

    new TreeScanner<Void, Void>() {

        @Override
        public Void visitVariable(VariableTree node, Void p) {
            if ("in".contentEquals(node.getName())) {
                JCTree.JCVariableDecl var = (JCTree.JCVariableDecl) node;
                assertEquals("testVarPos","in = null; } }",
                        code.substring(var.pos));
            }
            return super.visitVariable(node, p);
        }
    }.scan(cut, null);
}
 
Example 22
Source Project: netbeans   Source File: AbstractTestGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a public static {@code main(String[])} method
 * with the body taken from settings.
 *
 * @param  maker  {@code TreeMaker} to use for creating the method
 * @return  created {@code main(...)} method,
 *          or {@code null} if the method body would be empty
 */
private MethodTree createMainMethod(TreeMaker maker) {
    String initialMainMethodBody = getInitialMainMethodBody();
    if (initialMainMethodBody.length() == 0) {
        return null;
    }

    ModifiersTree modifiers = maker.Modifiers(
            createModifierSet(Modifier.PUBLIC, Modifier.STATIC));
    VariableTree param = maker.Variable(
                    maker.Modifiers(Collections.<Modifier>emptySet()),
                    "argList",                                      //NOI18N
                    maker.Identifier("String[]"),                   //NOI18N
                    null);            //initializer - not used in params
    MethodTree mainMethod = maker.Method(
          modifiers,                            //public static
          "main",                               //method name "main"//NOI18N
          maker.PrimitiveType(TypeKind.VOID),   //return type "void"
          Collections.<TypeParameterTree>emptyList(),     //type params
          Collections.<VariableTree>singletonList(param), //method param
          Collections.<ExpressionTree>emptyList(),        //throws-list
          '{' + initialMainMethodBody + '}',    //body text
          null);                                //only for annotations

    return mainMethod;
}
 
Example 23
Source Project: netbeans   Source File: AbstractTestGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 */
private List<VariableTree> generateParamVariables(
                                        WorkingCopy workingCopy,
                                        ExecutableType srcMethod,
                                        String[] varNames) {
    TreeMaker maker = workingCopy.getTreeMaker();
    List<? extends TypeMirror> params = srcMethod.getParameterTypes();
    if ((params == null) || params.isEmpty()) {
        return Collections.<VariableTree>emptyList();
    }

    Set<Modifier> noModifiers = Collections.<Modifier>emptySet();
    List<VariableTree> paramVariables = new ArrayList<VariableTree>(params.size());
    int index = 0;
    for (TypeMirror param : params) {
        if (param.getKind() == TypeKind.TYPEVAR){
            param = getSuperType(workingCopy, param);
        }
        paramVariables.add(
                maker.Variable(maker.Modifiers(noModifiers),
                               varNames[index++],
                               maker.Type(param),
                               getDefaultValue(maker, param)));
    }
    return paramVariables;
}
 
Example 24
Source Project: netbeans   Source File: TestGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 */
@Override
protected MethodTree composeNewTestMethod(String testMethodName,
                                          BlockTree testMethodBody,
                                          List<ExpressionTree> throwsList,
                                          WorkingCopy workingCopy) {
    TreeMaker maker = workingCopy.getTreeMaker();
    return maker.Method(
            createModifiersTree(ANN_TEST,
                                createModifierSet(PUBLIC),
                                workingCopy),
            testMethodName,
            maker.PrimitiveType(TypeKind.VOID),
            Collections.<TypeParameterTree>emptyList(),
            Collections.<VariableTree>emptyList(),
            throwsList,
            testMethodBody,
            null);          //default value - used by annotations
}
 
Example 25
Source Project: NullAway   Source File: NullabilityUtil.java    License: MIT License 5 votes vote down vote up
/**
 * determines whether a lambda parameter is missing an explicit type declaration
 *
 * @param lambdaParameter the parameter
 * @return true if there is no type declaration, false otherwise
 */
public static boolean lambdaParamIsImplicitlyTyped(VariableTree lambdaParameter) {
  // kind of a hack; the "preferred position" seems to be the position
  // of the variable name.  if this differs from the start position, it
  // means there is an explicit type declaration
  JCDiagnostic.DiagnosticPosition diagnosticPosition =
      (JCDiagnostic.DiagnosticPosition) lambdaParameter;
  return diagnosticPosition.getStartPosition() == diagnosticPosition.getPreferredPosition();
}
 
Example 26
Source Project: netbeans   Source File: ImportAnalysis2Test.java    License: Apache License 2.0 5 votes vote down vote up
public void testStringQualIdentNewlyCreatedSamePackage() throws Exception {
    testFile = new File(getWorkDir(), "hierbas/del/litoral/Test.java");
    assertTrue(testFile.getParentFile().mkdirs());
    TestUtilities.copyStringToFile(testFile,
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n" +
        "\n" +
        "    A l;\n" +
        "}\n";

    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree nueClass = make.Class(make.Modifiers(EnumSet.noneOf(Modifier.class)), "A", Collections.<TypeParameterTree>emptyList(), null, Collections.<Tree>emptyList(), Collections.<Tree>emptyList());
            CompilationUnitTree nueCUT = make.CompilationUnit(FileUtil.toFileObject(getWorkDir()), "hierbas/del/litoral/A.java", Collections.<ImportTree>emptyList(), Collections.singletonList(nueClass));
            workingCopy.rewrite(null, nueCUT);
            CompilationUnitTree node = workingCopy.getCompilationUnit();
            ClassTree clazz = (ClassTree) node.getTypeDecls().get(0);
            VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "l", make.QualIdent("hierbas.del.litoral.A"), null);
            workingCopy.rewrite(clazz, make.addClassMember(clazz, vt));
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 27
Source Project: netbeans   Source File: ElementScanningTask.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Context visitVariable(VariableTree node, Void p) {
    Element e = this.trees.getElement(this.getCurrentPath());
    if (e != null) {
        long pos = this.sourcePositions.getStartPosition(cu, node);
        ctx.pos.put(e, pos);
    }
    return null;
}
 
Example 28
Source Project: netbeans   Source File: JerseyGenerationStrategy.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClassTree generateFields(TreeMaker maker, WorkingCopy copy,
        ClassTree classTree,String resourceURI,Security security) 
{
    // add 3 fields
    ModifiersTree fieldModif =  maker.Modifiers(Collections.<Modifier>singleton(Modifier.PRIVATE));
    Tree typeTree = JavaSourceHelper.createTypeTree(copy, "com.sun.jersey.api.client.WebResource"); //NOI18N
    VariableTree fieldTree = maker.Variable(fieldModif, "webResource", typeTree, null); //NOI18N
    ClassTree modifiedClass = maker.addClassMember(classTree, fieldTree);

    fieldModif =  maker.Modifiers(Collections.<Modifier>singleton(Modifier.PRIVATE));
    typeTree = JavaSourceHelper.createTypeTree(copy, "com.sun.jersey.api.client.Client"); //NOI18N
    fieldTree = maker.Variable(fieldModif, "client", typeTree, null); //NOI18N
    modifiedClass = maker.addClassMember(modifiedClass, fieldTree);

    Set<Modifier> modifiersSet = new HashSet<Modifier>();
    modifiersSet.add(Modifier.PRIVATE);
    modifiersSet.add(Modifier.STATIC);
    modifiersSet.add(Modifier.FINAL);
    fieldModif =  maker.Modifiers(modifiersSet);
    typeTree = maker.Identifier("String"); //NOI18N

    String baseUri = resourceURI;
    if (security.isSSL() && resourceURI.startsWith("http:")) { //NOI18N
        baseUri = "https:"+resourceURI.substring(5); //NOI18N
    }
    fieldTree = maker.Variable(fieldModif, "BASE_URI", typeTree, maker.Literal(baseUri)); //NOI18N
    modifiedClass = maker.addClassMember(modifiedClass, fieldTree);      
    return modifiedClass;
}
 
Example 29
Source Project: netbeans   Source File: SAXGeneratorSupport.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Stub's method. It is SAX 2.0 method
 */
private MethodTree genStartPrefixMappingMethod(TreeMaker make)  {
    MethodTree method = null;
    if (sax == 2) {
        //first create the body
         StringBuffer code = new StringBuffer("{\n");
         if (model.isPropagateSAX())
            code.append ("handler." + M_START_PREFIX_MAPPING + "(prefix, uri);\n"); // NOI18N
         code.append("}\n");
         
         //method params
         Tree stree = make.Identifier("java.lang.String");
         VariableTree par1 = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "prefix", stree, null);
         VariableTree par2 = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "uri", stree, null);
         List parList = new ArrayList(2);
         parList.add(par1);
         parList.add(par2);
         ModifiersTree mods = make.Modifiers(EnumSet.of(Modifier.PUBLIC,Modifier.FINAL));
    
          method = make.Method(
                        mods,
                        M_START_PREFIX_MAPPING,
                        make.PrimitiveType(TypeKind.VOID),
                        Collections.<TypeParameterTree>emptyList(),
                        parList,
                        Collections.singletonList(make.Identifier(SAX_EXCEPTION)),
                        code.toString(),
                        null
                    );
    }

    return method;
}
 
Example 30
Source Project: netbeans   Source File: GenerationUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new field.
 *
 * @param  scope the scope in which to create the field (will be e.g. used
 *         to parse <code>fieldType</code>).
 * @param  modifiersTree the field modifiers; cannot be null.
 * @param  fieldType the fully-qualified name of the field type; cannot be null.
 * @param  fieldName the field name; cannot be null.
 * @param  expressionTree expression to initialize the field; can be null.
 * @return the new field; never null.
 */
public VariableTree createField(TypeElement scope, ModifiersTree modifiersTree, String fieldName, String fieldType, ExpressionTree expressionTree) {
    Parameters.notNull("modifiersTree", modifiersTree); // NOI18N
    Parameters.javaIdentifier("fieldName", fieldName); // NOI18N
    Parameters.notNull("fieldType", fieldType); // NOI18N

    return getTreeMaker().Variable(
            modifiersTree,
            fieldName,
            createType(fieldType, scope),
            expressionTree);
}