private static void addCreateProposal(
     Collection<ICompletionProposal> proposals,
     boolean local,
     DefinitionGenerator dg,
     PhasedUnit unit,
     Tree.Statement statement) {
   IFile file = getFile(unit);
   TextFileChange change = new TextFileChange(local ? "Create Local" : "Create Toplevel", file);
   change.setEdit(new MultiTextEdit());
   IDocument doc = EditorUtil.getDocument(change);
   String indent = getIndent(statement, doc);
   int offset = statement.getStartIndex();
   String delim = getDefaultLineDelimiter(doc);
   Tree.CompilationUnit cu = unit.getCompilationUnit();
   int il = applyImports(change, dg.getImports(), cu, doc);
   String def = dg.generate(indent, delim) + delim + indent;
   if (!local) def += delim;
   change.addEdit(new InsertEdit(offset, def));
   String desc = (local ? "Create local " : "Create toplevel ") + dg.getDescription();
   final Scope scope = local ? statement.getScope() : cu.getUnit().getPackage();
   int exitPos = dg.getNode().getStopIndex() + 1;
   proposals.add(
       new CreateProposal(
           def,
           desc,
           scope,
           cu.getUnit(),
           dg.getReturnType(),
           dg.getImage(),
           offset + il,
           change,
           exitPos,
           dg instanceof ObjectClassDefinitionGenerator));
 }
Esempio n. 2
0
 private void loadCompiledModules(
     List<JCCompilationUnit> trees, LinkedList<JCCompilationUnit> moduleTrees) {
   compilerDelegate.visitModules(phasedUnits);
   Modules modules = ceylonContext.getModules();
   // now make sure the phase units have their modules and packages set correctly
   for (PhasedUnit pu : phasedUnits.getPhasedUnits()) {
     Package pkg = pu.getPackage();
     loadModuleFromSource(pkg, modules, moduleTrees, trees);
   }
   // also make sure we have packages and modules set up for every Java file we compile
   for (JCCompilationUnit cu : trees) {
     // skip Ceylon CUs
     if (cu instanceof CeylonCompilationUnit) continue;
     String packageName = "";
     if (cu.pid != null) packageName = TreeInfo.fullName(cu.pid).toString();
     /*
      * Stef: see javadoc for findOrCreateModulelessPackage() for why this is here.
      */
     Package pkg = modelLoader.findOrCreateModulelessPackage(packageName);
     loadModuleFromSource(pkg, modules, moduleTrees, trees);
   }
   for (PhasedUnit phasedUnit : phasedUnits.getPhasedUnits()) {
     for (Tree.ModuleDescriptor modDescr :
         phasedUnit.getCompilationUnit().getModuleDescriptors()) {
       String name = phasedUnit.getPackage().getNameAsString();
       CeylonPhasedUnit cpu = (CeylonPhasedUnit) phasedUnit;
       CeylonFileObject cfo = (CeylonFileObject) cpu.getFileObject();
       moduleNamesToFileObjects.put(name, cfo);
     }
   }
 }
Esempio n. 3
0
 public static void refactorProjectImportsAndDocLinks(
     Tree.Declaration node,
     IFile originalFile,
     IFile targetFile,
     CompositeChange change,
     String originalPackage,
     String targetPackage) {
   if (!originalPackage.equals(targetPackage)) {
     for (PhasedUnit pu : getAllUnits(originalFile.getProject())) {
       //                if (!node.getUnit().equals(pu.getUnit())) {
       IFile file = ((IFileVirtualFile) pu.getUnitFile()).getFile();
       if (!file.equals(originalFile) && !file.equals(targetFile)) {
         TextFileChange tfc = new TextFileChange("Fix Import", file);
         tfc.setEdit(new MultiTextEdit());
         CompilationUnit rootNode = pu.getCompilationUnit();
         refactorImports(node, originalPackage, targetPackage, rootNode, tfc);
         refactorDocLinks(node, targetPackage, rootNode, tfc);
         if (tfc.getEdit().hasChildren()) {
           change.add(tfc);
         }
       }
       //                }
     }
   }
 }
 static void addCreateProposal(
     Collection<ICompletionProposal> proposals,
     String def,
     boolean local,
     String desc,
     Image image,
     PhasedUnit unit,
     Tree.Statement statement,
     ProducedType t) {
   IFile file = CeylonBuilder.getFile(unit);
   TextFileChange change = new TextFileChange(local ? "Create Local" : "Create Toplevel", file);
   change.setEdit(new MultiTextEdit());
   IDocument doc = CreateProposal.getDocument(change);
   String indent = CeylonQuickFixAssistant.getIndent(statement, doc);
   int offset = statement.getStartIndex();
   def = def.replace("$indent", indent);
   int il = importType(change, t, unit.getCompilationUnit());
   change.addEdit(new InsertEdit(offset, def + "\n" + indent));
   proposals.add(
       new CreateProposal(
           def,
           (local ? "Create local " : "Create toplevel ") + desc,
           image,
           0,
           offset + il,
           file,
           change));
 }
 static void addCreateParameterProposal(
     Collection<ICompletionProposal> proposals,
     String def,
     String desc,
     Image image,
     Declaration dec,
     PhasedUnit unit,
     Tree.Declaration decNode,
     Tree.ParameterList paramList,
     ProducedType t) {
   IFile file = CeylonBuilder.getFile(unit);
   TextFileChange change = new TextFileChange("Add Parameter", file);
   change.setEdit(new MultiTextEdit());
   int offset = paramList.getStopIndex();
   int il = importType(change, t, unit.getCompilationUnit());
   change.addEdit(new InsertEdit(offset, def));
   proposals.add(
       new CreateProposal(
           def,
           "Add " + desc + " to '" + dec.getName() + "'",
           image,
           0,
           offset + il,
           file,
           change));
 }
  @Override
  public void typeCheck(java.util.List<PhasedUnit> listOfUnits) {
    for (PhasedUnit pu : listOfUnits) {
      pu.validateTree();
      pu.scanDeclarations();
    }
    for (PhasedUnit pu : listOfUnits) {
      pu.scanTypeDeclarations();
    }
    for (PhasedUnit pu : listOfUnits) {
      pu.validateRefinement();
    }

    for (PhasedUnit pu : listOfUnits) {
      pu.analyseTypes();
    }

    for (PhasedUnit pu : listOfUnits) {
      pu.analyseFlow();
    }

    UnknownTypeCollector utc = new UnknownTypeCollector();
    for (PhasedUnit pu : listOfUnits) {
      pu.getCompilationUnit().visit(utc);
    }
  }
  protected void updateRefsToMovedCeylonFile(
      final IProject project,
      final String newName,
      final String oldName,
      final List<Change> changes,
      PhasedUnit movedPhasedUnit,
      final List<Declaration> declarations) {
    if (!getArguments().getUpdateReferences()) return;
    TypeChecker tc = getProjectTypeChecker(project);
    if (tc == null) return;
    for (PhasedUnit phasedUnit : tc.getPhasedUnits().getPhasedUnits()) {
      if (phasedUnit == movedPhasedUnit
          || phasedUnit.getUnit() instanceof ProjectSourceFile
              && movingFiles.contains(
                  ((ProjectSourceFile) phasedUnit.getUnit()).getFileResource())) {
        continue;
      }
      final Map<Declaration, String> imports = new HashMap<Declaration, String>();
      phasedUnit
          .getCompilationUnit()
          .visit(
              new Visitor() {
                @Override
                public void visit(ImportMemberOrType that) {
                  super.visit(that);
                  visitIt(that.getIdentifier(), that.getDeclarationModel());
                }
                //                    @Override
                //                    public void visit(QualifiedMemberOrTypeExpression that) {
                //                        super.visit(that);
                //                        visitIt(that.getIdentifier(), that.getDeclaration());
                //                    }
                @Override
                public void visit(BaseMemberOrTypeExpression that) {
                  super.visit(that);
                  visitIt(that.getIdentifier(), that.getDeclaration());
                }

                @Override
                public void visit(BaseType that) {
                  super.visit(that);
                  visitIt(that.getIdentifier(), that.getDeclarationModel());
                }
                //                    @Override
                //                    public void visit(QualifiedType that) {
                //                        super.visit(that);
                //                        visitIt(that.getIdentifier(), that.getDeclarationModel());
                //                    }
                protected void visitIt(Tree.Identifier id, Declaration dec) {
                  if (dec != null && declarations.contains(dec)) {
                    imports.put(dec, id.getText());
                  }
                }
                // TODO: DocLinks!!
              });
      collectEdits(newName, oldName, changes, phasedUnit, imports);
    }
  }
  protected void updateRefsFromMovedCeylonFile(
      final IProject project,
      final String newName,
      final String oldName,
      final List<Change> changes,
      final PhasedUnit movedPhasedUnit,
      final List<Declaration> declarations) {
    final Map<Declaration, String> imports = new HashMap<Declaration, String>();
    movedPhasedUnit
        .getCompilationUnit()
        .visit(
            new Visitor() {
              @Override
              public void visit(ImportMemberOrType that) {
                super.visit(that);
                visitIt(that.getIdentifier(), that.getDeclarationModel());
              }
              //            @Override
              //            public void visit(QualifiedMemberOrTypeExpression that) {
              //                super.visit(that);
              //                visitIt(that.getIdentifier(), that.getDeclaration());
              //            }
              @Override
              public void visit(BaseMemberOrTypeExpression that) {
                super.visit(that);
                visitIt(that.getIdentifier(), that.getDeclaration());
              }

              @Override
              public void visit(BaseType that) {
                super.visit(that);
                visitIt(that.getIdentifier(), that.getDeclarationModel());
              }
              //            @Override
              //            public void visit(QualifiedType that) {
              //                super.visit(that);
              //                visitIt(that.getIdentifier(), that.getDeclarationModel());
              //            }
              protected void visitIt(Tree.Identifier id, Declaration dec) {
                if (dec != null && !declarations.contains(dec)) {
                  Unit unit = dec.getUnit();
                  if (unit instanceof ProjectSourceFile
                      && movingFiles.contains(((ProjectSourceFile) unit).getFileResource())) {
                    // also moving
                  } else if (unit.getPackage().equals(movedPhasedUnit.getPackage())) {
                    imports.put(dec, id.getText());
                  }
                }
              }
              // TODO: DocLinks!!
            });
    collectEditsToMovedFile(newName, oldName, changes, movedPhasedUnit, imports);
  }
Esempio n. 9
0
 public static boolean isUnsharedUsedLocally(
     Tree.Declaration node, IFile originalFile, String originalPackage, String targetPackage) {
   Declaration dec = node.getDeclarationModel();
   if (!dec.isShared() && !originalPackage.equals(targetPackage)) {
     for (PhasedUnit pu : getAllUnits(originalFile.getProject())) {
       Tree.CompilationUnit cu = pu.getCompilationUnit();
       String pn = cu.getUnit().getPackage().getNameAsString();
       if (pn.equals(originalPackage) && isUsedInUnit(cu, dec)) {
         return true;
       }
     }
   }
   return false;
 }
 @SuppressWarnings("unchecked")
 @BeforeClass
 public static void initModel() {
   initTypechecker();
   MetamodelVisitor mmg = null;
   for (PhasedUnit pu : tc.getPhasedUnits().getPhasedUnits()) {
     if (pu.getPackage().getModule().getNameAsString().equals("t1")) {
       if (mmg == null) {
         mmg = new MetamodelVisitor(pu.getPackage().getModule());
       }
       pu.getCompilationUnit().visit(mmg);
     }
   }
   topLevelModel = mmg.getModel();
   model = (Map<String, Object>) topLevelModel.get("t1");
 }
 static Tree.CompilationUnit getRootNode(PhasedUnit unit) {
   IEditorPart ce = getCurrentEditor();
   if (ce instanceof CeylonEditor) {
     CeylonEditor editor = (CeylonEditor) ce;
     CeylonParseController cpc = editor.getParseController();
     if (cpc != null) {
       Tree.CompilationUnit rn = cpc.getTypecheckedRootNode();
       if (rn != null) {
         Unit u = rn.getUnit();
         if (u.equals(unit.getUnit())) {
           return rn;
         }
       }
     }
   }
   return unit.getCompilationUnit();
 }
 static void addCreateParameterAndAttributeProposal(
     Collection<ICompletionProposal> proposals,
     String pdef,
     String adef,
     String desc,
     Image image,
     Declaration dec,
     PhasedUnit unit,
     Tree.Declaration decNode,
     Tree.ParameterList paramList,
     Tree.Body body,
     ProducedType t) {
   IFile file = CeylonBuilder.getFile(unit);
   TextFileChange change = new TextFileChange("Add Attribute", file);
   change.setEdit(new MultiTextEdit());
   int offset = paramList.getStopIndex();
   IDocument doc = CreateProposal.getDocument(change);
   String indent;
   String indentAfter;
   int offset2;
   List<Tree.Statement> statements = body.getStatements();
   if (statements.isEmpty()) {
     indentAfter = "\n" + CeylonQuickFixAssistant.getIndent(decNode, doc);
     indent = indentAfter + getDefaultIndent();
     offset2 = body.getStartIndex() + 1;
   } else {
     Tree.Statement statement = statements.get(statements.size() - 1);
     indent = "\n" + CeylonQuickFixAssistant.getIndent(statement, doc);
     offset2 = statement.getStopIndex() + 1;
     indentAfter = "";
   }
   int il = importType(change, t, unit.getCompilationUnit());
   change.addEdit(new InsertEdit(offset, pdef));
   change.addEdit(new InsertEdit(offset2, indent + adef + indentAfter));
   proposals.add(
       new CreateProposal(
           pdef,
           "Add " + desc + " to '" + dec.getName() + "'",
           image,
           0,
           offset + il,
           file,
           change));
 }
Esempio n. 13
0
 @Override
 public void initRound(JavaCompiler prev) {
   super.initRound(prev);
   // round compilers don't add module trees, it's already done by the first one
   addModuleTrees = false;
   PhasedUnits oldPUs = ((LanguageCompiler) prev).phasedUnits;
   ModuleManager moduleManager = phasedUnits.getModuleManager();
   ModuleSourceMapper moduleSourceMapper = phasedUnits.getModuleSourceMapper();
   for (PhasedUnit pu : oldPUs.getPhasedUnits()) {
     if (pu instanceof CeylonPhasedUnit) {
       CeylonPhasedUnit cpu = (CeylonPhasedUnit) pu;
       // FIXME: this is bad in many ways
       String pkgName;
       try {
         pkgName = getPackage(((CeylonPhasedUnit) pu).getFileObject());
       } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
         continue;
       }
       // 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.model.typechecker.model.Package p =
           modelLoader.findOrCreateModulelessPackage(pkgName == null ? "" : pkgName);
       CeylonPhasedUnit newPu =
           new CeylonPhasedUnit(
               pu.getUnitFile(),
               pu.getSrcDir(),
               pu.getCompilationUnit(),
               p,
               moduleManager,
               moduleSourceMapper,
               ceylonContext,
               cpu.getFileObject(),
               cpu.getLineMap());
       phasedUnits.addPhasedUnit(pu.getUnitFile(), newPu);
     } else {
       phasedUnits.addPhasedUnit(pu.getUnitFile(), pu);
     }
   }
 }
 private void collectEdits(
     String newName,
     String oldName,
     List<Change> changes,
     PhasedUnit phasedUnit,
     Map<Declaration, String> imports) {
   try {
     Tree.CompilationUnit cu = phasedUnit.getCompilationUnit();
     if (!imports.isEmpty()) {
       IFileVirtualFile virtualFile = (IFileVirtualFile) phasedUnit.getUnitFile();
       IFile file = virtualFile.getFile();
       String path = file.getProjectRelativePath().toPortableString();
       TextFileChange change = fileChanges.get(path);
       if (change == null) {
         change = new TextFileChange(file.getName(), file);
         change.setEdit(new MultiTextEdit());
         changes.add(change);
         fileChanges.put(path, change);
       }
       List<TextEdit> edits =
           importEditForMove(
               cu,
               imports.keySet(),
               imports.values(),
               newName,
               oldName,
               EditorUtil.getDocument(change));
       if (!edits.isEmpty()) {
         for (TextEdit edit : edits) {
           change.addEdit(edit);
         }
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 private void collectEditsToMovedFile(
     String newName,
     String oldName,
     List<Change> changes,
     PhasedUnit movedPhasedUnit,
     Map<Declaration, String> imports) {
   try {
     IFileVirtualFile virtualFile = (IFileVirtualFile) movedPhasedUnit.getUnitFile();
     IFile file = virtualFile.getFile();
     String path = file.getProjectRelativePath().toPortableString();
     TextFileChange change = fileChanges.get(path);
     if (change == null) {
       change = new TextFileChange(file.getName(), file);
       change.setEdit(new MultiTextEdit());
       changes.add(change);
       fileChanges.put(path, change);
     }
     Tree.CompilationUnit cu = movedPhasedUnit.getCompilationUnit();
     if (!imports.isEmpty()) {
       List<InsertEdit> edits =
           importEdits(
               cu, imports.keySet(), imports.values(), null, EditorUtil.getDocument(change));
       for (TextEdit edit : edits) {
         change.addEdit(edit);
       }
     }
     Tree.Import toDelete = findImportNode(cu, newName);
     if (toDelete != null) {
       change.addEdit(
           new DeleteEdit(
               toDelete.getStartIndex(), toDelete.getStopIndex() - toDelete.getStartIndex() + 1));
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  protected void updateRefsToMovedJavaFile(
      final IProject project,
      final String newName,
      final String oldName,
      final List<Change> changes)
      throws JavaModelException {
    if (!getArguments().getUpdateReferences()) return;
    ICompilationUnit jcu = (ICompilationUnit) JavaCore.create(file);
    final IType[] types = jcu.getTypes();
    TypeChecker tc = getProjectTypeChecker(project);
    if (tc == null) return;
    for (PhasedUnit phasedUnit : tc.getPhasedUnits().getPhasedUnits()) {
      final Map<Declaration, String> imports = new HashMap<Declaration, String>();
      phasedUnit
          .getCompilationUnit()
          .visit(
              new Visitor() {
                @Override
                public void visit(ImportMemberOrType that) {
                  super.visit(that);
                  visitIt(that.getIdentifier(), that.getDeclarationModel());
                }
                //                    @Override
                //                    public void visit(QualifiedMemberOrTypeExpression that) {
                //                        super.visit(that);
                //                        visitIt(that.getIdentifier(), that.getDeclaration());
                //                    }
                @Override
                public void visit(BaseMemberOrTypeExpression that) {
                  super.visit(that);
                  visitIt(that.getIdentifier(), that.getDeclaration());
                }

                @Override
                public void visit(BaseType that) {
                  super.visit(that);
                  visitIt(that.getIdentifier(), that.getDeclarationModel());
                }
                //                    @Override
                //                    public void visit(QualifiedType that) {
                //                        super.visit(that);
                //                        visitIt(that.getIdentifier(), that.getDeclarationModel());
                //                    }
                protected void visitIt(Tree.Identifier id, Declaration dec) {
                  for (IType type : types) {
                    if (dec != null
                        && dec.getQualifiedNameString().equals(getQualifiedName(type))) {
                      imports.put(dec, id.getText());
                    }
                  }
                }

                protected String getQualifiedName(IMember dec) {
                  IJavaElement parent = dec.getParent();
                  if (parent instanceof ICompilationUnit) {
                    return parent.getParent().getElementName() + "::" + dec.getElementName();
                  } else if (dec.getDeclaringType() != null) {
                    return getQualifiedName(dec.getDeclaringType()) + "." + dec.getElementName();
                  } else {
                    return "@";
                  }
                }
              });
      collectEdits(newName, oldName, changes, phasedUnit, imports);
    }
  }
 static void addCreateMemberProposal(
     Collection<ICompletionProposal> proposals,
     DefinitionGenerator dg,
     Declaration typeDec,
     PhasedUnit unit,
     Tree.Declaration decNode,
     Tree.Body body,
     Tree.Statement statement) {
   IFile file = getFile(unit);
   TextFileChange change = new TextFileChange("Create Member", file);
   change.setEdit(new MultiTextEdit());
   IDocument doc = EditorUtil.getDocument(change);
   String indentBefore;
   String indentAfter;
   String indent;
   int offset;
   List<Tree.Statement> statements = body.getStatements();
   String delim = getDefaultLineDelimiter(doc);
   if (statements.isEmpty()) {
     String bodyIndent = getIndent(decNode, doc);
     indent = bodyIndent + getDefaultIndent();
     indentBefore = delim + indent;
     try {
       boolean singleLineBody =
           doc.getLineOfOffset(body.getStartIndex()) == doc.getLineOfOffset(body.getStopIndex());
       if (singleLineBody) {
         indentAfter = delim + bodyIndent;
       } else {
         indentAfter = "";
       }
     } catch (BadLocationException e) {
       e.printStackTrace();
       indentAfter = delim;
     }
     offset = body.getStartIndex() + 1;
   } else {
     Tree.Statement st;
     if (statement != null
         && statement.getUnit().equals(body.getUnit())
         && statement.getStartIndex() >= body.getStartIndex()
         && statement.getStopIndex() <= body.getStopIndex()) {
       st = statements.get(0);
       for (Tree.Statement s : statements) {
         if (statement.getStartIndex() >= s.getStartIndex()
             && statement.getStopIndex() <= s.getStopIndex()) {
           st = s;
         }
       }
       indent = getIndent(st, doc);
       indentBefore = "";
       indentAfter = delim + indent;
       offset = st.getStartIndex();
     } else {
       st = statements.get(statements.size() - 1);
       indent = getIndent(st, doc);
       indentBefore = delim + indent;
       indentAfter = "";
       offset = st.getStopIndex() + 1;
     }
   }
   String generated =
       typeDec instanceof Interface
           ? dg.generateSharedFormal(indent, delim)
           : dg.generateShared(indent, delim);
   String def = indentBefore + generated + indentAfter;
   int il = applyImports(change, dg.getImports(), unit.getCompilationUnit(), doc);
   change.addEdit(new InsertEdit(offset, def));
   String desc = "Create " + memberKind(dg) + " in '" + typeDec.getName() + "'";
   int exitPos = dg.getNode().getStopIndex() + 1;
   proposals.add(
       new CreateProposal(
           def,
           desc,
           body.getScope(),
           body.getUnit(),
           dg.getReturnType(),
           dg.getImage(),
           offset + il,
           change,
           exitPos,
           dg instanceof ObjectClassDefinitionGenerator));
 }
Esempio n. 18
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;
  }
Esempio n. 19
0
  private JCCompilationUnit ceylonParse(JavaFileObject filename, CharSequence readSource) {
    if (ceylonEnter.hasRun())
      throw new RunTwiceException(
          "Trying to load new source file after CeylonEnter has been called: " + filename);
    try {
      ModuleManager moduleManager = phasedUnits.getModuleManager();
      ModuleSourceMapper moduleSourceMapper = phasedUnits.getModuleSourceMapper();
      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);

      String suppressWarnings = options.get(Option.CEYLONSUPPRESSWARNINGS);
      final EnumSet<Warning> suppressedWarnings;
      if (suppressWarnings != null) {
        if (suppressWarnings.trim().isEmpty()) {
          suppressedWarnings = EnumSet.allOf(Warning.class);
        } else {
          suppressedWarnings = EnumSet.noneOf(Warning.class);
          for (String name : suppressWarnings.trim().split(" *, *")) {
            suppressedWarnings.add(Warning.valueOf(name));
          }
        }
      } else {
        suppressedWarnings = EnumSet.noneOf(Warning.class);
      }

      if (externalPhasedUnit != null) {
        phasedUnit = new CeylonPhasedUnit(externalPhasedUnit, filename, map);
        phasedUnit.setSuppressedWarnings(suppressedWarnings);
        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 NewlineFixingStringStream(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 we continue and it's not a descriptor, we don't care about errors
        if ((options.get(Option.CEYLONCONTINUE) != null
                && !ModuleManager.MODULE_FILE.equals(sourceFile.getName())
                && !ModuleManager.PACKAGE_FILE.equals(sourceFile.getName()))
            // otherwise we care about errors
            || (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.model.typechecker.model.Package p =
              modelLoader.findOrCreateModulelessPackage(pkgName == null ? "" : pkgName);
          phasedUnit =
              new CeylonPhasedUnit(
                  file,
                  srcDir,
                  cu,
                  p,
                  moduleManager,
                  moduleSourceMapper,
                  ceylonContext,
                  filename,
                  map);
          phasedUnit.setSuppressedWarnings(suppressedWarnings);
          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;
  }