Пример #1
0
 private Context prepareContext(Context baseContext, JCCompilationUnit compilationUnit) {
   Context context = new SubContext(baseContext);
   if (context.get(JavaFileManager.class) == null) {
     JavacFileManager.preRegister(context);
   }
   context.put(JCCompilationUnit.class, compilationUnit);
   context.put(PackageSymbol.class, compilationUnit.packge);
   context.put(RULE_TYPE_VARS, typeVariables());
   return context;
 }
Пример #2
0
  /** Construct a log with given I/O redirections. */
  protected Log(
      Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) {
    super(JCDiagnostic.Factory.instance(context));
    context.put(logKey, this);
    this.errWriter = errWriter;
    this.warnWriter = warnWriter;
    this.noticeWriter = noticeWriter;

    @SuppressWarnings("unchecked") // FIXME
    DiagnosticListener<? super JavaFileObject> dl = context.get(DiagnosticListener.class);
    this.diagListener = dl;

    diagnosticHandler = new DefaultDiagnosticHandler();

    messages = JavacMessages.instance(context);
    messages.add(Main.javacBundleName);

    final Options options = Options.instance(context);
    initOptions(options);
    options.addListener(
        new Runnable() {
          public void run() {
            initOptions(options);
          }
        });
  }
  /** Construct a new compiler from a shared context. */
  public AptJavaCompiler(Context context) {
    super(preRegister(context));

    context.put(compilerKey, this);
    apt = Apt.instance(context);

    ClassReader classReader = ClassReader.instance(context);
    classReader.preferSource = true;

    // TEMPORARY NOTE: bark==log, but while refactoring, we maintain their
    // original identities, to remember the original intent.
    log = Log.instance(context);
    bark = Bark.instance(context);

    Options options = Options.instance(context);
    classOutput = options.get("-retrofit") == null;
    nocompile = options.get("-nocompile") != null;
    print = options.get("-print") != null;
    classesAsDecls = options.get("-XclassesAsDecls") != null;

    genSourceFileNames = new java.util.LinkedHashSet<String>();
    genClassFileNames = new java.util.LinkedHashSet<String>();

    // this forces a copy of the line map to be kept in the tree,
    // for use by com.sun.mirror.util.SourcePosition.
    lineDebugInfo = true;
  }
Пример #4
0
 // @ non_null
 public static Nowarns instance(Context context) {
   Nowarns instance = context.get(nowarnsKey);
   if (instance == null) {
     instance = new Nowarns(context);
     context.put(nowarnsKey, instance);
   }
   return instance;
 }
Пример #5
0
 public static void preRegister(Context context) {
   context.put(
       enterKey,
       new Context.Factory<Enter>() {
         public Enter make(Context c) {
           return new JavadocEnter(c);
         }
       });
 }
Пример #6
0
 public static void preRegister(final Context context) {
   context.put(
       memberEnterKey,
       new Context.Factory<MemberEnter>() {
         public MemberEnter make() {
           return new JavadocMemberEnter(context);
         }
       });
 }
Пример #7
0
 public static void preRegister(Context context, final String programName) {
   context.put(
       logKey,
       new Context.Factory<Log>() {
         public Log make(Context c) {
           return new Messager(c, programName);
         }
       });
 }
Пример #8
0
  /** Construct a new module finder. */
  protected ModuleFinder(Context context) {
    context.put(moduleFinderKey, this);
    names = Names.instance(context);
    syms = Symtab.instance(context);
    fileManager = context.get(JavaFileManager.class);
    log = Log.instance(context);
    classFinder = ClassFinder.instance(context);

    diags = JCDiagnostic.Factory.instance(context);
  }
Пример #9
0
 protected Operators(Context context) {
   context.put(operatorsKey, this);
   syms = Symtab.instance(context);
   names = Names.instance(context);
   log = Log.instance(context);
   types = Types.instance(context);
   initOperatorNames();
   initUnaryOperators();
   initBinaryOperators();
 }
Пример #10
0
 public static void preRegister(Context context) {
   context.put(
       resolveKey,
       new Context.Factory<Resolve>() {
         public Resolve make(Context c) {
           Resolve instance = new ResolveWithDeps(c);
           c.put(Resolve.class, instance);
           return instance;
         }
       });
 }
Пример #11
0
  public <T> void put(Class<T> clazz, Factory<T> fac) {
    DEBUG.P(this, "put(Class<T> clazz, Factory<T> fac)");
    if (fac != null) DEBUG.P("fac=" + fac.getClass().getName());
    else DEBUG.P("fac=" + fac);
    // DEBUG.P("context前="+toString());

    put(key(clazz), fac);

    // DEBUG.P("context后="+toString());
    DEBUG.P(0, this, "put(Class<T> clazz, Factory<T> fac)");
  }
Пример #12
0
  public <T> void put(Class<T> clazz, T data) {
    DEBUG.P(this, "put(Class<T> clazz, T data)");
    if (data != null) DEBUG.P("data=" + data.getClass().getName());
    else DEBUG.P("data=" + data);
    // DEBUG.P("context前="+toString());

    put(key(clazz), data);

    // DEBUG.P("context后="+toString());
    DEBUG.P(0, this, "put(Class<T> clazz, T data)");
  }
Пример #13
0
 public static void preRegister(Context context) {
   context.put(
       attrKey,
       new Context.Factory<Attr>() {
         public Attr make(Context c) {
           Attr instance = new AttrWithDeps(c);
           c.put(Attr.class, instance);
           return instance;
         }
       });
 }
 protected Annotate(Context context) {
   context.put(annotateKey, this);
   attr = Attr.instance(context);
   make = TreeMaker.instance(context);
   log = Log.instance(context);
   syms = Symtab.instance(context);
   names = Names.instance(context);
   rs = Resolve.instance(context);
   types = Types.instance(context);
   cfolder = ConstFold.instance(context);
   chk = Check.instance(context);
 }
Пример #15
0
    /** Create a new diagnostic factory. */
    protected Factory(Context context) {
      this(JavacMessages.instance(context), "compiler");
      context.put(diagnosticFactoryKey, this);

      final Options options = Options.instance(context);
      initOptions(options);
      options.addListener(
          new Runnable() {
            public void run() {
              initOptions(options);
            }
          });
    }
Пример #16
0
 /** Get the Ceylon context instance for this context. */
 public static com.redhat.ceylon.compiler.typechecker.context.Context getCeylonContextInstance(
     Context context) {
   com.redhat.ceylon.compiler.typechecker.context.Context ceylonContext =
       context.get(ceylonContextKey);
   if (ceylonContext == null) {
     CeyloncFileManager fileManager = (CeyloncFileManager) context.get(JavaFileManager.class);
     VFS vfs = new VFS();
     ceylonContext =
         new com.redhat.ceylon.compiler.typechecker.context.Context(
             fileManager.getRepositoryManager(), vfs);
     context.put(ceylonContextKey, ceylonContext);
   }
   return ceylonContext;
 }
Пример #17
0
 public static void preRegister(
     Context context,
     final String programName,
     final PrintWriter errWriter,
     final PrintWriter warnWriter,
     final PrintWriter noticeWriter) {
   context.put(
       logKey,
       new Context.Factory<Log>() {
         public Log make(Context c) {
           return new Messager(c, programName, errWriter, warnWriter, noticeWriter);
         }
       });
 }
 /** Get the PhasedUnits instance for this context. */
 public static PhasedUnits getPhasedUnitsInstance(final Context context) {
   PhasedUnits phasedUnits = context.get(phasedUnitsKey);
   if (phasedUnits == null) {
     com.redhat.ceylon.compiler.typechecker.context.Context ceylonContext =
         getCeylonContextInstance(context);
     phasedUnits =
         new PhasedUnits(
             ceylonContext,
             new ModuleManagerFactory() {
               @Override
               public ModuleManager createModuleManager(
                   com.redhat.ceylon.compiler.typechecker.context.Context ceylonContext) {
                 return new CompilerModuleManager(ceylonContext, context);
               }
             });
     context.put(phasedUnitsKey, phasedUnits);
   }
   return phasedUnits;
 }
Пример #19
0
  protected Enter(Context context) {
    context.put(enterKey, this);

    log = Log.instance(context);
    reader = ClassReader.instance(context);
    make = TreeMaker.instance(context);
    syms = Symtab.instance(context);
    chk = Check.instance(context);
    memberEnter = MemberEnter.instance(context);
    types = Types.instance(context);
    annotate = Annotate.instance(context);
    lint = Lint.instance(context);

    predefClassDef =
        make.ClassDef(make.Modifiers(PUBLIC), syms.predefClass.name, null, null, null, null);
    predefClassDef.sym = syms.predefClass;
    todo = Todo.instance(context);
    fileManager = context.get(JavaFileManager.class);
  }
Пример #20
0
 /** The default writer for diagnostics */
 static PrintWriter defaultWriter(Context context) {
   PrintWriter result = context.get(outKey);
   if (result == null) context.put(outKey, result = new PrintWriter(System.err));
   return result;
 }
Пример #21
0
 protected Paths(Context context) {
   context.put(pathsKey, this);
   pathsForLocation = new HashMap<Location, Path>(16);
   setContext(context);
 }
Пример #22
0
 /**
  * Use a new context. May be called from outside to update internal state for a new
  * annotation-processing round.
  */
 public void setContext(Context context) {
   context.put(JavacTypes.class, this);
   syms = Symtab.instance(context);
   types = Types.instance(context);
 }
Пример #23
0
    /**
     * Get the context for the next round of processing. Important values are propogated from round
     * to round; other values are implicitly reset.
     */
    private Context nextContext() {
      Context next = new Context(context);

      Options options = Options.instance(context);
      Assert.checkNonNull(options);
      next.put(Options.optionsKey, options);

      PrintWriter out = context.get(Log.outKey);
      Assert.checkNonNull(out);
      next.put(Log.outKey, out);
      Locale locale = context.get(Locale.class);
      if (locale != null) next.put(Locale.class, locale);
      Assert.checkNonNull(messages);
      next.put(JavacMessages.messagesKey, messages);

      final boolean shareNames = true;
      if (shareNames) {
        Names names = Names.instance(context);
        Assert.checkNonNull(names);
        next.put(Names.namesKey, names);
      }

      DiagnosticListener<?> dl = context.get(DiagnosticListener.class);
      if (dl != null) next.put(DiagnosticListener.class, dl);

      TaskListener tl = context.get(TaskListener.class);
      if (tl != null) next.put(TaskListener.class, tl);

      FSInfo fsInfo = context.get(FSInfo.class);
      if (fsInfo != null) next.put(FSInfo.class, fsInfo);

      JavaFileManager jfm = context.get(JavaFileManager.class);
      Assert.checkNonNull(jfm);
      next.put(JavaFileManager.class, jfm);
      if (jfm instanceof JavacFileManager) {
        ((JavacFileManager) jfm).setContext(next);
      }

      Names names = Names.instance(context);
      Assert.checkNonNull(names);
      next.put(Names.namesKey, names);

      Keywords keywords = Keywords.instance(context);
      Assert.checkNonNull(keywords);
      next.put(Keywords.keywordsKey, keywords);

      JavaCompiler oldCompiler = JavaCompiler.instance(context);
      JavaCompiler nextCompiler = JavaCompiler.instance(next);
      nextCompiler.initRound(oldCompiler);

      filer.newRound(next);
      messager.newRound(next);
      elementUtils.setContext(next);
      typeUtils.setContext(next);

      JavacTaskImpl task = context.get(JavacTaskImpl.class);
      if (task != null) {
        next.put(JavacTaskImpl.class, task);
        task.updateContext(next);
      }

      JavacTrees trees = context.get(JavacTrees.class);
      if (trees != null) {
        next.put(JavacTrees.class, trees);
        trees.updateContext(next);
      }

      context.clear();
      return next;
    }
Пример #24
0
 protected DPrinter(Context context) {
   context.put(DPrinter.class, this);
   out = context.get(Log.outKey);
   trees = JavacTrees.instance(context);
 }
Пример #25
0
  /**
   * Programmatic interface for main function.
   *
   * @param args The command line parameters.
   */
  int compile(String[] args, Context context) {
    boolean assertionsEnabled = false;
    assert assertionsEnabled = true;
    if (!assertionsEnabled) {
      // Bark.printLines(out, "fatal error: assertions must be enabled when running javac");
      // return EXIT_ABNORMAL;
    }
    int exitCode = EXIT_OK;

    JavaCompiler comp = null;
    try {
      context.put(Bark.outKey, out);

      comp = JavaCompiler.instance(context);
      if (comp == null) return EXIT_SYSERR;

      java.util.List<String> nameList = new java.util.LinkedList<String>();
      nameList.addAll(sourceFileNames);
      if (options.get("-XclassesAsDecls") != null) nameList.addAll(classFileNames);

      List<Symbol.ClassSymbol> cs =
          comp.compile(
              List.from(nameList.toArray(new String[0])),
              origOptions,
              aptCL,
              providedFactory,
              productiveFactories,
              aggregateGenFiles);

      /*
       * If there aren't new source files, we shouldn't bother
       *  running javac if there were errors.
       *
       * If there are new files, we should try running javac in
       * case there were typing errors.
       *
       */

      if (comp.errorCount() != 0 || options.get("-Werror") != null && comp.warningCount() != 0)
        return EXIT_ERROR;
    } catch (IOException ex) {
      ioMessage(ex);
      return EXIT_SYSERR;
    } catch (OutOfMemoryError ex) {
      resourceMessage(ex);
      return EXIT_SYSERR;
    } catch (StackOverflowError ex) {
      resourceMessage(ex);
      return EXIT_SYSERR;
    } catch (FatalError ex) {
      feMessage(ex);
      return EXIT_SYSERR;
    } catch (UsageMessageNeededException umne) {
      help();
      return EXIT_CMDERR; // will cause usage message to be printed
    } catch (AnnotationProcessingError ex) {
      apMessage(ex);
      return EXIT_ABNORMAL;
    } catch (sun.misc.ServiceConfigurationError sce) {
      sceMessage(sce);
      return EXIT_ABNORMAL;
    } catch (Throwable ex) {
      bugMessage(ex);
      return EXIT_ABNORMAL;
    } finally {
      if (comp != null) {
        comp.close();
        genSourceFileNames.addAll(comp.getSourceFileNames());
        genClassFileNames.addAll(comp.getClassFileNames());
      }
      sourceFileNames = new java.util.LinkedList<String>();
      classFileNames = new java.util.LinkedList<String>();
    }
    return exitCode;
  }
Пример #26
0
 public Delombok() {
   context.put(DeleteLombokAnnotations.class, new DeleteLombokAnnotations(true));
 }
Пример #27
0
  public boolean delombok() throws IOException {
    Options options = Options.instance(context);
    options.put(OptionName.ENCODING, charset.name());
    if (classpath != null) options.put(OptionName.CLASSPATH, classpath);
    if (sourcepath != null) options.put(OptionName.SOURCEPATH, sourcepath);
    options.put("compilePolicy", "attr");
    CommentCollectingScanner.Factory.preRegister(context);

    JavaCompiler compiler = new JavaCompiler(context);
    compiler.keepComments = true;
    compiler.genEndPos = true;

    List<JCCompilationUnit> roots = new ArrayList<JCCompilationUnit>();
    Map<JCCompilationUnit, Comments> commentsMap =
        new IdentityHashMap<JCCompilationUnit, Comments>();
    Map<JCCompilationUnit, File> baseMap = new IdentityHashMap<JCCompilationUnit, File>();

    compiler.initProcessAnnotations(Collections.singleton(new lombok.javac.apt.Processor()));

    for (File fileToParse : filesToParse) {
      Comments comments = new Comments();
      context.put(Comments.class, comments);

      @SuppressWarnings("deprecation")
      JCCompilationUnit unit = compiler.parse(fileToParse.getAbsolutePath());

      commentsMap.put(unit, comments);
      baseMap.put(unit, fileToBase.get(fileToParse));
      roots.add(unit);
    }

    if (compiler.errorCount() > 0) {
      // At least one parse error. No point continuing (a real javac run doesn't either).
      return false;
    }

    TrackChangedAsts tca = new TrackChangedAsts();

    context.put(TrackChangedAsts.class, tca);

    JavaCompiler delegate = compiler.processAnnotations(compiler.enterTrees(toJavacList(roots)));
    for (JCCompilationUnit unit : roots) {
      DelombokResult result =
          new DelombokResult(
              commentsMap.get(unit).comments.toList(), unit, force || tca.changed.contains(unit));
      if (verbose)
        feedback.printf(
            "File: %s [%s]\n",
            unit.sourcefile.getName(), result.isChanged() ? "delomboked" : "unchanged");
      Writer rawWriter;
      if (presetWriter != null) rawWriter = presetWriter;
      else if (output == null) rawWriter = createStandardOutWriter();
      else rawWriter = createFileWriter(output, baseMap.get(unit), unit.sourcefile.toUri());
      BufferedWriter writer = new BufferedWriter(rawWriter);
      try {
        result.print(writer);
      } finally {
        writer.close();
      }
    }
    delegate.close();

    return true;
  }
Пример #28
0
 public void setDiagnosticsListener(DiagnosticListener<JavaFileObject> diagnostics) {
   if (diagnostics != null) context.put(DiagnosticListener.class, diagnostics);
 }
Пример #29
0
  /**
   * Programmatic interface for main function.
   *
   * @param args The command line parameters.
   */
  public int compile(
      String[] args,
      Context context,
      List<JavaFileObject> fileObjects,
      Iterable<? extends Processor> processors) {
    if (options == null) options = Options.instance(context); // creates a new one

    filenames = new ListBuffer<File>();
    classnames = new ListBuffer<String>();
    JavaCompiler comp = null;
    /*
     * TODO: Logic below about what is an acceptable command line
     * should be updated to take annotation processing semantics
     * into account.
     */
    try {
      if (args.length == 0 && fileObjects.isEmpty()) {
        help();
        return EXIT_CMDERR;
      }

      List<File> files;
      try {
        files = processArgs(CommandLine.parse(args));
        if (files == null) {
          // null signals an error in options, abort
          return EXIT_CMDERR;
        } else if (files.isEmpty() && fileObjects.isEmpty() && classnames.isEmpty()) {
          // it is allowed to compile nothing if just asking for help or version info
          if (options.get("-help") != null
              || options.get("-X") != null
              || options.get("-version") != null
              || options.get("-fullversion") != null) return EXIT_OK;
          error("err.no.source.files");
          return EXIT_CMDERR;
        }
      } catch (java.io.FileNotFoundException e) {
        Log.printLines(
            out, ownName + ": " + getLocalizedString("err.file.not.found", e.getMessage()));
        return EXIT_SYSERR;
      }

      boolean forceStdOut = options.get("stdout") != null;
      if (forceStdOut) {
        out.flush();
        out = new PrintWriter(System.out, true);
      }

      context.put(Log.outKey, out);

      // allow System property in following line as a Mustang legacy
      boolean batchMode =
          (options.get("nonBatchMode") == null && System.getProperty("nonBatchMode") == null);
      if (batchMode) CacheFSInfo.preRegister(context);

      fileManager = context.get(JavaFileManager.class);

      comp = JavaCompiler.instance(context);
      if (comp == null) return EXIT_SYSERR;

      if (!files.isEmpty()) {
        // add filenames to fileObjects
        comp = JavaCompiler.instance(context);
        List<JavaFileObject> otherFiles = List.nil();
        JavacFileManager dfm = (JavacFileManager) fileManager;
        for (JavaFileObject fo : dfm.getJavaFileObjectsFromFiles(files))
          otherFiles = otherFiles.prepend(fo);
        for (JavaFileObject fo : otherFiles) fileObjects = fileObjects.prepend(fo);
      }
      comp.compile(fileObjects, classnames.toList(), processors);

      if (comp.errorCount() != 0) return EXIT_ERROR;
    } catch (IOException ex) {
      ioMessage(ex);
      return EXIT_SYSERR;
    } catch (OutOfMemoryError ex) {
      resourceMessage(ex);
      return EXIT_SYSERR;
    } catch (StackOverflowError ex) {
      resourceMessage(ex);
      return EXIT_SYSERR;
    } catch (FatalError ex) {
      feMessage(ex);
      return EXIT_SYSERR;
    } catch (AnnotationProcessingError ex) {
      apMessage(ex);
      return EXIT_SYSERR;
    } catch (ClientCodeException ex) {
      // as specified by javax.tools.JavaCompiler#getTask
      // and javax.tools.JavaCompiler.CompilationTask#call
      throw new RuntimeException(ex.getCause());
    } catch (PropagatedException ex) {
      throw ex.getCause();
    } catch (Throwable ex) {
      // Nasty.  If we've already reported an error, compensate
      // for buggy compiler error recovery by swallowing thrown
      // exceptions.
      if (comp == null || comp.errorCount() == 0 || options == null || options.get("dev") != null)
        bugMessage(ex);
      return EXIT_ABNORMAL;
    } finally {
      if (comp != null) comp.close();
      filenames = null;
      options = null;
    }
    return EXIT_OK;
  }
Пример #30
0
 protected Options(Context context) {
   // DEBUGGING -- Use LinkedHashMap for reproducability
   values = new LinkedHashMap<String, String>();
   context.put(optionsKey, this);
 }