/**
   * Ensures that creating a DOM AST and computing the bindings takes the owner's working copies
   * into account.
   *
   * @deprecated using deprecated code
   */
  public void testParseCompilationUnit3() throws CoreException {
    try {
      createJavaProject("P1", new String[] {"src"}, new String[] {"JCL_LIB", "lib"}, "bin");

      // create X.class in lib folder
      /* Evaluate the following in a scrapbook:
      	org.eclipse.jdt.core.tests.model.ModifyingResourceTests.generateClassFile(
      		"X",
      		"public class X {\n" +
      		"}")
      */
      byte[] bytes =
          new byte[] {
            -54, -2, -70, -66, 0, 3, 0, 45, 0, 13, 1, 0, 1, 88, 7, 0, 1, 1, 0, 16, 106, 97, 118, 97,
                47, 108, 97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 7, 0, 3, 1, 0, 6, 60, 105,
                110, 105, 116, 62, 1, 0, 3, 40, 41, 86, 1, 0, 4, 67, 111, 100, 101, 12, 0, 5, 0, 6,
                10, 0, 4, 0, 8, 1, 0, 15, 76, 105, 110, 101, 78, 117,
            109, 98, 101, 114, 84, 97, 98, 108, 101, 1, 0, 10, 83, 111, 117, 114, 99, 101, 70, 105,
                108, 101, 1, 0, 6, 88, 46, 106, 97, 118, 97, 0, 33, 0, 2, 0, 4, 0, 0, 0, 0, 0, 1, 0,
                1, 0, 5, 0, 6, 0, 1, 0, 7, 0, 0, 0, 29, 0, 1, 0, 1, 0, 0, 0, 5, 42, -73, 0, 9, -79,
                0, 0, 0, 1, 0, 10, 0, 0, 0, 6,
            0, 1, 0, 0, 0, 1, 0, 1, 0, 11, 0, 0, 0, 2, 0, 12,
          };
      this.createFile("P1/lib/X.class", bytes);

      // create libsrc and attach source
      createFolder("P1/libsrc");
      createFile("P1/libsrc/X.java", "public class X extends Y {\n" + "}");
      IPackageFragmentRoot lib = getPackageFragmentRoot("P1/lib");
      lib.attachSource(new Path("/P1/libsrc"), null, null);

      // create Y.java in src folder
      createFile("P1/src/Y.java", "");

      // create working copy on Y.java
      TestWorkingCopyOwner owner = new TestWorkingCopyOwner();
      this.workingCopy = getCompilationUnit("P1/src/Y.java").getWorkingCopy(owner, null);
      this.workingCopy.getBuffer().setContents("public class Y {\n" + "}");
      this.workingCopy.makeConsistent(null);

      // parse and resolve class file
      IClassFile classFile = getClassFile("P1/lib/X.class");
      ASTParser parser = ASTParser.newParser(AST.JLS2);
      parser.setSource(classFile);
      parser.setResolveBindings(true);
      parser.setWorkingCopyOwner(owner);
      CompilationUnit cu = (CompilationUnit) parser.createAST(null);
      List types = cu.types();
      assertEquals("Unexpected number of types in AST", 1, types.size());
      TypeDeclaration type = (TypeDeclaration) types.get(0);
      ITypeBinding typeBinding = type.resolveBinding();
      ITypeBinding superType = typeBinding.getSuperclass();
      assertEquals(
          "Unexpected super type",
          "Y",
          superType == null ? "<null>" : superType.getQualifiedName());
    } finally {
      deleteProject("P1");
    }
  }
  /**
   * Ensures that creating a DOM AST and computing the bindings takes the owner's working copies
   * into account. (regression test for bug 39533 Working copy with no corresponding file not
   * considered by NameLookup)
   *
   * @deprecated using deprecated code
   */
  public void testParseCompilationUnit1() throws CoreException {
    ICompilationUnit workingCopy1 = null;
    ICompilationUnit workingCopy2 = null;
    try {
      TestWorkingCopyOwner owner = new TestWorkingCopyOwner();
      workingCopy1 = getCompilationUnit("P/X.java").getWorkingCopy(owner, null);
      workingCopy1.getBuffer().setContents("public class X implements I {\n" + "}");
      workingCopy1.makeConsistent(null);

      workingCopy2 = getCompilationUnit("P/I.java").getWorkingCopy(owner, null);
      workingCopy2.getBuffer().setContents("public interface I {\n" + "}");
      workingCopy2.makeConsistent(null);

      ASTParser parser = ASTParser.newParser(AST.JLS2);
      parser.setSource(workingCopy1);
      parser.setResolveBindings(true);
      parser.setWorkingCopyOwner(owner);
      CompilationUnit cu = (CompilationUnit) parser.createAST(null);
      List types = cu.types();
      assertEquals("Unexpected number of types in AST", 1, types.size());
      TypeDeclaration type = (TypeDeclaration) types.get(0);
      ITypeBinding typeBinding = type.resolveBinding();
      assertTypeBindingsEqual("Unexpected interfaces", "I", typeBinding.getInterfaces());
    } finally {
      if (workingCopy1 != null) {
        workingCopy1.discardWorkingCopy();
      }
      if (workingCopy2 != null) {
        workingCopy2.discardWorkingCopy();
      }
    }
  }
Пример #3
0
  public synchronized void cleanClassmodel() {
    // helps to keep alive even if some error appeared elsewhere leads to memory leak!!!
    if (createdPackages != null) {
      final Iterator packages = createdPackages.values().iterator();
      while (packages.hasNext()) {
        final BinPackage pack = (BinPackage) packages.next();
        pack.cleanUpForRebuild();
      }
    }

    createdPackages.clear();

    for (int i = 0, max = compilationUnits.size(); i < max; i++) {
      final CompilationUnit source = (CompilationUnit) compilationUnits.get(i);
      source.getSource().invalidateCaches();
    }
    SourceMap.invalidateSourceCaches();

    compilationUnits.clear();
    nonJavaUnits.clear();
    definedTypeNames.clear();
    loadedTypes.clear();
    javaLangPackage = createPackageForName("java.lang");
    defaultPackage = createPackageForName("");
    objectRef = null;
    arrayInterfaces = null;

    getProjectLoader().projectCleanup();
  }
Пример #4
0
  public List<CompilationFault> getCompilationFaults() {
    List<CompilationFault> compilationFaults = new ArrayList<CompilationFault>();

    for (CompilationUnit compilationUnit : compilationUnits)
      compilationFaults.addAll(compilationUnit.getCompilationFaults());

    return compilationFaults;
  }
 /*
  * Ensures that no bindings are created when reconciling a new working copy with no resource.
  */
 public void testNewWorkingCopy07() throws CoreException {
   this.workingCopy = newExternalWorkingCopy("X.java", "public class X {\n" + "}");
   this.workingCopy.getBuffer().setContents("public class X {\n" + "  int field;\n" + "}");
   CompilationUnit ast =
       this.workingCopy.reconcile(JLS3_INTERNAL, true /*force resolution*/, null, null);
   TypeDeclaration type = (TypeDeclaration) ast.types().get(0);
   assertNull("Unexpected binding", type.resolveBinding());
 }
Пример #6
0
 /** Gets the fully qualified name of the main type in this compilation unit. */
 public static String getQualifiedMainTypeName(CompilationUnit unit) {
   PackageDeclaration pkg = unit.getPackage();
   if (pkg.isDefaultPackage()) {
     return unit.getMainTypeName();
   } else {
     return pkg.getName().getFullyQualifiedName() + '.' + unit.getMainTypeName();
   }
 }
Пример #7
0
  private void finishUnit() {
    CompilationUnit unit = this.units.pop();
    unit.finishNotify(this);

    if (log.isLoggable(Level.FINE)) {
      log.fine("Finished Unit: " + unit);
    }
  }
  /**
   * Performs the rewrite: The rewrite events are translated to the corresponding in text changes.
   * The given options can be null in which case the global options {@link JavaCore#getOptions()
   * JavaCore.getOptions()} will be used.
   *
   * @param document Document which describes the code of the AST that is passed in in the
   *     constructor. This document is accessed read-only.
   * @param options the given options
   * @throws IllegalArgumentException if the rewrite fails
   * @return Returns the edit describing the text changes.
   */
  public TextEdit rewriteAST(IDocument document, Map options) {
    TextEdit result = new MultiTextEdit();

    final CompilationUnit rootNode = getRootNode();
    if (rootNode != null) {
      TargetSourceRangeComputer xsrComputer =
          new TargetSourceRangeComputer() {
            /**
             * This implementation of {@link TargetSourceRangeComputer#computeSourceRange(ASTNode)}
             * is specialized to work in the case of internal AST rewriting, where the original AST
             * has been modified from its original form. This means that one cannot trust that the
             * root of the given node is the compilation unit.
             */
            public SourceRange computeSourceRange(ASTNode node) {
              int extendedStartPosition = rootNode.getExtendedStartPosition(node);
              int extendedLength = rootNode.getExtendedLength(node);
              return new SourceRange(extendedStartPosition, extendedLength);
            }
          };
      char[] content = document.get().toCharArray();
      LineInformation lineInfo = LineInformation.create(document);
      String lineDelim = TextUtilities.getDefaultLineDelimiter(document);
      List comments = rootNode.getCommentList();

      // MERGECONFLICT
      // AspectJ Extension - use the factory instead of building one directly
      // old code:
      // ASTRewriteAnalyzer visitor = new ASTRewriteAnalyzer(content, lineInfo, lineDelim, result,
      // this.eventStore, this.nodeStore, comments, options, xsrComputer);
      // new code:
      //			ASTVisitor visitor = ASTRewriteAnalyzer.getAnalyzerVisitor(content, lineInfo,
      // lineInfoneDelim, result, this.eventStore, this.nodeStore, comments, options, xsrComputer);
      // End AspectJ Extension

      Map currentOptions = options == null ? JavaCore.getOptions() : options;
      // OLD
      //			ASTRewriteAnalyzer visitor = new ASTRewriteAnalyzer(content, lineInfo, lineDelim, result,
      // this.eventStore, this.nodeStore, comments, currentOptions, xsrComputer,
      // (RecoveryScannerData)rootNode.getStatementsRecoveryData());

      // NEW  CAST NEEDED???
      ASTRewriteAnalyzer visitor =
          (ASTRewriteAnalyzer)
              ASTRewriteAnalyzer.getAnalyzerVisitor(
                  content,
                  lineInfo,
                  lineDelim,
                  result,
                  this.eventStore,
                  this.nodeStore,
                  comments,
                  currentOptions,
                  xsrComputer,
                  (RecoveryScannerData) rootNode.getStatementsRecoveryData());
      rootNode.accept(visitor);
    }
    return result;
  }
Пример #9
0
 /** @return list of {@link BinTypeRef types} having sources. */
 public List getDefinedTypes() {
   final ArrayList result = new ArrayList(this.definedTypeNames.size());
   for (int i = 0, max = compilationUnits.size(); i < max; ++i) {
     final CompilationUnit aCompilationUnit = (CompilationUnit) compilationUnits.get(i);
     final List definedTypes = aCompilationUnit.getDefinedTypes();
     result.addAll(definedTypes);
   }
   return result;
 }
Пример #10
0
 /** read all source files to their compilation units. Return true if no error. */
 public boolean readSourceFiles() {
   for (CompilationUnit compilationUnit : program.getCompilationUnitList()) {
     try {
       compilationUnit.readSourceFile();
     } catch (Exception e) {
       return false;
     }
   }
   return true;
 }
Пример #11
0
 @Override
 public Void visitCompilationUnit(CompilationUnit node) {
   ScriptTag scriptTag = node.getScriptTag();
   NodeList<Directive> directives = node.getDirectives();
   visit(scriptTag);
   String prefix = scriptTag == null ? "" : " ";
   visitList(prefix, directives, " ");
   prefix = scriptTag == null && directives.isEmpty() ? "" : " ";
   visitList(prefix, node.getDeclarations(), " ");
   return null;
 }
 private void assertProblems(
     String expectedProblems, String path, String source, WorkingCopyOwner owner)
     throws JavaModelException {
   this.workingCopy = getWorkingCopy(path, source);
   ASTParser parser = ASTParser.newParser(JLS3_INTERNAL);
   parser.setSource(this.workingCopy);
   parser.setResolveBindings(true);
   parser.setWorkingCopyOwner(owner);
   CompilationUnit cu = (CompilationUnit) parser.createAST(null);
   assertProblems("Unexpected problems", expectedProblems, cu.getProblems(), source.toCharArray());
 }
Пример #13
0
 /**
  * Possible failures:
  *
  * <ul>
  *   <li>INVALID_ELEMENT_TYPES - the compilation unit supplied to this operation is not a working
  *       copy
  *   <li>ELEMENT_NOT_PRESENT - the compilation unit the working copy is based on no longer exists.
  *   <li>UPDATE_CONFLICT - the original compilation unit has changed since the working copy was
  *       created and the operation specifies no force
  *   <li>READ_ONLY - the original compilation unit is in read-only mode
  * </ul>
  */
 public IJavaModelStatus verify() {
   CompilationUnit cu = getCompilationUnit();
   if (!cu.isWorkingCopy()) {
     return new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, cu);
   }
   if (cu.hasResourceChanged() && !this.force) {
     return new JavaModelStatus(IJavaModelStatusConstants.UPDATE_CONFLICT);
   }
   // no read-only check, since some repository adapters can change the flag on save
   // operation.
   return JavaModelStatus.VERIFIED_OK;
 }
Пример #14
0
 /**
  * Helper method to resolve type names.
  *
  * @param compilationUnit
  * @param fqjt
  * @return
  */
 public static final void addTypeName(
     StringBuilder sb, CompilationUnit compilationUnit, FullyQualifiedJavaType fqjt) {
   if (fqjt != null) {
     if (!fqjt.isExplicitlyImported()
         || compilationUnit == null
         || fqjt.getPackageName().equals(compilationUnit.getType().getPackageName())
         || compilationUnit.getImportedTypes().contains(fqjt)) {
       sb.append(fqjt.getShortName());
     } else {
       sb.append(fqjt.getFullyQualifiedName());
     }
   }
 }
Пример #15
0
  public boolean process(String[] args, BytecodeReader reader, JavaParser parser) {
    program.initBytecodeReader(reader);
    program.initJavaParser(parser);

    initOptions();
    processArgs(args);

    Collection files = program.options().files();

    if (program.options().hasOption("-version")) {
      printVersion();
      return false;
    }
    if (program.options().hasOption("-help") || files.isEmpty()) {
      printUsage();
      return false;
    }

    try {
      for (Iterator iter = files.iterator(); iter.hasNext(); ) {
        String name = (String) iter.next();
        if (!new File(name).exists())
          System.err.println("WARNING: file \"" + name + "\" does not exist");
        program.addSourceFile(name);
      }

      for (Iterator iter = program.compilationUnitIterator(); iter.hasNext(); ) {
        CompilationUnit unit = (CompilationUnit) iter.next();
        if (unit.fromSource()) {
          Collection errors = unit.parseErrors();
          Collection warnings = new LinkedList();
          // compute static semantic errors when there are no parse errors or
          // the recover from parse errors option is specified
          if (errors.isEmpty() || program.options().hasOption("-recover"))
            unit.errorCheck(errors, warnings);
          if (!errors.isEmpty()) {
            processErrors(errors, unit);
            return false;
          } else {
            if (!warnings.isEmpty()) processWarnings(warnings, unit);
            processNoErrors(unit);
          }
        }
      }
    } catch (Exception e) {
      System.err.println(e.getMessage());
      e.printStackTrace();
    }
    return true;
  }
 /*
  * @see ASTVisitor#visit(CompilationUnit)
  */
 @Override
 public boolean visit(CompilationUnit node) {
   if (node.getPackage() != null) {
     node.getPackage().accept(this);
   }
   for (Iterator<ImportDeclaration> it = node.imports().iterator(); it.hasNext(); ) {
     ImportDeclaration d = it.next();
     d.accept(this);
   }
   for (Iterator<AbstractTypeDeclaration> it = node.types().iterator(); it.hasNext(); ) {
     AbstractTypeDeclaration d = it.next();
     d.accept(this);
   }
   return false;
 }
Пример #17
0
 /** Use previously compiled {@link CompilationUnit}s to pre-populate the unit cache. */
 public static void addArchive(
     CompilerContext compilerContext, CompilationUnitArchive compilationUnitArchive) {
   UnitCache unitCache = compilerContext.getUnitCache();
   for (CachedCompilationUnit archivedUnit : compilationUnitArchive.getUnits().values()) {
     if (archivedUnit.getTypesSerializedVersion() != GwtAstBuilder.getSerializationVersion()) {
       continue;
     }
     CompilationUnit cachedCompilationUnit = unitCache.find(archivedUnit.getResourcePath());
     // A previously cached unit might be from the persistent cache or another
     // archive.
     if (cachedCompilationUnit == null
         || cachedCompilationUnit.getLastModified() < archivedUnit.getLastModified()) {
       unitCache.addArchivedUnit(archivedUnit);
     }
   }
 }
Пример #18
0
  public AnalyzerResults analyzeTestCases() throws IOException {
    Collection<CompilationUnit> units = findTestCasesSources();

    // match test cases sources with class
    matchTestCasesClasses(units);

    List<TestCase> testCases = new ArrayList<TestCase>();
    for (CompilationUnit unit : units) {
      TestCase testCase = new TestCase(unit);
      final File classFile = unit.getClassFile();
      final FileInputStream inputStream = new FileInputStream(classFile);
      TestCaseMethod[] methods = engine.getTestMethods(inputStream);
      testCase.setTestCaseMethods(methods);
      testCases.add(testCase);
    }

    return new AnalyzerResults(testCases);
  }
Пример #19
0
  private void matchTestCasesClasses(Collection<CompilationUnit> units)
      throws FileNotFoundException {

    for (CompilationUnit unit : units) {
      for (String baseDir : classesDirs) {
        File classFile = unit.getClassFile(baseDir);
        System.out.println(classFile.getAbsolutePath());
        if (classFile.exists()) {
          unit.setClassFile(classFile);
          break;
        }
      }
      if (unit.getClassFile() == null) {
        throw new FileNotFoundException(
            "Class file for source " + unit.getSourceFile().getAbsolutePath() + " not found");
      }
    }
  }
Пример #20
0
  private void startUnit(CompilationUnit unit) {

    if (log.isLoggable(Level.FINE)) {
      log.fine("Starting Unit: " + unit + " and adding it to parent: " + this.currentUnit());
    }

    this.currentUnit().addChild(unit);
    this.units.push(unit);
    unit.startNotify(this);
  }
Пример #21
0
  private static void apply_ati_ActionsToGenericPrototype(Env env, CompilationUnit compUnit) {
    ICompiler_ati compiler_ati = new Compiler_ati(env);
    CompilerManager_ati compilerManager = new CompilerManager_ati(env);

    compUnit.ati_actions(compiler_ati, compilerManager);

    /*
     * all changes demanded by metaobject calls collected above are made in the call
     * to CompilerManager_ati#changeCheckProgram.
     */
    compilerManager.changeCheckProgram();
  }
  /**
   * Ensures that creating a DOM AST and computing the bindings takes the owner's working copies
   * into account.
   *
   * @deprecated using deprecated code
   */
  public void testParseCompilationUnit2() throws CoreException {
    TestWorkingCopyOwner owner = new TestWorkingCopyOwner();
    this.workingCopy = getCompilationUnit("P/Y.java").getWorkingCopy(owner, null);
    this.workingCopy.getBuffer().setContents("public class Y {\n" + "}");
    this.workingCopy.makeConsistent(null);

    char[] source = ("public class Z extends Y {\n" + "}").toCharArray();
    ASTParser parser = ASTParser.newParser(AST.JLS2);
    parser.setSource(source);
    parser.setUnitName("Z.java");
    parser.setProject(getJavaProject("P"));
    parser.setWorkingCopyOwner(owner);
    parser.setResolveBindings(true);
    CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    List types = cu.types();
    assertEquals("Unexpected number of types in AST", 1, types.size());
    TypeDeclaration type = (TypeDeclaration) types.get(0);
    ITypeBinding typeBinding = type.resolveBinding();
    assertNotNull("No binding", typeBinding);
    assertEquals("Unexpected super type", "Y", typeBinding.getSuperclass().getQualifiedName());
  }
Пример #23
0
  /**
   * Compile new generated units into an existing state.
   *
   * <p>TODO: maybe use a finer brush than to synchronize the whole thing.
   */
  synchronized Collection<CompilationUnit> doBuildGeneratedTypes(
      TreeLogger logger,
      CompilerContext compilerContext,
      Collection<GeneratedUnit> generatedUnits,
      CompileMoreLater compileMoreLater)
      throws UnableToCompleteException {
    UnitCache unitCache = compilerContext.getUnitCache();

    // Units we definitely want to build.
    List<CompilationUnitBuilder> builders = new ArrayList<CompilationUnitBuilder>();

    // Units we don't want to rebuild unless we have to.
    Map<CompilationUnitBuilder, CompilationUnit> cachedUnits =
        new IdentityHashMap<CompilationUnitBuilder, CompilationUnit>();

    // For each incoming generated Java source file...
    for (GeneratedUnit generatedUnit : generatedUnits) {
      // Create a builder for all incoming units.
      CompilationUnitBuilder builder = CompilationUnitBuilder.create(generatedUnit);

      // Look for units previously compiled
      CompilationUnit cachedUnit = unitCache.find(builder.getContentId());
      if (cachedUnit != null) {
        // Recompile generated units with errors so source can be dumped.
        if (!cachedUnit.isError()) {
          cachedUnits.put(builder, cachedUnit);
          compileMoreLater.addValidUnit(cachedUnit);
          continue;
        }
      }
      builders.add(builder);
    }
    return compileMoreLater.compile(
        logger,
        compilerContext,
        builders,
        cachedUnits,
        CompilerEventType.JDT_COMPILER_CSB_GENERATED);
  }
 @Override
 public void visit(final CompilationUnit n, final A arg) {
   visitComment(n.getComment(), arg);
   if (n.getPackage() != null) {
     n.getPackage().accept(this, arg);
   }
   if (n.getImports() != null) {
     for (final ImportDeclaration i : n.getImports()) {
       i.accept(this, arg);
     }
   }
   if (n.getTypes() != null) {
     for (final TypeDeclaration<?> typeDeclaration : n.getTypes()) {
       typeDeclaration.accept(this, arg);
     }
   }
 }
Пример #25
0
 public void visit(CompilationUnit n, Object arg) {
   if (n.getPackage() != null) {
     n.getPackage().accept(this, arg);
   }
   if (n.getImports() != null) {
     for (ImportDeclaration i : n.getImports()) {
       i.accept(this, arg);
     }
   }
   if (n.getTypes() != null) {
     for (Iterator<TypeDeclaration> i = n.getTypes().iterator(); i.hasNext(); ) {
       i.next().accept(this, arg);
       if (i.hasNext()) {}
     }
   }
 }
Пример #26
0
  /**
   * Create an instantiation of a generic prototype given by parameter gt
   *
   * @param gt
   * @param env
   * @return
   */
  private CompilationUnit createGenericPrototypeInstantiation(
      ExprGenericPrototypeInstantiation gt, Env env) {

    CompilationUnit genericProto = null;

    /* if ( gt.getName().equals("generic02.gb.G1<X>") ) {
    	System.out.println("generic02.gb.G1<X>");
    	gt.ifPrototypeReturnsNameWithPackageAndType(env);
    } */

    String genSourceFileName = gt.getGenericSourceFileName();

    String genSourceFileNameVaryingNumberOfParameters =
        gt.getGenericSourceFileNameWithVaryingNumberOfParameters();
    // if ( gt.getRealTypeListList().size() > 1 )
    // System.out.println("3");

    boolean isInterface = false;
    if (NameServer.isPrototypeFromInterface(genSourceFileName)) {
      // int sizePrefix = NameServer.prefixProtoInterface.length();
      isInterface = true;
      /*
      genSourceFileName = genSourceFileName.substring(sizePrefix);
      genSourceFileNameVaryingNumberOfParameters = genSourceFileNameVaryingNumberOfParameters.substring(sizePrefix);
      */
      genSourceFileName = NameServer.prototypeFileNameFromInterfaceFileName(genSourceFileName);
      genSourceFileNameVaryingNumberOfParameters =
          NameServer.prototypeFileNameFromInterfaceFileName(
              genSourceFileNameVaryingNumberOfParameters);
    }
    // something like util.Stack if gt is "util.Stack<Int>" or
    // Stack if gt is Stack<Int>
    ExprIdentStar typeIdent = gt.getTypeIdent();
    if (typeIdent.getIdentSymbolArray().size() == 1) {
      // no package preceding the generic prototype name as in "Stack<Int>"
      ProgramUnit pu =
          env.searchProgramUnitBySourceFileName(genSourceFileName, gt.getFirstSymbol(), false);
      if (pu != null) {
        genericProto = pu.getCompilationUnit();
        ProgramUnit pu2 =
            env.searchProgramUnitBySourceFileName(
                genSourceFileNameVaryingNumberOfParameters, gt.getFirstSymbol(), false);
        if (pu2 != null)
          /* found both generic prototype and generic prototype with varying number of parameters
           * Example: found both Tuple<T> and Tuple<T+>
           */
          env.error(
              gt.getFirstSymbol(),
              "Ambiguity in creating a real prototype from a generic prototype. There is both "
                  + pu.getCompilationUnit().getPackageName()
                  + "."
                  + genSourceFileName
                  + " and "
                  + pu2.getCompilationUnit().getPackageName()
                  + "."
                  + genSourceFileNameVaryingNumberOfParameters,
              true);
      }
      if (genericProto == null) {
        pu =
            env.searchProgramUnitBySourceFileName(
                genSourceFileNameVaryingNumberOfParameters, gt.getFirstSymbol(), false);
        if (pu != null) genericProto = pu.getCompilationUnit();
      }
    } else {
      // package preceding the generic prototype name as in "util.Stack<Int>"
      int i = 0;
      ArrayList<Symbol> symbolList = typeIdent.getIdentSymbolArray();
      int sizeLessOne = symbolList.size() - 1;
      String packageName = "";
      while (i < sizeLessOne) {
        packageName = packageName + symbolList.get(i).getSymbolString();
        ++i;
        if (i < sizeLessOne) packageName += ".";
      }
      CyanPackage cyanPackage = env.getProject().searchPackage(packageName);
      if (cyanPackage == null) {
        env.error(typeIdent.getFirstSymbol(), "Package '" + packageName + "' was not found", true);
        return null;
      }
      // first searches for something like "Stack(1)" in package 'util'
      for (CompilationUnit cunit : cyanPackage.getCompilationUnitList()) {
        if (genSourceFileName.equals(cunit.getFileNameWithoutExtension())) {
          genericProto = cunit;
          break;
        }
      }
      CompilationUnit genericProto2 = null;
      // searches for a generic prototype with varying number of parameters
      // something like "Stack(1+)"
      for (CompilationUnit cunit : cyanPackage.getCompilationUnitList()) {
        if (genSourceFileNameVaryingNumberOfParameters.equals(
            cunit.getFileNameWithoutExtension())) {
          genericProto2 = cunit;
          break;
        }
      }

      if (genericProto != null && genericProto2 != null) {
        env.error(
            gt.getFirstSymbol(),
            "Ambiguity in creating a real prototype from a generic prototype. There is both "
                + genericProto.getPackageName()
                + "."
                + genSourceFileName
                + " and "
                + genericProto2.getPackageName()
                + "."
                + genSourceFileNameVaryingNumberOfParameters,
            true);
      }
      if (genericProto == null) genericProto = genericProto2;
    }

    // genericProto = nameGenProtoUnitTable.get(genSourceFileName);

    if (genericProto == null) {
      env.error(
          true,
          gt.getFirstSymbol(),
          "Prototype '" + gt.getName() + "' was not found",
          gt.getName(),
          ErrorKind.prototype_was_not_found_inside_method);
      /*gt.getProgramUnit().getCompilationUnit().error(null,
      "Internal error at CompilerManager::createInterfaceObjectFunctionAndArray: cannot create " + gt.getName()); */
      return null;
    } else {
      /**
       * if there was no compilation error in "Stack(1).cyan", then create an instance of the
       * generic prototype
       */
      if (isInterface) {
        gt.removeProtoPrefix();
      }

      CompilationUnit newCompilationUnit = genericProto.createInstanceGenericPrototype(gt, env);
      CompilationUnit interCompilationUnit = null;
      /**
       * if the package for this generic prototype instantiation was not created before, create it
       * now.
       */
      CyanPackage cyanPackage = genericProto.getCyanPackage();

      cyanPackage.addCompilationUnit(newCompilationUnit);
      newCompilationUnit.setCyanPackage(cyanPackage);
      nonGenericCompilationUnitList.add(newCompilationUnit);

      if (nameSet.contains(newCompilationUnit.getFullFileNamePath())) {
        env.error(gt.getFirstSymbol(), "Internal error in CompilerManager");
        gt.ifPrototypeReturnsNameWithPackageAndType(env);
      } else nameSet.add(newCompilationUnit.getFullFileNamePath());

      program.addCompilationUnit(newCompilationUnit);

      newCompilationUnit.readSourceFile();
      HashSet<saci.CompilationInstruction> compInstSet = new HashSet<>();
      compInstSet.add(CompilationInstruction.dpa_actions);
      compInstSet.add(CompilationInstruction.pp_addCode);
      if (compilationStep.compareTo(CompilationStep.step_5) >= 0)
        compInstSet.add(CompilationInstruction.new_addCode);
      Compiler compiler =
          new Compiler(newCompilationUnit, compInstSet, compilationStep, project, null);
      compiler.parse();

      if (newCompilationUnit.hasCompilationError()) {
        // newCompilationUnit.printErrorList(printWriter);
        env.setThereWasError(true);
        throw new CompileErrorException();
      } else if (compInstSet.contains(CompilationInstruction.createPrototypesForInterfaces)
          && newCompilationUnit.getPrototypeIsNotGeneric()
          && newCompilationUnit.getPublicPrototype() instanceof InterfaceDec) {
        // if public program unit is an interface, create ProtoInterface

        interCompilationUnit = newCompilationUnit.createProtoInterface();
        if (interCompilationUnit != null) {

          interCompilationUnit.setCyanPackage(cyanPackage);
          cyanPackage.addCompilationUnit(interCompilationUnit);
          newCompilationUnit.setCyanPackage(cyanPackage);
          nonGenericCompilationUnitList.add(interCompilationUnit);

          String nameInter = interCompilationUnit.getFilename();
          if (nameInter.endsWith(NameServer.dotCyanSourceFileExtension))
            nameInter =
                nameInter.substring(
                    0, nameInter.length() - NameServer.sizeCyanSourceFileExtensionPlusOne);

          // nameRealGenProtoUnitTable.put(nameInter, interCompilationUnit);
          program.addCompilationUnit(interCompilationUnit);

          interCompilationUnit.readSourceFile();
          compiler =
              new Compiler(interCompilationUnit, compInstSet, compilationStep, project, null);
          compiler.parse();
          if (interCompilationUnit.getActionList().size() > 0)
            interCompilationUnit.doActionList(printWriter);
          interCompilationUnit.clearErrorsActions();
        }
      }
      // newCompilationUnit.clearErrorsActions();
      if (isInterface) return interCompilationUnit;
      else return newCompilationUnit;
    }
  }
 public void addCompiledUnit(CompilationUnit unit) {
   addPackages(Shared.getPackageName(unit.getTypeName()).replace('.', '/'));
   addBinaryTypes(unit.getCompiledClasses());
 }
Пример #28
0
  /**
   * compile the project passed as parameter to the constructor. The basic packages of Cyan, stored
   * in project <code>cyanLangPackageProject</code>, are added to the project. Currently there is
   * only one basic package of the language: "cyan.lang". This should be included in every
   * compilation.
   *
   * @return <code>false</code> in error
   */
  public boolean compile(HashSet<saci.CompilationInstruction> compInstSet) {

    Compiler compiler;

    try {

      // list of non-generic prototypes of the programc
      nonGenericCompilationUnitList = new ArrayList<CompilationUnit>();
      // list of generic prototypes of the program
      ArrayList<CompilationUnit> genericCompilationUnitList = new ArrayList<CompilationUnit>();

      /* separates the compilation units (source files) that have generic prototypes from
         those that don´t.
         A prototype whose file has a digit after '(' is a generic prototype. For example,
            Proto(1)(1).cyan has a generic prototype Proto<T><R>. And file
         MyData<main.Person><Int> is put in file MyData(main.Person)(Int).cyan.
      */

      for (CompilationUnit compilationUnit : program.getCompilationUnitList()) {

        /*
        // if the file name has a '(' character followed by a digit, then it is a
        // generic prototype. Note that "Stack(Int).cyan" contains prototype "Stack<Int>"
        // which is not considered generic
        	 *
        	 */
        String filename = compilationUnit.getFilename();
        boolean foundDigit = false;
        int ifn = 0;
        int sizeFilename = filename.length();
        while (ifn < sizeFilename) {
          if (filename.charAt(ifn) == '(' && Character.isDigit(filename.charAt(ifn + 1))) {
            foundDigit = true;
            break;
          }
          ++ifn;
        }
        if (foundDigit) {
          compilationUnit.setHasGenericPrototype(true);
          genericCompilationUnitList.add(compilationUnit);
        } else nonGenericCompilationUnitList.add(compilationUnit);
        /*
        if ( indexOfLeftPar > 0 && Character.isDigit(compilationUnit.getFilename().charAt(indexOfLeftPar + 1))  )
        	genericCompilationUnitList.add(compilationUnit);
        else
        	nonGenericCompilationUnitList.add(compilationUnit);
        */
      }

      /**
       * delete all files from "tmp" directories. If a generic prototype is in a directory "D", the
       * Compiler creates the generic instantiations in "D\tmp". For example, if "Stack<T>" is in
       * directory "util", the Compiler creates prototypes "Stack<Int>" and "Stack<Person>"
       * (assuming the program uses "Stack<Int>" and "Stack<Person>") in directory "util\tmp".
       */
      Set<String> pathCompilationUnitTable = new HashSet<String>();
      for (CompilationUnit c : genericCompilationUnitList) {
        pathCompilationUnitTable.add(c.getPackageCanonicalPath());

        c.getCyanPackage().setHasGenericPrototype(true);
      }
      for (String path : pathCompilationUnitTable) {
        File dir = new File(path + NameServer.temporaryDirName);
        if (dir.exists()) for (File file : dir.listFiles()) file.delete();
      }

      String dotExtension = "." + NameServer.cyanSourceFileExtension;

      boolean hasCompilationError = false;

      /**
       * first of all, parse all generic prototypes. This is not allowed in step 7 of the
       * compilation because all generic prototype instantiation should have been created before
       * that.
       */
      if (this.compilationStep.compareTo(CompilationStep.step_7) < 0) {
        for (CompilationUnit compilationUnit : genericCompilationUnitList) {
          compiler = new Compiler(compilationUnit, compInstSet, compilationStep, project, null);
          compiler.parse();
          /**
           * print the errors found in the generic prototypes and apply all actions to them. An
           * action is a small refactoring like insert a ";"
           */
          if (compilationUnit.hasCompilationError()) {
            // compilationUnit.printErrorList(printWriter);
            hasCompilationError = true;
          }
          if (compilationUnit.getActionList().size() > 0) compilationUnit.doActionList(printWriter);
        }
      }

      /* if ( hasCompilationError )
      	return false;
      */

      /*
       * in the first step of this while statement, all non-generic prototypes are compiled.
       *
       * In the second step of the while statement, the real prototypes created in the previous step
       * are compiled. They may instantiate new generic prototypes. For example, Stack<Int> may
       * declare a variable of type "Array<Int>". This new Cyan prototype should be created and
       * compiled. The process continues till no new prototypes should be created.
       */
      CompilationUnit compilationUnit;
      int numCompilationUnitsAlreadyCompiled = 0;
      int sizeNonGenericCompilationUnitList;
      while (numCompilationUnitsAlreadyCompiled < nonGenericCompilationUnitList.size()) {

        sizeNonGenericCompilationUnitList = nonGenericCompilationUnitList.size();
        boolean thereWasErrors = false;

        // parse of all source files that were not yet parsed. That may include some
        // generic prototypes that were instantiated in the previous round of the above
        // while statement.
        for (int i = numCompilationUnitsAlreadyCompiled;
            i < sizeNonGenericCompilationUnitList;
            i++) {
          compilationUnit = nonGenericCompilationUnitList.get(i);

          // System.out.println("cc: " + compilationUnit.getFilename());
          compiler = new Compiler(compilationUnit, compInstSet, compilationStep, project, null);
          compiler.parse();
          // if ( ! compilationUnit.hasCompilationError() ) {
          // }
          if (compilationUnit.hasCompilationError()) {
            thereWasErrors = true;
            // compilationUnit.printErrorList(printWriter);
          } else if (compInstSet.contains(CompilationInstruction.createPrototypesForInterfaces)
              && compilationUnit.getPrototypeIsNotGeneric()
              && compilationUnit.getPublicPrototype() instanceof InterfaceDec) {
            // if public program unit is an interface, create ProtoInterface
            CompilationUnit newCompilationUnit = compilationUnit.createProtoInterface();
            if (newCompilationUnit == null) {
              if (compilationUnit.hasCompilationError()) {
                thereWasErrors = true;
                compilationUnit.printErrorList(printWriter);
              }
            } else {
              CyanPackage thisCyanPackage = compilationUnit.getCyanPackage();

              thisCyanPackage.addCompilationUnit(newCompilationUnit);
              newCompilationUnit.setCyanPackage(thisCyanPackage);
              nonGenericCompilationUnitList.add(newCompilationUnit);

              String name = newCompilationUnit.getFilename();
              int indexDotCyan = name.indexOf(dotExtension);
              if (indexDotCyan > 0) name = name.substring(0, indexDotCyan);

              program.addCompilationUnit(newCompilationUnit);

              if (nameSet.contains(newCompilationUnit.getFilename()))
                System.out.println("error: " + newCompilationUnit.getFilename());
              else nameSet.add(newCompilationUnit.getFilename());
            }
          }
          // if there was not any errors and there is a list of actions ...
          /*if ( compilationUnit.getActionList().size() > 0 )
          	compilationUnit.doActionList(printWriter);
          compilationUnit.clearErrorsActions(); */
        }

        if (thereWasErrors) {
          return false;
        }
        numCompilationUnitsAlreadyCompiled = sizeNonGenericCompilationUnitList;
      }

    } catch (Exception e) {
      System.out.println(
          "Internal error at CompilerManager::compile(). e = " + e.getClass().getName());
      e.printStackTrace();
      return false;
    }

    project.printErrorList(printWriter);
    return true;
  }
Пример #29
0
 public void addChild(CompilationUnit unit) {
   super.addChild(unit);
 }
Пример #30
0
  /**
   * Create a generic prototype from parameter gpi. The new prototype is compiled. If it is an
   * interface, the prototype Proto_IntefaceName is created too. Methods calcInterfaceTypes and
   * calcInternalTypes are called for both the prototype and its Proto_InterfaceName, if any.
   *
   * @param gpi
   * @param env
   * @return
   */
  public static ProgramUnit createGenericPrototype(ExprGenericPrototypeInstantiation gpi, Env env) {

    saci.Tuple<String, Type> t = gpi.ifPrototypeReturnsNameWithPackageAndType(env);

    // t.f1 is the name of the prototype
    if (t != null && t.f2 != null) {
      /*
       * prototype has already been created before
       */
      if (t.f2 instanceof ProgramUnit) {
        return (ProgramUnit) t.f2;
      } else {
        env.error(
            gpi.getFirstSymbol(),
            "Internal error: a type that is not a program unit is used to instantiate a generic prototype");
        return null;
      }

    } else {
      /*
       * prototype has not been created. Create it.
       */
      // if ( env.getCurrentMethod() != null && env.getCurrentMethod().getName().contains("run2") )
      //	gpi.ifPrototypeReturnsItsNameWithPackage(env);

      /*
       * first, create all prototypes that are real parameters to this generic prototype instantiation
       */
      for (ArrayList<Expr> realTypeList : gpi.getRealTypeListList()) {
        for (Expr realType : realTypeList) {
          if (realType instanceof ExprGenericPrototypeInstantiation) {
            ExprGenericPrototypeInstantiation genRealType =
                (ExprGenericPrototypeInstantiation) realType;
            genRealType.setType(createGenericPrototype(genRealType, env));
            // 		javaName = type.getJavaName();
            genRealType.setJavaName(genRealType.getType().getJavaName());
          }
        }
      }

      CompilationUnit compUnit =
          env.getProject().getCompilerManager().createGenericPrototypeInstantiation(gpi, env);

      Env newEnv = new Env(env.getProject());
      /*
      * If a generic prototype is created when method calcInterfaceTypes of Program is being executed
      * (env.getProject().getProgram().getInCalcInterfaceTypes() returns true), it is not necessary
      * to call its method calcInterfaceTypes. It will be called in the loop of
      * method Program::calcInterfaceTypes.

      * If a generic prototype is created when method calcInternalTypes of Program is being executed,
      * method calcInterfaceTypes of this generic prototype should be called because the interface
      * of this prototype is necessary in methods calcInternalTypes. Method calcInternalTypes
      * of this newly created generic prototype will be called in the loop of
      * method Program::calcInternalTypes.
      *
      * calcInternalTypes cannot be called when a generic prototype is created when
      * the compiler is calling calcInterfaceTypes. If this is allowed, some calcInternalType
      * method could try to use the interface of some prototype P whose method calcInterfaceTypes
      * have not been called.
      */
      if (!env.getProject().getProgram().getInCalcInterfaceTypes()) {
        compUnit.calcInterfaceTypes(newEnv);
        // compUnit.calcInternalTypes(newEnv);
      }
      CompilationUnit interfaceCompilationUnit = compUnit.getInterfaceCompilationUnit();
      if (interfaceCompilationUnit != null) {
        newEnv = new Env(env.getProject());
        if (!env.getProject().getProgram().getInCalcInterfaceTypes()) {
          interfaceCompilationUnit.calcInterfaceTypes(newEnv);
        }
      }
      /*
       * if the generic prototype was created from phase (4), included, onwards, then execute
       * the ati actions. A generic prototype instantiation can only change itself and
       * no other prototype can change it.
       */
      if (env.getProject().getCompilerManager().getCompilationStep().ordinal()
          > CompilationStep.step_3.ordinal()) {
        apply_ati_ActionsToGenericPrototype(newEnv, compUnit);
        if (interfaceCompilationUnit != null) {
          apply_ati_ActionsToGenericPrototype(env, interfaceCompilationUnit);
        }
      }

      return compUnit.getPublicPrototype();
    }
  }