/**
   * Parse the source for the specified compilation unit and resolve any elements found in it. Any
   * exceptions thrown by the {@link DartParser} will be added to the given collection.
   *
   * @param compilationUnit the compilation unit (not <code>null</code>)
   * @param parseErrors a collection to which parse errors are added or <code>null</code> if parse
   *     errors should be ignored
   * @return the parse result
   */
  public static DartUnit resolveUnit(
      CompilationUnit compilationUnit, Collection<DartCompilationError> parseErrors)
      throws DartModelException {

    long start = System.currentTimeMillis();

    DartLibraryImpl library = (DartLibraryImpl) compilationUnit.getLibrary();
    if (library == null) {
      // If we cannot get the library, we cannot resolve any elements so we
      // revert to simply parsing the compilation unit.
      DartUnit ret = parseUnit(compilationUnit, parseErrors);

      long elapsed = System.currentTimeMillis() - start;
      Instrumentation.metric("DartCompilerUtils-resolveUnit", elapsed)
          .with("ParseOnlyFallback", "true")
          .log();

      Instrumentation.operation("DartCompilerUtils-resolveUnit", elapsed)
          .with("ParseOnlyFallback", "true")
          .with("CompilaitonUnit-ElementName", compilationUnit.getElementName())
          .log();

      return ret;
    }
    IResource resource = compilationUnit.getResource();
    URI unitUri = null;
    if (resource != null) {
      unitUri = resource.getLocationURI();
    }
    if (unitUri == null && compilationUnit instanceof ExternalCompilationUnitImpl) {
      unitUri = ((ExternalCompilationUnitImpl) compilationUnit).getUri();
    }
    if (unitUri == null) {
      unitUri = ((CompilationUnitImpl) compilationUnit).getSourceRef().getUri();
    }
    String unitSource = compilationUnit.getSource();
    Map<URI, String> suppliedSources = new HashMap<URI, String>();
    if (unitSource != null) {
      suppliedSources.put(unitUri, unitSource);
    }
    DartUnit ret =
        resolveUnit(library.getLibrarySourceFile(), unitUri, suppliedSources, parseErrors);

    long elapsed = System.currentTimeMillis() - start;
    Instrumentation.metric("DartCompilerUtils-resolveUnit", elapsed)
        .with("ParseOnlyFallback", "false")
        .log();

    Instrumentation.operation("DartCompilerUtils-resolveUnit", elapsed)
        .with("ParseOnlyFallback", "false")
        .with("CompilaitonUnit-ElementName", compilationUnit.getElementName())
        .with("compilationUnit.LastModified", compilationUnit.getModificationStamp())
        .log();

    return ret;
  }
 /**
  * Parse the source for the specified compilation unit. Any exceptions thrown by the {@link
  * DartParser} will be logged and a {@link DartModelException} thrown.
  *
  * @param compilationUnit the compilation unit (not <code>null</code>)
  * @param parseErrors a collection to which parse errors are appended or <code>null</code> if
  *     parse errors should be ignored
  * @return the parse result
  */
 public static DartUnit parseUnit(
     CompilationUnit compilationUnit, Collection<DartCompilationError> parseErrors)
     throws DartModelException {
   String name = compilationUnit.getElementName();
   String source = compilationUnit.getSource();
   return parseSource(name, source, parseErrors);
 }
Exemple #3
0
 /**
  * Search within the given AST node for an identifier representing a {@link DartElement Dart
  * element} in the specified source range. Return the element that was found, or <code>null</code>
  * if no element was found.
  *
  * @param node the AST node within which to search
  * @return the element that was found
  */
 public DartElement searchWithin(DartNode node) {
   try {
     node.accept(this);
   } catch (DartElementFoundException exception) {
     // A node with the right source position was found.
   } catch (Exception exception) {
     DartCore.logInformation(
         "Unable to locate element at offset ("
             + startOffset
             + " - "
             + endOffset
             + ") in "
             + compilationUnit.getElementName(),
         exception);
     return null;
   }
   return foundElement;
 }
 @Override
 public Change createChange(IProgressMonitor pm) throws CoreException {
   pm.beginTask("", 1 + occurrences.size()); // $NON-NLS-1$
   try {
     // configure Change
     {
       change = new CompilationUnitChange(unit.getElementName(), unit);
       change.setEdit(new MultiTextEdit());
       change.setKeepPreviewEdits(true);
     }
     // replace occurrences with method invocation
     for (Occurrence occurence : occurrences) {
       pm.worked(1);
       SourceRange range = occurence.range;
       // may be replacement of duplicates disabled
       if (!replaceAllOccurrences && !occurence.isSelection) {
         continue;
       }
       // prepare invocation source
       String invocationSource;
       {
         StringBuilder sb = new StringBuilder();
         // may be returns value
         if (returnVariable != null) {
           String varTypeName = ExtractUtils.getTypeSource(returnVariable.getType());
           String originalName = returnVariable.getName();
           String occurrenceName = occurence.parameterOldToOccurrenceName.get(originalName);
           if (varTypeName.equals("dynamic")) {
             sb.append("var ");
           } else {
             sb.append(varTypeName);
             sb.append(" ");
           }
           sb.append(occurrenceName);
           sb.append(" = ");
         }
         // invocation itself
         sb.append(methodName);
         sb.append("(");
         boolean firstParameter = true;
         for (ParameterInfo parameter : parameters) {
           // may be comma
           if (firstParameter) {
             firstParameter = false;
           } else {
             sb.append(", ");
           }
           // argument name
           {
             String parameterOldName = parameter.getOldName();
             String argumentName = occurence.parameterOldToOccurrenceName.get(parameterOldName);
             sb.append(argumentName);
           }
         }
         sb.append(")");
         invocationSource = sb.toString();
         // statements as extracted with their ";", so add new one after invocation
         if (selectionStatements != null) {
           invocationSource += ";";
         }
       }
       // add replace edit
       TextEdit edit = new ReplaceEdit(range.getOffset(), range.getLength(), invocationSource);
       change.addEdit(edit);
       String msg =
           Messages.format(
               occurence.isSelection
                   ? RefactoringCoreMessages.ExtractMethodRefactoring_substitute_with_call
                   : RefactoringCoreMessages.ExtractMethodRefactoring_duplicates_single,
               methodName);
       change.addTextEditGroup(new TextEditGroup(msg, edit));
     }
     // add method declaration
     {
       // prepare environment
       String prefix = utils.getNodePrefix(parentMember);
       String eol = utils.getEndOfLine();
       // prepare annotations
       String annotations = "";
       {
         // may be "static"
         if (staticContext) {
           annotations = "static ";
         }
       }
       // prepare declaration source
       String declarationSource = null;
       {
         String returnExpressionSource = getMethodBodySource();
         // expression
         if (selectionExpression != null) {
           // add return type
           String returnTypeName = ExtractUtils.getTypeSource(selectionExpression);
           if (returnTypeName != null && !returnTypeName.equals("dynamic")) {
             annotations += returnTypeName + " ";
           }
           // just return expression
           declarationSource =
               annotations + getSignature() + " => " + returnExpressionSource + ";";
         }
         // statements
         if (selectionStatements != null) {
           if (returnVariable != null) {
             String returnTypeName = ExtractUtils.getTypeSource(returnVariable.getType());
             if (returnTypeName != null && !returnTypeName.equals("dynamic")) {
               annotations += returnTypeName + " ";
             }
           } else {
             annotations += "void ";
           }
           declarationSource = annotations + getSignature() + " {" + eol;
           declarationSource += returnExpressionSource;
           if (returnVariable != null) {
             declarationSource += prefix + "  return " + returnVariable.getName() + ";" + eol;
           }
           declarationSource += prefix + "}";
         }
       }
       // insert declaration
       if (declarationSource != null) {
         int offset = parentMember.getSourceInfo().getEnd();
         TextEdit edit = new ReplaceEdit(offset, 0, eol + eol + prefix + declarationSource);
         change.addEdit(edit);
         change.addTextEditGroup(
             new TextEditGroup(
                 Messages.format(
                     selectionExpression != null
                         ? RefactoringCoreMessages.ExtractMethodRefactoring_add_method_expression
                         : RefactoringCoreMessages.ExtractMethodRefactoring_add_method,
                     methodName),
                 edit));
       }
     }
     pm.worked(1);
     // done
     return change;
   } finally {
     pm.done();
   }
 }