Java Code Examples for javax.lang.model.element.TypeElement#getNestingKind()

The following examples show how to use javax.lang.model.element.TypeElement#getNestingKind() .
Example 1
Project: buck   File: AccessFlags.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets the class access flags (see JVMS8 4.1) for the given type element as they should appear in
 * the ClassNode of a class file. Inner-class specific flags are not allowed in that node,
 * presumably for compatibility reasons.
 */
public int getAccessFlagsForClassNode(TypeElement e) {
  // Static never makes it into the file for classes
  int accessFlags = getAccessFlags(e) & ~Opcodes.ACC_STATIC;
  if (e.getNestingKind() != NestingKind.TOP_LEVEL) {
    if (e.getModifiers().contains(Modifier.PROTECTED)) {
      // It looks like inner classes with protected visibility get marked as public, and then
      // their InnerClasses attributes override that more specifically
      accessFlags = (accessFlags & ~Opcodes.ACC_PROTECTED) | Opcodes.ACC_PUBLIC;
    } else if (e.getModifiers().contains(Modifier.PRIVATE)) {
      // It looks like inner classes with private visibility get marked as package, and then
      // their InnerClasses attributes override that more specifically
      accessFlags = (accessFlags & ~Opcodes.ACC_PRIVATE);
    }
  }

  return accessFlags;
}
 
Example 2
Project: netbeans   File: InstanceRefFinder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Registers an instance for the resolved constructor. If a 
 * 
 * @param el 
 */
private void addInstanceForConstructor(Element el) {
    TypeElement pt = findEnclosingType(el);
    if (pt == null) {
        return;
    }
    switch (pt.getNestingKind()) {
        case ANONYMOUS:
            // the anonymous class itself may not need an enclosing instance, if its
            // contents do not reference anything from the instance.
            break;
            
        case LOCAL:
            // implicit reference to the enclosing instance, but since a type with no qualname is referenced,
            // the expression / statement can't be probably moved anywhere.
            addLocalReference(pt);
            break;
        case MEMBER:
            // add enclosing type's reference
            if (!pt.getModifiers().contains(Modifier.STATIC)) {
                addRequiredInstance((TypeElement)pt.getEnclosingElement());
            }
            break;
    }
}
 
Example 3
Project: doma   File: EmbeddableMetaFactory.java    License: Apache License 2.0 5 votes vote down vote up
void validateEnclosingElement(Element element) {
  TypeElement typeElement = ctx.getMoreElements().toTypeElement(element);
  if (typeElement == null) {
    return;
  }
  String simpleName = typeElement.getSimpleName().toString();
  if (simpleName.contains(Constants.BINARY_NAME_DELIMITER)
      || simpleName.contains(Constants.TYPE_NAME_DELIMITER)) {
    throw new AptException(
        Message.DOMA4417, typeElement, new Object[] {typeElement.getQualifiedName()});
  }
  NestingKind nestingKind = typeElement.getNestingKind();
  if (nestingKind == NestingKind.TOP_LEVEL) {
    return;
  } else if (nestingKind == NestingKind.MEMBER) {
    Set<Modifier> modifiers = typeElement.getModifiers();
    if (modifiers.containsAll(Arrays.asList(Modifier.STATIC, Modifier.PUBLIC))) {
      validateEnclosingElement(typeElement.getEnclosingElement());
    } else {
      throw new AptException(
          Message.DOMA4415, typeElement, new Object[] {typeElement.getQualifiedName()});
    }
  } else {
    throw new AptException(
        Message.DOMA4416, typeElement, new Object[] {typeElement.getQualifiedName()});
  }
}
 
Example 4
Project: dagger2-sample   File: Util.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean requiresEnclosingInstance(TypeElement typeElement) {
  switch (typeElement.getNestingKind()) {
    case TOP_LEVEL:
      return false;
    case MEMBER:
      return !typeElement.getModifiers().contains(STATIC);
    case ANONYMOUS:
    case LOCAL:
      return true;
    default:
      throw new AssertionError("TypeElement cannot have nesting kind: "
          + typeElement.getNestingKind());
  }
}
 
Example 5
Project: netbeans   File: InitializerCanBeStatic.java    License: Apache License 2.0 5 votes vote down vote up
@TriggerTreeKind(Tree.Kind.BLOCK)
public static ErrorDescription run(HintContext ctx) {
    TreePath path = ctx.getPath();
    if (((BlockTree)path.getLeaf()).isStatic()) {
        return null;
    }
    TreePath parentPath = path.getParentPath();
    if (parentPath == null) {
        return null;
    }
    Tree l = parentPath.getLeaf();
    if (!(l instanceof ClassTree)) {
        return null;
    }
    Element el = ctx.getInfo().getTrees().getElement(parentPath);
    if (el == null || !el.getKind().isClass()) {
        return null;
    }
    TypeElement tel = (TypeElement)el;
    // do not suggest for anonymous classes, local classes or members which are not static.
    if (tel.getNestingKind() != NestingKind.TOP_LEVEL && 
        (tel.getNestingKind() != NestingKind.MEMBER || !tel.getModifiers().contains(Modifier.STATIC))) {
        return null;
    }
    InstanceRefFinder finder = new InstanceRefFinder(ctx.getInfo(), path);
    finder.process();
    if (finder.containsInstanceReferences() || finder.containsReferencesToSuper()) {
        return null;
    }
    
    return ErrorDescriptionFactory.forTree(ctx, path, Bundle.TEXT_InitializerCanBeStatic(),
            new MakeInitStatic(TreePathHandle.create(path, ctx.getInfo())).toEditorFix());
}
 
Example 6
Project: netbeans   File: InstanceRefFinder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * If the variable is typed as a local class, record the local class; it may need to go along
 * with the factored expression, unless the expression only uses some specific interface
 * implemented by the local class.
 * 
 * @param el 
 */
private void addLocalClassVariable(Element el) {
    TypeMirror tm = el.asType();
    if (tm.getKind() != TypeKind.DECLARED)  {
        return;
    }
    Element e = ((DeclaredType)tm).asElement();
    if (!(e instanceof TypeElement)) {
        return;
    }
    TypeElement t = (TypeElement)e;
    if (t.getNestingKind() == NestingKind.LOCAL) {
        addLocalReference(t);
    }
}
 
Example 7
Project: netbeans   File: Utilities.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isAnonymousType(TypeMirror type) {
    if (type.getKind() == TypeKind.DECLARED) {
        DeclaredType dt = (DeclaredType) type;
        TypeElement typeElem = (TypeElement) dt.asElement();
        if (typeElem.getNestingKind() == NestingKind.ANONYMOUS) {
            return true;
        }
    }
    return false;
}
 
Example 8
Project: netbeans   File: TopLevelClass.java    License: Apache License 2.0 5 votes vote down vote up
@TriggerPatterns(value = {
    @TriggerPattern(value = JPAAnnotations.ENTITY),
    @TriggerPattern(value = JPAAnnotations.EMBEDDABLE),
    @TriggerPattern(value = JPAAnnotations.MAPPED_SUPERCLASS)})
public static ErrorDescription apply(HintContext hc) {
    if (hc.isCanceled() || (hc.getPath().getLeaf().getKind() != Tree.Kind.IDENTIFIER || hc.getPath().getParentPath().getLeaf().getKind() != Tree.Kind.ANNOTATION)) {//NOI18N
        return null;//we pass only if it is an annotation
    }

    final JPAProblemContext ctx = ModelUtils.getOrCreateCachedContext(hc);
    if (ctx == null || hc.isCanceled()) {
        return null;
    }

    TypeElement subject = ctx.getJavaClass();
    
    if (subject.getNestingKind() == NestingKind.TOP_LEVEL){
        return null;
    }
    TreePath par = hc.getPath();
    while (par != null && par.getParentPath() != null && par.getLeaf().getKind() != Tree.Kind.CLASS) {
        par = par.getParentPath();
    }

    Utilities.TextSpan underlineSpan = Utilities.getUnderlineSpan(
            ctx.getCompilationInfo(), par.getLeaf());

    return ErrorDescriptionFactory.forSpan(
            hc,
            underlineSpan.getStartOffset(),
            underlineSpan.getEndOffset(),
            NbBundle.getMessage(TopLevelClass.class, "MSG_NestedClassAsEntity"));        
}
 
Example 9
Project: j2objc   File: ElementUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Determines if a type element can access fields and methods from an outer class.
 */
public static boolean hasOuterContext(TypeElement type) {
  switch (type.getNestingKind()) {
    case ANONYMOUS:
    case LOCAL:
      return !isStatic(type.getEnclosingElement());
    case MEMBER:
      return !isStatic(type);
    case TOP_LEVEL:
      return false;
  }
  throw new AssertionError("Unknown NestingKind");
}
 
Example 10
Project: doma   File: ExternalDomainMetaFactory.java    License: Apache License 2.0 5 votes vote down vote up
private void validateEnclosingElement(Element element) {
  TypeElement typeElement = ctx.getMoreElements().toTypeElement(element);
  if (typeElement == null) {
    return;
  }
  String simpleName = typeElement.getSimpleName().toString();
  if (simpleName.contains(Constants.BINARY_NAME_DELIMITER)
      || simpleName.contains(Constants.TYPE_NAME_DELIMITER)) {
    throw new AptException(
        Message.DOMA4280, typeElement, new Object[] {typeElement.getQualifiedName()});
  }
  NestingKind nestingKind = typeElement.getNestingKind();
  if (nestingKind == NestingKind.TOP_LEVEL) {
    return;
  } else if (nestingKind == NestingKind.MEMBER) {
    Set<Modifier> modifiers = typeElement.getModifiers();
    if (modifiers.containsAll(Arrays.asList(Modifier.STATIC, Modifier.PUBLIC))) {
      validateEnclosingElement(typeElement.getEnclosingElement());
    } else {
      throw new AptException(
          Message.DOMA4278, typeElement, new Object[] {typeElement.getQualifiedName()});
    }
  } else {
    throw new AptException(
        Message.DOMA4279, typeElement, new Object[] {typeElement.getQualifiedName()});
  }
}
 
Example 11
Project: doma   File: EntityMetaFactory.java    License: Apache License 2.0 5 votes vote down vote up
void validateEnclosingElement(Element element) {
  TypeElement typeElement = ctx.getMoreElements().toTypeElement(element);
  if (typeElement == null) {
    return;
  }
  String simpleName = typeElement.getSimpleName().toString();
  if (simpleName.contains(Constants.BINARY_NAME_DELIMITER)
      || simpleName.contains(Constants.TYPE_NAME_DELIMITER)) {
    throw new AptException(
        Message.DOMA4317, typeElement, new Object[] {typeElement.getQualifiedName()});
  }
  NestingKind nestingKind = typeElement.getNestingKind();
  if (nestingKind == NestingKind.TOP_LEVEL) {
    return;
  } else if (nestingKind == NestingKind.MEMBER) {
    Set<Modifier> modifiers = typeElement.getModifiers();
    if (modifiers.containsAll(Arrays.asList(Modifier.STATIC, Modifier.PUBLIC))) {
      validateEnclosingElement(typeElement.getEnclosingElement());
    } else {
      throw new AptException(
          Message.DOMA4315, typeElement, new Object[] {typeElement.getQualifiedName()});
    }
  } else {
    throw new AptException(
        Message.DOMA4316, typeElement, new Object[] {typeElement.getQualifiedName()});
  }
}
 
Example 12
Project: Akatsuki   File: SourceTreeModel.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean enclosingClassValid(ProcessorContext context, Element element) {
	Element enclosingElement = element.getEnclosingElement();
	while (enclosingElement != null) {
		// skip until we find a class
		if (!enclosingElement.getKind().equals(ElementKind.CLASS))
			break;

		if (!enclosingElement.getKind().equals(ElementKind.CLASS)) {
			context.messager().printMessage(Kind.ERROR,
					"enclosing element(" + enclosingElement.toString() + ") is not a class",
					element);
			return false;
		}

		TypeElement enclosingClass = (TypeElement) enclosingElement;

		// protected, package-private, and public all allow same package
		// access
		if (enclosingClass.getModifiers().contains(Modifier.PRIVATE)) {
			context.messager().printMessage(Kind.ERROR,
					"enclosing class (" + enclosingElement.toString() + ") cannot be private",
					element);
			return false;
		}

		if (enclosingClass.getNestingKind() != NestingKind.TOP_LEVEL
				&& !enclosingClass.getModifiers().contains(Modifier.STATIC)) {
			context.messager().printMessage(Kind.ERROR,
					"enclosing class is nested but not static", element);
			return false;
		}
		enclosingElement = enclosingClass.getEnclosingElement();
	}

	return true;
}
 
Example 13
Project: gama   File: ProcessorContext.java    License: GNU General Public License v3.0 4 votes vote down vote up
public String nameOf(final TypeElement e) {
	if (e.getNestingKind() == NestingKind.TOP_LEVEL) { return e.getQualifiedName().toString(); }
	return nameOf((TypeElement) e.getEnclosingElement()) + "." + e.getSimpleName().toString();
}
 
Example 14
Project: netbeans   File: JavaClassCompletor.java    License: Apache License 2.0 4 votes vote down vote up
private static boolean isAccessibleClass(TypeElement te) {
    NestingKind nestingKind = te.getNestingKind();
    return (nestingKind == NestingKind.TOP_LEVEL) || (nestingKind == NestingKind.MEMBER && te.getModifiers().contains(Modifier.STATIC));
}
 
Example 15
Project: j2objc   File: ElementUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static boolean isLocal(TypeElement type) {
  NestingKind nestingKind = type.getNestingKind();
  return nestingKind == NestingKind.ANONYMOUS || nestingKind == NestingKind.LOCAL;
}
 
Example 16
Project: j2objc   File: CaptureInfo.java    License: Apache License 2.0 4 votes vote down vote up
private static boolean automaticOuterParam(TypeElement type) {
  return type.getNestingKind() == NestingKind.MEMBER && !ElementUtil.isStatic(type);
}
 
Example 17
Project: j2cl   File: JavaEnvironment.java    License: Apache License 2.0 4 votes vote down vote up
private static boolean isAnonymous(TypeElement typeElement) {
  return typeElement.getNestingKind() == NestingKind.ANONYMOUS;
}
 
Example 18
Project: immutables   File: Encodings.java    License: Apache License 2.0 4 votes vote down vote up
Encoding(TypeElement type) {
  this.typeEncoding = type;
  if (type.getKind() != ElementKind.CLASS || type.getNestingKind() != NestingKind.TOP_LEVEL) {
    reporter.withElement(type).error("Encoding type '%s' should be top-level class", type.getSimpleName());
  }

  this.$$package = processing().getElementUtils().getPackageOf(type).getQualifiedName().toString();
  this.name = type.getSimpleName().toString();

  CharSequence source = SourceExtraction.extract(processing(), type);
  if (source.length() == 0) {
    reporter.withElement(type)
        .error("No source code can be extracted for @Encoding class. Unsupported compilation mode");
  }

  this.imports = SourceExtraction.importsFrom(source);
  this.sourceMapper = new SourceMapper(source);
  this.typesReader = new TypeExtractor(types, type);

  this.encodingSelfType = typesReader.get(type.asType());

  addTypeParameters(type);

  for (Element e : type.getEnclosedElements()) {
    processMember(e);
  }

  if (postValidate()) {
    provideSyntheticElements();
  }

  this.allElements = Iterables.concat(
      Arrays.asList(
          Iterables.filter(
              Arrays.asList(
                  impl,
                  from,
                  toString,
                  hashCode,
                  equals,
                  build,
                  isInit),
              Predicates.notNull()),
          fields,
          expose,
          copy,
          helpers,
          builderFields,
          builderHelpers,
          builderInits));

  this.linkage = new Linkage();
  this.generatedImports = generatedImports();
}
 
Example 19
Project: buck   File: MoreElements.java    License: Apache License 2.0 4 votes vote down vote up
public static boolean isInnerClass(TypeElement e) {
  return e.getNestingKind() == NestingKind.MEMBER && !e.getModifiers().contains(Modifier.STATIC);
}
 
Example 20
Project: FreeBuilder   File: Analyser.java    License: Apache License 2.0 4 votes vote down vote up
/** Basic sanity-checking to ensure we can fulfil the &#64;FreeBuilder contract for this type. */
private void verifyType(TypeElement type, PackageElement pkg) throws CannotGenerateCodeException {
  if (pkg.isUnnamed()) {
    messager.printMessage(ERROR, "FreeBuilder does not support types in unnamed packages", type);
    throw new CannotGenerateCodeException();
  }
  switch (type.getNestingKind()) {
    case TOP_LEVEL:
      break;

    case MEMBER:
      if (!type.getModifiers().contains(Modifier.STATIC)) {
        messager.printMessage(
            ERROR,
            "Inner classes cannot be FreeBuilder types (did you forget the static keyword?)",
            type);
        throw new CannotGenerateCodeException();
      }

      if (type.getModifiers().contains(Modifier.PRIVATE)) {
        messager.printMessage(ERROR, "FreeBuilder types cannot be private", type);
        throw new CannotGenerateCodeException();
      }

      for (Element e = type.getEnclosingElement(); e != null; e = e.getEnclosingElement()) {
        if (e.getModifiers().contains(Modifier.PRIVATE)) {
          messager.printMessage(
              ERROR,
              "FreeBuilder types cannot be private, but enclosing type "
                  + e.getSimpleName() + " is inaccessible",
              type);
          throw new CannotGenerateCodeException();
        }
      }
      break;

    default:
      messager.printMessage(
          ERROR, "Only top-level or static nested types can be FreeBuilder types", type);
      throw new CannotGenerateCodeException();
  }
  switch (type.getKind()) {
    case ANNOTATION_TYPE:
      messager.printMessage(ERROR, "FreeBuilder does not support annotation types", type);
      throw new CannotGenerateCodeException();

    case CLASS:
      verifyTypeIsConstructible(type);
      break;

    case ENUM:
      messager.printMessage(ERROR, "FreeBuilder does not support enum types", type);
      throw new CannotGenerateCodeException();

    case INTERFACE:
      // Nothing extra needs to be checked on an interface
      break;

    default:
      throw new AssertionError("Unexpected element kind " + type.getKind());
  }
}