Java Code Examples for com.sun.source.tree.Tree.Kind#VARIABLE

The following examples show how to use com.sun.source.tree.Tree.Kind#VARIABLE . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UtilitiesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void performResolveFieldGroupTest(String code, int numOfElements) throws Exception {
    String[] split = code.split("\\|");
    int start = split[0].length();
    int end   = split[0].length() + split[1].length();

    code = split[0] + split[1] + split[2];

    prepareTest(code);

    TreePath tp = info.getTreeUtilities().pathFor(start + 1);

    while (tp.getLeaf().getKind() != Kind.VARIABLE) {
        tp = tp.getParentPath();
    }

    Collection<? extends TreePath> tps = Utilities.resolveFieldGroup(info, tp);

    assertFieldGroup(info, tps, start, end, numOfElements);

    for (TreePath inGroup : tps) {
        assertFieldGroup(info, Utilities.resolveFieldGroup(info, inGroup), start, end, numOfElements);
    }
}
 
Example 2
Source File: TreeConverter.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private SourcePosition getNamePosition(Tree node) {
  int start = (int) sourcePositions.getStartPosition(unit, node);
  if (start == -1) {
    return SourcePosition.NO_POSITION;
  }
  String src = newUnit.getSource();
  Kind kind = node.getKind();
  if (kind == Kind.ANNOTATION_TYPE
      || kind == Kind.CLASS
      || kind == Kind.ENUM
      || kind == Kind.INTERFACE) {
    // Skip the class/enum/interface token.
    while (src.charAt(start++) != ' ') {}
  } else if (kind != Kind.METHOD && kind != Kind.VARIABLE) {
    return getPosition(node);
  }
  if (!Character.isJavaIdentifierStart(src.charAt(start))) {
    return getPosition(node);
  }
  int endPos = start + 1;
  while (Character.isJavaIdentifierPart(src.charAt(endPos))) {
    endPos++;
  }
  return getSourcePosition(start, endPos);
}
 
Example 3
Source File: Tiny.java    From netbeans with 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 4
Source File: JavadocHint.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Hint(id = "error-in-javadoc", category = "JavaDoc", description = "#DESC_ERROR_IN_JAVADOC_HINT", displayName = "#DN_ERROR_IN_JAVADOC_HINT", hintKind = Hint.Kind.INSPECTION, severity = Severity.WARNING, customizerProvider = JavadocHint.CustomizerProviderImplError.class)
@TriggerTreeKind({Kind.METHOD, Kind.ANNOTATION_TYPE, Kind.CLASS, Kind.ENUM, Kind.INTERFACE, Kind.VARIABLE})
public static List<ErrorDescription> errorHint(final HintContext ctx) {
    Preferences pref = ctx.getPreferences();
    boolean correctJavadocForNonPublic = pref.getBoolean(AVAILABILITY_KEY + false, false);

    CompilationInfo javac = ctx.getInfo();
    Boolean publiclyAccessible = AccessibilityQuery.isPubliclyAccessible(javac.getFileObject().getParent());
    boolean isPubliclyA11e = publiclyAccessible == null ? true : publiclyAccessible;

    if (!isPubliclyA11e && !correctJavadocForNonPublic) {
        return null;
    }

    if (javac.getElements().getTypeElement("java.lang.Object") == null) { // NOI18N
        // broken java platform
        return Collections.<ErrorDescription>emptyList();
    }

    TreePath path = ctx.getPath();
    {
        Document doc = null;
        try {
            doc = javac.getDocument();
        } catch (IOException e) {
            Exceptions.printStackTrace(e);
        }
        if (doc != null && isGuarded(path.getLeaf(), javac, doc)) {
            return null;
        }
    }
    
    Access access = Access.resolve(pref.get(SCOPE_KEY, SCOPE_DEFAULT));
    Analyzer a = new Analyzer(javac, path, access, ctx);
    return a.analyze();
}
 
Example 5
Source File: TreeConverter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private TreeNode convertEnum(ClassTree node, TreePath parent) {
  TreePath path = getTreePath(parent, node);
  TypeElement element = (TypeElement) getElement(path);
  if (ElementUtil.isAnonymous(element)) {
    return convertClassDeclaration(node, parent).setPosition(getPosition(node));
  }
  EnumDeclaration newNode = new EnumDeclaration();
  convertBodyDeclaration(node, parent, node.getModifiers(), newNode);
  newNode
      .setName(convertSimpleName(element, getTypeMirror(path), getNamePosition(node)))
      .setTypeElement(element);
  for (Tree bodyDecl : node.getMembers()) {
    if (bodyDecl.getKind() == Kind.VARIABLE) {
      TreeNode var = convertVariableDeclaration((VariableTree) bodyDecl, path);
      if (var.getKind() == TreeNode.Kind.ENUM_CONSTANT_DECLARATION) {
        newNode.addEnumConstant((EnumConstantDeclaration) var);
      } else {
        newNode.addBodyDeclaration((BodyDeclaration) var);
      }
    } else if (bodyDecl.getKind() == Kind.BLOCK) {
      BlockTree javacBlock = (BlockTree) bodyDecl;
      Block block = (Block) convert(javacBlock, path);
      newNode.addBodyDeclaration(new Initializer(block, javacBlock.isStatic()));
    } else {
      newNode.addBodyDeclaration((BodyDeclaration) convert(bodyDecl, path));
    }
  }
  return newNode;
}
 
Example 6
Source File: ClassStructure.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.ClassStructure.protectedMemberInFinalClass", description = "#DESC_org.netbeans.modules.java.hints.ClassStructure.protectedMemberInFinalClass", category = "class_structure", enabled = false, suppressWarnings = {"ProtectedMemberInFinalClass"}) //NOI18N
@TriggerTreeKind({Kind.METHOD, Kind.VARIABLE})
public static ErrorDescription protectedMemberInFinalClass(HintContext context) {
    final Tree tree = context.getPath().getLeaf();
    final Tree parent = context.getPath().getParentPath().getLeaf();
    if (TreeUtilities.CLASS_TREE_KINDS.contains(parent.getKind())) {
        if (tree.getKind() == Kind.METHOD) {
            final MethodTree mth = (MethodTree) tree;
            if (mth.getModifiers().getFlags().contains(Modifier.PROTECTED) && ((ClassTree) parent).getModifiers().getFlags().contains(Modifier.FINAL)) {
                Element el = context.getInfo().getTrees().getElement(context.getPath());
                if (el == null || el.getKind() != ElementKind.METHOD) {
                    return null;
                }
                List<ElementDescription> overrides = new LinkedList<ElementDescription>();
                ComputeOverriding.detectOverrides(context.getInfo(), (TypeElement) el.getEnclosingElement(), (ExecutableElement) el, overrides);
                for (ElementDescription ed : overrides) {
                    Element res = ed.getHandle().resolve(context.getInfo());
                    if (res == null) {
                        continue; //XXX: log
                    }
                    if (   res.getModifiers().contains(Modifier.PROTECTED)
                        || /*to prevent reports for broken sources:*/ res.getModifiers().contains(Modifier.PUBLIC)) {
                        return null;
                    }
                }
                return ErrorDescriptionFactory.forName(context, mth, NbBundle.getMessage(ClassStructure.class, "MSG_ProtectedMethodInFinalClass", mth.getName()), //NOI18N
                        FixFactory.removeModifiersFix(context.getInfo(), TreePath.getPath(context.getPath(), mth.getModifiers()), EnumSet.of(Modifier.PROTECTED), NbBundle.getMessage(ClassStructure.class, "FIX_RemoveProtectedFromMethod", mth.getName()))); //NOI18N
            }
        } else {
            final VariableTree var = (VariableTree) tree;
            if (var.getModifiers().getFlags().contains(Modifier.PROTECTED) && ((ClassTree) parent).getModifiers().getFlags().contains(Modifier.FINAL)) {
                return ErrorDescriptionFactory.forName(context, var, NbBundle.getMessage(ClassStructure.class, "MSG_ProtectedFieldInFinalClass", var.getName()), //NOI18N
                        FixFactory.removeModifiersFix(context.getInfo(), TreePath.getPath(context.getPath(), var.getModifiers()), EnumSet.of(Modifier.PROTECTED), NbBundle.getMessage(ClassStructure.class, "FIX_RemoveProtectedFromField", var.getName()))); //NOI18N
            }
        }
    }
    return null;
}
 
Example 7
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Finds the top-level block or expression that contains the 'from' path.
 * The result could be a 
 * <ul>
 * <li>BlockTree representing method body
 * <li>ExpressionTree representing field initializer
 * <li>BlockTree representing class initializer
 * <li>ExpressionTree representing lambda expression
 * <li>BlockTree representing lambda expression
 * </ul>
 * @param from start from 
 * @return nearest enclosing top-level block/expression as defined above.
 */
public static TreePath findTopLevelBlock(TreePath from) {
    if (from.getLeaf().getKind() == Tree.Kind.COMPILATION_UNIT) {
        return null;
    }
    TreePath save = null;
    
    while (from != null) {
        Tree.Kind k = from.getParentPath().getLeaf().getKind();
        if (k == Kind.METHOD || k == Kind.LAMBDA_EXPRESSION) {
            return from;
        } else if (k == Kind.VARIABLE) {
            save = from;
        } else if (TreeUtilities.CLASS_TREE_KINDS.contains(k)) {
            if (save != null) {
                // variable initializer from the previous iteration
                return save;
            }
            if (from.getLeaf().getKind() == Kind.BLOCK) {
                // parent is class, from is block -> initializer
                return from;
            }
            return null;
        } else {
            save = null;
        }
        from = from.getParentPath();
    }
    return null;
}
 
Example 8
Source File: AddParameterOrLocalFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isEnhancedForLoopVariable(TreePath tp) {
    if (tp.getLeaf().getKind() != Kind.VARIABLE)
        return false;
    TreePath context = tp.getParentPath();
    if (context == null || context.getLeaf().getKind() != Kind.ENHANCED_FOR_LOOP)
        return false;
    return true;
}
 
Example 9
Source File: EqualsHashCodeGeneratorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testObjectEditing1() throws Exception {
    FileObject java = FileUtil.createData(fo, "X.java");
    final String what1 = "package java.lang; public class Object {\n" +
                         "  public int hashCode() {return 0;}" +
                         "  public static int hashCode(Object o) {return 0;}" +
                         "  public boolean equals(Object o) {return false;}" +
                         "  public boolean equals(Object o1, Object o2) {return false;}" +
                         "  \n";

    String what2 =
        "}\n";
    String what = what1 + what2;
    GeneratorUtilsTest.writeIntoFile(java, what);

    JavaSource js = JavaSource.forFileObject(java);
    assertNotNull("Created", js);

    class TaskImpl implements Task<WorkingCopy> {
        public void run(WorkingCopy copy) throws Exception {
            copy.toPhase(JavaSource.Phase.RESOLVED);
            ClassTree clazzTree = (ClassTree) copy.getCompilationUnit().getTypeDecls().get(0);
            TreePath clazz = new TreePath(new TreePath(copy.getCompilationUnit()), clazzTree);
            List<VariableElement> vars = new LinkedList<VariableElement>();

            for (Tree m : clazzTree.getMembers()) {
                if (m.getKind() == Kind.VARIABLE) {
                    vars.add((VariableElement) copy.getTrees().getElement(new TreePath(clazz, m)));
                }
            }

            EqualsHashCodeGenerator.overridesHashCodeAndEquals(copy, copy.getTrees().getElement(clazz), null);
        }
    }

    TaskImpl t = new TaskImpl();

    js.runModificationTask(t);
}
 
Example 10
Source File: FieldEncapsulation.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.encapsulation.FieldEncapsulation.publicField", description = "#DESC_org.netbeans.modules.java.hints.encapsulation.FieldEncapsulation.publicField", category="encapsulation", suppressWarnings={"PublicField"}, enabled=false, options=Options.QUERY) //NOI18N
@UseOptions(ALLOW_ENUMS_KEY)
@TriggerTreeKind(Kind.VARIABLE)
public static ErrorDescription publicField(final HintContext ctx) {
    return create(ctx,
        Visibility.PUBLIC,
        NbBundle.getMessage(FieldEncapsulation.class, "TXT_PublicField"));
}
 
Example 11
Source File: FieldEncapsulation.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.encapsulation.FieldEncapsulation.protectedField", description = "#DESC_org.netbeans.modules.java.hints.encapsulation.FieldEncapsulation.protectedField", category="encapsulation", suppressWarnings={"ProtectedField"}, enabled=false, options=Options.QUERY) //NOI18N
@UseOptions(ALLOW_ENUMS_KEY)
@TriggerTreeKind(Kind.VARIABLE)
public static ErrorDescription protectedField(final HintContext ctx) {
    return create(ctx,
        Visibility.PROTECTED,
        NbBundle.getMessage(FieldEncapsulation.class, "TXT_ProtectedField"));
}
 
Example 12
Source File: JavadocCompletionUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static TreePath findJavadoc(CompilationInfo javac, int offset) {
    TokenSequence<JavaTokenId> ts = SourceUtils.getJavaTokenSequence(javac.getTokenHierarchy(), offset);
    if (ts == null || !movedToJavadocToken(ts, offset)) {
        return null;
    }

    int offsetBehindJavadoc = ts.offset() + ts.token().length();

    while (ts.moveNext()) {
        TokenId tid = ts.token().id();
        if (tid == JavaTokenId.BLOCK_COMMENT) {
            if ("/**/".contentEquals(ts.token().text())) { // NOI18N
                // see #147533
                return null;
            }
        } else if (tid == JavaTokenId.JAVADOC_COMMENT) {
            if (ts.token().partType() == PartType.COMPLETE) {
                return null;
            }
        } else if (!IGNORE_TOKES.contains(tid)) {
            offsetBehindJavadoc = ts.offset();
            // it is magic for TreeUtilities.pathFor
            ++offsetBehindJavadoc;
            break;
        }
    }

    TreePath tp = javac.getTreeUtilities().pathFor(offsetBehindJavadoc);
    
    while (!TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind()) && tp.getLeaf().getKind() != Kind.METHOD && tp.getLeaf().getKind() != Kind.VARIABLE && tp.getLeaf().getKind() != Kind.COMPILATION_UNIT) {
        tp = tp.getParentPath();
        if (tp == null) {
            break;
        }
    }
    
    return tp;
}
 
Example 13
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private SourcePosition getNamePosition(String name, JCTree node) {
  int start = node.getPreferredPosition();
  if (start == -1) {
    return null;
  }

  try {
    String src = javacUnit.sourcefile.getCharContent(true).toString();
    Kind kind = node.getKind();
    if (kind == Kind.ANNOTATION_TYPE
        || kind == Kind.CLASS
        || kind == Kind.ENUM
        || kind == Kind.INTERFACE) {
      // Skip the class/enum/interface token.
      while (src.charAt(start++) != ' ') {}
    } else if (kind != Kind.METHOD && kind != Kind.VARIABLE) {
      return getSourcePosition(node);
    }
    if (!Character.isJavaIdentifierStart(src.charAt(start))) {
      return getSourcePosition(node);
    }
    int endPos = start + 1;
    while (Character.isJavaIdentifierPart(src.charAt(endPos))) {
      endPos++;
    }
    return getSourcePosition(name, start, endPos);
  } catch (IOException e) {
    throw internalCompilerError(e, "Error getting name Position for: %s.", node);
  }
}
 
Example 14
Source File: TreeUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static TypeMirror attributeTree(JavacTaskImpl jti, Tree tree, Scope scope, final List<Diagnostic<? extends JavaFileObject>> errors) {
        Log log = Log.instance(jti.getContext());
        JavaFileObject prev = log.useSource(new DummyJFO());
        Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log) {
            @Override
            public void report(JCDiagnostic diag) {
                errors.add(diag);
            }            
        };
        NBResolve resolve = NBResolve.instance(jti.getContext());
        resolve.disableAccessibilityChecks();
//        Enter enter = Enter.instance(jti.getContext());
//        enter.shadowTypeEnvs(true);
//        ArgumentAttr argumentAttr = ArgumentAttr.instance(jti.getContext());
//        ArgumentAttr.LocalCacheContext cacheContext = argumentAttr.withLocalCacheContext();
        try {
            Attr attr = Attr.instance(jti.getContext());
            Env<AttrContext> env = getEnv(scope);
            if (tree instanceof JCExpression)
                return attr.attribExpr((JCTree) tree,env, Type.noType);
            if (env.tree != null && env.tree.getKind() == Kind.VARIABLE && !VARIABLE_CAN_OWN_VARIABLES) {
                env = env.next;
            }
            return attr.attribStat((JCTree) tree,env);
        } finally {
//            cacheContext.leave();
            log.useSource(prev);
            log.popDiagnosticHandler(discardHandler);
            resolve.restoreAccessbilityChecks();
//            enter.shadowTypeEnvs(false);
        }
    }
 
Example 15
Source File: TreePathHandle.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Kind getKind() {
    switch (el.getKind()) {
        case PACKAGE:
            return Kind.COMPILATION_UNIT;
            
        case ENUM:
        case CLASS:
        case ANNOTATION_TYPE:
        case INTERFACE:
            return Kind.CLASS;
            
        case ENUM_CONSTANT:
        case FIELD:
        case PARAMETER:
        case LOCAL_VARIABLE:
        case RESOURCE_VARIABLE:
        case EXCEPTION_PARAMETER:
            return Kind.VARIABLE;
            
        case METHOD:
        case CONSTRUCTOR:
            return Kind.METHOD;
            
        case STATIC_INIT:
        case INSTANCE_INIT:
            return Kind.BLOCK;
            
        case TYPE_PARAMETER:
            return Kind.TYPE_PARAMETER;
            
        case OTHER:
        default:
            return Kind.OTHER;
    }
}
 
Example 16
Source File: IntroduceHint.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static TreePath validateSelection(CompilationInfo ci, int start, int end, Set<TypeKind> ignoredTypes) {
    int[] span = TreeUtils.ignoreWhitespaces(ci, Math.min(start, end), Math.max(start, end));

    start = span[0];
    end   = span[1];
    
    TreePath tp = ci.getTreeUtilities().pathFor((start + end) / 2 + 1);

    for ( ; tp != null; tp = tp.getParentPath()) {
        Tree leaf = tp.getLeaf();

        if (   !ExpressionTree.class.isAssignableFrom(leaf.getKind().asInterface())
            && (leaf.getKind() != Kind.VARIABLE || ((VariableTree) leaf).getInitializer() == null))
           continue;

        long treeStart = ci.getTrees().getSourcePositions().getStartPosition(ci.getCompilationUnit(), leaf);
        long treeEnd   = ci.getTrees().getSourcePositions().getEndPosition(ci.getCompilationUnit(), leaf);

        if (treeStart != start || treeEnd != end) {
            continue;
        }

        TypeMirror type = ci.getTrees().getTypeMirror(tp);

        if (type != null && type.getKind() == TypeKind.ERROR) {
            type = ci.getTrees().getOriginalType((ErrorType) type);
        }

        if (type == null || ignoredTypes.contains(type.getKind()))
            continue;

        if(tp.getLeaf().getKind() == Kind.ASSIGNMENT)
            continue;

        if (tp.getLeaf().getKind() == Kind.ANNOTATION)
            continue;

        if (!TreeUtils.isInsideClass(tp))
            return null;

        TreePath candidate = tp;

        tp = tp.getParentPath();

        while (tp != null) {
            switch (tp.getLeaf().getKind()) {
                case VARIABLE:
                    VariableTree vt = (VariableTree) tp.getLeaf();
                    if (vt.getInitializer() == leaf) {
                        return candidate;
                    } else {
                        return null;
                    }
                case NEW_CLASS:
                    NewClassTree nct = (NewClassTree) tp.getLeaf();
                    
                    if (nct.getIdentifier().equals(candidate.getLeaf())) { //avoid disabling hint ie inside of anonymous class higher in treepath
                        for (Tree p : nct.getArguments()) {
                            if (p == leaf) {
                                return candidate;
                            }
                        }

                        return null;
                    }
            }

            leaf = tp.getLeaf();
            tp = tp.getParentPath();
        }

        return candidate;
    }

    return null;
}
 
Example 17
Source File: IteratorToFor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private String assignedToVariable(TransformationContext ctx, TypeMirror variableType, TreePath forStatement, List<TreePath> toReplace) {
    if (forStatement.getLeaf().getKind() != Kind.BLOCK) return null;

    BlockTree block = (BlockTree) forStatement.getLeaf();

    if (block.getStatements().isEmpty()) return null;

    StatementTree first = block.getStatements().get(0);

    if (first.getKind() != Kind.VARIABLE) return null;

    VariableTree var = (VariableTree) first;
    TypeMirror varType = ctx.getWorkingCopy().getTrees().getTypeMirror(new TreePath(forStatement, var.getType()));

    if (varType == null || !ctx.getWorkingCopy().getTypes().isSameType(variableType, varType)) return null;

    for (TreePath tp : toReplace) {
        if (tp.getLeaf() == var.getInitializer()) return var.getName().toString();
    }

    return null;
}
 
Example 18
Source File: EqualsHashCodeGeneratorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void test142212() throws Exception {
    EqualsHashCodeGenerator.randomNumber = 1;
    
    FileObject java = FileUtil.createData(fo, "X.java");
    final String what1 = "class X {\n" +
                         "  private byte b;\n" +
                         "  private int[] x;\n" +
                         "  private String[] y;\n" +
                         "  private String s;\n" +
                         "  private Object o;\n";

    String what2 =
        "}\n";
    String what = what1 + what2;
    GeneratorUtilsTest.writeIntoFile(java, what);

    JavaSource js = JavaSource.forFileObject(java);
    assertNotNull("Created", js);

    class TaskImpl implements Task<WorkingCopy> {
        public void run(WorkingCopy copy) throws Exception {
            copy.toPhase(JavaSource.Phase.RESOLVED);
            ClassTree clazzTree = (ClassTree) copy.getCompilationUnit().getTypeDecls().get(0);
            TreePath clazz = new TreePath(new TreePath(copy.getCompilationUnit()), clazzTree);
            List<VariableElement> vars = new LinkedList<VariableElement>();

            for (Tree m : clazzTree.getMembers()) {
                if (m.getKind() == Kind.VARIABLE) {
                    vars.add((VariableElement) copy.getTrees().getElement(new TreePath(clazz, m)));
                }
            }

            EqualsHashCodeGenerator.generateEqualsAndHashCode(copy, clazz, vars, vars, -1);
        }
    }

    TaskImpl t = new TaskImpl();

    js.runModificationTask(t).commit();

    DataObject dObj = DataObject.find(java);
    EditorCookie ec = dObj != null ? dObj.getCookie(org.openide.cookies.EditorCookie.class) : null;
    Document doc = ec != null ? ec.getDocument() : null;
    
    String result = doc != null ? doc.getText(0, doc.getLength()) : TestUtilities.copyFileToString(FileUtil.toFile(java));
    String golden = "\nimport java.util.Arrays;\n" +
                    "class X {\n" +
                    "  private byte b;\n" +
                    "  private int[] x;\n" +
                    "  private String[] y;\n" +
                    "  private String s;\n" +
                    "  private Object o;\n" +
                    "    @Override\n" +
                    "    public int hashCode() {\n" +
                    "        int hash = 1;\n" +
                    "        hash = 1 * hash + this.b;\n" +
                    "        hash = 1 * hash + Arrays.hashCode(this.x);\n" +
                    "        hash = 1 * hash + Arrays.deepHashCode(this.y);\n" +
                    "        hash = 1 * hash + (this.s != null ? this.s.hashCode() : 0);\n" +
                    "        hash = 1 * hash + (this.o != null ? this.o.hashCode() : 0);\n" +
                    "        return hash;\n" +
                    "    }\n" +
                    "    @Override\n" +
                    "    public boolean equals(Object obj) {\n" +
                    "        if (this == obj) {\n" +
                    "            return true;\n" +
                    "        }\n" +
                    "        if (obj == null) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        if (getClass() != obj.getClass()) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        final X other = (X) obj;\n" +
                    "        if (this.b != other.b) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        if ((this.s == null) ? (other.s != null) : !this.s.equals(other.s)) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        if (!Arrays.equals(this.x, other.x)) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        if (!Arrays.deepEquals(this.y, other.y)) {\n" +
                    "            return false;\n" +
                    "        }" +
                    "        if (this.o != other.o && (this.o == null || !this.o.equals(other.o))) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        return true;\n" +
                    "    }\n" +
                    "}\n";

    result = result.replaceAll("[ \t\n]+", " ");
    golden = golden.replaceAll("[ \t\n]+", " ");
    
    assertEquals(golden, result);
}
 
Example 19
Source File: EqualsHashCodeGeneratorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void test227171() throws Exception {
    sourceLevel = "1.7";
    
    EqualsHashCodeGenerator.randomNumber = 1;
    
    FileObject java = FileUtil.createData(fo, "X.java");
    final String what1 = "class X {\n" +
                         "  private final E e;\n" +
                         "  enum E {A}\n";
    String what2 =
        "}\n";
    String what = what1 + what2;
    GeneratorUtilsTest.writeIntoFile(java, what);

    JavaSource js = JavaSource.forFileObject(java);
    assertNotNull("Created", js);

    class TaskImpl implements Task<WorkingCopy> {
        @Override public void run(WorkingCopy copy) throws Exception {
            copy.toPhase(JavaSource.Phase.RESOLVED);
            ClassTree clazzTree = (ClassTree) copy.getCompilationUnit().getTypeDecls().get(0);
            TreePath clazz = new TreePath(new TreePath(copy.getCompilationUnit()), clazzTree);
            List<VariableElement> vars = new LinkedList<>();

            for (Tree m : clazzTree.getMembers()) {
                if (m.getKind() == Kind.VARIABLE) {
                    vars.add((VariableElement) copy.getTrees().getElement(new TreePath(clazz, m)));
                }
            }

            EqualsHashCodeGenerator.generateEqualsAndHashCode(copy, clazz, vars, vars, -1);
        }
    }

    TaskImpl t = new TaskImpl();

    js.runModificationTask(t).commit();

    DataObject dObj = DataObject.find(java);
    EditorCookie ec = dObj != null ? dObj.getLookup().lookup(org.openide.cookies.EditorCookie.class) : null;
    Document doc = ec != null ? ec.getDocument() : null;
    
    String result = doc != null ? doc.getText(0, doc.getLength()) : TestUtilities.copyFileToString(FileUtil.toFile(java));
    String golden = "\nimport java.util.Objects;\n" +
                    "class X {\n" +
                    "  private final E e;\n" +
                    "    @Override\n" +
                    "    public int hashCode() {\n" +
                    "        int hash = 1;\n" +
                    "        hash = 1 * hash + Objects.hashCode(this.e);\n" +
                    "        return hash;\n" +
                    "    }\n" +
                    "    @Override\n" +
                    "    public boolean equals(Object obj) {\n" +
                    "        if (this == obj) {\n" +
                    "            return true;\n" +
                    "        }\n" +
                    "        if (obj == null) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        if (getClass() != obj.getClass()) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        final X other = (X) obj;\n" +
                    "        if (this.e != other.e) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        return true;\n" +
                    "    }\n" +
                    "  enum E {A}\n" +
                    "}\n";

    result = result.replaceAll("[ \t\n]+", " ");
    golden = golden.replaceAll("[ \t\n]+", " ");
    
    assertEquals(golden, result);
}
 
Example 20
Source File: CreateQualifier.java    From netbeans with Apache License 2.0 4 votes vote down vote up
protected List<Fix> analyze( CompilationInfo compilationInfo, int offset )
    throws IOException 
{
    TreePath errorPath = findUnresolvedElement(compilationInfo, offset);
    if ( !checkProject(compilationInfo) || errorPath == null) {
        return Collections.<Fix>emptyList();
    }

    if (compilationInfo.getElements().getTypeElement("java.lang.Object") == null) { // NOI18N
        // broken java platform
        return Collections.<Fix>emptyList();
    }
    
    Element element = compilationInfo.getTrees().getElement(errorPath);
    if ( element == null || element.getSimpleName() == null || 
            errorPath.getLeaf().getKind() != Kind.IDENTIFIER )
    {
        return Collections.<Fix>emptyList();
    }
    
    TreePath parentPath = errorPath.getParentPath();
    if ( parentPath.getLeaf().getKind() != Kind.ANNOTATION ){
        return Collections.<Fix>emptyList();
    }
    Element annotation = compilationInfo.getTrees().getElement(parentPath);
    TreePath path = parentPath;
    while (path != null ){
        Tree leaf = path.getLeaf();
        Kind leafKind = leaf.getKind();
        if ( TreeUtilities.CLASS_TREE_KINDS.contains(leafKind) ){
            Element clazz = compilationInfo.getTrees().getElement(path);
            if ( clazz != null && clazz.getKind() == ElementKind.CLASS )
            {
                return analyzeClass( compilationInfo , (TypeElement)clazz , 
                        annotation );
            }
        }
        else if ( leafKind == Kind.VARIABLE){
            Element var = compilationInfo.getTrees().getElement(path);
            if ( var == null ){
                return null;
            }
            Element parent = var.getEnclosingElement();
            if ( var.getKind() == ElementKind.FIELD && 
                    (parent instanceof TypeElement))
            {
                return analyzeField( compilationInfo , var , annotation ,
                        (TypeElement)parent);
            }
        }
        else if ( leafKind == Kind.METHOD ){
            Element method = compilationInfo.getTrees().getElement(path);
            if ( method != null && method.getKind() == ElementKind.METHOD){
                return analyzeMethodParameter( compilationInfo , 
                        (ExecutableElement)method , annotation );
            }
        }
        path = path.getParentPath();
    }
    
    return null;
}