Example #1
1
  /**
   * When looking at a result set that consists of a Map/HashTable we cannot rely on the output
   * order, as the hashing algorithm or other aspects of the implementation may be different on
   * differnt JDKs or platforms. Hence we take the Map, convert the keys to a List, sort them and
   * Stringify the Map, which is a bit of a hack, but guarantees that we get the same order on all
   * systems. We assume that the keys are strings.
   *
   * @param m The Map that contains keys we wish to return in sorted order
   * @return A string that represents all the keys in sorted order.
   */
  public String sortMapToString(Map m) {

    System.out.println("Map toString looks like: " + m.toString());
    // Pass in crap, and get nothing back
    //
    if (m == null) {
      return null;
    }

    // Sort the keys in the Map
    //
    TreeMap nset = new TreeMap(m);

    System.out.println("Tree map looks like: " + nset.toString());
    return nset.toString();
  }
  /**
   * Translate the given abstract syntax trees to elements.
   *
   * @param trees a list of abstract syntax trees.
   * @throws java.io.IOException TODO
   * @return a list of elements corresponding to the top level classes in the abstract syntax trees
   */
  public Iterable<? extends TypeElement> enter(Iterable<? extends CompilationUnitTree> trees)
      throws IOException {
    prepareCompiler();

    ListBuffer<JCCompilationUnit> roots = null;

    if (trees == null) {
      // If there are still files which were specified to be compiled
      // (i.e. in fileObjects) but which have not yet been entered,
      // then we make sure they have been parsed and add them to the
      // list to be entered.
      if (notYetEntered.size() > 0) {
        if (!parsed) parse(); // TODO would be nice to specify files needed to be parsed
        for (JavaFileObject file : fileObjects) {
          JCCompilationUnit unit = notYetEntered.remove(file);
          if (unit != null) {
            if (roots == null) roots = new ListBuffer<JCCompilationUnit>();
            roots.append(unit);
          }
        }
        notYetEntered.clear();
      }
    } else {
      for (CompilationUnitTree cu : trees) {
        if (cu instanceof JCCompilationUnit) {
          if (roots == null) roots = new ListBuffer<JCCompilationUnit>();
          roots.append((JCCompilationUnit) cu);
          notYetEntered.remove(cu.getSourceFile());
        } else throw new IllegalArgumentException(cu.toString());
      }
    }

    if (roots == null) return List.nil();

    try {
      List<JCCompilationUnit> units = compiler.enterTrees(roots.toList());

      if (notYetEntered.isEmpty()) compiler = compiler.processAnnotations(units);

      ListBuffer<TypeElement> elements = new ListBuffer<TypeElement>();
      for (JCCompilationUnit unit : units) {
        for (JCTree node : unit.defs) {
          if (node.getTag() == JCTree.CLASSDEF) {
            JCClassDecl cdef = (JCClassDecl) node;
            if (cdef.sym != null) // maybe null if errors in anno processing
            elements.append(cdef.sym);
          }
        }
      }
      return elements.toList();
    } finally {
      compiler.log.flush();
    }
  }
  public ExitCode build(
      final CompileContext context,
      final ModuleChunk chunk,
      DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget> dirtyFilesHolder,
      OutputConsumer outputConsumer)
      throws ProjectBuildException {
    if (!IS_ENABLED.get(context, Boolean.TRUE)) {
      return ExitCode.NOTHING_DONE;
    }
    try {
      final Map<File, ModuleBuildTarget> filesToCompile =
          new THashMap<File, ModuleBuildTarget>(FileUtil.FILE_HASHING_STRATEGY);

      dirtyFilesHolder.processDirtyFiles(
          new FileProcessor<JavaSourceRootDescriptor, ModuleBuildTarget>() {
            public boolean apply(
                ModuleBuildTarget target, File file, JavaSourceRootDescriptor descriptor)
                throws IOException {
              if (JAVA_SOURCES_FILTER.accept(file)) {
                filesToCompile.put(file, target);
              }
              return true;
            }
          });

      if (context.isMake()) {
        final ProjectBuilderLogger logger = context.getLoggingManager().getProjectBuilderLogger();
        if (logger.isEnabled()) {
          if (filesToCompile.size() > 0) {
            logger.logCompiledFiles(filesToCompile.keySet(), BUILDER_NAME, "Compiling files:");
          }
        }
      }

      return compile(context, chunk, dirtyFilesHolder, filesToCompile.keySet(), outputConsumer);
    } catch (ProjectBuildException e) {
      throw e;
    } catch (Exception e) {
      String message = e.getMessage();
      if (message == null) {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final PrintStream stream = new PrintStream(out);
        try {
          e.printStackTrace(stream);
        } finally {
          stream.close();
        }
        message = "Internal error: \n" + out.toString();
      }
      context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, message));
      throw new ProjectBuildException(message, e);
    }
  }
 /**
  * Parse the specified files returning a list of abstract syntax trees.
  *
  * @throws java.io.IOException TODO
  * @return a list of abstract syntax trees
  */
 public Iterable<? extends CompilationUnitTree> parse() throws IOException {
   try {
     prepareCompiler();
     List<JCCompilationUnit> units = compiler.parseFiles(fileObjects);
     for (JCCompilationUnit unit : units) {
       JavaFileObject file = unit.getSourceFile();
       if (notYetEntered.containsKey(file)) notYetEntered.put(file, unit);
     }
     return units;
   } finally {
     parsed = true;
     if (compiler != null && compiler.log != null) compiler.log.flush();
   }
 }
Example #5
0
 @NotNull
 public static Map<String, String> parseDirectives(String expectedText) {
   Map<String, String> directives = Maps.newHashMap();
   Matcher directiveMatcher = DIRECTIVE_PATTERN.matcher(expectedText);
   int start = 0;
   while (directiveMatcher.find()) {
     if (directiveMatcher.start() != start) {
       Assert.fail(
           "Directives should only occur at the beginning of a file: " + directiveMatcher.group());
     }
     String name = directiveMatcher.group(1);
     String value = directiveMatcher.group(3);
     String oldValue = directives.put(name, value);
     Assert.assertNull(
         "Directive overwritten: " + name + " old value: " + oldValue + " new value: " + value,
         oldValue);
     start = directiveMatcher.end() + 1;
   }
   return directives;
 }
 @Override
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
   for (Element annotatedElt : roundEnv.getElementsAnnotatedWith(CodeTranslate.class)) {
     ExecutableElement methodElt = (ExecutableElement) annotatedElt;
     TypeElement typeElt = (TypeElement) methodElt.getEnclosingElement();
     if (typeElt.getQualifiedName().toString().equals(fqn)
         && methodElt.getSimpleName().toString().equals(method)) {
       for (Lang lang : langs) {
         Result result;
         try {
           String translation = translator.translate(methodElt, lang);
           result = new Result.Source(translation);
         } catch (Exception e) {
           result = new Result.Failure(e);
         }
         results.put(lang, result);
       }
     }
   }
   return false;
 }
 private void prepareCompiler() throws IOException {
   if (used.getAndSet(true)) {
     if (compiler == null) throw new IllegalStateException();
   } else {
     initContext();
     compilerMain.setOptions(Options.instance(context));
     compilerMain.filenames = new LinkedHashSet<File>();
     Collection<File> filenames = compilerMain.processArgs(CommandLine.parse(args), classNames);
     if (!filenames.isEmpty())
       throw new IllegalArgumentException("Malformed arguments " + toString(filenames, " "));
     compiler = JavaCompiler.instance(context);
     compiler.keepComments = true;
     compiler.genEndPos = true;
     // NOTE: this value will be updated after annotation processing
     compiler.initProcessAnnotations(processors);
     notYetEntered = new HashMap<JavaFileObject, JCCompilationUnit>();
     for (JavaFileObject file : fileObjects) notYetEntered.put(file, null);
     genList = new ListBuffer<Env<AttrContext>>();
     // endContext will be called when all classes have been generated
     // TODO: should handle the case after each phase if errors have occurred
     args = null;
     classNames = null;
   }
 }