javax.lang.model.type.ErrorType Java Examples

The following examples show how to use javax.lang.model.type.ErrorType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: netbeans   Author: apache   File: TypeUtilities.java    License: Apache License 2.0 6 votes vote down vote up
private static TypeMirror resolveCapturedType(CompilationInfo info, TypeMirror tm) {
    if (tm == null) {
        return tm;
    }
    if (tm.getKind() == TypeKind.ERROR) {
        tm = info.getTrees().getOriginalType((ErrorType) tm);
    }
    TypeMirror type = resolveCapturedTypeInt(info, tm);
    if (type == null) {
        return tm;
    }
    if (type.getKind() == TypeKind.WILDCARD) {
        TypeMirror tmirr = ((WildcardType) type).getExtendsBound();
        if (tmirr != null)
            return tmirr;
        else { //no extends, just '?'
            TypeElement te = info.getElements().getTypeElement("java.lang.Object"); // NOI18N
            return te == null ? null : te.asType();
        }
            
    }
    
    return type;
}
 
Example #2
Source Project: netbeans   Author: apache   File: Utilities.java    License: Apache License 2.0 6 votes vote down vote up
public static TypeMirror resolveCapturedType(CompilationInfo info, TypeMirror tm) {
    if (tm == null) {
        return tm;
    }
    if (tm.getKind() == TypeKind.ERROR) {
        tm = info.getTrees().getOriginalType((ErrorType) tm);
    }
    TypeMirror type = resolveCapturedTypeInt(info, tm);
    if (type == null) {
        return tm;
    }
    if (type.getKind() == TypeKind.WILDCARD) {
        TypeMirror tmirr = ((WildcardType) type).getExtendsBound();
        if (tmirr != null)
            return tmirr;
        else { //no extends, just '?'
            TypeElement te = info.getElements().getTypeElement("java.lang.Object"); // NOI18N
            return te == null ? null : te.asType();
        }
            
    }
    
    return type;
}
 
Example #3
Source Project: RetroFacebook   Author: yongjhih   File: TypeSimplifierTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testErrorTypes() {
  TypeElement extendsUndefinedType =
      processingEnv.getElementUtils().getTypeElement("ExtendsUndefinedType");
  ErrorType errorType = (ErrorType) extendsUndefinedType.getSuperclass();
  TypeMirror javaLangObject = typeMirrorOf("java.lang.Object");
  TypeElement list = typeElementOf("java.util.List");
  TypeMirror listOfError = typeUtil.getDeclaredType(list, errorType);
  TypeMirror queryExtendsError = typeUtil.getWildcardType(errorType, null);
  TypeMirror listOfQueryExtendsError = typeUtil.getDeclaredType(list, queryExtendsError);
  TypeMirror querySuperError = typeUtil.getWildcardType(null, errorType);
  TypeMirror listOfQuerySuperError = typeUtil.getDeclaredType(list, querySuperError);
  TypeMirror arrayOfError = typeUtil.getArrayType(errorType);
  TypeMirror[] typesWithErrors = {
      errorType, listOfError, listOfQueryExtendsError, listOfQuerySuperError, arrayOfError
  };
  for (TypeMirror typeWithError : typesWithErrors) {
    try {
      new TypeSimplifier(typeUtil, "foo.bar", ImmutableSet.of(typeWithError), javaLangObject);
      fail("Expected exception for type: " + typeWithError);
    } catch (MissingTypeException expected) {
    }
  }
}
 
Example #4
Source Project: RetroFacebook   Author: yongjhih   File: TypeSimplifierTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testErrorTypes() {
  TypeElement extendsUndefinedType =
      processingEnv.getElementUtils().getTypeElement("ExtendsUndefinedType");
  ErrorType errorType = (ErrorType) extendsUndefinedType.getSuperclass();
  TypeMirror javaLangObject = typeMirrorOf("java.lang.Object");
  TypeElement list = typeElementOf("java.util.List");
  TypeMirror listOfError = typeUtil.getDeclaredType(list, errorType);
  TypeMirror queryExtendsError = typeUtil.getWildcardType(errorType, null);
  TypeMirror listOfQueryExtendsError = typeUtil.getDeclaredType(list, queryExtendsError);
  TypeMirror querySuperError = typeUtil.getWildcardType(null, errorType);
  TypeMirror listOfQuerySuperError = typeUtil.getDeclaredType(list, querySuperError);
  TypeMirror arrayOfError = typeUtil.getArrayType(errorType);
  TypeMirror[] typesWithErrors = {
      errorType, listOfError, listOfQueryExtendsError, listOfQuerySuperError, arrayOfError
  };
  for (TypeMirror typeWithError : typesWithErrors) {
    try {
      new TypeSimplifier(typeUtil, "foo.bar", ImmutableSet.of(typeWithError), javaLangObject);
      fail("Expected exception for type: " + typeWithError);
    } catch (MissingTypeException expected) {
    }
  }
}
 
Example #5
Source Project: SimpleWeibo   Author: 8tory   File: TypeSimplifierTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testErrorTypes() {
  TypeElement extendsUndefinedType =
      processingEnv.getElementUtils().getTypeElement("ExtendsUndefinedType");
  ErrorType errorType = (ErrorType) extendsUndefinedType.getSuperclass();
  TypeMirror javaLangObject = typeMirrorOf("java.lang.Object");
  TypeElement list = typeElementOf("java.util.List");
  TypeMirror listOfError = typeUtil.getDeclaredType(list, errorType);
  TypeMirror queryExtendsError = typeUtil.getWildcardType(errorType, null);
  TypeMirror listOfQueryExtendsError = typeUtil.getDeclaredType(list, queryExtendsError);
  TypeMirror querySuperError = typeUtil.getWildcardType(null, errorType);
  TypeMirror listOfQuerySuperError = typeUtil.getDeclaredType(list, querySuperError);
  TypeMirror arrayOfError = typeUtil.getArrayType(errorType);
  TypeMirror[] typesWithErrors = {
      errorType, listOfError, listOfQueryExtendsError, listOfQuerySuperError, arrayOfError
  };
  for (TypeMirror typeWithError : typesWithErrors) {
    try {
      new TypeSimplifier(typeUtil, "foo.bar", ImmutableSet.of(typeWithError), javaLangObject);
      fail("Expected exception for type: " + typeWithError);
    } catch (MissingTypeException expected) {
    }
  }
}
 
Example #6
Source Project: auto   Author: google   File: TypeEncoderTest.java    License: Apache License 2.0 6 votes vote down vote up
private void test() {
  TypeElement extendsUndefinedType = elementUtils.getTypeElement("ExtendsUndefinedType");
  ErrorType errorType = (ErrorType) extendsUndefinedType.getSuperclass();
  TypeElement list = elementUtils.getTypeElement("java.util.List");
  TypeMirror listOfError = typeUtils.getDeclaredType(list, errorType);
  TypeMirror queryExtendsError = typeUtils.getWildcardType(errorType, null);
  TypeMirror listOfQueryExtendsError = typeUtils.getDeclaredType(list, queryExtendsError);
  TypeMirror querySuperError = typeUtils.getWildcardType(null, errorType);
  TypeMirror listOfQuerySuperError = typeUtils.getDeclaredType(list, querySuperError);
  TypeMirror arrayOfError = typeUtils.getArrayType(errorType);
  testErrorType(errorType);
  testErrorType(listOfError);
  testErrorType(listOfQueryExtendsError);
  testErrorType(listOfQuerySuperError);
  testErrorType(arrayOfError);
}
 
Example #7
Source Project: netbeans   Author: apache   File: JavaSymbolProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public StringBuilder visitError(ErrorType t, Boolean p) {
    Element e = t.asElement();
    if (e instanceof TypeElement) {
        TypeElement te = (TypeElement)e;
        return DEFAULT_VALUE.append((p ? te.getQualifiedName() : te.getSimpleName()).toString());
    }
    return DEFAULT_VALUE;
}
 
Example #8
Source Project: netbeans   Author: apache   File: TypeUtilities.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public StringBuilder visitError(ErrorType t, Boolean p) {
    Element e = t.asElement();
    if (e instanceof TypeElement) {
        TypeElement te = (TypeElement)e;
        return DEFAULT_VALUE.append((p ? te.getQualifiedName() : te.getSimpleName()).toString());
    }
    return DEFAULT_VALUE;
}
 
Example #9
Source Project: netbeans   Author: apache   File: SpringXMLConfigCompletionItem.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public StringBuilder visitError(ErrorType t, Boolean p) {
    Element e = t.asElement();
    if (e instanceof TypeElement) {
        TypeElement te = (TypeElement)e;
        return DEFAULT_VALUE.append((p ? te.getQualifiedName() : te.getSimpleName()).toString());
    }
    return DEFAULT_VALUE;
}
 
Example #10
Source Project: netbeans   Author: apache   File: ChangeMethodReturnType.java    License: Apache License 2.0 5 votes vote down vote up
private TypeMirror purify(CompilationInfo info, TypeMirror targetType) {
    if (targetType != null && targetType.getKind() == TypeKind.ERROR) {
        targetType = info.getTrees().getOriginalType((ErrorType) targetType);
    }

    if (targetType == null || targetType.getKind() == /*XXX:*/TypeKind.ERROR || targetType.getKind() == TypeKind.NONE || targetType.getKind() == TypeKind.NULL) return null;

    return Utilities.resolveTypeForDeclaration(info, targetType);
}
 
Example #11
Source Project: netbeans   Author: apache   File: ExpectedTypeResolver.java    License: Apache License 2.0 5 votes vote down vote up
private TypeMirror purify(CompilationInfo info, TypeMirror targetType) {
    if (targetType != null && targetType.getKind() == TypeKind.ERROR) {
        targetType = info.getTrees().getOriginalType((ErrorType) targetType);
    }

    if (targetType == null || targetType.getKind() == /*XXX:*/TypeKind.ERROR || targetType.getKind() == TypeKind.NONE || targetType.getKind() == TypeKind.NULL) return null;

    return Utilities.resolveCapturedType(info, targetType);
}
 
Example #12
Source Project: netbeans   Author: apache   File: AutoImport.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Void visitError(ErrorType type, Void p) {
    Element e = type.asElement();
    if (e instanceof TypeElement) {
        TypeElement te = (TypeElement)e;
        builder.append(te.getSimpleName());            
    }
    return null;
}
 
Example #13
Source Project: netbeans   Author: apache   File: MethodModelSupport.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public StringBuilder visitError(ErrorType t, Boolean p) {
    Element e = t.asElement();
    if (e instanceof TypeElement) {
        TypeElement te = (TypeElement)e;
        return DEFAULT_VALUE.append((p ? te.getQualifiedName() : te.getSimpleName()).toString());
    }
    return DEFAULT_VALUE;
}
 
Example #14
Source Project: netbeans   Author: apache   File: Utilities.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public StringBuilder visitError(ErrorType t, Boolean p) {
    Element e = t.asElement();
    if (e instanceof TypeElement) {
        TypeElement te = (TypeElement)e;
        return DEFAULT_VALUE.append((p ? te.getQualifiedName() : te.getSimpleName()).toString());
    }
    return DEFAULT_VALUE;
}
 
Example #15
Source Project: netbeans   Author: apache   File: Utilities.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public StringBuilder visitError(ErrorType t, Void p) {
    Element e = t.asElement();
    if (e instanceof TypeElement) {
        TypeElement te = (TypeElement) e;
        return DEFAULT_VALUE.append(te.getQualifiedName().toString());
    }
    return DEFAULT_VALUE;
}
 
Example #16
Source Project: auto-parcel   Author: aitorvs   File: MoreTypes.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@link ExecutableType} if the {@link TypeMirror} represents an executable type such
 * as may result from missing code, or bad compiles or throws an {@link IllegalArgumentException}.
 */
public static ErrorType asError(TypeMirror maybeErrorType) {
    return maybeErrorType.accept(new CastingTypeVisitor<ErrorType>() {
        @Override
        public ErrorType visitError(ErrorType type, String p) {
            return type;
        }
    }, "error type");
}
 
Example #17
Source Project: FreeBuilder   Author: inferred   File: MethodFinder.java    License: Apache License 2.0 5 votes vote down vote up
private static <E extends Exception> Optional<TypeElement> maybeTypeElement(
    TypeMirror mirror, ErrorTypeHandling<E> errorTypeHandling) throws E {
  if (mirror.getKind() == TypeKind.ERROR) {
    errorTypeHandling.handleErrorType((ErrorType) mirror);
  }
  return maybeAsTypeElement(mirror);
}
 
Example #18
Source Project: FreeBuilder   Author: inferred   File: Analyser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Any reference to the as-yet-ungenerated builder should be an unresolved ERROR.
 * Similarly for many copy-and-paste errors
 */
@Override
public Boolean visitError(ErrorType t, Void p) {
  if (typeParameters.isEmpty()) {
    // For non-generic types, the ErrorType will have the correct name.
    String simpleName = t.toString();
    return equal(simpleName, superclass.getSimpleName());
  }
  // For generic types, we'll just have to hope for the best.
  // TODO: Revalidate in a subsequent round?
  return true;
}
 
Example #19
Source Project: FreeBuilder   Author: inferred   File: MethodFinderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSkipsErrorTypes() {
  TypeElement testClass = model.newType(
      "package com.example;",
      "class TestClass extends MissingType implements OtherMissingType {",
      "  public int foo(short a);",
      "}");
  List<ErrorType> errorTypes = new ArrayList<>();

  List<String> methods =
      toStrings(MethodFinder.methodsOn(testClass, model.elementUtils(), errorTypes::add));

  assertThat(methods).containsExactly("int TestClass::foo(short)");
  assertThat(errorTypes).hasSize(2);
}
 
Example #20
Source Project: squidb   Author: yahoo   File: ModelMethodPlugin.java    License: Apache License 2.0 5 votes vote down vote up
private boolean checkFirstArgType(TypeMirror type, DeclaredTypeName generatedClassName) {
    if (type instanceof ErrorType) {
        return true;
    }
    if (!(type instanceof DeclaredType)) {
        return false;
    }

    DeclaredTypeName typeName = (DeclaredTypeName) utils.getTypeNameFromTypeMirror(type);

    return typeName.equals(generatedClassName) || typeName.equals(TypeConstants.ABSTRACT_MODEL);
}
 
Example #21
Source Project: revapi   Author: revapi   File: Util.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public final T visitError(ErrorType t, StringBuilderAndState<S> st) {
    try {
        st.depth++;
        return doVisitError(t, st);
    } finally {
        st.depth--;
    }
}
 
Example #22
Source Project: buck   Author: facebook   File: StandaloneTypeMirror.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <R, P> R accept(TypeVisitor<R, P> v, P p) {
  switch (kind) {
    case BOOLEAN:
    case BYTE:
    case SHORT:
    case INT:
    case LONG:
    case CHAR:
    case FLOAT:
    case DOUBLE:
      return v.visitPrimitive((PrimitiveType) this, p);
    case PACKAGE:
    case VOID:
    case NONE:
      return v.visitNoType((NoType) this, p);
    case NULL:
      return v.visitNull((NullType) this, p);
    case ARRAY:
      return v.visitArray((ArrayType) this, p);
    case DECLARED:
      return v.visitDeclared((DeclaredType) this, p);
    case ERROR:
      return v.visitError((ErrorType) this, p);
    case TYPEVAR:
      return v.visitTypeVariable((TypeVariable) this, p);
    case WILDCARD:
      return v.visitWildcard((WildcardType) this, p);
    case EXECUTABLE:
      return v.visitExecutable((ExecutableType) this, p);
    case OTHER:
      return v.visit(this, p);
    case UNION:
      return v.visitUnion((UnionType) this, p);
    case INTERSECTION:
      return v.visitIntersection((IntersectionType) this, p);
    default:
      throw new AssertionError(String.format("Unknown TypeKind: %s", kind));
  }
}
 
Example #23
Source Project: buck   Author: facebook   File: SignatureFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Void visitError(ErrorType t, SignatureVisitor visitor) {
  // We don't really know, but if there's an error type the compilation is going to fail
  // anyway, so just pretend it's Object.
  visitor.visitClassType("java/lang/Object");
  visitor.visitEnd();
  return null;
}
 
Example #24
Source Project: javapoet   Author: square   File: AbstractTypesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test public void errorTypes() {
  JavaFileObject hasErrorTypes =
      JavaFileObjects.forSourceLines(
          "com.squareup.tacos.ErrorTypes",
          "package com.squareup.tacos;",
          "",
          "@SuppressWarnings(\"hook-into-compiler\")",
          "class ErrorTypes {",
          "  Tacos tacos;",
          "  Ingredients.Guacamole guacamole;",
          "}");
  Compilation compilation = javac().withProcessors(new AbstractProcessor() {
    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
      TypeElement classFile =
          processingEnv.getElementUtils().getTypeElement("com.squareup.tacos.ErrorTypes");
      List<VariableElement> fields = fieldsIn(classFile.getEnclosedElements());
      ErrorType topLevel = (ErrorType) fields.get(0).asType();
      ErrorType member = (ErrorType) fields.get(1).asType();

      assertThat(TypeName.get(topLevel)).isEqualTo(ClassName.get("", "Tacos"));
      assertThat(TypeName.get(member)).isEqualTo(ClassName.get("Ingredients", "Guacamole"));
      return false;
    }

    @Override
    public Set<String> getSupportedAnnotationTypes() {
      return Collections.singleton("*");
    }
  }).compile(hasErrorTypes);

  assertThat(compilation).failed();
}
 
Example #25
Source Project: netbeans   Author: apache   File: WatchPanel.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public TypeMirror getOriginalType(ErrorType arg0) {
    return trees.getOriginalType(arg0);
}
 
Example #26
Source Project: netbeans   Author: apache   File: ContextAnalyzer.java    License: Apache License 2.0 4 votes vote down vote up
public static TreePath validateSelection(CompilationInfo ci, int start, int end, Set<TypeKind> ignoredTypes) {
    if(start == end) {
        TokenSequence<JavaTokenId> cts = ci.getTokenHierarchy().tokenSequence(JavaTokenId.language());

        if (cts != null) {
            cts.move(start);

            if (cts.moveNext() && cts.token().id() != JavaTokenId.WHITESPACE && cts.offset() == start) {
                start = end += 1;
            }
        }
    }
    
    TreePath tp = ci.getTreeUtilities().pathFor(start == end? start : (start + end) / 2 + 1);

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

        if (   !ExpressionTree.class.isAssignableFrom(leaf.getKind().asInterface())
            && (leaf.getKind() != Tree.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 (start != end) {
            if (treeStart != start || treeEnd != end) {
                continue;
            }
        } else {
            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() == Tree.Kind.ASSIGNMENT)
            continue;

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

        if (!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 #27
Source Project: netbeans   Author: apache   File: CompletionFilter.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public TypeMirror getOriginalType(ErrorType et) {
    return delegate.getOriginalType(et);
}
 
Example #28
Source Project: netbeans   Author: apache   File: IntroduceHint.java    License: 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 #29
Source Project: netbeans   Author: apache   File: MissingReturnStatement.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public List<Fix> run(CompilationInfo compilationInfo, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    TreePath method = null;
    if (diagnosticKey != null && diagnosticKey.contains("/compiler.misc.incompatible.ret.type.in.lambda/")) { // NOI18N
        // PENDING: when issue #258201 is implemented, use the new method instead of this HACK
        offset++;
    }
    TreePath tp = compilationInfo.getTreeUtilities().pathFor(offset);

    while (tp != null && !TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind())) {
        Kind kind = tp.getLeaf().getKind();
        if (kind == Kind.METHOD || kind == Kind.LAMBDA_EXPRESSION) {
            method = tp;
            break;
        }

        tp = tp.getParentPath();
    }

    if (method == null) {
        return null;
    }
    
    if (method.getLeaf().getKind() == Kind.METHOD) {
        MethodTree mt = (MethodTree) tp.getLeaf();
        if (mt.getReturnType() == null) {
            return null;
        }
    } else if (method.getLeaf().getKind() == Kind.LAMBDA_EXPRESSION) {
        LambdaExpressionTree let = (LambdaExpressionTree)method.getLeaf();
        TreePath bodyPath = new TreePath(method, let.getBody());
        if (let.getBodyKind() == LambdaExpressionTree.BodyKind.EXPRESSION) {
            TypeMirror m = compilationInfo.getTrees().getTypeMirror(
                bodyPath);
            if (m == null) {
                return null;
            }
            if (m.getKind() == TypeKind.ERROR) {
                m = compilationInfo.getTrees().getOriginalType((ErrorType)m);
            }
            if (m.getKind() != TypeKind.VOID) {
                // do not offer to add return for something, which already has
                // some type
                return null;
            }
        } else if (Utilities.exitsFromAllBranchers(compilationInfo, bodyPath)) {
            // do not add return, returns are already there.
            return null;
        }
    }

    List<Fix> result = new ArrayList<Fix>(2);

    result.add(new FixImpl(compilationInfo.getSnapshot().getSource(), TreePathHandle.create(tp, compilationInfo)));
    if (method.getLeaf().getKind() == Kind.METHOD) {
        result.add(new ChangeMethodReturnType.FixImpl(compilationInfo, tp, TypeMirrorHandle.create(compilationInfo.getTypes().getNoType(TypeKind.VOID)), "void").toEditorFix());
    }

    return result;
}
 
Example #30
Source Project: netbeans   Author: apache   File: CreateElement.java    License: Apache License 2.0 4 votes vote down vote up
private static List<Fix> computeMissingMemberRefFixes(CompilationInfo info, int offset) {
    TreePath errorPath = info.getTreeUtilities().pathFor(offset + 1);
    while (errorPath != null && errorPath.getLeaf().getKind() != Kind.MEMBER_REFERENCE) {
        errorPath = errorPath.getParentPath();
    }
    if (errorPath == null) {
        return Collections.<Fix>emptyList();
    }
    MemberReferenceTree mref = (MemberReferenceTree) errorPath.getLeaf();
    TypeMirror mrefType = info.getTrees().getTypeMirror(errorPath);
    if (mrefType.getKind() == TypeKind.ERROR) {
        TypeMirror expectedTargetType = info.getTrees().getOriginalType((ErrorType) mrefType);
        if (expectedTargetType == null || expectedTargetType.getKind() != TypeKind.DECLARED) {
            return Collections.<Fix>emptyList();
        }
        ExecutableElement expectedMethod = Utilities.getFunctionalMethodFromElement(info, info.getTypes().asElement(expectedTargetType));
        if (expectedMethod == null) {
            return Collections.<Fix>emptyList();
        }
        ExecutableType methodType = (ExecutableType) info.getTypes().asMemberOf((DeclaredType) expectedTargetType, expectedMethod);
        if (Utilities.containsErrorsRecursively(methodType)) {
            return Collections.<Fix>emptyList();
        }
        TypeMirror targetType = /*XXX: check the target*/info.getTrees().getTypeMirror(new TreePath(errorPath, mref.getQualifierExpression()));
        TypeElement target = (TypeElement) info.getTypes().asElement(targetType);
        //TODO: use thrown types?
        //IZ 111048 -- don't offer anything if target file isn't writable
        if(!Utilities.isTargetWritable(target, info))
            return Collections.<Fix>emptyList();

        FileObject targetFile = SourceUtils.getFile(ElementHandle.create(target), info.getClasspathInfo());
        if (targetFile == null)
            return Collections.<Fix>emptyList();
        Set<Modifier> modifiers = EnumSet.noneOf(Modifier.class);
        TreePath tp = errorPath;
        while (tp != null && !TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind())) {
            tp = tp.getParentPath();
        }
        modifiers.addAll(Utilities.getAccessModifiers(info, (TypeElement) info.getTrees().getElement(tp), (TypeElement) target).getRequiredModifiers());
        Element targetExprEl = info.getTrees().getElement(new TreePath(errorPath, mref.getQualifierExpression()));
        List<Fix> fixes = new ArrayList<>();
        if (targetExprEl.getKind().isClass() || targetExprEl.getKind().isInterface()) {
            if (methodType.getParameterTypes().size() > 0 && target.equals(info.getTypes().asElement(methodType.getParameterTypes().get(0)))) {
                //static ref to instance type:
                fixes.add(new CreateMethodFix(info, mref.getName().toString(), EnumSet.copyOf(modifiers), target, methodType.getReturnType(), methodType.getParameterTypes().subList(1, methodType.getParameterTypes().size()), expectedMethod.getParameters().stream().skip(1).map(var -> var.getSimpleName().toString()).collect(Collectors.toList()), Collections.emptyList(), Collections.emptyList(), targetFile));
            }
            modifiers.add(Modifier.STATIC);
        }
        fixes.add(new CreateMethodFix(info, mref.getName().toString(), modifiers, target, methodType.getReturnType(), methodType.getParameterTypes(), expectedMethod.getParameters().stream().map(var -> var.getSimpleName().toString()).collect(Collectors.toList()), Collections.emptyList(), Collections.emptyList(), targetFile));
        return fixes;
    }

    return Collections.<Fix>emptyList();
}