private void searchForDeclarations(
     SearchEngine engine,
     DartIdentifier identifier,
     SearchScope scope,
     SearchFilter filter,
     SearchListener listener,
     IProgressMonitor monitor)
     throws CoreException, SearchException {
   // Index lacks relationships required to do direct search, so first get all classes.
   String name = identifier.getName();
   boolean isProperty = identifier.getParent() instanceof DartPropertyAccess;
   SearchPattern pattern = SearchPatternFactory.createWildcardPattern("*", false);
   List<SearchMatch> allMatches = engine.searchTypeDeclarations(scope, pattern, filter, monitor);
   // Then see if the type or a child of the type matches the given name.
   // We are NOT looking for local function or local variable declarations.
   for (SearchMatch typeMatch : allMatches) {
     DartElement type = typeMatch.getElement();
     if (!isProperty) {
       if (type.getElementName().equals(name)) {
         addResult(name, type, listener);
       }
     }
     for (DartElement child : type.getChildren()) {
       if (child.getElementName().equals(name)) {
         addResult(name, child, listener);
       }
     }
   }
 }
  /*
   * Method declared in IAction.
   */
  @Override
  public final void run() {
    DartElement inputElement = EditorUtility.getEditorInputJavaElement(fEditor, false);
    if (!(inputElement instanceof SourceReference && inputElement.exists())) {
      return;
    }

    SourceReference source = (SourceReference) inputElement;
    SourceRange sourceRange;
    try {
      sourceRange = source.getSourceRange();
      if (sourceRange == null || sourceRange.getLength() == 0) {
        MessageDialog.openInformation(
            fEditor.getEditorSite().getShell(),
            SelectionActionMessages.StructureSelect_error_title,
            SelectionActionMessages.StructureSelect_error_message);
        return;
      }
    } catch (DartModelException e) {
    }
    ITextSelection selection = getTextSelection();
    SourceRange newRange = getNewSelectionRange(createSourceRange(selection), source);
    // Check if new selection differs from current selection
    if (selection.getOffset() == newRange.getOffset()
        && selection.getLength() == newRange.getLength()) {
      return;
    }
    fSelectionHistory.remember(newSourceRange(selection.getOffset(), selection.getLength()));
    try {
      fSelectionHistory.ignoreSelectionChanges();
      fEditor.selectAndReveal(newRange.getOffset(), newRange.getLength());
    } finally {
      fSelectionHistory.listenToSelectionChanges();
    }
  }
 /**
  * Possible failures:
  *
  * <ul>
  *   <li>NO_ELEMENTS_TO_PROCESS - the compilation unit supplied to the operation is <code>null
  *       </code>.
  *   <li>INVALID_NAME - no name, a name was null or not a valid name.
  *   <li>INVALID_SIBLING - the sibling provided for positioning is not valid.
  * </ul>
  */
 @Override
 public DartModelStatus verify() {
   if (getParentElement() == null) {
     return new DartModelStatusImpl(DartModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
   }
   if (anchorElement != null) {
     DartElement domPresentParent = anchorElement.getParent();
     // if (domPresentParent.getElementType() == DartElement.IMPORT_CONTAINER)
     // {
     // domPresentParent = domPresentParent.getParent();
     // }
     if (!domPresentParent.equals(getParentElement())) {
       return new DartModelStatusImpl(DartModelStatusConstants.INVALID_SIBLING, anchorElement);
     }
   }
   return DartModelStatusImpl.VERIFIED_OK;
 }
 @Override
 public MatchQuality matches(DartElement element) {
   String name = element.getElementName();
   if (name == null) {
     return null;
   }
   if (CharOperation.camelCaseMatch(pattern, name.toCharArray(), samePartCount)) {
     return MatchQuality.EXACT;
   }
   return null;
 }
  private DartProject getProject() {
    ITextEditor editor = getEditor();
    if (editor == null) {
      return null;
    }

    DartElement element = null;
    IEditorInput input = editor.getEditorInput();
    IDocumentProvider provider = editor.getDocumentProvider();
    if (provider instanceof ICompilationUnitDocumentProvider) {
      ICompilationUnitDocumentProvider cudp = (ICompilationUnitDocumentProvider) provider;
      element = cudp.getWorkingCopy(input);
    }

    if (element == null) {
      return null;
    }

    return element.getDartProject();
  }
  private void acceptPotentialMethodDeclaration(CompletionProposal proposal) {
    try {
      DartElement enclosingElement = null;
      if (getContext().isExtended()) {
        enclosingElement = getContext().getEnclosingElement();
      } else if (fCompilationUnit != null) {
        enclosingElement = fCompilationUnit.getElementAt(proposal.getCompletionLocation() + 1);
      }
      if (enclosingElement == null) {
        return;
      }
      Type type = enclosingElement.getAncestor(Type.class);
      if (type != null) {
        String prefix = String.valueOf(proposal.getName());
        int completionStart = proposal.getReplaceStart();
        int completionEnd = proposal.getReplaceEnd();
        int relevance = computeRelevance(proposal);

        GetterSetterCompletionProposal.evaluateProposals(
            type,
            prefix,
            completionStart,
            completionEnd - completionStart,
            proposal.getReplaceEndIdentifier() - completionStart,
            relevance + 2,
            fSuggestedMethodNames,
            fDartProposals);
        MethodDeclarationCompletionProposal.evaluateProposals(
            type,
            prefix,
            completionStart,
            completionEnd - completionStart,
            proposal.getReplaceEndIdentifier() - completionStart,
            relevance,
            fSuggestedMethodNames,
            fDartProposals);
      }
    } catch (CoreException e) {
      DartToolsPlugin.log(e);
    }
  }
Example #7
0
 @Override
 public Void visitIdentifier(DartIdentifier node) {
   if (foundElement == null) {
     int start = node.getSourceInfo().getOffset();
     int length = node.getSourceInfo().getLength();
     int end = start + length;
     if (start <= startOffset && endOffset <= end) {
       wordRegion = new Region(start, length);
       Element targetElement = DartAstUtilities.getElement(node, includeDeclarations);
       if (targetElement == null) {
         foundElement = null;
       } else {
         if (targetElement instanceof VariableElement) {
           VariableElement variableElement = (VariableElement) targetElement;
           resolvedElement = variableElement;
           if (variableElement.getKind() == ElementKind.PARAMETER
               || variableElement.getKind() == ElementKind.VARIABLE) {
             foundElement =
                 BindingUtils.getDartElement(compilationUnit.getLibrary(), variableElement);
             candidateRegion =
                 new Region(
                     variableElement.getNameLocation().getOffset(),
                     variableElement.getNameLocation().getLength());
           } else {
             foundElement = null;
           }
         } else {
           findElementFor(targetElement);
           // Import prefix is resolved into LibraryElement, so it is correct that corresponding
           // DartElement is DartLibrary, but this is not what we (and user) wants, because
           // it looses information. We want DartImport, it gives both DartLibrary and name.
           if (foundElement instanceof DartLibrary) {
             try {
               DartImport[] imports = compilationUnit.getLibrary().getImports();
               for (DartImport imprt : imports) {
                 if (Objects.equal(imprt.getLibrary(), foundElement)
                     && Objects.equal(imprt.getPrefix(), node.getName())) {
                   foundElement = imprt;
                   SourceRange range = imprt.getNameRange();
                   candidateRegion = new Region(range.getOffset(), range.getLength());
                 }
               }
             } catch (DartModelException e) {
               DartCore.logError("Cannot resolve import " + foundElement.getElementName(), e);
             }
           }
         }
       }
       throw new DartElementFoundException();
     }
   }
   return null;
 }
 private void searchForReferences(
     SearchEngine engine,
     DartElement element,
     SearchScope scope,
     SearchFilter filter,
     SearchListener collector,
     IProgressMonitor monitor)
     throws SearchException {
   switch (element.getElementType()) {
     case DartElement.METHOD:
       engine.searchReferences((Method) element, scope, filter, collector, monitor);
       break;
     case DartElement.CLASS_TYPE_ALIAS:
       engine.searchReferences((DartClassTypeAlias) element, scope, filter, collector, monitor);
       break;
     case DartElement.FUNCTION_TYPE_ALIAS:
       engine.searchReferences((DartFunctionTypeAlias) element, scope, filter, collector, monitor);
       break;
     case DartElement.FIELD:
       engine.searchReferences((Field) element, scope, filter, collector, monitor);
       break;
     case DartElement.FUNCTION:
       engine.searchReferences((DartFunction) element, scope, filter, collector, monitor);
       break;
     case DartElement.TYPE:
       engine.searchReferences((Type) element, scope, filter, collector, monitor);
       break;
     case DartElement.IMPORT:
       engine.searchReferences((DartImport) element, scope, filter, collector, monitor);
       break;
     case DartElement.VARIABLE:
       engine.searchReferences(
           (DartVariableDeclaration) element, scope, filter, collector, monitor);
       break;
     default:
       throw new UnsupportedOperationException(
           "unsupported search type: " + element.getClass()); // $NON-NLS-1$
   }
 }
 private void searchForDeclarations(
     SearchEngine engine,
     DartElement element,
     SearchScope scope,
     SearchFilter filter,
     SearchResultCollector listener,
     IProgressMonitor monitor)
     throws CoreException, SearchException {
   switch (element.getElementType()) {
     case DartElement.CLASS_TYPE_ALIAS:
     case DartElement.FUNCTION_TYPE_ALIAS:
     case DartElement.FUNCTION:
     case DartElement.IMPORT:
     case DartElement.TYPE:
     case DartElement.TYPE_PARAMETER:
     case DartElement.VARIABLE:
       {
         SourceRange range = ((SourceReference) element).getSourceRange();
         SearchMatch match = new SearchMatch(MatchQuality.EXACT, element, range);
         if (filter == null || filter.passes(match)) {
           listener.matchFound(match);
         }
         break;
       }
     case DartElement.FIELD:
     case DartElement.METHOD:
       {
         // There's no way to tell which hierarchy an untyped reference might refer to, so find all
         // declarations.
         DartIdentifier identifier = new DartIdentifier(element.getElementName());
         searchForDeclarations(engine, identifier, scope, filter, listener, monitor);
         break;
       }
     default:
       throw new UnsupportedOperationException(
           "unsupported search type: " + element.getClass()); // $NON-NLS-1$
   }
 }
Example #10
0
 private void searchForOverrides(
     SearchEngine engine,
     DartElement element,
     SearchScope scope,
     SearchFilter filter,
     SearchResultCollector listener,
     IProgressMonitor monitor)
     throws CoreException {
   switch (element.getElementType()) {
     case DartElement.CLASS_TYPE_ALIAS:
     case DartElement.FUNCTION_TYPE_ALIAS:
     case DartElement.FUNCTION:
     case DartElement.FIELD:
     case DartElement.IMPORT:
     case DartElement.TYPE:
     case DartElement.TYPE_PARAMETER:
     case DartElement.VARIABLE:
       {
         break;
       }
     case DartElement.METHOD:
       {
         MemberDeclarationsReferences memberInfo;
         memberInfo = RenameAnalyzeUtil.findDeclarationsReferences((Method) element, monitor);
         for (TypeMember member : memberInfo.declarations) {
           SearchMatch match =
               new SearchMatch(MatchQuality.EXACT, member, member.getSourceRange());
           listener.matchFound(match);
         }
         break;
       }
     default:
       throw new UnsupportedOperationException(
           "unsupported search type: " + element.getClass()); // $NON-NLS-1$
   }
 }
Example #11
0
 private void addResult(String name, DartElement element, SearchListener listener)
     throws DartModelException {
   SourceRange range = null;
   switch (element.getElementType()) {
     case DartElement.FIELD:
     case DartElement.METHOD:
       SourceReference method = (SourceReference) element;
       range = method.getNameRange();
       break;
     default:
       return;
   }
   SearchMatch match = new SearchMatch(MatchQuality.EXACT, element, range);
   listener.matchFound(match);
 }
Example #12
0
  /** Map from the source language to the target language (Dart to Javascript). */
  public SourceLocation mapDartToJavascript(IFile file, int line) {
    // given the file, find the dart element
    DartElement dartElement = DartCore.create(file);

    if (dartElement == null) {
      return SourceLocation.UNKNOWN_LOCATION;
    }

    // given that, find the dart application / library
    DartLibraryImpl dartLibrary = (DartLibraryImpl) dartElement.getAncestor(DartLibrary.class);

    if (dartLibrary == null) {
      return SourceLocation.UNKNOWN_LOCATION;
    }

    try {
      // [out/DartAppFileName.app.js.map]

      IPath outputLocation = getMainDartProject().getOutputLocation();

      List<LibraryConfigurationFileImpl> libraryConfigurationFiles =
          dartLibrary.getChildrenOfType(LibraryConfigurationFileImpl.class);

      //      if (libraryConfigurationFiles.size() > 0) {
      //        String libraryName = libraryConfigurationFiles.get(0).getFile().getName();
      //
      //        IPath sourceMapPath = outputLocation.append(libraryName + ".js.map");
      //
      //        SourceMapping mapping = getCachedSourceMappingPath(sourceMapPath);
      //
      //        if (mapping != null && mapping instanceof SourceMappingReversable) {
      //          SourceMappingReversable revMapping = (SourceMappingReversable) mapping;
      //
      //          String sourcePath = findMatchingSourcePath(file, revMapping);
      //
      //          if (sourcePath != null) {
      //            Collection<OriginalMapping> mappings = revMapping.getReverseMapping(sourcePath,
      // line, 1);
      //
      //            // TODO(devoncarew): We need to handle the case where there are more then one
      // mappings
      //            // returned; this will probably involve setting one breakpoint per mapping. More
      // then
      //            // one mapping ==> something like a function that's been inlined into multiple
      // places.
      //            if (mappings.size() > 0) {
      //              OriginalMapping map = mappings.iterator().next();
      //
      //              String fileName = map.getOriginalFile();
      //              int lineNumber = map.getLineNumber();
      //
      //              return new SourceLocation(new Path(fileName), lineNumber);
      //            }
      //          }
      //        }
      //      }
    } catch (DartModelException exception) {
      DartCore.logError(exception);
    }

    return SourceLocation.UNKNOWN_LOCATION;
  }
Example #13
0
  private RenameSupport undoAndCreateRenameSupport(String newName) throws CoreException {
    // Assumption: the linked mode model should be shut down by now.

    final ISourceViewer viewer = fEditor.getViewer();

    try {
      if (!fOriginalName.equals(newName)) {
        fEditor
            .getSite()
            .getWorkbenchWindow()
            .run(
                false,
                true,
                new IRunnableWithProgress() {
                  @Override
                  public void run(IProgressMonitor monitor)
                      throws InvocationTargetException, InterruptedException {
                    if (viewer instanceof ITextViewerExtension6) {
                      IUndoManager undoManager = ((ITextViewerExtension6) viewer).getUndoManager();
                      if (undoManager instanceof IUndoManagerExtension) {
                        IUndoManagerExtension undoManagerExtension =
                            (IUndoManagerExtension) undoManager;
                        IUndoContext undoContext = undoManagerExtension.getUndoContext();
                        IOperationHistory operationHistory =
                            OperationHistoryFactory.getOperationHistory();
                        while (undoManager.undoable()) {
                          if (fStartingUndoOperation != null
                              && fStartingUndoOperation.equals(
                                  operationHistory.getUndoOperation(undoContext))) {
                            return;
                          }
                          undoManager.undo();
                        }
                      }
                    }
                  }
                });
      }
    } catch (InvocationTargetException e) {
      throw new CoreException(
          new Status(
              IStatus.ERROR,
              DartToolsPlugin.getPluginId(),
              ReorgMessages.RenameLinkedMode_error_saving_editor,
              e));
    } catch (InterruptedException e) {
      // canceling is OK
      return null;
    } finally {
      DartModelUtil.reconcile(getCompilationUnit());
    }

    viewer.setSelectedRange(fOriginalSelection.x, fOriginalSelection.y);

    if (newName.length() == 0) {
      return null;
    }

    switch (fDartElement.getElementType()) {
      case DartElement.FUNCTION:
        return RenameSupport.create((DartFunction) fDartElement, newName);
      case DartElement.FUNCTION_TYPE_ALIAS:
        return RenameSupport.create((DartFunctionTypeAlias) fDartElement, newName);
      case DartElement.TYPE:
        return RenameSupport.create((Type) fDartElement, newName);
      case DartElement.TYPE_PARAMETER:
        return RenameSupport.create((DartTypeParameter) fDartElement, newName);
      case DartElement.FIELD:
        return RenameSupport.create((Field) fDartElement, newName);
      case DartElement.METHOD:
        return RenameSupport.create((Method) fDartElement, newName);
      case DartElement.VARIABLE:
        return RenameSupport.create((DartVariableDeclaration) fDartElement, newName);
      default:
        return null;
    }
  }
Example #14
0
  @Override
  public IStatus run(IProgressMonitor monitor) {
    final DartSearchResult textResult = (DartSearchResult) getSearchResult();
    textResult.removeAll();
    SearchEngine engine = SearchEngineFactory.createSearchEngine();

    //  try {
    //  int totalTicks= 1000;
    // TODO (pquitslund): add search participant support
    //  IProject[] projects=
    // JavaSearchScopeFactory.getInstance().getProjects(fPatternData.getScope());
    //  final SearchParticipantRecord[] participantDescriptors=
    // SearchParticipantsExtensionPoint.getInstance().getSearchParticipants(projects);
    //  final int[] ticks= new int[participantDescriptors.length];
    //  for (int i= 0; i < participantDescriptors.length; i++) {
    //    final int iPrime= i;
    //    ISafeRunnable runnable= new ISafeRunnable() {
    //      public void handleException(Throwable exception) {
    //        ticks[iPrime]= 0;
    //        String message= SearchMessages.JavaSearchQuery_error_participant_estimate;
    //        DartToolsPlugin.log(new Status(IStatus.ERROR, DartToolsPlugin.getPluginId(), 0,
    // message, exception));
    //      }
    //
    //      public void run() throws Exception {
    //        ticks[iPrime]=
    // participantDescriptors[iPrime].getParticipant().estimateTicks(fPatternData);
    //      }
    //    };
    //
    //    SafeRunner.run(runnable);
    //    totalTicks+= ticks[i];
    //  }

    SearchResultCollector collector = new SearchResultCollector(textResult);
    SearchScope scope = patternData.getScope();

    if (patternData.hasElement()) {
      DartElement element = ((ElementQuerySpecification) patternData).getElement();
      if (!element.exists()) {
        String patternString =
            DartElementLabels.getElementLabel(element, DartElementLabels.ALL_DEFAULT);
        return new Status(
            IStatus.ERROR,
            DartToolsPlugin.getPluginId(),
            0,
            Messages.format(
                SearchMessages.DartSearchQuery_error_element_does_not_exist, patternString),
            null);
      }

      try {
        if (patternData.isReferencesSearch()) {
          searchForReferences(engine, element, scope, null, collector, monitor);
        }
        if (patternData.isDeclarationsSearch()) {
          searchForDeclarations(engine, element, scope, null, collector, monitor);
        }
        if (patternData.isOverridesSearch()) {
          searchForOverrides(engine, element, scope, null, collector, monitor);
        }
      } catch (SearchException e) {
        DartToolsPlugin.log(e);
        // TODO: do we need to update the UI as well? Or schedule another search?
      } catch (CoreException ex) {
        DartToolsPlugin.log(ex);
      }

    } else if (patternData.hasNode()) {

      DartNode node = ((NodeQuerySpecification) patternData).getNode();
      if (node instanceof DartIdentifier) {
        DartIdentifier id = (DartIdentifier) node;

        try {
          if (patternData.isReferencesSearch()) {
            searchForReferences(engine, id, scope, null, collector, monitor);
          }
          if (patternData.isDeclarationsSearch()) {
            searchForDeclarations(engine, id, scope, null, collector, monitor);
          }
        } catch (SearchException e) {
          DartToolsPlugin.log(e);
        } catch (CoreException ex) {
          DartToolsPlugin.log(ex);
        }
      }
    }

    //      engine.search(pattern, new SearchParticipant[] {
    // SearchEngine.getDefaultSearchParticipant() }, fPatternData.getScope(), collector,
    // mainSearchPM);
    // TODO (pquitslund): add search participant support
    //      for (int i= 0; i < participantDescriptors.length; i++) {
    //        final ISearchRequestor requestor= new
    // SearchRequestor(participantDescriptors[i].getParticipant(), textResult);
    //        final IProgressMonitor participantPM= new SubProgressMonitor(monitor, ticks[i]);
    //
    //        final int iPrime= i;
    //        ISafeRunnable runnable= new ISafeRunnable() {
    //          public void handleException(Throwable exception) {
    //            participantDescriptors[iPrime].getDescriptor().disable();
    //            String message= SearchMessages.JavaSearchQuery_error_participant_search;
    //            DartToolsPlugin.log(new Status(IStatus.ERROR, DartToolsPlugin.getPluginId(), 0,
    // message, exception));
    //          }
    //
    //          public void run() throws Exception {
    //
    //            final IQueryParticipant participant=
    // participantDescriptors[iPrime].getParticipant();
    //            final PerformanceStats stats= PerformanceStats.getStats(PERF_SEARCH_PARTICIPANT,
    // participant);
    //            stats.startRun();
    //
    //            participant.search(requestor, fPatternData, participantPM);
    //
    //            stats.endRun();
    //          }
    //        };

    //        SafeRunner.run(runnable);
    //      }

    //    } catch (CoreException e) {
    //      return e.getStatus();
    //    }

    String message =
        Messages.format(
            SearchMessages.DartSearchQuery_status_ok_message,
            String.valueOf(textResult.getMatchCount()));
    return new Status(IStatus.OK, DartToolsPlugin.getPluginId(), 0, message, null);
  }