@Override
  protected void setUp() throws Exception {
    cproject =
        cpp
            ? CProjectHelper.createCCProject(
                getName() + System.currentTimeMillis(), "bin", IPDOMManager.ID_NO_INDEXER)
            : CProjectHelper.createCProject(
                getName() + System.currentTimeMillis(), "bin", IPDOMManager.ID_NO_INDEXER);
    testData = testSourceReader.getContentsForTest(getName());

    if (testData.length > 0) {
      for (int i = 0; i < testData.length - 1; i++) {
        String filename = String.format("header%d.h", i + 1);
        IFile file =
            TestSourceReader.createFile(
                cproject.getProject(), new Path(filename), testData[i].toString());
        CCorePlugin.getIndexManager().setIndexerId(cproject, IPDOMManager.ID_FAST_INDEXER);
      }
    }

    IFile cppfile =
        TestSourceReader.createFile(
            cproject.getProject(), new Path("source.c" + (cpp ? "pp" : "")), getAstSource());
    waitForIndexer(cproject);

    if (DEBUG) {
      System.out.println("Project PDOM: " + getName());
      ((PDOM) CCoreInternals.getPDOMManager().getPDOM(cproject)).accept(new PDOMPrettyPrinter());
    }

    index = CCorePlugin.getIndexManager().getIndex(cproject);

    index.acquireReadLock();
    ast = TestSourceReader.createIndexBasedAST(index, cproject, cppfile);
  }
    private ICProject createReferencedContent() throws Exception {
      ICProject referenced =
          cpp
              ? CProjectHelper.createCCProject(
                  "ReferencedContent" + System.currentTimeMillis(),
                  "bin",
                  IPDOMManager.ID_NO_INDEXER)
              : CProjectHelper.createCProject(
                  "ReferencedContent" + System.currentTimeMillis(),
                  "bin",
                  IPDOMManager.ID_NO_INDEXER);
      String content = testData[0].toString();
      IFile file =
          TestSourceReader.createFile(referenced.getProject(), new Path("header.h"), content);

      IndexerPreferences.set(
          referenced.getProject(), IndexerPreferences.KEY_INDEXER_ID, IPDOMManager.ID_FAST_INDEXER);
      CCorePlugin.getIndexManager().reindex(referenced);

      waitForIndexer(referenced);

      if (DEBUG) {
        System.out.println("Referenced: " + getName());
        ((PDOM) CCoreInternals.getPDOMManager().getPDOM(referenced))
            .accept(new PDOMPrettyPrinter());
      }

      return referenced;
    }
  @Override
  protected IStatus run(IProgressMonitor monitor) {
    monitor.beginTask("", IProgressMonitor.UNKNOWN); // $NON-NLS-1$
    while (true) {
      ICProject cproject = fManager.getNextProject();
      if (cproject == null) return Status.OK_STATUS;

      final IProject project = cproject.getProject();
      monitor.setTaskName(project.getName());
      if (!project.isOpen()) {
        if (fManager.fTraceIndexerSetup)
          System.out.println("Indexer: Project is not open: " + project.getName()); // $NON-NLS-1$
      } else if (fManager.postponeSetup(cproject)) {
        if (fManager.fTraceIndexerSetup)
          System.out.println("Indexer: Setup is postponed: " + project.getName()); // $NON-NLS-1$
      } else {
        syncronizeProjectSettings(project, new SubProgressMonitor(monitor, 1));
        if (fManager.getIndexer(cproject) == null) {
          try {
            fManager.createIndexer(cproject, new SubProgressMonitor(monitor, 99));
          } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return Status.CANCEL_STATUS;
          }
        } else if (fManager.fTraceIndexerSetup) {
          System.out.println(
              "Indexer: No action, indexer already exists: " + project.getName()); // $NON-NLS-1$
        }
      }
    }
  }
Ejemplo n.º 4
0
 @Override
 protected void tearDown() throws Exception {
   for (ICProject cproject; (cproject = projectsToDeleteOnTearDown.pollLast()) != null; ) {
     cproject.getProject().delete(true, new NullProgressMonitor());
   }
   super.tearDown();
 }
    @Override
    public void setUp() throws Exception {
      cproject =
          cpp
              ? CProjectHelper.createCCProject(
                  getName() + System.currentTimeMillis(), "bin", IPDOMManager.ID_NO_INDEXER)
              : CProjectHelper.createCProject(
                  getName() + System.currentTimeMillis(), "bin", IPDOMManager.ID_NO_INDEXER);
      Bundle b = CTestPlugin.getDefault().getBundle();
      testData =
          TestSourceReader.getContentsForTest(
              b, "parser", IndexBindingResolutionTestBase.this.getClass(), getName(), 2);

      if (testData.length < 2) return;
      IFile file =
          TestSourceReader.createFile(
              cproject.getProject(), new Path("header.h"), testData[0].toString());
      CCorePlugin.getIndexManager().setIndexerId(cproject, IPDOMManager.ID_FAST_INDEXER);
      waitForIndexer(cproject);

      if (DEBUG) {
        System.out.println("Project PDOM: " + getName());
        ((PDOM) CCoreInternals.getPDOMManager().getPDOM(cproject)).accept(new PDOMPrettyPrinter());
      }

      index = CCorePlugin.getIndexManager().getIndex(cproject);

      index.acquireReadLock();
      IFile cppfile =
          TestSourceReader.createFile(
              cproject.getProject(),
              new Path("references.c" + (cpp ? "pp" : "")),
              testData[1].toString());
      ast = TestSourceReader.createIndexBasedAST(index, cproject, cppfile);
    }
Ejemplo n.º 6
0
  public void testExternalExportProjectProvider_BadCmdLine3() throws Exception {
    TestProjectProvider4 tpp4 = new TestProjectProvider4();
    ICProject cproject = tpp4.createProject();

    setExpectedNumberOfLoggedNonOKStatusObjects(1); // Expected failure: -target must be specified
    doGenerate(
        new String[] {
          GeneratePDOMApplication.OPT_PROJECTPROVIDER,
              ExternalExportProjectProvider.class.getName(),
          ExternalExportProjectProvider.OPT_SOURCE,
              cproject.getProject().getLocation().toFile().getAbsolutePath()
        });
    assertFalse(target.exists());
  }
Ejemplo n.º 7
0
 /**
  * Returns an ICProject based on the project name provided in the configuration. First look for a
  * project by name, and then confirm it is a C/C++ project.
  */
 public static ICProject getCProject(ILaunchConfiguration configuration) throws CoreException {
   String projectName = getProjectName(configuration);
   if (projectName != null) {
     projectName = projectName.trim();
     if (projectName.length() > 0) {
       IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
       ICProject cProject = CCorePlugin.getDefault().getCoreModel().create(project);
       if (cProject != null && cProject.exists()) {
         return cProject;
       }
     }
   }
   return null;
 }
 private void initProjects() {
   ArrayList<ICProject> input = new ArrayList<ICProject>();
   ICProject[] projects;
   try {
     projects = CoreModel.getDefault().getCModel().getCProjects();
     for (ICProject project : projects) {
       if (project.getProject().isOpen()) {
         input.add(project);
       }
     }
   } catch (CModelException e) {
     CUIPlugin.log(e);
   }
   fProjectViewer.setInput(input);
 }
  private void setupBasedOnInitialSelections() {
    HashSet<String> names = new HashSet<String>();
    Iterator<?> it = fInitialSelection.iterator();
    while (it.hasNext()) {
      IProject project = (IProject) it.next();
      names.add(project.getName());
    }

    Collection<?> prjs = (Collection<?>) fProjectViewer.getInput();
    for (Object element : prjs) {
      ICProject prj = (ICProject) element;
      if (names.contains(prj.getElementName())) {
        fProjectViewer.setChecked(prj, true);
      }
    }
  }
 @Override
 protected void tearDown() throws Exception {
   try {
     if (p1 != null) {
       p1.getProject().delete(true, null);
       p1 = null;
     }
     if (p2 != null) {
       p2.getProject().delete(true, null);
       p2 = null;
     }
     if (p3 != null) {
       p3.getProject().delete(true, null);
       p3 = null;
     }
   } catch (CoreException e) {
   }
 }
Ejemplo n.º 11
0
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.debug.ui.ILaunchConfigurationTab#performApply(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy)
   */
  @Override
  public void performApply(ILaunchConfigurationWorkingCopy config) {
    super.performApply(config);
    ICProject cProject = this.getCProject();
    if (cProject != null && cProject.exists()) {
      config.setMappedResources(new IResource[] {cProject.getProject()});
    } else {
      config.setMappedResources(null);
    }

    config.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, fProjText.getText());
    config.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, fProgText.getText());
    if (fCoreText != null) {
      config.setAttribute(ICDTLaunchConfigurationConstants.ATTR_COREFILE_PATH, fCoreText.getText());
      config.setAttribute(
          IGDBLaunchConfigurationConstants.ATTR_DEBUGGER_POST_MORTEM_TYPE, getSelectedCoreType());
    }
  }
Ejemplo n.º 12
0
	private IFile getFileForPathImpl(IPath path, IProject project) {
		IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		if (path.isAbsolute()) {
			IFile c = root.getFileForLocation(path);
			return c;
		}
		if (project != null && project.exists()) {
			ICProject cproject = CoreModel.getDefault().create(project);
			if (cproject != null) {
				try {
					ISourceRoot[] roots = cproject.getAllSourceRoots();
					for (ISourceRoot sourceRoot : roots) {
						IResource r = sourceRoot.getResource();
						if (r instanceof IContainer) {
							IContainer parent = (IContainer) r;
							IResource res = parent.findMember(path);
							if (res != null && res.exists() && res instanceof IFile) {
								IFile file = (IFile) res;
								return file;
							}
						}
					}

					IOutputEntry entries[] = cproject.getOutputEntries();
					for (IOutputEntry pathEntry : entries) {
						IPath p = pathEntry.getPath();
						IResource r = root.findMember(p);
						if (r instanceof IContainer) {
							IContainer parent = (IContainer) r;
							IResource res = parent.findMember(path);
							if (res != null && res.exists() && res instanceof IFile) {
								IFile file = (IFile) res;
								return file;
							}
						}
					}
					
				} catch (CModelException _) {
					Activator.getDefault().getLog().log(_.getStatus());
				}
			}
		}
		return null;
	}
  public void testCPathEntriesForOldStyle() throws Exception {
    p2 = CProjectHelper.createCCProject(PROJ_NAME_PREFIX + "b", null, IPDOMManager.ID_NO_INDEXER);
    ICProjectDescriptionManager mngr = CoreModel.getDefault().getProjectDescriptionManager();
    IProject project = p2.getProject();
    ICProjectDescription des = mngr.getProjectDescription(project, false);
    assertNotNull(des);
    assertEquals(1, des.getConfigurations().length);
    assertFalse(mngr.isNewStyleProject(des));
    assertFalse(mngr.isNewStyleProject(project));

    IPathEntry[] entries = CoreModel.getRawPathEntries(p2);
    entries =
        concatEntries(
            entries,
            new IPathEntry[] {
              CoreModel.newSourceEntry(project.getFullPath().append("test_src")),
              CoreModel.newOutputEntry(project.getFullPath().append("test_out")),
            });

    CoreModel.setRawPathEntries(p2, entries, null);

    ICSourceEntry[] expectedSourceEntries =
        new ICSourceEntry[] {
          new CSourceEntry(
              project.getFullPath(), new IPath[] {new Path("test_src")}, ICSettingEntry.RESOLVED),
          new CSourceEntry(project.getFullPath().append("test_src"), null, ICSettingEntry.RESOLVED),
        };

    ICOutputEntry[] expectedOutputEntries =
        new ICOutputEntry[] {
          new COutputEntry(
              project.getFullPath(),
              null,
              ICSettingEntry.RESOLVED | ICSettingEntry.VALUE_WORKSPACE_PATH),
          new COutputEntry(
              project.getFullPath().append("test_out"),
              null,
              ICSettingEntry.RESOLVED | ICSettingEntry.VALUE_WORKSPACE_PATH),
        };

    des = mngr.getProjectDescription(project, false);
    ICConfigurationDescription cfg = des.getDefaultSettingConfiguration();
    ICSourceEntry[] sEntries = cfg.getSourceEntries();
    ICOutputEntry[] oEntries = cfg.getBuildSetting().getOutputDirectories();

    checkCEntriesMatch(expectedSourceEntries, sEntries);
    checkCEntriesMatch(expectedOutputEntries, oEntries);

    des = mngr.getProjectDescription(project, true);
    cfg = des.getDefaultSettingConfiguration();
    sEntries = cfg.getSourceEntries();
    oEntries = cfg.getBuildSetting().getOutputDirectories();

    checkCEntriesMatch(expectedSourceEntries, sEntries);
    checkCEntriesMatch(expectedOutputEntries, oEntries);
  }
  public void testICDescriptorGetProjectData() throws Exception {
    p3 = CProjectHelper.createCCProject(PROJ_NAME_PREFIX + "c", null, IPDOMManager.ID_NO_INDEXER);
    IProject proj = p3.getProject();

    doTestRm(proj);
    doTestRm(proj);
    doTestRm(proj);
    doTestRm(proj);
    doTestRm(proj);
  }
Ejemplo n.º 15
0
 @Override
 public void tearDown() throws Exception {
   if (index != null) {
     index.releaseReadLock();
   }
   if (cproject != null) {
     cproject
         .getProject()
         .delete(
             IResource.FORCE | IResource.ALWAYS_DELETE_PROJECT_CONTENT,
             new NullProgressMonitor());
   }
   if (referenced != null) {
     referenced
         .getProject()
         .delete(
             IResource.FORCE | IResource.ALWAYS_DELETE_PROJECT_CONTENT,
             new NullProgressMonitor());
   }
 }
Ejemplo n.º 16
0
  private Object[] getProjectChildren(ICProject cproject) throws CModelException {
    Object[] extras = null;
    IArchiveContainer archive = cproject.getArchiveContainer();
    if (getArchives(archive).length > 0) {
      extras = new Object[] {archive};
    }
    IBinaryContainer bin = cproject.getBinaryContainer();
    if (getExecutables(bin).length > 0) {
      Object[] o = new Object[] {bin};
      if (extras != null && extras.length > 0) {
        extras = concatenate(extras, o);
      } else {
        extras = o;
      }
    }
    LibraryRefContainer libRefCont = new LibraryRefContainer(cproject);
    Object[] libRefs = libRefCont.getChildren(cproject);
    if (libRefs != null && libRefs.length > 0) {
      Object[] o = new Object[] {libRefCont};
      if (extras != null && extras.length > 0) {
        extras = concatenate(extras, o);
      } else {
        extras = o;
      }
    }

    IncludeRefContainer incRefCont = new IncludeRefContainer(cproject);
    Object[] incRefs = incRefCont.getChildren(cproject);
    if (incRefs != null && incRefs.length > 0) {
      Object[] o = new Object[] {incRefCont};
      if (extras != null && extras.length > 0) {
        extras = concatenate(extras, o);
      } else {
        extras = o;
      }
    }
    return extras;
  }
Ejemplo n.º 17
0
  /**
   * Verify that the executable path points to a valid binary file.
   *
   * @return An object representing the binary file.
   */
  public static IBinaryObject verifyBinary(ILaunchConfiguration configuration, IPath exePath)
      throws CoreException {
    ICProject cproject = getCProject(configuration);
    if (cproject != null) {
      ICConfigExtensionReference[] parserRefs =
          CCorePlugin.getDefault().getDefaultBinaryParserExtensions(cproject.getProject());
      for (ICConfigExtensionReference parserRef : parserRefs) {
        try {
          IBinaryParser parser = CoreModelUtil.getBinaryParser(parserRef);
          IBinaryObject exe = (IBinaryObject) parser.getBinary(exePath);
          if (exe != null) {
            return exe;
          }
        } catch (ClassCastException e) {
        } catch (IOException e) {
        }
      }
    }

    IBinaryParser parser = CCorePlugin.getDefault().getDefaultBinaryParser();
    try {
      return (IBinaryObject) parser.getBinary(exePath);
    } catch (ClassCastException e) {
    } catch (IOException e) {
    }

    abort(
        LaunchMessages.getString(
            "AbstractCLaunchDelegate.Program_is_not_a_recognized_executable"), //$NON-NLS-1$
        new FileNotFoundException(
            LaunchMessages.getFormattedString(
                "AbstractCLaunchDelegate.Program_is_not_a_recognized_executable", //$NON-NLS-1$
                exePath.toOSString())),
        ICDTLaunchConfigurationConstants.ERR_PROGRAM_NOT_BINARY);

    return null;
  }
Ejemplo n.º 18
0
  public DiscoveredScannerInfo getDiscoveredScannerInfo(IProject project, boolean cacheInfo)
      throws CoreException {
    DiscoveredScannerInfo scannerInfo = null;
    // See if there's already one associated with the resource for this
    // session
    scannerInfo = (DiscoveredScannerInfo) project.getSessionProperty(scannerInfoProperty);

    if (scannerInfo == null) {
      scannerInfo = new DiscoveredScannerInfo(project);
      // this will convert user info
      org.eclipse.cdt.make.core.MakeScannerInfo makeScannerInfo =
          org.eclipse.cdt.make.core.MakeScannerProvider.getDefault()
              .getMakeScannerInfo(project, cacheInfo);
      scannerInfo.setUserScannerInfo(makeScannerInfo);

      // migrate to new C Path Entries
      IContainerEntry container = CoreModel.newContainerEntry(DiscoveredPathContainer.CONTAINER_ID);
      ICProject cProject = CoreModel.getDefault().create(project);
      if (cProject != null) {
        IPathEntry[] entries = cProject.getRawPathEntries();
        List<IPathEntry> newEntries = new ArrayList<IPathEntry>(Arrays.asList(entries));
        if (!newEntries.contains(container)) {
          newEntries.add(container);
          cProject.setRawPathEntries(newEntries.toArray(new IPathEntry[newEntries.size()]), null);
        }
      }
      ICDescriptor descriptor = CCorePlugin.getDefault().getCProjectDescription(project);
      descriptor.remove(
          CCorePlugin.BUILD_SCANNER_INFO_UNIQ_ID); // remove scanner provider which will fallback to
      // default
      // cpath provider.
      // place holder to that we don't convert again.
      project.setSessionProperty(scannerInfoProperty, scannerInfo);
    }
    return scannerInfo;
  }
Ejemplo n.º 19
0
    @Override
    public void setUp() throws Exception {
      cproject =
          cpp
              ? CProjectHelper.createCCProject(
                  getName() + System.currentTimeMillis(), "bin", IPDOMManager.ID_NO_INDEXER)
              : CProjectHelper.createCProject(
                  getName() + System.currentTimeMillis(), "bin", IPDOMManager.ID_NO_INDEXER);
      Bundle b = CTestPlugin.getDefault().getBundle();
      testData =
          TestSourceReader.getContentsForTest(
              b, "parser", IndexBindingResolutionTestBase.this.getClass(), getName(), 0);

      List<IFile> astFiles = new ArrayList<IFile>();
      for (int i = 0; i < testData.length; i++) {
        StringBuilder contents = testData[i];
        int endOfLine = contents.indexOf("\n");
        if (endOfLine >= 0) endOfLine++;
        else endOfLine = contents.length();
        String filename = contents.substring(0, endOfLine).trim();
        contents.delete(0, endOfLine); // Remove first line from the file contents
        boolean astRequested = filename.endsWith("*");
        if (astRequested) {
          filename = filename.substring(0, filename.length() - 1).trim();
        }
        IFile file =
            TestSourceReader.createFile(
                cproject.getProject(), new Path(filename), contents.toString());
        if (astRequested || (i == testData.length - 1 && astFiles.isEmpty())) {
          astSources.add(contents);
          astFiles.add(file);
        }
      }
      CCorePlugin.getIndexManager().setIndexerId(cproject, IPDOMManager.ID_FAST_INDEXER);
      waitForIndexer(cproject);

      if (DEBUG) {
        System.out.println("Project PDOM: " + getName());
        ((PDOM) CCoreInternals.getPDOMManager().getPDOM(cproject)).accept(new PDOMPrettyPrinter());
      }

      index = CCorePlugin.getIndexManager().getIndex(cproject);

      index.acquireReadLock();
      for (IFile file : astFiles) {
        asts.add(TestSourceReader.createIndexBasedAST(index, cproject, file));
      }
    }
Ejemplo n.º 20
0
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    if (fIsCpp) {
      fCProject = CProjectHelper.createCCProject(getName(), "unused", IPDOMManager.ID_FAST_INDEXER);
    } else {
      fCProject = CProjectHelper.createCProject(getName(), "unused", IPDOMManager.ID_FAST_INDEXER);
    }
    fCFile = setUpProjectContent(fCProject.getProject());
    assertNotNull(fCFile);
    waitForIndexer(fCProject);
    fEditor = (ITextEditor) EditorTestHelper.openInEditor(fCFile, true);
    assertNotNull(fEditor);
    CPPASTNameBase.sAllowNameComputation = true;

    //		EditorTestHelper.joinBackgroundActivities((AbstractTextEditor)fEditor);
  }
Ejemplo n.º 21
0
  /**
   * Verify that program name of the configuration can be found as a file.
   *
   * @return Absolute path of the program location
   */
  public static IPath verifyProgramPath(ILaunchConfiguration configuration, ICProject cproject)
      throws CoreException {
    String programName =
        configuration.getAttribute(
            ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, (String) null);
    if (programName == null) {
      abort(
          LaunchMessages.getString("AbstractCLaunchDelegate.Program_file_not_specified"),
          null, //$NON-NLS-1$
          ICDTLaunchConfigurationConstants.ERR_NOT_A_C_PROJECT);
    }

    IPath programPath = new Path(programName);
    if (programPath.isEmpty()) {
      abort(
          LaunchMessages.getString("AbstractCLaunchDelegate.Program_file_does_not_exist"),
          null, //$NON-NLS-1$
          ICDTLaunchConfigurationConstants.ERR_NOT_A_C_PROJECT);
    }

    if (!programPath.isAbsolute() && cproject != null) {
      // Find the specified program within the specified project
      IFile wsProgramPath = cproject.getProject().getFile(programPath);
      programPath = wsProgramPath.getLocation();
    }

    if (!programPath.toFile().exists()) {
      abort(
          LaunchMessages.getString(
              "AbstractCLaunchDelegate.Program_file_does_not_exist"), //$NON-NLS-1$
          new FileNotFoundException(
              LaunchMessages.getFormattedString(
                  "AbstractCLaunchDelegate.PROGRAM_PATH_not_found", //$NON-NLS-1$
                  programPath.toOSString())),
          ICDTLaunchConfigurationConstants.ERR_PROGRAM_NOT_EXIST);
    }

    return programPath;
  }
Ejemplo n.º 22
0
    @Override
    public void setUp() throws Exception {
      cproject =
          cpp
              ? CProjectHelper.createCCProject(
                  "OnlineContent" + System.currentTimeMillis(), "bin", IPDOMManager.ID_NO_INDEXER)
              : CProjectHelper.createCProject(
                  "OnlineContent" + System.currentTimeMillis(), "bin", IPDOMManager.ID_NO_INDEXER);
      Bundle b = CTestPlugin.getDefault().getBundle();
      testData =
          TestSourceReader.getContentsForTest(
              b, "parser", IndexBindingResolutionTestBase.this.getClass(), getName(), 2);
      referenced = createReferencedContent();

      TestScannerProvider.sIncludes =
          new String[] {referenced.getProject().getLocation().toOSString()};
      IFile references =
          TestSourceReader.createFile(
              cproject.getProject(),
              new Path("refs.c" + (cpp ? "pp" : "")),
              testData[1].toString());

      IProject[] refs = new IProject[] {referenced.getProject()};
      IProjectDescription pd = cproject.getProject().getDescription();
      pd.setReferencedProjects(refs);
      cproject.getProject().setDescription(pd, new NullProgressMonitor());

      IndexerPreferences.set(
          cproject.getProject(), IndexerPreferences.KEY_INDEXER_ID, IPDOMManager.ID_FAST_INDEXER);
      CCorePlugin.getIndexManager().reindex(cproject);
      waitForIndexer(cproject);

      if (DEBUG) {
        System.out.println("Online: " + getName());
        ((PDOM) CCoreInternals.getPDOMManager().getPDOM(cproject)).accept(new PDOMPrettyPrinter());
      }

      index = CCorePlugin.getIndexManager().getIndex(cproject, IIndexManager.ADD_DEPENDENCIES);
      index.acquireReadLock();
      ast = TestSourceReader.createIndexBasedAST(index, cproject, references);
    }
Ejemplo n.º 23
0
  /**
   * selectionChanged() event handler. Fills the list of managed-built projects based on the
   * selection. If some non-managed-built projects are selected, disables the action.
   *
   * @param action The action
   * @param selection The selection
   */
  protected void onSelectionChanged(IAction action, ISelection selection) {
    fProjects.clear();

    boolean badObject = false;

    if (selection != null) {
      if (selection instanceof IStructuredSelection) {
        if (selection.isEmpty()) {
          // could be a form editor or something.  try to get the project from the active part
          IWorkbenchPage page = CUIPlugin.getActivePage();
          if (page != null) {
            IWorkbenchPart part = page.getActivePart();
            if (part != null) {
              Object o = part.getAdapter(IResource.class);
              if (o != null && o instanceof IResource) {
                fProjects.add(((IResource) o).getProject());
              }
            }
          }
        }
        Iterator<?> iter = ((IStructuredSelection) selection).iterator();
        while (iter.hasNext()) {
          Object selItem = iter.next();
          IProject project = null;
          if (selItem instanceof ICElement) {
            ICProject cproject = ((ICElement) selItem).getCProject();
            if (cproject != null) project = cproject.getProject();
          } else if (selItem instanceof IResource) {
            project = ((IResource) selItem).getProject();
          } else if (selItem instanceof IncludeRefContainer) {
            ICProject fCProject = ((IncludeRefContainer) selItem).getCProject();
            if (fCProject != null) project = fCProject.getProject();
          } else if (selItem instanceof IncludeReferenceProxy) {
            IncludeRefContainer irc = ((IncludeReferenceProxy) selItem).getIncludeRefContainer();
            if (irc != null) {
              ICProject fCProject = irc.getCProject();
              if (fCProject != null) project = fCProject.getProject();
            }
          } else if (selItem instanceof IAdaptable) {
            Object adapter = ((IAdaptable) selItem).getAdapter(IProject.class);
            if (adapter != null && adapter instanceof IProject) {
              project = (IProject) adapter;
            }
          }
          // Check whether the project is CDT project
          if (project != null) {
            if (!CoreModel.getDefault().isNewStyleProject(project)) project = null;
            else {
              ICConfigurationDescription[] tmp = getCfgs(project);
              if (tmp.length == 0) project = null;
            }
          }
          if (project != null) {
            fProjects.add(project);
          } else {
            badObject = true;
            break;
          }
        }
      } else if (selection instanceof ITextSelection) {
        // If a text selection check the selected part to see if we can find
        // an editor part that we can adapt to a resource and then
        // back to a project.
        IWorkbenchWindow window = CUIPlugin.getActiveWorkbenchWindow();
        if (window != null) {
          IWorkbenchPage page = window.getActivePage();
          if (page != null) {
            IWorkbenchPart part = page.getActivePart();
            if (part instanceof IEditorPart) {
              IEditorPart epart = (IEditorPart) part;
              IResource resource = epart.getEditorInput().getAdapter(IResource.class);
              if (resource != null) {
                IProject project = resource.getProject();
                badObject = !(project != null && CoreModel.getDefault().isNewStyleProject(project));

                if (!badObject) {
                  fProjects.add(project);
                }
              }
            }
          }
        }

      } else if (selection instanceof ImaginarySelection) {
        fProjects.add(((ImaginarySelection) selection).getProject());
      }
    }

    boolean enable = false;
    if (!badObject && !fProjects.isEmpty()) {
      Iterator<IProject> iter = fProjects.iterator();
      ICConfigurationDescription[] firstConfigs = getCfgs(iter.next());
      if (firstConfigs != null) {
        for (ICConfigurationDescription firstConfig : firstConfigs) {
          boolean common = true;
          Iterator<IProject> iter2 = fProjects.iterator();
          while (iter2.hasNext()) {
            ICConfigurationDescription[] currentConfigs = getCfgs(iter2.next());
            int j = 0;
            for (; j < currentConfigs.length; j++) {
              if (firstConfig.getName().equals(currentConfigs[j].getName())) break;
            }
            if (j == currentConfigs.length) {
              common = false;
              break;
            }
          }
          if (common) {
            enable = true;
            break;
          }
        }
      }
    }
    action.setEnabled(enable);

    // Bug 375760
    // If focus is on a view that doesn't provide a resource/project context. Use the selection in a
    // project/resource view. We support three views. If more than one is open, nevermind. If
    // there's only
    // one project in the workspace and it's a CDT one, use it unconditionally.
    //
    // Note that whatever project we get here is just a candidate; it's tested for suitability when
    // we
    // call ourselves recursively
    //
    if (badObject || fProjects.isEmpty()) {
      // Check for lone CDT project in workspace
      IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
      if (projects != null && projects.length == 1) {
        IProject project = projects[0];
        if (CoreModel.getDefault().isNewStyleProject(project) && (getCfgs(project).length > 0)) {
          onSelectionChanged(action, new ImaginarySelection(project));
          return;
        }
      }

      // Check the three supported views
      IWorkbenchPage page = CUIPlugin.getActivePage();
      int viewCount = 0;
      if (page != null) {
        IViewReference theViewRef = null;
        IViewReference viewRef = null;

        theViewRef = page.findViewReference("org.eclipse.cdt.ui.CView"); // $NON-NLS-1$
        viewCount += (theViewRef != null) ? 1 : 0;

        viewRef = page.findViewReference("org.eclipse.ui.navigator.ProjectExplorer"); // $NON-NLS-1$
        viewCount += (viewRef != null) ? 1 : 0;
        theViewRef = (theViewRef == null) ? viewRef : theViewRef;

        viewRef = page.findViewReference("org.eclipse.ui.views.ResourceNavigator"); // $NON-NLS-1$
        viewCount += (viewRef != null) ? 1 : 0;
        theViewRef = (theViewRef == null) ? viewRef : theViewRef;

        if (theViewRef != null && viewCount == 1) {
          IViewPart view = theViewRef.getView(false);
          if (view != null) {
            ISelection cdtSelection = view.getSite().getSelectionProvider().getSelection();
            if (cdtSelection != null) {
              if (!cdtSelection.isEmpty()) {
                if (!cdtSelection.equals(selection)) { // avoids infinite recursion
                  onSelectionChanged(action, cdtSelection);
                }
              }
            }
          }
        }
      }
    }
  }
Ejemplo n.º 24
0
 @Override
 public IIndexLocationConverter getLocationConverter(ICProject cproject) {
   return new ResourceContainerRelativeLocationConverter(cproject.getProject());
 }
Ejemplo n.º 25
0
  /**
   * Run analysis on a resource (e.g. File or Folder) Will descend to members of folder
   *
   * @param atu the resource
   * @param indent number of levels of nesting/recursion for prettyprinting
   * @param includes contains header files include paths from the Preference page
   * @return true if an error was encountered
   * @throws InterruptedException
   */
  public boolean runResource(
      IProgressMonitor monitor, ICElement ce, int indent, List<String> includes)
      throws InterruptedException {
    indent += INDENT_INCR;
    ScanReturn results;
    boolean foundError = false;

    if (!monitor.isCanceled()) {
      if (ce instanceof ITranslationUnit) {
        IResource res = ce.getResource(); // null if not part of C
        // project in ws
        // cdt40: eventually shd be able to deal with just tu;
        // tu.getResource() can always work later...
        if (res instanceof IFile) { // shd always be true (but might be
          // null)
          IFile file = (IFile) res;
          String filename = file.getName();
          // String fn2 = ce.getElementName();// shd be filename too
          // cdt40
          boolean cpp = isCPPproject(ce);
          // if (AnalysisUtil.validForAnalysis(filename,cpp)) {

          if (validForAnalysis(filename, cpp)) {
            if (traceOn) {
              println(getSpaces(indent) + "file: " + filename); // $NON-NLS-1$
            }
            results = analyse(monitor, (ITranslationUnit) ce, includes);

            foundError = foundError || results == null || results.wasError();
            if (foundError) {
              int stopHere = 0;
              System.out.println(
                  "found error on " //$NON-NLS-1$
                      + file.getName()
                      + " "
                      + stopHere); //$NON-NLS-1$
            }
            if (traceOn) {
              println(
                  "******** RunAnalyseBase, analysis complete; ScanReturn=" //$NON-NLS-1$
                      + results);
            }
            if (results != null) {
              // apply markers to the file
              processResults(results, file);
            }

          } else {
            if (traceOn) {
              println(getSpaces(indent) + "---omit: not valid file: " + filename); // $NON-NLS-1$
            }
          }
          return foundError;
        }
      } else if (ce instanceof ICContainer) {
        ICContainer container = (ICContainer) ce;
        try {
          ICElement[] mems = container.getChildren();
          for (int i = 0; i < mems.length; i++) {
            if (monitor.isCanceled()) {
              // this is usually hit while processing normal
              // analysis of e.g. container
              throw new InterruptedException();
            }
            boolean err = runResource(monitor, mems[i], indent, includes);
            foundError = foundError || err;
          }
        } catch (CoreException e) {
          e.printStackTrace();
        }

      } else if (ce instanceof ICProject) {
        ICProject proj = (ICProject) ce;
        try {
          ICElement[] mems = proj.getChildren();
          for (int i = 0; i < mems.length; i++) {
            if (monitor.isCanceled()) {
              // this is usually hit while processing normal
              // analysis of e.g. container
              throw new InterruptedException();
            }
            boolean err = runResource(monitor, mems[i], indent, includes);
            foundError = foundError || err;
          }
        } catch (CoreException e) {
          e.printStackTrace();
        }
      }
      // container could be project or folder
    } // end if !monitor.isCanceled()
    else {
      String name = ""; // $NON-NLS-1$
      // cdt40
      name = ce.getElementName();
      // String p=ce.getPath().toString();

      System.out.println(
          "Cancelled by User, aborting analysis on subsequent files... " //$NON-NLS-1$
              + name);
      throw new InterruptedException();
    }

    return foundError;
  }
  public void testPathEntriesForNewStyle() throws Exception {
    p1 =
        CProjectHelper.createNewStileCProject(
            PROJ_NAME_PREFIX + "a",
            TestUserAndDiscoveredEntriesCfgDataProvider.PROVIDER_ID,
            IPDOMManager.ID_NO_INDEXER);
    IProject project = p1.getProject();

    IPathEntry[] entries = CoreModel.getRawPathEntries(p1);
    IPathEntry[] resolvedentries = CoreModel.getResolvedPathEntries(p1);
    IPathEntry[] expectedRawEntries =
        new IPathEntry[] {
          CoreModel.newContainerEntry(new Path("org.eclipse.cdt.core.CFG_BASED_CONTAINER")),
          CoreModel.newSourceEntry(project.getFullPath()),
          CoreModel.newOutputEntry(project.getFullPath()),
        };
    checkEntriesMatch(expectedRawEntries, entries);

    IPathEntry[] expectedResolvedEntries =
        new IPathEntry[] {
          CoreModel.newSourceEntry(project.getFullPath()),
          CoreModel.newOutputEntry(project.getFullPath()),
          CoreModel.newMacroEntry(project.getFullPath(), "a", "b"),
          CoreModel.newMacroEntry(project.getFullPath(), "c", ""),
          CoreModel.newIncludeEntry(
              project.getFullPath(), null, project.getLocation().append("a/b/c")),
          CoreModel.newIncludeEntry(project.getFullPath(), null, new Path("/d/e/f")),
          CoreModel.newIncludeEntry(
              project.getFullPath(), project.getFullPath().makeRelative(), new Path("g/h/i")),
          CoreModel.newIncludeEntry(project.getFullPath(), new Path("j"), new Path("k/l")),
        };
    checkEntriesMatch(expectedResolvedEntries, resolvedentries);

    IPathEntry[] newEntries = new IPathEntry[entries.length + 1];
    System.arraycopy(entries, 0, newEntries, 0, entries.length);
    newEntries[entries.length] =
        CoreModel.newIncludeEntry(
            new Path("d"),
            null,
            new Path("/C/d/e"),
            true,
            new Path[] {new Path("a"), new Path("b")},
            false);

    IPathEntry[] newExpectedRawEntries = new IPathEntry[entries.length + 1];
    System.arraycopy(entries, 0, newExpectedRawEntries, 0, entries.length);
    newExpectedRawEntries[entries.length] =
        CoreModel.newIncludeEntry(
            project.getFullPath().append("d"),
            null,
            new Path("/C/d/e"),
            true,
            new Path[] {new Path("a"), new Path("b")},
            false);

    CoreModel.setRawPathEntries(p1, newEntries, null);

    entries = CoreModel.getRawPathEntries(p1);
    checkEntriesMatch(entries, newExpectedRawEntries);

    IPathEntry[] newExpectedResolved = new IPathEntry[resolvedentries.length + 1];
    System.arraycopy(resolvedentries, 0, newExpectedResolved, 0, resolvedentries.length);
    newExpectedResolved[resolvedentries.length] =
        CoreModel.newIncludeEntry(
            project.getFullPath().append("d"),
            null,
            new Path("/C/d/e"),
            true,
            new Path[] {new Path("a"), new Path("b")},
            false);
    resolvedentries = CoreModel.getResolvedPathEntries(p1);
    checkEntriesMatch(resolvedentries, newExpectedResolved);

    entries =
        concatEntries(
            entries,
            new IPathEntry[] {
              CoreModel.newSourceEntry(project.getFullPath().append("test_src")),
              CoreModel.newOutputEntry(project.getFullPath().append("test_out")),
            });

    newExpectedRawEntries =
        concatEntries(
            newExpectedRawEntries,
            new IPathEntry[] {
              CoreModel.newSourceEntry(project.getFullPath().append("test_src")),
              CoreModel.newOutputEntry(project.getFullPath().append("test_out")),
            });

    for (int i = 0; i < newExpectedRawEntries.length; i++) {
      IPathEntry entry = newExpectedRawEntries[i];
      if (entry.getEntryKind() == IPathEntry.CDT_SOURCE
          && entry.getPath().equals(project.getFullPath())) {
        newExpectedRawEntries[i] =
            CoreModel.newSourceEntry(project.getFullPath(), new Path[] {new Path("test_src")});
      }
      //			if(entry.getEntryKind() == IPathEntry.CDT_OUTPUT &&
      // entry.getPath().equals(project.getFullPath())){
      //				newExpectedRawEntries[i] = CoreModel.newOutputEntry(project.getFullPath(), new
      // Path[]{new Path("test_out")});
      //			}
    }

    newExpectedResolved =
        concatEntries(
            newExpectedResolved,
            new IPathEntry[] {
              CoreModel.newSourceEntry(project.getFullPath().append("test_src")),
              CoreModel.newOutputEntry(project.getFullPath().append("test_out")),
            });

    for (int i = 0; i < newExpectedResolved.length; i++) {
      IPathEntry entry = newExpectedResolved[i];
      if (entry.getEntryKind() == IPathEntry.CDT_SOURCE
          && entry.getPath().equals(project.getFullPath())) {
        newExpectedResolved[i] =
            CoreModel.newSourceEntry(project.getFullPath(), new Path[] {new Path("test_src")});
      }
      //			if(entry.getEntryKind() == IPathEntry.CDT_OUTPUT &&
      // entry.getPath().equals(project.getFullPath())){
      //				newExpectedResolved[i] = CoreModel.newOutputEntry(project.getFullPath(), new Path[]{new
      // Path("test_out")});
      //			}
    }

    CoreModel.setRawPathEntries(p1, entries, null);

    entries = CoreModel.getRawPathEntries(p1);
    resolvedentries = CoreModel.getResolvedPathEntries(p1);

    checkEntriesMatch(newExpectedRawEntries, entries);
    checkEntriesMatch(newExpectedResolved, resolvedentries);

    CoreModel.setRawPathEntries(p1, expectedRawEntries, null);
    entries = CoreModel.getRawPathEntries(p1);
    resolvedentries = CoreModel.getResolvedPathEntries(p1);

    checkEntriesMatch(expectedRawEntries, entries);
    checkEntriesMatch(expectedResolvedEntries, resolvedentries);

    // check to see that setting the same entries do not give errors
    CoreModel.setRawPathEntries(p1, expectedRawEntries, null);
    entries = CoreModel.getRawPathEntries(p1);
    resolvedentries = CoreModel.getResolvedPathEntries(p1);

    checkEntriesMatch(expectedRawEntries, entries);
    checkEntriesMatch(expectedResolvedEntries, resolvedentries);
  }
Ejemplo n.º 27
0
  /**
   * Applies the C++ code formatter to the code affected by refactoring.
   *
   * @param multiEdit The text edit produced by refactoring.
   * @param code The code being modified.
   * @param project The project containing the code.
   * @return The text edit containing formatted refactoring changes, or the original text edit in
   *     case of errors.
   */
  private MultiTextEdit formatChangedCode(MultiTextEdit multiEdit, String code, IProject project) {
    IDocument document = new Document(code);
    try {
      // Apply refactoring changes to a temporary document.
      TextEdit edit = multiEdit.copy();
      edit.apply(document, TextEdit.UPDATE_REGIONS);

      // Expand regions affected by the changes to cover complete lines. We calculate two
      // sets of regions, reflecting the state of the document before and after
      // the refactoring changes.
      TextEdit[] edits = edit.getChildren();
      TextEdit[] originalEdits = multiEdit.getChildren();
      IRegion[] regionsAfter = new IRegion[edits.length];
      IRegion[] regionsBefore = new IRegion[edits.length];
      int numRegions = 0;
      int prevEnd = -1;
      for (int i = 0; i < edits.length; i++) {
        edit = edits[i];
        int offset = edit.getOffset();
        int end = offset + edit.getLength();
        int newOffset = document.getLineInformationOfOffset(offset).getOffset();
        int newEnd = endOffset(document.getLineInformationOfOffset(end));
        edit = originalEdits[i];
        int offsetBefore = edit.getOffset();
        int newOffsetBefore = newOffset + offsetBefore - offset;
        int newEndBefore = newEnd + offsetBefore + edit.getLength() - end;
        if (newOffset <= prevEnd) {
          numRegions--;
          newOffset = regionsAfter[numRegions].getOffset();
          newOffsetBefore = regionsBefore[numRegions].getOffset();
        }
        prevEnd = newEnd;
        regionsAfter[numRegions] = new Region(newOffset, newEnd - newOffset);
        regionsBefore[numRegions] = new Region(newOffsetBefore, newEndBefore - newOffsetBefore);
        numRegions++;
      }

      if (numRegions < regionsAfter.length) {
        regionsAfter = Arrays.copyOf(regionsAfter, numRegions);
        regionsBefore = Arrays.copyOf(regionsBefore, numRegions);
      }

      // Calculate formatting changes for the regions after the refactoring changes.
      ICProject proj = CCorePlugin.getDefault().getCoreModel().create(project);
      Map<String, String> options = proj.getOptions(true);
      // Allow all comments to be indented.
      options.put(
          DefaultCodeFormatterConstants
              .FORMATTER_COMMENT_NEVER_INDENT_LINE_COMMENTS_ON_FIRST_COLUMN,
          DefaultCodeFormatterConstants.FALSE);
      CodeFormatter formatter = ToolFactory.createCodeFormatter(options);
      code = document.get();
      TextEdit[] formatEdits =
          formatter.format(
              CodeFormatter.K_TRANSLATION_UNIT,
              code,
              regionsAfter,
              TextUtilities.getDefaultLineDelimiter(document));

      // For each of the regions we apply formatting changes and create a ReplaceEdit using
      // the region before the refactoring changes and the text after the formatting changes.
      MultiTextEdit resultEdit = new MultiTextEdit();
      for (int i = 0; i < regionsAfter.length; i++) {
        IRegion region = regionsAfter[i];
        int offset = region.getOffset();
        edit = formatEdits[i];
        edit.moveTree(-offset);
        document = new Document(code.substring(offset, offset + region.getLength()));
        edit.apply(document, TextEdit.NONE);
        region = regionsBefore[i];
        edit = new ReplaceEdit(region.getOffset(), region.getLength(), document.get());
        resultEdit.addChild(edit);
      }
      return resultEdit;
    } catch (MalformedTreeException e) {
      CCorePlugin.log(e);
      return multiEdit;
    } catch (BadLocationException e) {
      CCorePlugin.log(e);
      return multiEdit;
    }
  }