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

The following examples show how to use com.sun.tools.javac.tree.JCTree#JCClassDecl . 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: JavacPlugin.java    From manifold with Apache License 2.0 6 votes vote down vote up
private void addInputFile( TaskEvent e )
{
  if( !_initialized )
  {
    CompilationUnitTree compilationUnit = e.getCompilationUnit();
    ExpressionTree pkg = compilationUnit.getPackageName();
    String packageQualifier = pkg == null ? "" : (pkg.toString() + '.');
    for( Tree classDecl : compilationUnit.getTypeDecls() )
    {
      if( classDecl instanceof JCTree.JCClassDecl )
      {
        _javaInputFiles.add( new Pair<>( packageQualifier + ((JCTree.JCClassDecl)classDecl).getSimpleName(), compilationUnit.getSourceFile() ) );
      }
    }
  }
}
 
Example 2
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 6 votes vote down vote up
private boolean isOnExtensionMethod( JCTree annotated, String fqn, JCTree.JCClassDecl enclosingClass )
{
  if( isExtensionClass( enclosingClass ) )
  {
    String extendedClassName = getExtendedClassName();
    if( extendedClassName != null && extendedClassName.equals( fqn ) )
    {
      JCTree.JCMethodDecl declMethod = findDeclMethod( annotated );
      if( declMethod != null )
      {
        List<JCTree.JCVariableDecl> parameters = declMethod.getParameters();
        for( JCTree.JCVariableDecl param: parameters )
        {
          if( hasAnnotation( param.getModifiers().getAnnotations(), This.class ) )
          {
            return true;
          }
        }
      }
    }
  }
  return false;
}
 
Example 3
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 5 votes vote down vote up
private Symbol getEnclosingSymbol( Tree tree, Context ctx )
{
  if( tree == null )
  {
    return null;
  }
  if( tree instanceof JCTree.JCClassDecl )
  {
    // should not really get here, but should be static block scope if possible
    return new Symbol.MethodSymbol( STATIC | BLOCK,
      Names.instance( ctx ).empty, null, ((JCTree.JCClassDecl)tree).sym );
  }
  if( tree instanceof JCTree.JCMethodDecl )
  {
    return ((JCTree.JCMethodDecl)tree).sym;
  }
  if( tree instanceof JCTree.JCVariableDecl )
  {
    Tree parent = _tp.getParent( tree );
    if( parent instanceof JCTree.JCClassDecl )
    {
      // field initializers have a block scope
      return new Symbol.MethodSymbol( (((JCTree.JCVariableDecl)tree).mods.flags & STATIC) | BLOCK,
        Names.instance( ctx ).empty, null, ((JCTree.JCClassDecl)parent).sym );
    }
  }
  return getEnclosingSymbol( _tp.getParent( tree ), ctx );
}
 
Example 4
Source File: NBJavaCompiler.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void desugar(Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCTree.JCClassDecl>> results) {
    boolean prevDesugaring = desugaring;
    try {
        desugaring = true;
    super.desugar(env, results);
    } finally {
        desugaring = prevDesugaring;
    }
}
 
Example 5
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 5 votes vote down vote up
/**
 * Issue errors/warnings if an extension method violates extension method grammar or conflicts with an existing method
 */
@Override
public void visitMethodDef( JCTree.JCMethodDecl tree )
{
  if( isBridgeMethod( tree ) )
  {
    // we process bridge methods during Generation, since they don't exist prior to Generation
    _bridgeMethod = true;
  }
  try
  {
    super.visitMethodDef( tree );
  }
  finally
  {
    _bridgeMethod = false;
  }

  if( _tp.isGenerate() )
  {
    // Don't process tree during GENERATE, unless the tree was generated e.g., a bridge method
    return;
  }

  if( tree.sym.owner.isAnonymous() )
  {
    // Keep track of anonymous classes so we can process any bridge methods added to them
    JCTree.JCClassDecl anonymousClassDef = (JCTree.JCClassDecl)_tp.getTreeUtil().getTree( tree.sym.owner );
    _tp.preserveInnerClassForGenerationPhase( anonymousClassDef );
  }

  verifyExtensionMethod( tree );
  result = tree;
}
 
Example 6
Source File: CompiledTypeProcessor.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void preserveInnerClassesForGeneration( JCTree.JCClassDecl tree )
{
  for( JCTree def: tree.defs )
  {
    if( def instanceof JCTree.JCClassDecl )
    {
      JCTree.JCClassDecl classDecl = (JCTree.JCClassDecl)def;

      preserveInnerClassForGenerationPhase( classDecl );
      preserveInnerClassesForGeneration( classDecl );
    }
  }
}
 
Example 7
Source File: StringLiteralTemplateProcessor.java    From manifold with Apache License 2.0 5 votes vote down vote up
@Override
public void finished( TaskEvent e )
{
  if( e.getKind() != TaskEvent.Kind.PARSE )
  {
    return;
  }

  try
  {
    // Uninstall the handler after the file parses (we create new handler for each file)
    Log.instance( _javacTask.getContext() ).popDiagnosticHandler( _manDiagnosticHandler );
  }
  catch( Throwable ignore ) {}

  for( Tree tree : e.getCompilationUnit().getTypeDecls() )
  {
    if( !(tree instanceof JCTree.JCClassDecl) )
    {
      continue;
    }
    
    JCTree.JCClassDecl classDecl = (JCTree.JCClassDecl)tree;
    if( !isTypeExcluded( classDecl, e.getCompilationUnit() ) )
    {
      classDecl.accept( this );
    }
  }
}
 
Example 8
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 5 votes vote down vote up
private boolean isExtensionClass( Tree parent )
{
  if( parent instanceof JCTree.JCClassDecl )
  {
    return hasAnnotation( ((JCTree.JCClassDecl)parent).getModifiers().getAnnotations(), Extension.class );
  }
  return false;
}
 
Example 9
Source File: JavacPlugin.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void insertBootstrap( JCTree.JCClassDecl tree )
{
  // we construct BootstrapInserter reflectively because it extends TreeTranslator,
  // which we have yet to open/export as JavacPlugin is loaded before that time
  TreeTranslator visitor = (TreeTranslator)ReflectUtil
    .constructor( "manifold.internal.javac.BootstrapInserter", JavacPlugin.class ).newInstance( this );
  tree.accept( visitor );
}
 
Example 10
Source File: SingletonJavacHandler.java    From tutorials with MIT License 5 votes vote down vote up
private void addInstanceVar(JavacNode singletonClass, JavacTreeMaker singletonClassTM, JavacNode holderClass) {
    JCTree.JCModifiers fieldMod = singletonClassTM.Modifiers(Flags.PRIVATE | Flags.STATIC | Flags.FINAL);

    JCTree.JCClassDecl singletonClassDecl = (JCTree.JCClassDecl) singletonClass.get();
    JCTree.JCIdent singletonClassType = singletonClassTM.Ident(singletonClassDecl.name);

    JCTree.JCNewClass newKeyword = singletonClassTM.NewClass(null, List.nil(), singletonClassType, List.nil(), null);

    JCTree.JCVariableDecl instanceVar = singletonClassTM.VarDef(fieldMod, singletonClass.toName("INSTANCE"), singletonClassType, newKeyword);
    JavacHandlerUtil.injectField(holderClass, instanceVar);
}
 
Example 11
Source File: DarkJavaTypeManifold.java    From manifold with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isInnerType( String topLevel, String relativeInner )
{
  if( isAnonymous( relativeInner ) )
  {
    return true;
  }

  Model model = getModel( topLevel );
  if( model == null )
  {
    return false;
  }

  JCTree.JCClassDecl classDecl = getClassDecl( model );
  if( classDecl == null )
  {
    return false;
  }

  for( JCTree m: classDecl.getMembers() )
  {
    if( m instanceof JCTree.JCClassDecl )
    {
      return isInnerClass( (JCTree.JCClassDecl)m, relativeInner );
    }
  }

  return false;
}
 
Example 12
Source File: DarkJavaTypeManifold.java    From manifold with Apache License 2.0 5 votes vote down vote up
private boolean isInnerClass( JCTree.JCClassDecl cls, String relativeInner )
{
  String name;
  String remainder;
  int iDot = relativeInner.indexOf( '.' );
  if( iDot > 0 )
  {
    name = relativeInner.substring( 0, iDot );
    remainder = relativeInner.substring( iDot+1 );
  }
  else
  {
    name = relativeInner;
    remainder = null;
  }
  if( cls.getSimpleName().toString().equals( name ) )
  {
    if( remainder != null )
    {
      for( JCTree m: cls.getMembers() )
      {
        if( m instanceof JCTree.JCClassDecl )
        {
          if( isInnerClass( (JCTree.JCClassDecl)m, remainder ) )
          {
            return true;
          }
        }
      }
    }
    else
    {
      return true;
    }
  }
  return false;
}
 
Example 13
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void incrementalCompileClasses( JCTree.JCClassDecl tree )
{
  if( _tp.isGenerate() )
  {
    return;
  }

  // Keep track of Manifold types compiled, for hotswap compile drivers, and more generally for JPS build management
  // e.g., to keep track of resource file to .class files so subsequent incremental build can delete .class files and
  // recompile changed resources.
  mapResourceFileToTargetClassFiles( tree );

  // Ensure modified resource files are compiled, stemming from incremental compilation only
  incrementalCompile( tree );
}
 
Example 14
Source File: BootstrapInserter.java    From manifold with Apache License 2.0 5 votes vote down vote up
private boolean okToInsertBootstrap( JCTree.JCClassDecl tree )
{
  return !annotatedWith_NoBootstrap( tree.getModifiers().getAnnotations() ) &&
         !JavacPlugin.instance().isNoBootstrapping() &&
         isExtensionsEnabled() &&
         !alreadyHasBootstrap( tree ) &&
         !skipForOtherReasons( tree );
}
 
Example 15
Source File: CompiledTypeProcessor.java    From manifold with Apache License 2.0 5 votes vote down vote up
private JCTree.JCClassDecl findTopLevel( Symbol.ClassSymbol type, List<? extends Tree> typeDecls )
{
  for( Tree tree: typeDecls )
  {
    if( tree instanceof JCTree.JCClassDecl && ((JCTree.JCClassDecl)tree).sym == type )
    {
      return (JCTree.JCClassDecl)tree;
    }
  }
  return null;
}
 
Example 16
Source File: CompiledTypeProcessor.java    From manifold with Apache License 2.0 4 votes vote down vote up
public JavaFileObject getFile( Tree node )
{
  JCTree.JCClassDecl classDecl = getClassDecl( node );
  return classDecl == null ? null : classDecl.sym.sourcefile;
}
 
Example 17
Source File: CompiledTypeProcessor.java    From manifold with Apache License 2.0 4 votes vote down vote up
public void preserveInnerClassForGenerationPhase( JCTree.JCClassDecl def )
{
  _innerClassForGeneration.put( def.sym.flatName().toString(), def );
}
 
Example 18
Source File: Model.java    From manifold with Apache License 2.0 4 votes vote down vote up
public JCTree.JCClassDecl getClassDecl()
{
  return _classDecl;
}
 
Example 19
Source File: JavaParser.java    From manifold with Apache License 2.0 4 votes vote down vote up
public JCTree.JCExpression parseExpr( String expr, DiagnosticCollector<JavaFileObject> errorHandler )
{
  //!! Do not init() here; do not use _javac or _mfm for parseExpr() since this method is generally used
  //!! during the Parse phase, which happens earlier than the Enter phase where the plugin initializes much
  //!! of its state i.e., if parseExpr() is called before an Enter phase, it could use Manifold prematurely
  //!! and screw the pooch.  Also, we don't need Manifold for parsing expressions since it only produces a
  //!! simple AST with nothing resolved.
  // init();

  ArrayList<JavaFileObject> javaStringObjects = new ArrayList<>();
  String src =
    "class Sample {\n" +
    "  Object foo = " + expr + ";\n" +
    "}\n";
  javaStringObjects.add( new StringJavaFileObject( "sample", src ) );
  StringWriter errors = new StringWriter();
  BasicJavacTask javacTask = (BasicJavacTask)Objects.requireNonNull( _parserJavac.get() )
    .getTask( errors, null, errorHandler, Collections.singletonList( "-proc:none" ), null, javaStringObjects );
  try
  {
    initTypeProcessing( javacTask, Collections.singleton( "sample" ) );
    Iterable<? extends CompilationUnitTree> iterable = javacTask.parse();
    if( errors.getBuffer().length() > 0 )
    {
      System.err.println( errors.getBuffer() );
    }
    for( CompilationUnitTree x : iterable )
    {
      List<? extends Tree> typeDecls = x.getTypeDecls();
      if( !typeDecls.isEmpty() )
      {
        JCTree.JCClassDecl tree = (JCTree.JCClassDecl)typeDecls.get( 0 );
        JCTree.JCVariableDecl field = (JCTree.JCVariableDecl)tree.getMembers().get( 0 );
        return field.getInitializer();
      }
    }
    return null;
  }
  catch( Exception e )
  {
    return null;
  }
}
 
Example 20
Source File: CommentCollectorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testMethod() throws Exception {
    File testFile = new File(work, "Test.java");
    String origin = "\n" +
            "import java.io.File;\n" +
            "\n" +
            "public class Test {\n" +
            "\n" +
            "    void method() {\n" +
            "        // Test\n" +
            "        System.out.println(\"Slepitchka\");\n" +
            "    }\n" +
            "\n" +
            "}\n";
    TestUtilities.copyStringToFile(testFile, origin);
    JavaSource src = getJavaSource(testFile);

    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        protected CommentHandlerService service;

        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(JavaSource.Phase.PARSED);
            CompilationUnitTree cu = workingCopy.getCompilationUnit();
            GeneratorUtilities.get(workingCopy).importComments(cu, cu);

            service = CommentHandlerService.instance(workingCopy.impl.getJavacTask().getContext());
            CommentPrinter printer = new CommentPrinter(service);
            cu.accept(printer, null);

            JCTree.JCClassDecl clazz = (JCTree.JCClassDecl) cu.getTypeDecls().get(0);
            final boolean[] processed = new boolean[1];
            TreeVisitor<Void, Void> w = new ErrorAwareTreeScanner<Void, Void>() {
                @Override
                public Void visitExpressionStatement(ExpressionStatementTree node, Void p) {
                    verify(node, CommentSet.RelativePosition.PRECEDING, service, "// Test");
                    processed[0] = true;
                    return super.visitExpressionStatement(node, p);
                }
            };
            clazz.accept(w, null);
            if (!processed[0]) {
                fail("Tree has not been processed!");
            }
        }


    };
    src.runModificationTask(task);

}