コード例 #1
0
ファイル: CCL.java プロジェクト: JoonasVali/CoCoViLa
  public void writeProblemLog(Appendable out) throws IOException {
    out.append("----------\n");
    if (problems != null) {
      int errorCount = 0;
      for (CompilationResult r : problems) {
        for (CategorizedProblem p : r.getAllProblems()) {
          out.append(Integer.toString(++errorCount));
          out.append(". ");
          if (p.isError()) {
            out.append("ERROR in ");
          } else if (p.isWarning()) {
            out.append("WARNING in ");
          } else {
            out.append("Problem in ");
          }
          out.append(new String(p.getOriginatingFileName()));

          String errorReportSource =
              ((DefaultProblem) p).errorReportSource(r.compilationUnit.getContents());

          out.append(errorReportSource);
          out.append("\n");
          out.append(p.getMessage());
          out.append("\n----------\n");
        }
      }
    }
  }
コード例 #2
0
ファイル: GeneratorUtil.java プロジェクト: rkrijgsheld/MPS
 @Override
 public void onCompilationResult(CompilationResult result) {
   if (result.hasErrors()) {
     myHasErrors = true;
     for (CategorizedProblem error : result.getErrors()) {
       myBuffer.append(error.getMessage());
       myBuffer.append("\n");
     }
   }
 }
コード例 #3
0
  protected void finishedWith(
      String sourceLocator,
      CompilationResult result,
      char[] mainTypeName,
      ArrayList definedTypeNames,
      ArrayList duplicateTypeNames) {
    char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(sourceLocator);
    if (previousTypeNames == null) previousTypeNames = new char[][] {mainTypeName};
    IPath packagePath = null;
    next:
    for (int i = 0, l = previousTypeNames.length; i < l; i++) {
      char[] previous = previousTypeNames[i];
      for (int j = 0, m = definedTypeNames.size(); j < m; j++)
        if (CharOperation.equals(previous, (char[]) definedTypeNames.get(j))) continue next;

      SourceFile sourceFile = (SourceFile) result.getCompilationUnit();
      if (packagePath == null) {
        int count = sourceFile.sourceLocation.sourceFolder.getFullPath().segmentCount();
        packagePath =
            sourceFile.resource.getFullPath().removeFirstSegments(count).removeLastSegments(1);
      }
      if (this.secondaryTypesToRemove == null)
        this.secondaryTypesToRemove = new SimpleLookupTable();
      ArrayList types =
          (ArrayList) this.secondaryTypesToRemove.get(sourceFile.sourceLocation.binaryFolder);
      if (types == null) types = new ArrayList(definedTypeNames.size());
      types.add(packagePath.append(new String(previous)));
      this.secondaryTypesToRemove.put(sourceFile.sourceLocation.binaryFolder, types);
    }
    super.finishedWith(sourceLocator, result, mainTypeName, definedTypeNames, duplicateTypeNames);
  }
コード例 #4
0
  public void checkParse(char[] source, String expectedSyntaxErrorDiagnosis, String testName) {

    /* using regular parser in DIET mode */
    Parser parser =
        new Parser(
            new ProblemReporter(
                DefaultErrorHandlingPolicies.proceedWithAllProblems(),
                new CompilerOptions(getCompilerOptions()),
                new DefaultProblemFactory(Locale.getDefault())),
            optimizeStringLiterals);
    ICompilationUnit sourceUnit = new CompilationUnit(source, testName, null);
    CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, 0);

    parser.parse(sourceUnit, compilationResult);

    StringBuffer buffer = new StringBuffer(100);
    if (compilationResult.hasProblems() || compilationResult.hasTasks()) {
      CategorizedProblem[] problems = compilationResult.getAllProblems();
      int count = problems.length;
      int problemCount = 0;
      char[] unitSource = compilationResult.compilationUnit.getContents();
      for (int i = 0; i < count; i++) {
        if (problems[i] != null) {
          if (problemCount == 0) buffer.append("----------\n");
          problemCount++;
          buffer.append(problemCount + (problems[i].isError() ? ". ERROR" : ". WARNING"));
          buffer.append(
              " in " + new String(problems[i].getOriginatingFileName()).replace('/', '\\'));
          try {
            buffer.append(((DefaultProblem) problems[i]).errorReportSource(unitSource));
            buffer.append("\n");
            buffer.append(problems[i].getMessage());
            buffer.append("\n");
          } catch (Exception e) {
          }
          buffer.append("----------\n");
        }
      }
    }
    String computedSyntaxErrorDiagnosis = buffer.toString();
    // System.out.println(Util.displayString(computedSyntaxErrorDiagnosis));
    assertEquals(
        "Invalid syntax error diagnosis" + testName,
        Util.convertToIndependantLineDelimiter(expectedSyntaxErrorDiagnosis),
        Util.convertToIndependantLineDelimiter(computedSyntaxErrorDiagnosis));
  }
コード例 #5
0
 public void acceptResult(CompilationResult compilationResult) {
   this.hasErrors |= compilationResult.hasErrors();
   this.problemLog +=
       Util.getProblemLog(compilationResult, this.showCategory, this.showWarningToken);
   outputClassFiles(compilationResult);
   if (this.clientRequestor != null) {
     this.clientRequestor.acceptResult(compilationResult);
   }
 }
コード例 #6
0
  protected void updateTasksFor(SourceFile sourceFile, CompilationResult result)
      throws CoreException {
    IMarker[] markers = JavaBuilder.getTasksFor(sourceFile.resource);
    CategorizedProblem[] tasks = result.getTasks();
    if (tasks == null && markers.length == 0) return;

    JavaBuilder.removeTasksFor(sourceFile.resource);
    storeTasksFor(sourceFile, tasks);
  }
コード例 #7
0
ファイル: CCL.java プロジェクト: JoonasVali/CoCoViLa
 protected void addProblem(CompilationResult result) {
   if (problems == null) {
     problems = new ArrayList<CompilationResult>();
   }
   problems.add(result);
   if (result.hasErrors()) {
     hasErrors = true;
   }
 }
コード例 #8
0
ファイル: TestMain.java プロジェクト: markusvoelter/MPS
    public static List<String> createCompilationProblemsList(
        List<CompilationResult> compilationResults) {
      List<String> res = new ArrayList<String>();

      for (CompilationResult r : compilationResults) {
        if (r.getErrors() != null) {
          for (CategorizedProblem p : r.getErrors()) {
            res.add(
                new String(r.getCompilationUnit().getFileName())
                    + " ("
                    + p.getSourceLineNumber()
                    + "): "
                    + p.getMessage());
          }
        }
      }

      return res;
    }
コード例 #9
0
  protected void updateProblemsFor(SourceFile sourceFile, CompilationResult result)
      throws CoreException {
    IMarker[] markers = JavaBuilder.getProblemsFor(sourceFile.resource);
    CategorizedProblem[] problems = result.getProblems();
    if (problems == null && markers.length == 0) return;

    this.notifier.updateProblemCounts(markers, problems);
    JavaBuilder.removeProblemsFor(sourceFile.resource);
    storeProblemsFor(sourceFile, problems);
  }
コード例 #10
0
 protected void outputClassFiles(CompilationResult unitResult) {
   if ((unitResult != null) && (!unitResult.hasErrors() || this.forceOutputGeneration)) {
     ClassFile[] classFiles = unitResult.getClassFiles();
     if (this.outputPath != null) {
       for (int i = 0, fileCount = classFiles.length; i < fileCount; i++) {
         // retrieve the key and the corresponding classfile
         ClassFile classFile = classFiles[i];
         String relativeName =
             new String(classFile.fileName()).replace('/', File.separatorChar) + ".class";
         try {
           org.eclipse.jdt.internal.compiler.util.Util.writeToDisk(
               true, this.outputPath, relativeName, classFile);
         } catch (IOException e) {
           e.printStackTrace();
         }
       }
     }
   }
 }
コード例 #11
0
 protected IProblem[] getJavaCompilationErrors(CompilationResult result) {
   try {
     Method getErrorsMethod = result.getClass().getMethod("getErrors", null);
     return (IProblem[]) getErrorsMethod.invoke(result, null);
   } catch (SecurityException e) {
     throw new JRRuntimeException("Error resolving JDT methods", e);
   } catch (NoSuchMethodException e) {
     throw new JRRuntimeException("Error resolving JDT methods", e);
   } catch (IllegalArgumentException e) {
     throw new JRRuntimeException("Error invoking JDT methods", e);
   } catch (IllegalAccessException e) {
     throw new JRRuntimeException("Error invoking JDT methods", e);
   } catch (InvocationTargetException e) {
     throw new JRRuntimeException("Error invoking JDT methods", e);
   }
 }
コード例 #12
0
  /**
   * Bytecode generation for a method
   *
   * @param classScope
   * @param classFile
   */
  public void generateCode(ClassScope classScope, ClassFile classFile) {

    classFile.codeStream.wideMode = false; // reset wideMode to false
    if (this.ignoreFurtherInvestigation) {
      // method is known to have errors, dump a problem method
      if (this.binding == null) return; // handle methods with invalid signature or duplicates
      int problemsLength;
      CategorizedProblem[] problems =
          this.scope.referenceCompilationUnit().compilationResult.getProblems();
      CategorizedProblem[] problemsCopy = new CategorizedProblem[problemsLength = problems.length];
      System.arraycopy(problems, 0, problemsCopy, 0, problemsLength);
      classFile.addProblemMethod(this, this.binding, problemsCopy);
      return;
    }
    int problemResetPC = 0;
    CompilationResult unitResult = null;
    int problemCount = 0;
    if (classScope != null) {
      TypeDeclaration referenceContext = classScope.referenceContext;
      if (referenceContext != null) {
        unitResult = referenceContext.compilationResult();
        problemCount = unitResult.problemCount;
      }
    }
    boolean restart = false;
    boolean abort = false;
    // regular code generation
    do {
      try {
        problemResetPC = classFile.contentsOffset;
        this.generateCode(classFile);
        restart = false;
      } catch (AbortMethod e) {
        // a fatal error was detected during code generation, need to restart code gen if possible
        if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) {
          // a branch target required a goto_w, restart code gen in wide mode.
          classFile.contentsOffset = problemResetPC;
          classFile.methodCount--;
          classFile.codeStream.resetInWideMode(); // request wide mode
          // reset the problem count to prevent reporting the same warning twice
          if (unitResult != null) {
            unitResult.problemCount = problemCount;
          }
          restart = true;
        } else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) {
          classFile.contentsOffset = problemResetPC;
          classFile.methodCount--;
          classFile.codeStream.resetForCodeGenUnusedLocals();
          // reset the problem count to prevent reporting the same warning twice
          if (unitResult != null) {
            unitResult.problemCount = problemCount;
          }
          restart = true;
        } else {
          restart = false;
          abort = true;
        }
      }
    } while (restart);
    // produce a problem method accounting for this fatal error
    if (abort) {
      int problemsLength;
      CategorizedProblem[] problems =
          this.scope.referenceCompilationUnit().compilationResult.getAllProblems();
      CategorizedProblem[] problemsCopy = new CategorizedProblem[problemsLength = problems.length];
      System.arraycopy(problems, 0, problemsCopy, 0, problemsLength);
      classFile.addProblemMethod(this, this.binding, problemsCopy, problemResetPC);
    }
  }
コード例 #13
0
ファイル: MethodSpec.java プロジェクト: eclipse/objectteams
  /**
   * Resolve the method or field (see FieldAccessSpec).
   *
   * @param receiverType receiver of the method call.
   * @param scope
   * @param callinExpected whether this method spec is the LHS of a replace callin.
   * @param isBaseSide whether this method spec is the RHS (any binding kind)
   * @param allowEnclosing whether a method may be found in an enclosing type of receiverType
   * @return the resolved method (may be problem method) or null
   */
  public MethodBinding resolveFeature(
      ReferenceBinding receiverType,
      BlockScope scope,
      boolean callinExpected,
      boolean isBaseSide,
      boolean allowEnclosing) {
    // getRealClass() is used, because decapsulation needs to find private methods,
    // which for roles are found only in the class part.
    ReferenceBinding receiverClass = receiverType.getRealClass();
    boolean isConstructorSpec = CharOperation.equals(this.selector, receiverClass.sourceName());
    char[] realSelector = isConstructorSpec ? TypeConstants.INIT : this.selector;
    if (this.hasSignature) {
      TypeBinding[] enhancedParameters = this.parameters;
      // first chance: try enhanced:
      enhancedParameters = MethodSignatureEnhancer.enhanceParameters(scope, this.parameters);
      CompilationResult compilationResult = scope.referenceContext().compilationResult();
      CheckPoint cp = compilationResult.getCheckPoint(scope.referenceContext());

      this.resolvedMethod =
          TypeAnalyzer.findMethod(
              scope,
              receiverClass,
              realSelector,
              enhancedParameters,
              isBaseSide,
              isBaseSide ? this : null);
      if (!this.resolvedMethod.isValidBinding()
          && this.resolvedMethod.problemId() == ProblemReasons.NotFound) {
        // second+ chance: try plain:
        while (receiverClass != null) {
          compilationResult.rollBack(cp);
          MethodBinding plainMethod =
              TypeAnalyzer.findMethod(
                  scope,
                  receiverClass,
                  realSelector,
                  this.parameters,
                  isBaseSide,
                  isBaseSide ? this : null);
          if (!callinExpected) {
            this.resolvedMethod = plainMethod;
          } else {
            if (plainMethod != null && plainMethod.isValidBinding())
              scope.problemReporter().replaceMappingToNonCallin(this, plainMethod);
            // mark the ProblemMethodBinding consistently to what we have been looking for last:
            this.resolvedMethod.modifiers |=
                ExtraCompilerModifiers.AccCallin | ClassFileConstants.AccStatic;
          }
          if (plainMethod != null && plainMethod.isValidBinding()) break;
          if (allowEnclosing) receiverClass = receiverClass.enclosingType();
          else receiverClass = null;
        }
      }
    } else {
      CompilationResult compilationResult = scope.referenceContext().compilationResult();
      CheckPoint cp = compilationResult.getCheckPoint(scope.referenceContext());
      while (receiverClass != null) {
        this.resolvedMethod = receiverClass.getMethod(scope, realSelector);
        if (this.resolvedMethod != null && this.resolvedMethod.isValidBinding()) break; // good
        if (!allowEnclosing) break; // bad
        compilationResult.rollBack(cp);
        receiverClass = receiverClass.enclosingType();
      }
    }
    if (this.resolvedMethod != null) {
      if (this.resolvedMethod.isValidBinding()) {
        // check visibility of role-side in callin:
        if (!isBaseSide
            && scope.referenceContext() instanceof CallinMappingDeclaration
            && !this.resolvedMethod.canBeSeenBy(this, scope)) {
          scope.problemReporter().invisibleMethod(this, this.resolvedMethod);
          this.resolvedMethod =
              new ProblemMethodBinding(
                  this.resolvedMethod, this.selector, this.parameters, ProblemReasons.NotVisible);
        }
      }
      if (!this.resolvedMethod.isValidBinding() && this.resolvedMethod.declaringClass == null)
        this.resolvedMethod.declaringClass = receiverClass; // needed for computeUniqueKey (via
      // CallinCalloutBinding.computeUniqueKey)
    }
    return this.resolvedMethod;
  }
コード例 #14
0
  // Dump classfiles onto disk for all compilation units that where successful
  // and do not carry a -d none spec, either directly or inherited from Main.
  @Override
  public void outputClassFiles(CompilationResult unitResult) {
    if (!((unitResult == null) || (unitResult.hasErrors() && !this.proceedOnError))) {
      ClassFile[] classFiles = unitResult.getClassFiles();
      boolean generateClasspathStructure =
          this.fileManager.hasLocation(StandardLocation.CLASS_OUTPUT);
      String currentDestinationPath = this.destinationPath;
      File outputLocation = null;
      if (currentDestinationPath != null) {
        outputLocation = new File(currentDestinationPath);
        outputLocation.mkdirs();
      }
      for (int i = 0, fileCount = classFiles.length; i < fileCount; i++) {
        // retrieve the key and the corresponding classfile
        ClassFile classFile = classFiles[i];
        char[] filename = classFile.fileName();
        int length = filename.length;
        char[] relativeName = new char[length + 6];
        System.arraycopy(filename, 0, relativeName, 0, length);
        System.arraycopy(SuffixConstants.SUFFIX_class, 0, relativeName, length, 6);
        CharOperation.replace(relativeName, '/', File.separatorChar);
        String relativeStringName = new String(relativeName);
        if (this.compilerOptions.verbose) {
          EclipseCompilerImpl.this.out.println(
              Messages.bind(
                  Messages.compilation_write,
                  new String[] {
                    String.valueOf(this.exportedClassFilesCounter + 1), relativeStringName
                  }));
        }
        try {
          JavaFileObject javaFileForOutput =
              this.fileManager.getJavaFileForOutput(
                  StandardLocation.CLASS_OUTPUT,
                  new String(filename),
                  JavaFileObject.Kind.CLASS,
                  this.javaFileObjectMap.get(unitResult.compilationUnit));

          if (generateClasspathStructure) {
            if (currentDestinationPath != null) {
              int index = CharOperation.lastIndexOf(File.separatorChar, relativeName);
              if (index != -1) {
                File currentFolder =
                    new File(currentDestinationPath, relativeStringName.substring(0, index));
                currentFolder.mkdirs();
              }
            } else {
              // create the subfolfers is necessary
              // need a way to retrieve the folders to create
              String path = javaFileForOutput.toUri().getPath();
              int index = path.lastIndexOf('/');
              if (index != -1) {
                File file = new File(path.substring(0, index));
                file.mkdirs();
              }
            }
          }

          OutputStream openOutputStream = javaFileForOutput.openOutputStream();
          BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(openOutputStream);
          bufferedOutputStream.write(classFile.header, 0, classFile.headerOffset);
          bufferedOutputStream.write(classFile.contents, 0, classFile.contentsOffset);
          bufferedOutputStream.flush();
          bufferedOutputStream.close();
        } catch (IOException e) {
          this.logger.logNoClassFileCreated(currentDestinationPath, relativeStringName, e);
        }
        this.logger.logClassFile(
            generateClasspathStructure, currentDestinationPath, relativeStringName);
        this.exportedClassFilesCounter++;
      }
      this.batchCompiler.lookupEnvironment.releaseClassFiles(classFiles);
    }
  }
コード例 #15
0
  protected CompilationUnitDeclaration endParse(int act) {
    if (this.hasRecoveredOnExpression) {
      CompilationResult unitResult = this.compilationUnit.compilationResult;
      if (act != ERROR_ACTION) { // expression recovery worked
        // flush previously recorded problems
        for (int i = 0; i < unitResult.problemCount; i++) {
          unitResult.problems[i] = null; // discard problem
        }
        unitResult.problemCount = 0;
        if (this.referenceContext instanceof AbstractMethodDeclaration) {
          ((AbstractMethodDeclaration) this.referenceContext).ignoreFurtherInvestigation = false;
        }
        if (this.referenceContext instanceof CompilationUnitDeclaration) {
          ((CompilationUnitDeclaration) this.referenceContext).ignoreFurtherInvestigation = false;
        }

        // consume expresion as a return statement
        consumeStatementReturn();
        int fieldsCount =
            (this.evaluationContext.localVariableNames == null
                    ? 0
                    : this.evaluationContext.localVariableNames.length)
                + (this.evaluationContext.declaringTypeName == null ? 0 : 1);
        if (this.astPtr > (this.diet ? 0 : 2 + fieldsCount)) {
          // in diet mode, the ast stack was empty when we went for method body
          // otherwise it contained the type, the generated fields for local variables,
          // the generated field for 'this' and the method
          consumeBlockStatements();
        }
        consumeMethodBody();
        if (!this.diet) {
          consumeMethodDeclaration(true);
          if (fieldsCount > 0) {
            consumeClassBodyDeclarations();
          }
          consumeClassBodyDeclarationsopt();
          consumeClassDeclaration();
          consumeInternalCompilationUnitWithTypes();
          consumeCompilationUnit();
        }
        this.lastAct = ACCEPT_ACTION;
      } else {
        // might have more than one error recorded:
        // 1. during regular parse
        // 2. during expression recovery
        // -> must filter out one of them, the earliest one is less accurate
        int maxRegularPos = 0, problemCount = unitResult.problemCount;
        for (int i = 0; i < this.problemCountBeforeRecovery; i++) {
          // skip unmatched bracket problems
          if (unitResult.problems[i].getID() == IProblem.UnmatchedBracket) continue;

          int start = unitResult.problems[i].getSourceStart();
          if (start > maxRegularPos && start <= this.codeSnippetEnd) {
            maxRegularPos = start;
          }
        }
        int maxRecoveryPos = 0;
        for (int i = this.problemCountBeforeRecovery; i < problemCount; i++) {
          // skip unmatched bracket problems
          if (unitResult.problems[i].getID() == IProblem.UnmatchedBracket) continue;

          int start = unitResult.problems[i].getSourceStart();
          if (start > maxRecoveryPos && start <= this.codeSnippetEnd) {
            maxRecoveryPos = start;
          }
        }
        if (maxRecoveryPos > maxRegularPos) {
          System.arraycopy(
              unitResult.problems,
              this.problemCountBeforeRecovery,
              unitResult.problems,
              0,
              problemCount - this.problemCountBeforeRecovery);
          unitResult.problemCount -= this.problemCountBeforeRecovery;
        } else {
          unitResult.problemCount -= (problemCount - this.problemCountBeforeRecovery);
        }
        for (int i = unitResult.problemCount; i < problemCount; i++) {
          unitResult.problems[i] = null; // discard problem
        }
      }
    }
    return super.endParse(act);
  }
コード例 #16
0
 public void record(
     CategorizedProblem problem, CompilationResult unitResult, ReferenceContext referenceContext) {
   unitResult.record(problem, referenceContext);
 }
コード例 #17
0
  public void handle(
      int problemId,
      String[] problemArguments,
      int elaborationId,
      String[] messageArguments,
      int severity,
      int problemStartPosition,
      int problemEndPosition,
      ReferenceContext referenceContext,
      CompilationResult unitResult) {

    if (severity == ProblemSeverities.Ignore) return;

    // if no reference context, we need to abort from the current compilation process
    if (referenceContext == null) {
      if ((severity & ProblemSeverities.Error) != 0) { // non reportable error is fatal
        CategorizedProblem problem =
            this.createProblem(
                null,
                problemId,
                problemArguments,
                elaborationId,
                messageArguments,
                severity,
                0,
                0,
                0,
                0);
        throw new AbortCompilation(null, problem);
      } else {
        return; // ignore non reportable warning
      }
    }

    int[] lineEnds;
    int lineNumber =
        problemStartPosition >= 0
            ? Util.getLineNumber(
                problemStartPosition,
                lineEnds = unitResult.getLineSeparatorPositions(),
                0,
                lineEnds.length - 1)
            : 0;
    int columnNumber =
        problemStartPosition >= 0
            ? Util.searchColumnNumber(
                unitResult.getLineSeparatorPositions(), lineNumber, problemStartPosition)
            : 0;
    CategorizedProblem problem =
        this.createProblem(
            unitResult.getFileName(),
            problemId,
            problemArguments,
            elaborationId,
            messageArguments,
            severity,
            problemStartPosition,
            problemEndPosition,
            lineNumber,
            columnNumber);

    if (problem == null) return; // problem couldn't be created, ignore

    switch (severity & ProblemSeverities.Error) {
      case ProblemSeverities.Error:
        record(problem, unitResult, referenceContext);
        if ((severity & ProblemSeverities.Fatal) != 0) {
          referenceContext.tagAsHavingErrors();
          // should abort ?
          int abortLevel;
          if ((abortLevel =
                  this.policy.stopOnFirstError()
                      ? ProblemSeverities.AbortCompilation
                      : severity & ProblemSeverities.Abort)
              != 0) {
            referenceContext.abort(abortLevel, problem);
          }
        }
        break;
      case ProblemSeverities.Warning:
        record(problem, unitResult, referenceContext);
        break;
    }
  }
コード例 #18
0
 protected TypeBinding internalResolveType(Scope scope, int location) {
   // handle the error here
   this.constant = Constant.NotAConstant;
   if (this.resolvedType != null) { // is a shared type reference which was already resolved
     if (this.resolvedType.isValidBinding()) {
       return this.resolvedType;
     } else {
       switch (this.resolvedType.problemId()) {
         case ProblemReasons.NotFound:
         case ProblemReasons.NotVisible:
         case ProblemReasons.InheritedNameHidesEnclosingName:
           TypeBinding type = this.resolvedType.closestMatch();
           if (type == null) return null;
           return scope
               .environment()
               .convertToRawType(type, false /*do not force conversion of enclosing types*/);
         default:
           return null;
       }
     }
   }
   boolean hasError;
   // {ObjectTeams: don't let SelectionNodeFound(null) prevent alternate searching strategies:
   SelectionNodeFound caughtException = null;
   TypeBinding type = null;
   try {
     // base import scope first:
     CompilationResult compilationResult = scope.referenceCompilationUnit().compilationResult();
     CompilationResult.CheckPoint cp = compilationResult.getCheckPoint(scope.referenceContext());
     try {
       type =
           checkResolveUsingBaseImportScope(
               scope, location, false); // apply TOLERATE strategy only as a last resort below
       // copied from below:
       if (type != null && type.isValidBinding()) {
         type =
             scope
                 .environment()
                 .convertToRawType(type, false /*do not force conversion of enclosing types*/);
         if (type.leafComponentType().isRawType()
             && (this.bits & ASTNode.IgnoreRawTypeCheck) == 0
             && scope.compilerOptions().getSeverity(CompilerOptions.RawTypeReference)
                 != ProblemSeverities.Ignore) {
           scope.problemReporter().rawTypeReference(this, type);
         }
         return type;
       }
     } catch (SelectionNodeFound snf) {
       if (snf.binding != null) throw snf; // found a valid node.
       caughtException = snf;
     } finally {
       if (caughtException != null || (type == null) || !type.isValidBinding())
         compilationResult.rollBack(cp);
     }
     // ~orig~:
     type = this.resolvedType = getTypeBinding(scope);
     if (type == null) {
       return null; // detected cycle while resolving hierarchy
     }
     // :~giro~
   } catch (SelectionNodeFound snf) {
     if (snf.binding != null) throw snf; // found a valid node.
     caughtException = snf;
   }
   // a third chance trying an anchored type:
   try {
     if ((caughtException != null) || (this.resolvedType.problemId() == ProblemReasons.NotFound)) {
       // anchored type
       TypeBinding result = resolveAnchoredType(scope);
       if (result != null) // did we do any better than before?
       type = this.resolvedType = result; // if non-null but ProblemBinding report below.
     }
   } catch (SelectionNodeFound snf2) {
     caughtException = snf2; // throw the newer exception instead.
   }
   // a forth chance trying a TOLERATED base imported type:
   try {
     if ((caughtException != null) || (this.resolvedType.problemId() == ProblemReasons.NotFound)) {
       if (this.baseclassDecapsulation == DecapsulationState.TOLERATED) {
         TypeBinding result = checkResolveUsingBaseImportScope(scope, -1, true);
         if (result != null) // did we do any better than before?
         type = this.resolvedType = result; // if non-null but ProblemBinding report below.
       }
     }
   } catch (SelectionNodeFound snf2) {
     caughtException = snf2; // throw the newer exception instead.
   } finally {
     // the attempt to prevent an exception failed:
     if (caughtException != null) throw caughtException;
   }
   // SH}
   if ((hasError = !type.isValidBinding()) == true) {
     reportInvalidType(scope);
     switch (type.problemId()) {
       case ProblemReasons.NotFound:
       case ProblemReasons.NotVisible:
       case ProblemReasons.InheritedNameHidesEnclosingName:
         type = type.closestMatch();
         if (type == null) return null;
         break;
       default:
         return null;
     }
   }
   // {ObjectTeams: Split method to make tail accessible:
   return checkResolvedType(type, scope, location, hasError);
 }
コード例 #19
0
ファイル: ModuleMaker.java プロジェクト: yan96in/MPS
    @Override
    public void onCompilationResult(CompilationResult cr) {
      Set<String> classesWithErrors = new HashSet<String>();
      if (cr.getErrors() != null) {
        myTracer.push("handling errors", false);
        for (final CategorizedProblem cp : cr.getErrors()) {
          String fileName = new String(cp.getOriginatingFileName());
          final String fqName =
              NameUtil.namespaceFromPath(
                  fileName.substring(0, fileName.length() - MPSExtentions.DOT_JAVAFILE.length()));
          classesWithErrors.add(fqName);

          SModule containingModule = myContainingModules.get(fqName);
          assert containingModule != null;
          JavaFile javaFile = myModuleSources.get(containingModule).getJavaFile(fqName);

          String messageString = new String(cp.getOriginatingFileName()) + " : " + cp.getMessage();

          // final SNode nodeToShow = getNodeByLine(cp, fqName);

          Object hintObject = new FileWithPosition(javaFile.getFile(), cp.getSourceStart());

          String errMsg = messageString + " (line: " + cp.getSourceLineNumber() + ")";
          if (cp.isWarning()) {
            myMessages.add(createMessage(MessageKind.WARNING, errMsg, hintObject));
          } else {
            if (myOutputtedErrors == 0) {
              myMessages.add(createMessage(MessageKind.ERROR, "Compilation problems", null));
              myMessages.add(
                  createMessage(
                      MessageKind.INFORMATION,
                      "Modules: "
                          + myModules.toString()
                          + "\nClasspath: "
                          + myClassPathItems
                          + "\n",
                      null));
            }
            if (myOutputtedErrors < MAX_ERRORS) {
              myOutputtedErrors++;
              myMessages.add(createMessage(MessageKind.ERROR, errMsg, hintObject));
            }
          }
        }
        myTracer.pop();

        myErrorCount += cr.getErrors().length;
      }

      myTracer.push("storing files", false);
      for (ClassFile cf : cr.getClassFiles()) {
        String fqName = convertCompoundToFqName(cf.getCompoundName());
        String containerClassName = fqName;
        if (containerClassName.contains("$")) {
          int index = containerClassName.indexOf('$');
          containerClassName = containerClassName.substring(0, index);
        }
        if (myContainingModules.containsKey(containerClassName)) {
          SModule m = myContainingModules.get(containerClassName);
          myChangedModules.add(m);
          File classesGen = new File(getJavaFacet(m).getClassesGen().getPath());
          String packageName = NameUtil.namespaceFromLongName(fqName);
          File outputDir =
              new File(classesGen + File.separator + NameUtil.pathFromNamespace(packageName));
          if (!outputDir.exists()) {
            if (!outputDir.mkdirs()) {
              throw new RuntimeException("Can't create " + outputDir.getPath() + " directory");
            }
          }
          String className = NameUtil.shortNameFromLongName(fqName);
          File output = new File(outputDir, className + ".class");
          if (!classesWithErrors.contains(containerClassName)) {
            FileOutputStream os = null;
            try {
              os = new FileOutputStream(output);
              os.write(cf.getBytes());
            } catch (IOException e) {
              String errMsg = "Can't write to " + output.getAbsolutePath();
              myMessages.add(createMessage(MessageKind.ERROR, errMsg, null));
            } finally {
              if (os != null) {
                try {
                  os.close();
                } catch (IOException e) {
                  myHandler.handle(createMessage(MessageKind.ERROR, e.toString(), e));
                }
              }
            }
          } else {
            if (output.exists() && !(output.delete())) {
              String errMsg = "Can't delete " + output.getPath();
              myMessages.add(createMessage(MessageKind.ERROR, errMsg, null));
            }
          }
        } else {
          String errMsg =
              "I don't know in which module's output path I should place class file for " + fqName;
          myMessages.add(createMessage(MessageKind.ERROR, errMsg, null));
        }
      }
      myTracer.pop();
    }