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);
     }
   }
 }
Example #2
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);
         }
       }
       //                }
     }
   }
 }
  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);
    }
  }
 static void addCreateToplevelProposals(
     Collection<ICompletionProposal> proposals, IProject project, DefinitionGenerator dg) {
   Tree.Statement statement = findToplevelStatement(dg.getRootNode(), dg.getNode());
   if (statement != null) {
     for (PhasedUnit unit : getUnits(project)) {
       if (unit.getUnit().equals(dg.getRootNode().getUnit())) {
         addCreateProposal(proposals, false, dg, unit, statement);
         break;
       }
     }
   }
 }
Example #5
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 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));
 }
 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));
 }
 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();
 }
 private void loadCompiledModules(
     List<JCCompilationUnit> trees, LinkedList<JCCompilationUnit> moduleTrees) {
   phasedUnits.visitModules();
   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);
   }
   // 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();
     Package pkg = modelLoader.findOrCreatePackage(null, packageName);
     loadModuleFromSource(pkg, modules, moduleTrees);
   }
 }
  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);
  }
 static void addCreateMemberProposals(
     Collection<ICompletionProposal> proposals,
     IProject project,
     DefinitionGenerator dg,
     Declaration typeDec,
     Tree.Statement statement) {
   if (typeDec != null
       && (typeDec instanceof Class || (typeDec instanceof Interface && dg.isFormalSupported()))) {
     for (PhasedUnit unit : getUnits(project)) {
       if (typeDec.getUnit().equals(unit.getUnit())) {
         // TODO: "object" declarations?
         FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(typeDec);
         getRootNode(unit).visit(fdv);
         Tree.Declaration decNode = (Tree.Declaration) fdv.getDeclarationNode();
         Tree.Body body = getClassOrInterfaceBody(decNode);
         if (body != null) {
           addCreateMemberProposal(proposals, dg, typeDec, unit, decNode, body, statement);
           break;
         }
       }
     }
   }
 }
 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();
   }
 }
 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));
 }
Example #17
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);
     }
   }
 }
  @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);
    }
  }
 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));
 }
  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;
  }
Example #21
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;
  }
  private void writeConstantValue(Value v) throws IOException {
    Node node = tool.getDeclarationNode(v);
    PhasedUnit pu = tool.getDeclarationUnit(v);
    if (pu == null || !(node instanceof Tree.AttributeDeclaration)) {
      return;
    }

    Tree.AttributeDeclaration attribute = (Tree.AttributeDeclaration) node;
    Tree.SpecifierOrInitializerExpression specifierExpression =
        attribute.getSpecifierOrInitializerExpression();
    if (specifierExpression == null || specifierExpression.getExpression() == null) {
      return;
    }

    Token startToken = specifierExpression.getExpression().getToken();
    int startLine = startToken.getLine();
    int startLinePosition = startToken.getCharPositionInLine();

    Token endToken = attribute.getEndToken();
    int endLine = endToken.getLine();
    int endLinePosition = endToken.getCharPositionInLine();

    StringBuilder valueBuilder = new StringBuilder(" ");
    BufferedReader sourceCodeReader =
        new BufferedReader(new InputStreamReader(pu.getUnitFile().getInputStream()));
    try {
      int lineIndex = 1;
      String line = sourceCodeReader.readLine();
      while (line != null) {
        if (lineIndex == startLine && lineIndex == endLine) {
          valueBuilder.append(line.substring(startLinePosition, endLinePosition));
          break;
        } else if (lineIndex == startLine) {
          valueBuilder.append(line.substring(startLinePosition, line.length()));
        } else if (lineIndex > startLine && lineIndex < endLine) {
          valueBuilder.append("\n");
          valueBuilder.append(line);
        } else if (lineIndex == endLine) {
          valueBuilder.append("\n");
          valueBuilder.append(line.substring(0, endLinePosition));
          break;
        }

        line = sourceCodeReader.readLine();
        lineIndex++;
      }
    } finally {
      sourceCodeReader.close();
    }

    String value = valueBuilder.toString();
    int newLineIndex = value.indexOf("\n");
    String valueFirstLine = newLineIndex != -1 ? value.substring(0, newLineIndex) : value;

    around("span class='specifier-operator'", " = ");
    around("span class='specifier-start'", valueFirstLine);
    if (newLineIndex != -1) {
      around(
          "a class='specifier-ellipsis' href='#' title='Click for expand the rest of value.'",
          "...");
      open("div class='specifier-rest'");
      write(value.substring(newLineIndex + 1));
      around("span class='specifier-semicolon'", ";");
      close("div");
    } else {
      around("span class='specifier-semicolon'", ";");
    }
  }
  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);
    }
  }
Example #24
0
 private Module loadModuleFromSource(
     String pkgName,
     LinkedList<JCCompilationUnit> moduleTrees,
     List<JCCompilationUnit> parsedTrees) {
   if (pkgName.isEmpty()) return null;
   String moduleClassName = pkgName + ".module";
   JavaFileObject fileObject;
   try {
     if (options.get(Option.VERBOSE) != null) {
       log.printRawLines(
           WriterKind.NOTICE, "[Trying to load source for module " + moduleClassName + "]");
     }
     fileObject =
         fileManager.getJavaFileForInput(
             StandardLocation.SOURCE_PATH, moduleClassName, Kind.SOURCE);
     if (options.get(Option.VERBOSE) != null) {
       log.printRawLines(WriterKind.NOTICE, "[Got file object: " + fileObject + "]");
     }
   } catch (IOException e) {
     e.printStackTrace();
     return loadModuleFromSource(getParentPackage(pkgName), moduleTrees, parsedTrees);
   }
   if (fileObject != null) {
     // first make sure we're not already compiling it: this can happen if we have several versions
     // of the
     // same module already loaded: we will get one which isn't the one we compile, but that's not
     // the one
     // we really want to compile.
     for (JCCompilationUnit parsedTree : parsedTrees) {
       if (parsedTree.sourcefile.equals(fileObject)
           && parsedTree instanceof CeylonCompilationUnit) {
         // same file! we already parsed it, let's return this one's module
         PhasedUnit phasedUnit = ((CeylonCompilationUnit) parsedTree).phasedUnit;
         // the module visitor does load the module but does not set the unit's package module
         if (phasedUnit.getPackage().getModule() == null) {
           // so find the module it created
           for (Module mod : ceylonContext.getModules().getListOfModules()) {
             // we recognise it with the unit
             if (mod.getUnit() == phasedUnit.getUnit()) {
               // set the package's module
               Package pkg = phasedUnit.getPackage();
               pkg.setModule(mod);
               mod.getPackages().add(pkg);
               modulesLoadedFromSource.add(mod);
               break;
             }
           }
         }
         // now return it
         return phasedUnit.getPackage().getModule();
       }
     }
     JCCompilationUnit javaCompilationUnit = parse(fileObject);
     Module module;
     if (javaCompilationUnit instanceof CeylonCompilationUnit) {
       CeylonCompilationUnit ceylonCompilationUnit = (CeylonCompilationUnit) javaCompilationUnit;
       moduleTrees.add(ceylonCompilationUnit);
       // parse the module info from there
       module = ceylonCompilationUnit.phasedUnit.visitSrcModulePhase();
       ceylonCompilationUnit.phasedUnit.visitRemainingModulePhase();
       // now set the module
       if (module != null) {
         ceylonCompilationUnit.phasedUnit.getPackage().setModule(module);
       }
     } else {
       // there was a syntax error in the module descriptor, make a pretend module so that we can
       // correctly mark all declarations as part of that module, but we won't generate any code
       // for it
       ModuleManager moduleManager = phasedUnits.getModuleManager();
       module = moduleManager.getOrCreateModule(Arrays.asList(pkgName.split("\\.")), "bogus");
     }
     // now remember it
     if (module != null) {
       modulesLoadedFromSource.add(module);
       return module;
     }
   }
   return loadModuleFromSource(getParentPackage(pkgName), moduleTrees, parsedTrees);
 }
  @Override
  public Change createPreChange(IProgressMonitor pm)
      throws CoreException, OperationCanceledException {
    try {
      IProject project = file.getProject();
      Object destination = getArguments().getDestination();
      if (!(destination instanceof IFolder)) {
        return null;
      }
      IFolder folder = (IFolder) destination;
      String newName =
          folder
              .getProjectRelativePath()
              .removeFirstSegments(1)
              .toPortableString()
              .replace('/', '.');
      String movedRelFilePath =
          file.getProjectRelativePath().removeFirstSegments(1).toPortableString();
      String movedRelPath =
          file.getParent().getProjectRelativePath().removeFirstSegments(1).toPortableString();
      String oldName = movedRelPath.replace('/', '.');

      List<Change> changes = new ArrayList<Change>();

      if (file.getFileExtension().equals("java")) {
        updateRefsToMovedJavaFile(project, newName, oldName, changes);
      } else {
        TypeChecker tc = getProjectTypeChecker(project);
        if (tc == null) return null;
        PhasedUnit movedPhasedUnit = tc.getPhasedUnitFromRelativePath(movedRelFilePath);
        if (movedPhasedUnit == null) {
          return null;
        }

        List<Declaration> declarations = movedPhasedUnit.getDeclarations();
        if (newName.equals(oldName)) return null;
        updateRefsFromMovedCeylonFile(
            project, newName, oldName, changes, movedPhasedUnit, declarations);
        updateRefsToMovedCeylonFile(
            project, newName, oldName, changes, movedPhasedUnit, declarations);
      }

      if (changes.isEmpty()) return null;

      CompositeChange result =
          new CompositeChange("Ceylon source changes") {
            @Override
            public Change perform(IProgressMonitor pm) throws CoreException {
              fileChanges.clear();
              movingFiles.clear();
              return super.perform(pm);
            }
          };
      for (Change change : changes) {
        result.add(change);
      }
      return result;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }