@Override
 public String resolve(TemplateContext context) {
   ITranslationUnit unit = ((TranslationUnitContext) context).getTranslationUnit();
   return (unit == null)
       ? null
       : new Path(unit.getElementName()).removeFileExtension().lastSegment();
 }
  /**
   * Creates the text change for this proposal. This method is only called once and only when no
   * text change has been passed in {@link #TUCorrectionProposal(String, ITranslationUnit,
   * TextChange, int, Image)}.
   *
   * @return returns the created text change.
   * @throws CoreException thrown if the creation of the text change failed.
   */
  protected TextChange createTextChange() throws CoreException {
    ITranslationUnit tu = getTranslationUnit();
    String name = getName();
    TextChange change;
    if (!tu.getResource().exists()) {
      String source;
      try {
        source = tu.getSource();
      } catch (CModelException e) {
        CUIPlugin.log(e);
        source = ""; // $NON-NLS-1$
      }
      Document document = new Document(source);
      document.setInitialLineDelimiter(StubUtility.getLineDelimiterUsed(tu));
      change = new DocumentChange(name, document);
    } else {
      CTextFileChange tuChange = new CTextFileChange(name, tu);
      tuChange.setSaveMode(TextFileChange.LEAVE_DIRTY);
      change = tuChange;
    }
    TextEdit rootEdit = new MultiTextEdit();
    change.setEdit(rootEdit);

    // Initialize text change.
    IDocument document = change.getCurrentDocument(new NullProgressMonitor());
    addEdits(document, rootEdit);
    return change;
  }
 @Override
 public void apply(IDocument document) {
   try {
     ITranslationUnit unit = getTranslationUnit();
     IEditorPart part = null;
     if (unit.getResource().exists()) {
       boolean canEdit = performValidateEdit(unit);
       if (!canEdit) {
         return;
       }
       part = EditorUtility.isOpenInEditor(unit);
       if (part == null) {
         part = EditorUtility.openInEditor(unit);
         if (part != null) {
           document =
               CUIPlugin.getDefault().getDocumentProvider().getDocument(part.getEditorInput());
         }
       }
       IWorkbenchPage page = CUIPlugin.getActivePage();
       if (page != null && part != null) {
         page.bringToTop(part);
       }
       if (part != null) {
         part.setFocus();
       }
     }
     performChange(part, document);
   } catch (CoreException e) {
     ExceptionHandler.handle(
         e,
         CorrectionMessages.TUCorrectionProposal_error_title,
         CorrectionMessages.TUCorrectionProposal_error_message);
   }
 }
 /**
  * Runs an artifact analysis for the given file by searching the given extension point for an
  * {@link IArtifactAnalysis} that matches its language ID.
  *
  * <p>This is a utility method generally invoked from {@link #doArtifactAnalysis(ITranslationUnit,
  * List)}.
  *
  * <p>It is assumed that only one extension will be contributed per language ID. If multiple
  * extensions are found, it is unspecified which one will be run.
  *
  * @param extensionPointID
  * @param tu
  * @param includes
  * @param allowPrefixOnlyMatch
  * @return {@link ScanReturn}
  * @since 6.0
  */
 protected ScanReturn runArtifactAnalysisFromExtensionPoint(
     String extensionPointID,
     final ITranslationUnit tu,
     final List<String> includes,
     final boolean allowPrefixOnlyMatch) {
   try {
     final String languageID = tu.getLanguage().getId();
     for (IConfigurationElement config :
         Platform.getExtensionRegistry().getConfigurationElementsFor(extensionPointID)) {
       try {
         if (languageID.equals(config.getAttribute("languageID"))) {
           IArtifactAnalysis artifactAnalysis =
               (IArtifactAnalysis) config.createExecutableExtension("class"); // $NON-NLS-1$
           return artifactAnalysis.runArtifactAnalysis(
               languageID, tu, includes, allowPrefixOnlyMatch);
         }
       } catch (CoreException e) {
         CommonPlugin.log(e.getClass().getSimpleName() + ": " + e.getMessage());
       }
     }
   } catch (CoreException e) {
     e.printStackTrace();
     CommonPlugin.log(
         IStatus.ERROR,
         "RunAnalyseMPICommandHandler: Error setting up analysis for project "
             + tu.getCProject()
             + " error="
             + e.getMessage()); // $NON-NLS-1$ //$NON-NLS-2$
   }
   return new ScanReturn();
 }
 private String getFunctionName(IFunction function) {
   String functionName = function.getElementName();
   StringBuffer name = new StringBuffer(functionName);
   ITranslationUnit tu = function.getTranslationUnit();
   if (tu != null && tu.isCXXLanguage()) {
     appendParameters(name, function);
   }
   return name.toString();
 }
 protected String getSourceHandle(IDeclaration declaration) {
   ITranslationUnit tu = declaration.getTranslationUnit();
   if (tu != null) {
     IPath location = tu.getLocation();
     if (location != null) {
       return location.toOSString();
     }
   }
   return ""; //$NON-NLS-1$
 }
    @Override
    protected String resolve(TemplateContext context) {
      TranslationUnitContext cContext = (TranslationUnitContext) context;
      ITranslationUnit tUnit = cContext.getTranslationUnit();
      if (tUnit == null) return "XXX"; // $NON-NLS-1$

      ICProject cProject = tUnit.getCProject();
      String todoTaskTag = StubUtility.getTodoTaskTag(cProject);
      if (todoTaskTag == null) return "XXX"; // $NON-NLS-1$

      return todoTaskTag;
    }
  IStatus performNavigation(IProgressMonitor monitor) throws CoreException {
    fAction.clearStatusLine();

    assert fIndex == null;
    if (fIndex != null) return Status.CANCEL_STATUS;

    fMonitor = monitor;
    fIndex =
        CCorePlugin.getIndexManager()
            .getIndex(
                fTranslationUnit.getCProject(),
                IIndexManager.ADD_DEPENDENCIES | IIndexManager.ADD_DEPENDENT);

    try {
      fIndex.acquireReadLock();
    } catch (InterruptedException e) {
      return Status.CANCEL_STATUS;
    }

    try {
      return ASTProvider.getASTProvider()
          .runOnAST(fTranslationUnit, ASTProvider.WAIT_ACTIVE_ONLY, monitor, this);
    } finally {
      fIndex.releaseReadLock();
    }
  }
  /**
   * Called after CEditor contents is changed. Existing elements can change their offset and length.
   *
   * @param sdata delta information
   */
  public void contentShift(CShiftData sdata) {
    try {
      ICElement[] el = root.getChildren();
      for (int i = 0; i < el.length; i++) {
        if (!(el[i] instanceof SourceManipulation)) continue;

        SourceManipulation sm = (SourceManipulation) el[i];
        ISourceRange src = sm.getSourceRange();
        int endOffset = src.getStartPos() + src.getLength();

        // code BELOW this element changed - do nothing !
        if (sdata.getOffset() > endOffset) {
          continue;
        }

        if (sdata.getOffset() < src.getStartPos()) {
          // code ABOVE this element changed - modify offset
          sm.setIdPos(src.getIdStartPos() + sdata.getSize(), src.getIdLength());
          sm.setPos(src.getStartPos() + sdata.getSize(), src.getLength());
          sm.setLines(src.getStartLine() + sdata.getLines(), src.getEndLine() + sdata.getLines());
        } else {
          // code INSIDE of this element changed - modify length
          sm.setPos(src.getStartPos(), src.getLength() + sdata.getSize());
          sm.setLines(src.getStartLine(), src.getEndLine() + sdata.getLines());
        }
      }
    } catch (CModelException e) {
    }
  }
 /** @see org.eclipse.cdt.internal.ui.BaseCElementContentProvider#getChildren(java.lang.Object) */
 @Override
 public Object[] getChildren(Object element) {
   Object[] children = null;
   // Use the deferred manager for the first time (when parsing)
   if (element instanceof ITranslationUnit) {
     ITranslationUnit unit = (ITranslationUnit) element;
     if (!unit.isOpen()) {
       fInitialDeltaPending = true;
       children = new Object[] {new PendingUpdateAdapter()};
     }
   }
   if (children == null) {
     children = super.getChildren(element);
   }
   return children;
 }
Exemple #11
0
  private void processDelta(ICElementDelta delta, Set<IResource> handled) throws CoreException {
    final int flags = delta.getFlags();

    final boolean hasChildren = (flags & ICElementDelta.F_CHILDREN) != 0;
    if (hasChildren) {
      for (ICElementDelta child : delta.getAffectedChildren()) {
        processDelta(child, handled);
      }
    }

    final ICElement element = delta.getElement();
    switch (element.getElementType()) {
      case ICElement.C_UNIT:
        ITranslationUnit tu = (ITranslationUnit) element;
        if (!tu.isWorkingCopy()) {
          handled.add(element.getResource());
          switch (delta.getKind()) {
            case ICElementDelta.CHANGED:
              if ((flags & ICElementDelta.F_CONTENT) != 0) {
                fChanged.add(tu);
              }
              break;
            case ICElementDelta.ADDED:
              fChanged.add(tu);
              break;
            case ICElementDelta.REMOVED:
              fRemoved.add(tu);
              break;
          }
        }
        break;
      case ICElement.C_CCONTAINER:
        ICContainer folder = (ICContainer) element;
        if (delta.getKind() == ICElementDelta.ADDED) {
          handled.add(element.getResource());
          collectSources(folder, fChanged);
        }
        break;
    }

    if (!sSuppressPotentialTUs) {
      // Always look at the children of the resource delta (bug 343538)
      final IResourceDelta[] rDeltas = delta.getResourceDeltas();
      processResourceDelta(rDeltas, element, handled);
    }
  }
 private String getLocationSignature(ISourceReference elem) {
   ITranslationUnit tu = elem.getTranslationUnit();
   ISourceRange sourceRange;
   try {
     sourceRange = elem.getSourceRange();
     if (tu != null && sourceRange != null) {
       return tu.getPath().toString()
           + IPath.SEPARATOR
           + sourceRange.getIdStartPos()
           + IPath.SEPARATOR
           + sourceRange.getIdLength();
     }
   } catch (CoreException e) {
     CUIPlugin.log(e);
   }
   return null;
 }
 private boolean performValidateEdit(ITranslationUnit unit) {
   IStatus status =
       Resources.makeCommittable(unit.getResource(), CUIPlugin.getActiveWorkbenchShell());
   if (!status.isOK()) {
     String label = CorrectionMessages.TUCorrectionProposal_error_title;
     String message = CorrectionMessages.TUCorrectionProposal_error_message;
     ErrorDialog.openError(CUIPlugin.getActiveWorkbenchShell(), label, message, status);
     return false;
   }
   return true;
 }
Exemple #14
0
 @Override
 protected void processTranslationUnitUnlocked(ITranslationUnit tu) {
   try {
     index = CCorePlugin.getIndexManager().getIndex(tu.getCProject());
     // lock the index for read access
     index.acquireReadLock();
     try {
       // traverse the translation unit using the visitor pattern.
       this.file = tu.getFile();
       processUnit(tu);
     } finally {
       this.file = null;
       index.releaseReadLock();
     }
   } catch (CoreException e) {
     CodanCorePlugin.log(e);
   } catch (InterruptedException e) {
     // ignore
   }
 }
  @Override
  public Object execute(ExecutionEvent event) throws ExecutionException {
    ISelection selection = HandlerUtil.getCurrentSelection(event);

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

    if (selection instanceof IStructuredSelection) {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      PrintStream ps = new PrintStream(baos);

      Iterator<?> iter = ((IStructuredSelection) selection).iterator();
      while (iter.hasNext()) {
        Object obj = iter.next();
        if (obj instanceof Executable) {
          Executable exe = (Executable) obj;
          ps.println(exe.getName());
        } else if (obj instanceof ITranslationUnit) {
          ITranslationUnit tu = (ITranslationUnit) obj;
          ps.println(tu.getLocation().toFile().getName());
        } else ps.println(obj.toString());
      }
      ps.flush();
      try {
        baos.flush();
      } catch (IOException e) {
        throw new ExecutionException("", e); // $NON-NLS-1$
      }
      Clipboard cp = getClipboard();
      cp.setContents(
          new Object[] {baos.toString().trim()}, new Transfer[] {TextTransfer.getInstance()});
    }

    return null;
  }
 /**
  * Returns the best file for the given location, linkage, and translation unit. May return {@code
  * null}, if no such file exists.
  *
  * <p>The "best" file (variant) is the one with the most content, as measured by the total number
  * of macros defined in the file. The rationale is that often one of the variants will contain
  * most of the code and the others just small pieces, and we are usually interested in the one
  * with most of the code. As a tiebreaker, a variant that was parsed in the context of a source
  * file is preferred, since a header parsed outside of the context of a code file may not
  * represent code that a compiler actually sees.
  *
  * @param linkageID the id of the linkage in which the file has been parsed.
  * @param location the IIndexFileLocation representing the location of the file
  * @param tu the translation unit from which 'location' originates
  * @return the best file for the location, or {@code null} if the file is not present in the index
  * @throws CoreException
  */
 private PDOMFile getBestFile(int linkageID, IIndexFileLocation location, ITranslationUnit tu)
     throws CoreException {
   IIndexFile[] files = getFiles(linkageID, location);
   IIndexFile best = null;
   int bestScore = -1;
   for (IIndexFile file : files) {
     int score = file.getMacros().length * 2;
     if (tu != null
         && TranslationUnit.isSourceFile(
             TranslationUnit.getParsedInContext(file), tu.getCProject().getProject())) score++;
     if (score > bestScore) {
       bestScore = score;
       best = file;
     }
   }
   return (PDOMFile) best;
 }
 /**
  * Returns the C model element at the given selection.
  *
  * @param part Workbench part where the selection is.
  * @param selection Selection in part.
  * @return C model element if found.
  */
 protected ICElement getCElementFromSelection(IWorkbenchPart part, ISelection selection) {
   if (selection instanceof ITextSelection) {
     ITextSelection textSelection = (ITextSelection) selection;
     String text = textSelection.getText();
     if (text != null) {
       if (part instanceof ITextEditor) {
         ICElement editorElement =
             CDTUITools.getEditorInputCElement(((ITextEditor) part).getEditorInput());
         if (editorElement instanceof ITranslationUnit) {
           ITranslationUnit tu = (ITranslationUnit) editorElement;
           try {
             if (tu.isStructureKnown() && tu.isConsistent()) {
               return tu.getElementAtOffset(textSelection.getOffset());
             }
           } catch (CModelException exc) {
             // ignored on purpose
           }
         }
       } else {
         IResource resource = getResource(part);
         if (resource instanceof IFile) {
           ITranslationUnit tu = getTranslationUnit((IFile) resource);
           if (tu != null) {
             try {
               ICElement element = tu.getElement(text.trim());
               if (element == null) {
                 element = tu.getElementAtLine(textSelection.getStartLine());
               }
               return element;
             } catch (CModelException e) {
             }
           }
         }
       }
     }
   } else if (selection instanceof IStructuredSelection) {
     IStructuredSelection ss = (IStructuredSelection) selection;
     if (ss.size() == 1) {
       Object object = ss.getFirstElement();
       if (object instanceof ICElement) {
         return (ICElement) object;
       }
     }
   }
   return null;
 }
 @Override
 public void modifyAST(IIndex index, IMarker marker) {
   CompositeChange c = new CompositeChange(Messages.QuickFixCreateParameter_0);
   try {
     ITranslationUnit baseTU = getTranslationUnitViaEditor(marker);
     IASTTranslationUnit baseAST = baseTU.getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS);
     IASTName astName = getASTNameFromMarker(marker, baseAST);
     if (astName == null) {
       return;
     }
     IASTDeclaration declaration =
         CxxAstUtils.createDeclaration(astName, baseAST.getASTNodeFactory(), index);
     // We'll need a FunctionParameterDeclaration later
     final IASTDeclSpecifier finalDeclSpec = (IASTDeclSpecifier) declaration.getChildren()[0];
     final IASTDeclarator finalDeclarator = (IASTDeclarator) declaration.getChildren()[1];
     IASTFunctionDefinition function = CxxAstUtils.getEnclosingFunction(astName);
     if (function == null) {
       return;
     }
     // Find the function declarations
     NameFinderVisitor nameFinderVisitor = new NameFinderVisitor();
     function.accept(nameFinderVisitor);
     IASTName funcName = nameFinderVisitor.name;
     IBinding binding = funcName.resolveBinding();
     IIndexName[] declarations = index.findNames(binding, IIndex.FIND_DECLARATIONS_DEFINITIONS);
     if (declarations.length == 0) {
       return;
     }
     HashMap<ITranslationUnit, IASTTranslationUnit> cachedASTs =
         new HashMap<ITranslationUnit, IASTTranslationUnit>();
     HashMap<ITranslationUnit, ASTRewrite> cachedRewrites =
         new HashMap<ITranslationUnit, ASTRewrite>();
     for (IIndexName iname : declarations) {
       ITranslationUnit declTU = CxxAstUtils.getTranslationUnitFromIndexName(iname);
       if (declTU == null) {
         continue;
       }
       ASTRewrite rewrite;
       IASTTranslationUnit declAST;
       if (!cachedASTs.containsKey(declTU)) {
         declAST = declTU.getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS);
         rewrite = ASTRewrite.create(declAST);
         cachedASTs.put(declTU, declAST);
         cachedRewrites.put(declTU, rewrite);
       } else {
         declAST = cachedASTs.get(declTU);
         rewrite = cachedRewrites.get(declTU);
       }
       IASTFileLocation fileLocation = iname.getFileLocation();
       IASTName declName =
           declAST
               .getNodeSelector(null)
               .findEnclosingName(fileLocation.getNodeOffset(), fileLocation.getNodeLength());
       if (declName == null) {
         continue;
       }
       INodeFactory factory = declAST.getASTNodeFactory();
       IASTFunctionDeclarator functionDecl;
       {
         IASTNode n = declName;
         while (n instanceof IASTName) {
           n = n.getParent();
         }
         functionDecl = (IASTFunctionDeclarator) n;
       }
       IASTParameterDeclaration newParam =
           factory.newParameterDeclaration(finalDeclSpec, finalDeclarator);
       rewrite.insertBefore(functionDecl, null, newParam, null);
     }
     for (ASTRewrite rewrite : cachedRewrites.values()) {
       c.add(rewrite.rewriteAST());
     }
     c.perform(new NullProgressMonitor());
   } catch (CoreException e) {
     CheckersUiActivator.log(e);
   }
 }
  private boolean navigationFallBack(IASTTranslationUnit ast, IASTName sourceName, NameKind kind) {
    // Bug 102643, as a fall-back we look up the selected word in the index.
    if (fSelectedText != null && fSelectedText.length() > 0) {
      try {
        final ICProject project = fTranslationUnit.getCProject();
        final char[] name = fSelectedText.toCharArray();
        List<ICElement> elems = new ArrayList<ICElement>();

        // Bug 252549, search for names in the AST first.
        Set<IBinding> primaryBindings = new HashSet<IBinding>();
        ASTNameCollector nc = new ASTNameCollector(fSelectedText);
        ast.accept(nc);
        IASTName[] candidates = nc.getNames();
        for (IASTName astName : candidates) {
          try {
            IBinding b = astName.resolveBinding();
            if (b != null && !(b instanceof IProblemBinding)) {
              primaryBindings.add(b);
            }
          } catch (RuntimeException e) {
            CUIPlugin.log(e);
          }
        }

        // Search the index, also.
        final IndexFilter filter =
            IndexFilter.getDeclaredBindingFilter(ast.getLinkage().getLinkageID(), false);
        final IIndexBinding[] idxBindings = fIndex.findBindings(name, false, filter, fMonitor);
        for (IIndexBinding idxBinding : idxBindings) {
          primaryBindings.add(idxBinding);
        }

        // Search for a macro in the index.
        IIndexMacro[] macros = fIndex.findMacros(name, filter, fMonitor);
        for (IIndexMacro macro : macros) {
          ICElement elem = IndexUI.getCElementForMacro(project, fIndex, macro);
          if (elem != null) {
            elems.add(elem);
          }
        }

        Collection<IBinding> secondaryBindings;
        if (ast instanceof ICPPASTTranslationUnit) {
          secondaryBindings = cppRemoveSecondaryBindings(primaryBindings, sourceName);
        } else {
          secondaryBindings = defaultRemoveSecondaryBindings(primaryBindings, sourceName);
        }

        // Convert bindings to CElements.
        Collection<IBinding> bs = primaryBindings;
        for (int k = 0; k < 2; k++) {
          for (IBinding binding : bs) {
            IName[] names = findNames(fIndex, ast, kind, binding);
            // Exclude names of the same kind.
            for (int i = 0; i < names.length; i++) {
              if (getNameKind(names[i]) == kind) {
                names[i] = null;
              }
            }
            names = (IName[]) ArrayUtil.removeNulls(IName.class, names);
            convertToCElements(project, fIndex, names, elems);
          }
          // In case we did not find anything, consider the secondary bindings.
          if (!elems.isEmpty()) break;
          bs = secondaryBindings;
        }
        if (navigateCElements(elems)) {
          return true;
        }
        if (sourceName != null && sourceName.isDeclaration()) {
          // Select the name at the current location as the last resort.
          return navigateToName(sourceName);
        }
      } catch (CoreException e) {
        CUIPlugin.log(e);
      }
    }
    return false;
  }
 @Override
 public String resolve(TemplateContext context) {
   ITranslationUnit unit = ((TranslationUnitContext) context).getTranslationUnit();
   return (unit == null) ? null : unit.getElementName();
 }
  public IStatus runOnAST(ILanguage lang, IASTTranslationUnit ast) throws CoreException {
    if (ast == null) {
      return Status.OK_STATUS;
    }
    int selectionStart = fTextSelection.getOffset();
    int selectionLength = fTextSelection.getLength();

    final IASTNodeSelector nodeSelector = ast.getNodeSelector(null);

    IASTName sourceName = nodeSelector.findEnclosingName(selectionStart, selectionLength);
    IName[] implicitTargets =
        findImplicitTargets(ast, nodeSelector, selectionStart, selectionLength);
    if (sourceName == null) {
      if (implicitTargets.length > 0) {
        if (navigateViaCElements(fTranslationUnit.getCProject(), fIndex, implicitTargets))
          return Status.OK_STATUS;
      }
    } else {
      boolean found = false;
      final IASTNode parent = sourceName.getParent();
      if (parent instanceof IASTPreprocessorIncludeStatement) {
        openInclude(((IASTPreprocessorIncludeStatement) parent));
        return Status.OK_STATUS;
      }
      NameKind kind = getNameKind(sourceName);
      IBinding b = sourceName.resolveBinding();
      IBinding[] bindings = new IBinding[] {b};
      if (b instanceof IProblemBinding) {
        IBinding[] candidateBindings = ((IProblemBinding) b).getCandidateBindings();
        if (candidateBindings.length != 0) {
          bindings = candidateBindings;
        }
      } else if (kind == NameKind.DEFINITION && b instanceof IType) {
        // Don't navigate away from a type definition.
        // Select the name at the current location instead.
        navigateToName(sourceName);
        return Status.OK_STATUS;
      }
      IName[] targets = IName.EMPTY_ARRAY;
      String filename = ast.getFilePath();
      for (IBinding binding : bindings) {
        if (binding != null && !(binding instanceof IProblemBinding)) {
          IName[] names = findDeclNames(ast, kind, binding);
          for (final IName name : names) {
            if (name != null) {
              if (name instanceof IIndexName
                  && filename.equals(((IIndexName) name).getFileLocation().getFileName())) {
                // Exclude index names from the current file.
              } else if (areOverlappingNames(name, sourceName)) {
                // Exclude the current location.
              } else if (binding instanceof IParameter) {
                if (isInSameFunction(sourceName, name)) {
                  targets = ArrayUtil.append(targets, name);
                }
              } else if (binding instanceof ICPPTemplateParameter) {
                if (isInSameTemplate(sourceName, name)) {
                  targets = ArrayUtil.append(targets, name);
                }
              } else {
                targets = ArrayUtil.append(targets, name);
              }
            }
          }
        }
      }
      targets = ArrayUtil.trim(ArrayUtil.addAll(targets, implicitTargets));
      if (navigateViaCElements(fTranslationUnit.getCProject(), fIndex, targets)) {
        found = true;
      } else {
        // Leave old method as fallback for local variables, parameters and
        // everything else not covered by ICElementHandle.
        found = navigateOneLocation(targets);
      }
      if (!found && !navigationFallBack(ast, sourceName, kind)) {
        fAction.reportSymbolLookupFailure(new String(sourceName.toCharArray()));
      }
      return Status.OK_STATUS;
    }

    // No enclosing name, check if we're in an include statement
    IASTNode node = nodeSelector.findEnclosingNode(selectionStart, selectionLength);
    if (node instanceof IASTPreprocessorIncludeStatement) {
      openInclude((IASTPreprocessorIncludeStatement) node);
      return Status.OK_STATUS;
    } else if (node instanceof IASTPreprocessorFunctionStyleMacroDefinition) {
      IASTPreprocessorFunctionStyleMacroDefinition mdef =
          (IASTPreprocessorFunctionStyleMacroDefinition) node;
      for (IASTFunctionStyleMacroParameter par : mdef.getParameters()) {
        String parName = par.getParameter();
        if (parName.equals(fSelectedText)) {
          if (navigateToLocation(par.getFileLocation())) {
            return Status.OK_STATUS;
          }
        }
      }
    }
    if (!navigationFallBack(ast, null, NameKind.REFERENCE)) {
      fAction.reportSelectionMatchFailure();
    }
    return Status.OK_STATUS;
  }
 public CodeReader createCodeReaderForTranslationUnit(ITranslationUnit tu) {
   return new CodeReader(tu.getResource().getLocation().toOSString(), tu.getContents());
 }
 public CodeReader createCodeReaderForTranslationUnit(ITranslationUnit tu) {
   return new CodeReader(tu.getPath().toOSString(), tu.getContents());
 }
  public ScanReturn analyse(IProgressMonitor monitor, ITranslationUnit tu, List<String> includes) {
    if (traceOn) {
      println("RunAnalyseBase.analyse()..."); // $NON-NLS-1$
    }
    // ScanReturn nr = null;
    String errMsg = null;

    monitor.subTask(Messages.RunAnalyseHandlerBase_42);

    String rawPath = tu.getLocationURI().toString();
    if (traceOn) {
      println("RunAnalyseBase:              file = " + rawPath); // $NON-NLS-1$
    }

    monitor.subTask(Messages.RunAnalyseHandlerBase_on + rawPath);

    ScanReturn scanReturn = doArtifactAnalysis(tu, includes);
    monitor.worked(1);
    if (traceOn) {
      println("Artifact analysis complete..."); // $NON-NLS-1$
    }
    int numArtifacts = scanReturn.getArtifactList().size();
    cumulativeArtifacts = cumulativeArtifacts + numArtifacts;

    if (traceOn) {
      System.out.println(
          "Artifacts found for " //$NON-NLS-1$
              + tu.getResource().getProjectRelativePath()
              + ": "
              + numArtifacts); //$NON-NLS-1$
    }
    if (traceOn) {
      System.out.println("   Total # found: " + cumulativeArtifacts); // $NON-NLS-1$
    }

    if (scanReturn == null) {
      System.out.println(
          "ScanReturn result is NULL.  No results for " //$NON-NLS-1$
              + tu.getResource().getProjectRelativePath());
      errMsg =
          "Error: No results were returned from analysis of " //$NON-NLS-1$
              + tu.getResource().getProjectRelativePath();
      MessageDialog.openError(shell, "Error in Analysis", errMsg); // $NON-NLS-1$
    } else {
      if (traceOn) {
        System.out.println(
            "RunAnalyzeBase: ScanReturn received for " //$NON-NLS-1$
                + tu.getElementName());
      }
    }

    if (scanReturn != null) {
      boolean wasError = scanReturn.wasError();
      if (traceOn) {
        System.out.println("error occurred =" + wasError); // $NON-NLS-1$
      }
      if (wasError) {
        System.out.println("RunAnalyseBase.analyse...Error..."); // $NON-NLS-1$
      }
    }
    return scanReturn;
  }