Java Code Examples for com.sun.tools.javac.tree.JCTree#JCAnnotation

The following examples show how to use com.sun.tools.javac.tree.JCTree#JCAnnotation . 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: StringLiteralTemplateProcessor.java    From manifold with Apache License 2.0 6 votes vote down vote up
@Override
public void visitAnnotation( JCTree.JCAnnotation jcAnno )
{
  // Disable string templates inside annotations. Reasons:
  // 1. spring framework has its own $ processing that interferes
  // 2. annotation processors in IDEs won't work with it
  // 3. there's not enough benefit to justify the cost of fixing the above problems
  // See https://github.com/manifold-systems/manifold/issues/102

  pushDisabled( true );
  try
  {
    super.visitAnnotation( jcAnno );
  }
  finally
  {
    popDisabled( true );
  }
}
 
Example 2
Source File: HandleTable.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
private void generateDeleteTable(JavacTreeMaker maker, JavacNode tableElement, Set<String> allStaticMethodNames, String tableClassName) {
  final String callClassName = CLASS_DELETE_TABLE;
  final String methodName = METHOD_DELETE_TABLE;
  final String invokeKey = getCreateInvokeKey(callClassName, tableClassName);
  if (!allStaticMethodNames.contains(methodName)) {
    final JCTree.JCAnnotation invokesAnnotation = maker.Annotation(chainDotsString(tableElement, Invokes.class.getCanonicalName()),
        List.<JCTree.JCExpression>of(maker.Literal(invokeKey)));
    final JCTree.JCModifiers mods = maker.Modifiers(PUBLIC_STATIC, List.of(invokesAnnotation));
    final Name name = tableElement.toName(methodName);
    final JCTree.JCExpression returnType = getMagicMethodReturnType(tableElement, callClassName, tableClassName);
    final JCTree.JCBlock body = defaultMagicMethodBody(maker, tableElement);
    final JCTree.JCMethodDecl method = maker.MethodDef(mods, name, returnType,
        List.<JCTree.JCTypeParameter>nil(),
        List.<JCTree.JCVariableDecl>nil(),
        List.<JCTree.JCExpression>nil(),
        body,
        null);
    injectMethod(tableElement, recursiveSetGeneratedBy(method, tableElement.get(), tableElement.getContext()));
  }
}
 
Example 3
Source File: HandleTable.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
private void generateBulkMethod(JavacTreeMaker maker, JavacNode tableElement,
                                Set<String> allStaticMethodNames, String methodName,
                                String callClassName, String tableClassName,
                                CollectionType collectionType) {
  final String invokeKey = getCreateInvokeKey(callClassName, tableClassName);
  if (!allStaticMethodNames.contains(methodName)) {
    final JCTree.JCAnnotation invokesAnnotation = maker.Annotation(chainDotsString(tableElement, Invokes.class.getCanonicalName()),
        List.<JCTree.JCExpression>of(maker.Literal(invokeKey)));
    final JCTree.JCModifiers mods = maker.Modifiers(PUBLIC_STATIC, List.of(invokesAnnotation));
    final Name name = tableElement.toName(methodName);
    final JCTree.JCExpression returnType = getMagicMethodReturnType(tableElement, callClassName, tableClassName);
    final JCTree.JCExpression tableClassType = chainDotsString(tableElement, tableElement.getPackageDeclaration() + "." + tableClassName);
    final JCTree.JCExpression paramType = maker.TypeApply(collectionType.genericType(tableElement), List.of(tableClassType));
    long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, tableElement.getContext());
    final JCTree.JCVariableDecl param = maker.VarDef(maker.Modifiers(flags), tableElement.toName("o"), paramType, null);
    final JCTree.JCBlock body = defaultMagicMethodBody(maker, tableElement);
    final JCTree.JCMethodDecl method = maker.MethodDef(mods, name, returnType,
        List.<JCTree.JCTypeParameter>nil(),
        List.of(param),
        List.<JCTree.JCExpression>nil(),
        body,
        null);
    injectMethod(tableElement, recursiveSetGeneratedBy(method, tableElement.get(), tableElement.getContext()));
  }
}
 
Example 4
Source File: HandleTable.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
private void generateMethod(JavacTreeMaker maker, JavacNode tableElement, Set<String> allMethodNames, String methodName, String callClassName, String tableClassName) {
  final String invokeKey = getCreateInvokeKey(callClassName, tableClassName);
  if (!allMethodNames.contains(methodName)) {
    final JCTree.JCAssign value = maker.Assign(maker.Ident(tableElement.toName("value")),
        maker.Literal(invokeKey));
    final JCTree.JCAssign useThisAsOnlyParam = maker.Assign(maker.Ident(tableElement.toName("useThisAsOnlyParam")),
        maker.Literal(true));
    final JCTree.JCAnnotation invokesAnnotation = maker.Annotation(chainDotsString(tableElement, Invokes.class.getCanonicalName()),
        List.<JCTree.JCExpression>of(value, useThisAsOnlyParam));
    final JCTree.JCModifiers mods = maker.Modifiers(PUBLIC_FINAL, List.of(invokesAnnotation));
    final Name name = tableElement.toName(methodName);
    final JCTree.JCExpression returnType = getMagicMethodReturnType(tableElement, callClassName, tableClassName);
    final JCTree.JCBlock body = defaultMagicMethodBody(maker, tableElement);
    final JCTree.JCMethodDecl method = maker.MethodDef(mods, name, returnType,
        List.<JCTree.JCTypeParameter>nil(),
        List.<JCTree.JCVariableDecl>nil(),
        List.<JCTree.JCExpression>nil(),
        body,
        null);
    injectMethod(tableElement, recursiveSetGeneratedBy(method, tableElement.get(), tableElement.getContext()));
  }
}
 
Example 5
Source File: HandleTable.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(AnnotationValues<Table> annotation, JCTree.JCAnnotation ast, JavacNode annotationNode) {
  if (environment.isProcessingFailed()) {
    return;
  }
  Table tableInstance = annotation.getInstance();

  deleteAnnotationIfNeccessary(annotationNode, Table.class);
  deleteImportFromCompilationUnit(annotationNode, Table.class.getCanonicalName());

  JavacNode tableNode = annotationNode.up();
  final JavacTreeMaker maker = tableNode.getTreeMaker();

  final String tableName = getTableName(tableInstance, tableNode);
  final TableElement tableElement = environment.getTableElementByTableName(tableName);
  generateMagicMethods(maker, tableNode);
  generateMissingIdIfNeeded(maker, tableNode, tableElement);
}
 
Example 6
Source File: TreeAnalyzer.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
private static void analyzeAnnotationTree(
    final Source src, final EndPosTable endPosTable, final AnnotationTree at) {
  if (at instanceof JCTree.JCAnnotation) {
    JCTree.JCAnnotation anno = (JCTree.JCAnnotation) at;
    int startPos = anno.getPreferredPosition();
    int endPos = anno.getEndPosition(endPosTable);
    JCTree annotationType = anno.getAnnotationType();
    int annotationTypeEndPosition = annotationType.getEndPosition(endPosTable);
    Range range;
    if (endPos != annotationTypeEndPosition) {
      startPos = annotationTypeEndPosition;
    }
    range = Range.create(src, startPos + 1, endPos);
    Type type = anno.type;
    Annotation annotation;
    if (nonNull(type)) {
      annotation = new Annotation(type.toString(), startPos, range);
    } else {
      annotation = new Annotation(annotationType.toString(), startPos, range);
    }
    src.annotationMap.put(range.begin.line, annotation);
  }
}
 
Example 7
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 6 votes vote down vote up
private void precompileClasses( JCTree.JCClassDecl tree )
{
  Map<String, Set<String>> typeNames = new HashMap<>();
  for( JCTree.JCAnnotation anno: tree.getModifiers().getAnnotations() )
  {
    if( anno.getAnnotationType().type.toString().equals( Precompile.class.getCanonicalName() ) )
    {
      getTypesToCompile( anno, typeNames );
    }
  }

  if( !typeNames.isEmpty() )
  {
    precompile( typeNames );
  }
}
 
Example 8
Source File: TreeTypeInternal.java    From vertx-codegen with Apache License 2.0 6 votes vote down vote up
public TypeUse.TypeInternal forReturn(ProcessingEnvironment env, ExecutableElement methodElt) {
  Trees trees = Trees.instance(env);
  if (trees == null) {
    return null;
  }
  JCTree.JCMethodDecl tree = (JCTree.JCMethodDecl) trees.getTree(methodElt);
  if (tree == null) {
    return null;
  }
  JCTree type = tree.getReturnType();
  boolean nullable = isNullable(type);
  if (!nullable) {
    JCTree.JCModifiers mods = tree.mods;
    for (JCTree.JCAnnotation jca : mods.annotations) {
      if (jca.type.toString().equals(TypeUse.NULLABLE)) {
        nullable = true;
        break;
      }
    }
  }
  return new TreeTypeInternal(type, nullable);
}
 
Example 9
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 6 votes vote down vote up
@Override
public void visitAnnotation( JCTree.JCAnnotation tree )
{
  super.visitAnnotation( tree );
  if( tree.getAnnotationType().type == null || !Self.class.getTypeName().equals( tree.getAnnotationType().type.tsym.toString() ) )
  {
    return;
  }

  if( !isSelfInMethodDeclOrFieldDecl( tree, tree ) )
  {
    _tp.report( tree, Diagnostic.Kind.ERROR, ExtIssueMsg.MSG_SELF_NOT_ALLOWED_HERE.get() );
  }
  else
  {
    verifySelfOnThis( tree, tree );
  }
}
 
Example 10
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void getTypesToCompile( JCTree.JCAnnotation precompileAnno, Map<String, Set<String>> typeNames )
{
  Attribute.Compound attribute = precompileAnno.attribute;
  if( attribute == null )
  {
    return;
  }

  String typeManifoldClassName = null;
  String regex = ".*";
  String ext = "*";
  for( com.sun.tools.javac.util.Pair<Symbol.MethodSymbol, Attribute> pair: attribute.values )
  {
    Name argName = pair.fst.getSimpleName();
    switch( argName.toString() )
    {
      case "typeManifold":
        typeManifoldClassName = pair.snd.getValue().toString();
        break;
      case "fileExtension":
        ext = pair.snd.getValue().toString();
        break;
      case "typeNames":
        regex = pair.snd.getValue().toString();
        break;
    }
  }

  addToPrecompile( typeNames, typeManifoldClassName, ext, regex );
}
 
Example 11
Source File: SingletonJavacHandler.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void handle(AnnotationValues<Singleton> annotation, JCTree.JCAnnotation ast, JavacNode annotationNode) {

    Context context = annotationNode.getContext();

    Javac8BasedLombokOptions options = Javac8BasedLombokOptions.replaceWithDelombokOptions(context);
    options.deleteLombokAnnotations();

    //remove annotation
    deleteAnnotationIfNeccessary(annotationNode, Singleton.class);
    //remove import
    deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel");

    //private constructor
    JavacNode singletonClass = annotationNode.up();
    JavacTreeMaker singletonClassTreeMaker = singletonClass.getTreeMaker();

    addPrivateConstructor(singletonClass, singletonClassTreeMaker);

    //singleton holder
    JavacNode holderInnerClass = addInnerClass(singletonClass, singletonClassTreeMaker);

    //inject static field to this
    addInstanceVar(singletonClass, singletonClassTreeMaker, holderInnerClass);

    //add factory method
    addFactoryMethod(singletonClass, singletonClassTreeMaker, holderInnerClass);
}
 
Example 12
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void getIncrementalCompileDrivers( JCTree.JCAnnotation anno, Set<Object> drivers )
{
  Attribute.Compound attribute = anno.attribute;
  if( attribute == null )
  {
    return;
  }

  String fqnDriver = null;
  Integer driverId = null;
  for( com.sun.tools.javac.util.Pair<Symbol.MethodSymbol, Attribute> pair: attribute.values )
  {
    Name argName = pair.fst.getSimpleName();
    if( argName.toString().equals( "driverInstance" ) )
    {
      driverId = (int)pair.snd.getValue();
    }
    else if( argName.toString().equals( "driverClass" ) )
    {
      fqnDriver = (String)pair.snd.getValue();
    }
  }

  if( driverId != null )
  {
    Object driver = ReflectUtil.method( fqnDriver, "getInstance", int.class ).invokeStatic( driverId );
    drivers.add( driver );
  }
}
 
Example 13
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 5 votes vote down vote up
private boolean hasAnnotation( List<JCTree.JCAnnotation> annotations, Class<? extends Annotation> annoClass )
{
  for( JCTree.JCAnnotation anno: annotations )
  {
    if( anno.getAnnotationType().type.toString().equals( annoClass.getCanonicalName() ) )
    {
      return true;
    }
  }
  return false;
}
 
Example 14
Source File: BootstrapInserter.java    From manifold with Apache License 2.0 5 votes vote down vote up
private boolean annotatedWith_NoBootstrap( List<JCTree.JCAnnotation> annotations )
{
  for( JCTree.JCAnnotation anno : annotations )
  {
    if( anno.getAnnotationType().toString().endsWith( NoBootstrap.class.getSimpleName() ) )
    {
      return true;
    }
  }
  return false;
}
 
Example 15
Source File: TreeAnalyzer.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
private static void analyzeAnnotations(
    final SourceContext sc, final List<JCTree.JCAnnotation> annotations, final BlockScope bs) {
  Source src = sc.source;
  EndPosTable endPosTable = sc.endPosTable;
  for (JCTree.JCAnnotation anno : annotations) {
    analyzeAnnotationTree(src, endPosTable, anno);
  }
}
 
Example 16
Source File: TreeAnalyzer.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
private static String parseModifiers(
    SourceContext context, @Nullable JCTree.JCModifiers modifiers) throws IOException {

  if (nonNull(modifiers)) {
    List<JCTree.JCAnnotation> annotations = modifiers.getAnnotations();
    if (nonNull(annotations) && annotations.size() > 0) {
      for (JCTree.JCAnnotation anno : annotations) {
        JCTree annotationType = anno.getAnnotationType();
        if (nonNull(annotationType)) {

          analyzeParsedTree(context, annotationType);
        }
        List<JCTree.JCExpression> arguments = anno.getArguments();
        if (nonNull(arguments)) {
          for (JCTree.JCExpression jcExpression : arguments) {
            analyzeParsedTree(context, jcExpression);
          }
        }
      }

      String mod = modifiers.toString();
      int lastIndexOf = mod.lastIndexOf('\n');
      return mod.substring(lastIndexOf + 1);
    }
    return modifiers.toString();
  }
  return "";
}
 
Example 17
Source File: HandleColumn.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(AnnotationValues<Column> annotation, JCTree.JCAnnotation ast, JavacNode annotationNode) {
  // FIXME: 9.04.16 remove
  JavacNode node = annotationNode.up();
  if (node.getKind() == AST.Kind.FIELD) {
    JCTree.JCVariableDecl fieldDec = (JCTree.JCVariableDecl) node.get();
    if ((fieldDec.mods.flags & Flags.PRIVATE) != 0 && (fieldDec.mods.flags & (Flags.STATIC | Flags.FINAL)) == 0) {
      fieldDec.mods.flags &= ~Flags.PRIVATE;
    }
    node.rebuild();
  }
}
 
Example 18
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void verifySelfOnThis( JCTree annotated, JCTree.JCAnnotation selfAnno )
{
  String fqn;
  if( annotated instanceof JCTree.JCAnnotatedType )
  {
    fqn = ((JCTree.JCAnnotatedType)annotated).getUnderlyingType().type.tsym.getQualifiedName().toString();
  }
  else if( annotated instanceof JCTree.JCMethodDecl )
  {
    fqn = ((JCTree.JCMethodDecl)annotated).getReturnType().type.tsym.getQualifiedName().toString();
  }
  else
  {
    //## todo: shouldn't happen
    return;
  }

  try
  {
    JCTree.JCClassDecl enclosingClass = _tp.getClassDecl( annotated );
    if( !isDeclaringClassOrExtension( annotated, fqn, enclosingClass ) && !fqn.equals( "Array" ) )
    {
      _tp.report( selfAnno, Diagnostic.Kind.ERROR,
        ExtIssueMsg.MSG_SELF_NOT_ON_CORRECT_TYPE.get( fqn, enclosingClass.sym.getQualifiedName() ) );
    }
  }
  catch( Throwable ignore )
  {
  }
}
 
Example 19
Source File: StringLiteralTemplateProcessor.java    From manifold with Apache License 2.0 5 votes vote down vote up
private Boolean getDisableAnnotationValue( JCTree.JCModifiers modifiers )
{
  Boolean disable = null;
  for( JCTree.JCAnnotation anno: modifiers.getAnnotations() )
  {
    if( anno.annotationType.toString().contains( DisableStringLiteralTemplates.class.getSimpleName() ) )
    {
      try
      {
        com.sun.tools.javac.util.List<JCTree.JCExpression> args = anno.getArguments();
        if( args.isEmpty() )
        {
          disable = true;
        }
        else
        {
          JCTree.JCExpression argExpr = args.get( 0 );
          Object value;
          if( argExpr instanceof JCTree.JCLiteral &&
              (value = ((JCTree.JCLiteral)argExpr).getValue()) instanceof Boolean )
          {
            disable = (boolean)value;
          }
          else
          {
            IDynamicJdk.instance().logError( Log.instance( _javacTask.getContext() ), argExpr.pos(),
              "proc.messager", "Only boolean literal values 'true' and 'false' allowed here" );
            disable = true;
          }
        }
      }
      catch( Exception e )
      {
        disable = true;
      }
    }
  }
  return disable;
}
 
Example 20
Source File: TreeAnalyzer.java    From meghanada-server with GNU General Public License v3.0 4 votes vote down vote up
private static void analyzeTopLevelClass(SourceContext context, JCTree.JCClassDecl classDecl)
    throws IOException {
  Source src = context.source;
  EndPosTable endPosTable = context.endPosTable;

  Tree.Kind classDeclKind = classDecl.getKind();

  boolean isInterface = classDeclKind.equals(Tree.Kind.INTERFACE);
  boolean isEnum = classDeclKind.equals(Tree.Kind.ENUM);

  int startPos = classDecl.getPreferredPosition();
  int endPos = classDecl.getEndPosition(endPosTable);
  JCTree.JCModifiers modifiers = classDecl.getModifiers();
  List<JCTree.JCAnnotation> annotations = modifiers.getAnnotations();

  final String classModifiers = parseModifiers(context, modifiers);

  analyzeParsedTree(context, classDecl.getExtendsClause());

  analyzeSimpleExpressions(context, classDecl.getImplementsClause());

  Name simpleName = classDecl.getSimpleName();
  Range range = Range.create(src, startPos + 1, endPos);

  int nameStart = startPos + 6;
  if (isInterface) {
    nameStart = startPos + 10;
  } else if (isEnum) {
    nameStart = startPos + 5;
  }
  Range nameRange = Range.create(src, nameStart, nameStart + simpleName.length());

  String fqcn;
  if (src.getPackageName().isEmpty()) {
    fqcn = simpleName.toString();
  } else {
    fqcn = src.getPackageName() + '.' + simpleName.toString();
  }
  ClassScope classScope = new ClassScope(fqcn, nameRange, startPos, range);
  classScope.isEnum = isEnum;
  classScope.isInterface = isInterface;
  log.trace("class={}", classScope);
  analyzeAnnotations(context, annotations, classScope);

  src.startClass(classScope);

  for (JCTree tree : classDecl.getMembers()) {
    analyzeParsedTree(context, tree);
  }
  addClassNameIndex(
      src, classScope.range.begin.line, classScope.range.begin.column, classScope.getFQCN());
  Optional<ClassScope> endClass = src.endClass();
  log.trace("class={}", endClass);
}