Пример #1
0
 private void addResources() throws Abort {
   HashSet<String> written = new HashSet<String>();
   try {
     for (JavaFileObject fo : resourceFileObjects) {
       CeyloncFileManager dfm = (CeyloncFileManager) fileManager;
       String jarFileName =
           JarUtils.toPlatformIndependentPath(
               dfm.getLocation(CeylonLocation.RESOURCE_PATH), fo.getName());
       if (!written.contains(jarFileName)) {
         dfm.setModule(modelLoader.findModuleForFile(new File(jarFileName)));
         FileObject outFile =
             dfm.getFileForOutput(StandardLocation.CLASS_OUTPUT, "", jarFileName, null);
         OutputStream out = outFile.openOutputStream();
         try {
           InputStream in = new FileInputStream(new File(fo.getName()));
           try {
             JarUtils.copy(in, out);
           } finally {
             in.close();
           }
         } finally {
           out.close();
         }
         written.add(jarFileName);
       }
     }
   } catch (IOException ex) {
     throw new Abort(ex);
   }
 }
Пример #2
0
 public void close() throws IOException {
   if (closed) return;
   closed = true;
   String s = newContent.toString();
   if (!oldContent.equals(s)) {
     int p = file.getName().lastIndexOf(File.separatorChar);
     try (Writer writer = file.openWriter()) {
       writer.write(s);
     }
     stdout.println("Writing " + file.getName().substring(p + 1));
   }
 }
Пример #3
0
 private boolean isResource(JavaFileObject fo) {
   JavacFileManager dfm = (JavacFileManager) fileManager;
   for (File dir : dfm.getLocation(CeylonLocation.RESOURCE_PATH)) {
     String prefix = dir.getPath();
     if (fo.getName().startsWith(prefix)) {
       return true;
     }
     String absPrefix = dir.getAbsolutePath();
     if (fo.getName().startsWith(absPrefix)) {
       return true;
     }
   }
   return false;
 }
Пример #4
0
  @Override
  public CompilationUnit[] getCompilationUnits() {
    if (this.compilationUnits == null) return EclipseCompilerImpl.NO_UNITS;
    ArrayList<CompilationUnit> units = new ArrayList<CompilationUnit>();
    for (final JavaFileObject javaFileObject : this.compilationUnits) {
      if (javaFileObject.getKind() != JavaFileObject.Kind.SOURCE) {
        throw new IllegalArgumentException();
      }
      String name = javaFileObject.getName();
      name = name.replace('\\', '/');
      CompilationUnit compilationUnit =
          new CompilationUnit(null, name, null) {

            @Override
            public char[] getContents() {
              try {
                return javaFileObject.getCharContent(true).toString().toCharArray();
              } catch (IOException e) {
                e.printStackTrace();
                throw new AbortCompilationUnit(null, e, null);
              }
            }
          };
      units.add(compilationUnit);
      this.javaFileObjectMap.put(compilationUnit, javaFileObject);
    }
    CompilationUnit[] result = new CompilationUnit[units.size()];
    units.toArray(result);
    return result;
  }
  private List<Diagnostic<? extends JavaFileObject>> doCompile() {
    List<VolatileJavaFile> sources = packager.getEmitter().getEmitted();
    if (dump) {
      for (JavaFileObject java : sources) {
        try {
          System.out.println("====" + java.getName());
          System.out.println(java.getCharContent(true));
        } catch (IOException e) {
          // ignore.
        }
      }
    }

    for (JavaFileObject java : sources) {
      javaCompiler.addSource(java);
    }
    if (sources.isEmpty()) {
      javaCompiler.addSource(new VolatileJavaFile("A", "public class A {}"));
    }
    List<Diagnostic<? extends JavaFileObject>> diagnostics = javaCompiler.doCompile();
    if (dump) {
      for (Diagnostic<? extends JavaFileObject> d : diagnostics) {
        System.out.println("====");
        System.out.println(d);
      }
    }
    return diagnostics;
  }
 public String formatSource(JCDiagnostic d, boolean fullname, Locale l) {
   JavaFileObject fo = d.getSource();
   if (fo == null) throw new IllegalArgumentException(); // d should have source set
   if (fullname) return fo.getName();
   else if (fo instanceof BaseFileObject) return ((BaseFileObject) fo).getShortName();
   else return BaseFileObject.getSimpleName(fo);
 }
Пример #7
0
 void test(String... args) throws IOException {
   JavaFileObject file = fm.getJavaFileForInput(PLATFORM_CLASS_PATH, "java.lang.Object", CLASS);
   String fileName = file.getName();
   if (!fileName.matches(".*java/lang/Object.class\\)?")) {
     System.err.println(fileName);
     throw new AssertionError(file);
   }
 }
 @Override
 public void onSourceFile(JavaFileObject sourceFile) {
   try {
     writer.writeAttribute("filename", getRelativeFileName(sourceFile.getName()));
   } catch (XMLStreamException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Пример #9
0
 /** print an error or warning message: */
 private void printRawError(int pos, String msg) {
   if (source == null || pos == Position.NOPOS) {
     printRawLines(errWriter, "error: " + msg);
   } else {
     int line = source.getLineNumber(pos);
     JavaFileObject file = source.getFile();
     if (file != null) printRawLines(errWriter, file.getName() + ":" + line + ": " + msg);
     printErrLine(pos, errWriter);
   }
   errWriter.flush();
 }
Пример #10
0
 // This is a bit of a hack, but if we got passed a list of resources
 // without any accompaning source files we'll not be able to determine
 // the module to which the resource files belong. So to try to fix that
 // we see if a module file exists in the source folders and add it to
 // the list of source files
 private List<JavaFileObject> addModuleDescriptors(
     List<JavaFileObject> sourceFiles, List<JavaFileObject> resourceFiles) {
   List<JavaFileObject> result = sourceFiles;
   JavacFileManager dfm = (JavacFileManager) fileManager;
   for (JavaFileObject fo : resourceFiles) {
     String resName =
         JarUtils.toPlatformIndependentPath(
             dfm.getLocation(CeylonLocation.RESOURCE_PATH), fo.getName());
     JavaFileObject moduleFile = findModuleDescriptorForFile(new File(resName));
     if (moduleFile != null && !result.contains(moduleFile)) {
       result = result.append(moduleFile);
     }
   }
   return result;
 }
Пример #11
0
  /**
   * Parse contents of file.
   *
   * @param filename The name of the file to be parsed.
   */
  public JCTree.JCCompilationUnit parse(JavaFileObject filename) {
    JavaFileObject prev = log.useSource(filename);
    try {
      JCTree.JCCompilationUnit t;
      if (filename.getName().endsWith(".java")) {

        t = parse(filename, readSource(filename));
      } else {
        t = ceylonParse(filename, readSource(filename));
      }
      if (t.endPositions != null) log.setEndPosTable(filename, t.endPositions);
      return t;
    } finally {
      log.useSource(prev);
    }
  }
 /* (non-Javadoc)
  * @see javax.tools.JavaFileManager#inferBinaryName(javax.tools.JavaFileManager.Location, javax.tools.JavaFileObject)
  */
 @Override
 public String inferBinaryName(Location location, JavaFileObject file) {
   String name = file.getName();
   JavaFileObject javaFileObject = null;
   int index = name.lastIndexOf('.');
   if (index != -1) {
     name = name.substring(0, index);
   }
   try {
     javaFileObject = getJavaFileForInput(location, name, file.getKind());
   } catch (IOException e) {
     // ignore
   } catch (IllegalArgumentException iae) {
     return null; // Either unknown kind or location not present
   }
   if (javaFileObject == null) {
     return null;
   }
   return name.replace('/', '.');
 }
Пример #13
0
  private JCCompilationUnit ceylonParse(JavaFileObject filename, CharSequence readSource) {
    if (ceylonEnter.hasRun())
      throw new RuntimeException(
          "Trying to load new source file after CeylonEnter has been called: " + filename);
    try {
      ModuleManager moduleManager = phasedUnits.getModuleManager();
      File sourceFile = new File(filename.getName());
      // FIXME: temporary solution
      VirtualFile file = vfs.getFromFile(sourceFile);
      VirtualFile srcDir = vfs.getFromFile(getSrcDir(sourceFile));

      String source = readSource.toString();
      char[] chars = source.toCharArray();
      LineMap map = Position.makeLineMap(chars, chars.length, false);

      PhasedUnit phasedUnit = null;

      PhasedUnit externalPhasedUnit = compilerDelegate.getExternalSourcePhasedUnit(srcDir, file);

      if (externalPhasedUnit != null) {
        phasedUnit = new CeylonPhasedUnit(externalPhasedUnit, filename, map);
        phasedUnits.addPhasedUnit(externalPhasedUnit.getUnitFile(), phasedUnit);
        gen.setMap(map);

        String pkgName = phasedUnit.getPackage().getQualifiedNameString();
        if ("".equals(pkgName)) {
          pkgName = null;
        }
        return gen.makeJCCompilationUnitPlaceholder(
            phasedUnit.getCompilationUnit(), filename, pkgName, phasedUnit);
      }
      if (phasedUnit == null) {
        ANTLRStringStream input = new ANTLRStringStream(source);
        CeylonLexer lexer = new CeylonLexer(input);

        CommonTokenStream tokens = new CommonTokenStream(lexer);

        CeylonParser parser = new CeylonParser(tokens);
        CompilationUnit cu = parser.compilationUnit();

        java.util.List<LexError> lexerErrors = lexer.getErrors();
        for (LexError le : lexerErrors) {
          printError(le, le.getMessage(), "ceylon.lexer", map);
        }

        java.util.List<ParseError> parserErrors = parser.getErrors();
        for (ParseError pe : parserErrors) {
          printError(pe, pe.getMessage(), "ceylon.parser", map);
        }

        if (lexerErrors.size() == 0 && parserErrors.size() == 0) {
          // FIXME: this is bad in many ways
          String pkgName = getPackage(filename);
          // make a Package with no module yet, we will resolve them later
          /*
           * Stef: see javadoc for findOrCreateModulelessPackage() for why this is here.
           */
          com.redhat.ceylon.compiler.typechecker.model.Package p =
              modelLoader.findOrCreateModulelessPackage(pkgName == null ? "" : pkgName);
          phasedUnit =
              new CeylonPhasedUnit(
                  file, srcDir, cu, p, moduleManager, ceylonContext, filename, map);
          phasedUnits.addPhasedUnit(file, phasedUnit);
          gen.setMap(map);

          return gen.makeJCCompilationUnitPlaceholder(cu, filename, pkgName, phasedUnit);
        }
      }
    } catch (RuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    JCCompilationUnit result =
        make.TopLevel(List.<JCAnnotation>nil(), null, List.<JCTree>of(make.Erroneous()));
    result.sourcefile = filename;
    return result;
  }
Пример #14
0
 @Override
 public String inferBinaryName(Location location, JavaFileObject file) {
   return FileUtil.getNameWithoutExtension(new File(file.getName()).getName());
 }