1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-04-29 19:45:01 +02:00

Merge remote-tracking branch 'cdt/master' into sd90

This commit is contained in:
Andrew Gvozdev 2012-02-12 09:59:07 -05:00
commit da85c70e48
252 changed files with 17691 additions and 2663 deletions

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2000, 2010 QNX Software Systems and others.
* Copyright (c) 2000, 2012 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -7,6 +7,7 @@
*
* Contributors:
* QNX Software Systems - Initial API and implementation
* Baltasar Belyavsky (Texas Instruments) - bug 340219: Project metadata files are saved unnecessarily
*******************************************************************************/
package org.eclipse.cdt.make.internal.core;
@ -18,6 +19,10 @@ import java.util.Map.Entry;
import java.util.StringTokenizer;
import org.eclipse.cdt.core.ErrorParserManager;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.settings.model.ICConfigurationDescription;
import org.eclipse.cdt.core.settings.model.ICProjectDescription;
import org.eclipse.cdt.core.settings.model.extension.CBuildData;
import org.eclipse.cdt.make.core.IMakeBuilderInfo;
import org.eclipse.cdt.make.core.IMakeCommonBuildInfo;
import org.eclipse.cdt.make.core.MakeCorePlugin;
@ -493,12 +498,27 @@ public class BuildInfoFactory {
BuildInfoProject(IProject project, String builderID) throws CoreException {
this.project = project;
this.builderID = builderID;
ICommand builder;
builder = MakeProjectNature.getBuildSpec(project.getDescription(), builderID);
if (builder == null) {
throw new CoreException(new Status(IStatus.ERROR, MakeCorePlugin.getUniqueIdentifier(), -1,
MakeMessages.getString("BuildInfoFactory.Missing_Builder") + builderID, null)); //$NON-NLS-1$
ICommand builder = null;
// first, give the build-system a chance to return the build-command overlayed with data managed by it
ICProjectDescription cProjectDescription = CoreModel.getDefault().getProjectDescription(project, false);
if(cProjectDescription != null) {
ICConfigurationDescription cConfigDescription = cProjectDescription.getActiveConfiguration();
CBuildData buildData = cConfigDescription.getConfigurationData().getBuildData();
if(buildData != null) {
builder = buildData.getBuildSpecCommand();
}
}
if(builder == null) {
builder = MakeProjectNature.getBuildSpec(project.getDescription(), builderID);
if (builder == null) {
throw new CoreException(new Status(IStatus.ERROR, MakeCorePlugin.getUniqueIdentifier(), -1,
MakeMessages.getString("BuildInfoFactory.Missing_Builder") + builderID, null)); //$NON-NLS-1$
}
}
Map<String, String> builderArgs = builder.getArguments();
args = builderArgs;
}

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2007, 2010 Intel Corporation and others.
* Copyright (c) 2007, 2012 Intel Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -7,9 +7,11 @@
*
* Contributors:
* Intel Corporation - Initial API and implementation
* Baltasar Belyavsky (Texas Instruments) - bug 340219: Project metadata files are saved unnecessarily
*******************************************************************************/
package org.eclipse.cdt.projectmodel.tests;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@ -56,6 +58,7 @@ import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceDescription;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
@ -685,6 +688,69 @@ public class ProjectModelTests extends TestCase implements IElementChangedListen
}
/**
* Verifies that project-model is not re-serialized unnecessarily.
*/
public void testCompulsiveSerialization_Bug340219() throws Exception {
final String projectName = "test_bug340219";
CoreModel coreModel = CoreModel.getDefault();
IProject project = null;
try {
project = createProject(projectName, "cdt.managedbuild.target.gnu30.exe");
File projectFile = project.getFile(".project").getLocation().toFile();
File cprojectFile = project.getFile(".cproject").getLocation().toFile();
final long projectFileStamp = projectFile.lastModified();
final long cprojectFileStamp = cprojectFile.lastModified();
ICProjectDescription des = coreModel.getProjectDescription(project);
ICConfigurationDescription[] cfgs = des.getConfigurations();
// verify pre-condition - there are two configurations, and the first one is active by default
assertEquals(2, cfgs.length);
assertTrue(cfgs[0].isActive());
// verify that changing active or setting configuration does not touch project-model files
des.setActiveConfiguration(cfgs[1]);
des.setDefaultSettingConfiguration(cfgs[1]);
coreModel.setProjectDescription(project, des);
assertEquals(cfgs[1].getId(), des.getActiveConfiguration().getId());
assertEquals(projectFileStamp, projectFile.lastModified());
assertEquals(cprojectFileStamp, cprojectFile.lastModified());
// verify that closing/reopening the project preserves active configuration and does not touch project-model files
project.close(null);
project.open(null);
des = coreModel.getProjectDescription(project);
cfgs = des.getConfigurations();
assertEquals(cfgs[1].getId(), des.getActiveConfiguration().getId());
assertEquals(projectFileStamp, projectFile.lastModified());
assertEquals(cprojectFileStamp, cprojectFile.lastModified());
// verify that deleting/reimporting the project resets active configuration but does not touch project-model files
project.delete(false, true, null);
project.create(null);
project.open(null);
des = coreModel.getProjectDescription(project);
cfgs = des.getConfigurations();
assertEquals(cfgs[0].getId(), des.getActiveConfiguration().getId());
assertEquals(projectFileStamp, projectFile.lastModified());
assertEquals(cprojectFileStamp, cprojectFile.lastModified());
// verify that building the project does not touch project-model files
project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, null);
assertEquals(projectFileStamp, projectFile.lastModified());
assertEquals(cprojectFileStamp, cprojectFile.lastModified());
}
finally {
if(project != null)
project.delete(true, null);
}
}
private void checkArrays(Object[] a1, Object[] a2){
if(a1 == null){
assertTrue(a2 == null);

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2007, 2010 Intel Corporation and others.
* Copyright (c) 2007, 2012 Intel Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -7,6 +7,7 @@
*
* Contributors:
* Intel Corporation - Initial API and implementation
* Baltasar Belyavsky (Texas Instruments) - bug 340219: Project metadata files are saved unnecessarily
*******************************************************************************/
package org.eclipse.cdt.managedbuilder.internal.core;
@ -25,7 +26,6 @@ import org.eclipse.cdt.managedbuilder.core.IManagedProject;
import org.eclipse.cdt.managedbuilder.core.IToolChain;
import org.eclipse.cdt.managedbuilder.core.ManagedBuildManager;
import org.eclipse.cdt.managedbuilder.core.ManagedBuilderCorePlugin;
import org.eclipse.cdt.managedbuilder.core.ManagedCProjectNature;
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
@ -59,7 +59,6 @@ public class BuilderFactory {
static final String CONTENTS_BUILDER = PREFIX + ".builder"; //$NON-NLS-1$
static final String CONTENTS_BUILDER_CUSTOMIZATION = PREFIX + ".builderCustomization"; //$NON-NLS-1$
static final String CONTENTS_CONFIGURATION_IDS = PREFIX + ".configurationIds"; //$NON-NLS-1$
static final String CONTENTS_ACTIVE_CFG_SETTINGS = PREFIX + ".activeConfigSettings"; //$NON-NLS-1$
// static final String IDS = PREFIX + ".ids"; //$NON-NLS-1$
static final String CONFIGURATION_IDS = PREFIX + ".configurationIds"; //$NON-NLS-1$
@ -225,19 +224,6 @@ public class BuilderFactory {
return el.toStringMap();
}
private static Map<String, String> builderBuildArgsMap(IBuilder builder){
MapStorageElement el = new BuildArgsStorageElement("", null); //$NON-NLS-1$
((Builder)builder).serializeRawData(el);
Boolean d = Boolean.valueOf(builder.isDefaultBuildCmd());
el.setAttribute(BuilderFactory.USE_DEFAULT_BUILD_CMD, d.toString());
Map<String, String> map = el.toStringMap();
map.put(CONTENTS, CONTENTS_ACTIVE_CFG_SETTINGS);
return map;
}
public static IBuilder createCustomBuilder(IConfiguration cfg, String builderId) throws CoreException{
IBuilder builder = cfg.getBuilder();
if(!builderId.equals(builder.getId())){
@ -293,6 +279,31 @@ public class BuilderFactory {
// return createBuilder(cfg, args);
}
/**
* Creates a new build-command containing data dynamically obtained from the Builder.
*/
public static ICommand createCommandFromBuilder(IBuilder builder) throws CoreException {
IProject project = builder.getParent().getParent().getOwner().getProject();
ICommand command = getBuildSpec(project.getDescription(), CommonBuilder.BUILDER_ID);
if(command == null)
return null;
MapStorageElement el = new BuildArgsStorageElement("", null); //$NON-NLS-1$
((Builder)builder).serializeRawData(el);
// always set to false - the raw data will always explicitly contain the build-command
el.setAttribute(BuilderFactory.USE_DEFAULT_BUILD_CMD, Boolean.FALSE.toString());
command.setArguments(el.toStringMap());
command.setBuilding(IncrementalProjectBuilder.AUTO_BUILD, builder.isAutoBuildEnable());
command.setBuilding(IncrementalProjectBuilder.FULL_BUILD, builder.isFullBuildEnabled());
command.setBuilding(IncrementalProjectBuilder.INCREMENTAL_BUILD, builder.isIncrementalBuildEnabled());
command.setBuilding(IncrementalProjectBuilder.CLEAN_BUILD, builder.isCleanBuildEnabled());
return command;
}
public static ICommand getBuildSpec(IProjectDescription description, String builderID) {
ICommand[] commands = description.getBuildSpec();
for (int i = 0; i < commands.length; ++i) {
@ -350,6 +361,7 @@ public class BuilderFactory {
IConfiguration cfg = info.getDefaultConfiguration();
IBuilder builder = cfg.getEditableBuilder();
builders = new IBuilder[]{builder};
} else {
String type = args.get(CONTENTS);
if(type == null || CONTENTS_BUILDER_CUSTOMIZATION.equals(type)){
@ -361,12 +373,6 @@ public class BuilderFactory {
builder = createBuilder(cfg, args, true);
}
builders = new IBuilder[]{builder};
} else if (CONTENTS_ACTIVE_CFG_SETTINGS.equals(type)) {
IConfiguration cfg = info.getDefaultConfiguration();
IBuilder builder = cfg.getEditableBuilder();
builders = new IBuilder[]{builder};
} else if (CONTENTS_BUILDER.equals(type)){
IConfiguration cfgs[] = configsFromMap(args, info);
@ -379,6 +385,7 @@ public class BuilderFactory {
}
builders = list.toArray(new IBuilder[list.size()]);
}
} else if (CONTENTS_CONFIGURATION_IDS.equals(type)){
IConfiguration cfgs[] = configsFromMap(args, info);
if(cfgs.length != 0){
@ -388,6 +395,17 @@ public class BuilderFactory {
}
builders = list.toArray(new IBuilder[list.size()]);
}
} else if ("org.eclipse.cdt.make.core.activeConfigSettings".equals(type)) { //$NON-NLS-1$
/* NOTE: Here, only for backwards-compatibility support, since bug 340219 was fixed.
* Existing projects will still be going through this execution path, but new
* projects will no longer store the active-configuration's builder-arguments in the
* build-command, and will be going through the "args == null" condition above.
*/
IConfiguration cfg = info.getDefaultConfiguration();
IBuilder builder = cfg.getEditableBuilder();
builders = new IBuilder[]{builder};
} /*else if (CONTENTS_BUILDER_CUSTOMIZATION.equals(type)){
String idsString = (String)args.get(CONFIGURATION_IDS);
if(idsString != null){
@ -415,39 +433,4 @@ public class BuilderFactory {
return EMPTY_BUILDERS_ARRAY;
}
public static int applyBuilder(IProjectDescription eDes, IBuilder builder){
return applyBuilder(eDes, CommonBuilder.BUILDER_ID, builder);
}
public static final int CMD_UNDEFINED = -1;
public static final int NO_CHANGES = 0;
public static final int CMD_CHANGED = 1;
public static int applyBuilder(IProjectDescription eDes, String eBuilderId, IBuilder builder){
ICommand cmd = ManagedCProjectNature.getBuildSpec(eDes, eBuilderId);
if(cmd == null)
return CMD_UNDEFINED;
if(applyBuilder(cmd, builder)){
ManagedCProjectNature.setBuildSpec(eDes, cmd);
return CMD_CHANGED;
}
return NO_CHANGES;
}
public static boolean applyBuilder(ICommand cmd, IBuilder builder) {
Map<String, String> oldMap = cmd.getArguments();
Map<String, String> map = builderBuildArgsMap(builder);
if(oldMap.equals(map))
return false;
cmd.setArguments(map);
cmd.setBuilding(IncrementalProjectBuilder.AUTO_BUILD, builder.isAutoBuildEnable());
cmd.setBuilding(IncrementalProjectBuilder.FULL_BUILD, builder.isFullBuildEnabled());
cmd.setBuilding(IncrementalProjectBuilder.INCREMENTAL_BUILD, builder.isIncrementalBuildEnabled());
cmd.setBuilding(IncrementalProjectBuilder.CLEAN_BUILD, builder.isCleanBuildEnabled());
return true;
}
}

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2007 Intel Corporation and others.
* Copyright (c) 2007, 2012 Intel Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -7,6 +7,7 @@
*
* Contributors:
* Intel Corporation - Initial API and implementation
* Baltasar Belyavsky (Texas Instruments) - bug 340219: Project metadata files are saved unnecessarily
*******************************************************************************/
package org.eclipse.cdt.managedbuilder.internal.dataprovider;
@ -14,8 +15,12 @@ import org.eclipse.cdt.core.envvar.IEnvironmentContributor;
import org.eclipse.cdt.core.settings.model.ICOutputEntry;
import org.eclipse.cdt.core.settings.model.extension.CBuildData;
import org.eclipse.cdt.managedbuilder.core.IBuilder;
import org.eclipse.cdt.managedbuilder.core.ManagedBuilderCorePlugin;
import org.eclipse.cdt.managedbuilder.internal.core.Builder;
import org.eclipse.cdt.managedbuilder.internal.core.BuilderFactory;
import org.eclipse.cdt.managedbuilder.internal.core.Configuration;
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
@ -32,7 +37,7 @@ public class BuildBuildData extends CBuildData {
public IPath getBuilderCWD() {
return new Path(fBuilder.getBuildPath());//ManagedBuildManager.getBuildLocation(fCfg, fBuilder);
}
// private IPath createAbsolutePathFromWorkspacePath(IPath path){
// IStringVariableManager mngr = VariablesPlugin.getDefault().getStringVariableManager();
// String locationString = mngr.generateVariableExpression("workspace_loc", path.toString()); //$NON-NLS-1$
@ -90,7 +95,18 @@ public class BuildBuildData extends CBuildData {
// return fEnvContibutor;
return new BuildEnvironmentContributor(this);
}
@Override
public ICommand getBuildSpecCommand() {
try {
return BuilderFactory.createCommandFromBuilder(this.fBuilder);
}
catch(CoreException cx) {
ManagedBuilderCorePlugin.log(cx);
return null;
}
}
public IBuilder getBuilder(){
return fBuilder;
}

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2007, 2010 Intel Corporation and others.
* Copyright (c) 2007, 2012 Intel Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -7,6 +7,7 @@
*
* Contributors:
* Intel Corporation - Initial API and implementation
* Baltasar Belyavsky (Texas Instruments) - bug 340219: Project metadata files are saved unnecessarily
*******************************************************************************/
package org.eclipse.cdt.managedbuilder.internal.dataprovider;
@ -33,7 +34,6 @@ import org.eclipse.cdt.core.settings.model.IModificationContext;
import org.eclipse.cdt.core.settings.model.extension.CConfigurationData;
import org.eclipse.cdt.core.settings.model.extension.CConfigurationDataProvider;
import org.eclipse.cdt.managedbuilder.core.BuildException;
import org.eclipse.cdt.managedbuilder.core.IBuilder;
import org.eclipse.cdt.managedbuilder.core.IConfiguration;
import org.eclipse.cdt.managedbuilder.core.IFolderInfo;
import org.eclipse.cdt.managedbuilder.core.IInputType;
@ -47,7 +47,6 @@ import org.eclipse.cdt.managedbuilder.core.IToolChain;
import org.eclipse.cdt.managedbuilder.core.ManagedBuildManager;
import org.eclipse.cdt.managedbuilder.core.ManagedBuilderCorePlugin;
import org.eclipse.cdt.managedbuilder.internal.core.Builder;
import org.eclipse.cdt.managedbuilder.internal.core.BuilderFactory;
import org.eclipse.cdt.managedbuilder.internal.core.Configuration;
import org.eclipse.cdt.managedbuilder.internal.core.ISettingsChangeListener;
import org.eclipse.cdt.managedbuilder.internal.core.InputType;
@ -58,7 +57,6 @@ import org.eclipse.cdt.managedbuilder.internal.core.SettingsChangeEvent;
import org.eclipse.cdt.managedbuilder.internal.core.Tool;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.QualifiedName;
@ -87,28 +85,6 @@ public class ConfigurationDataProvider extends CConfigurationDataProvider implem
}
}
private static class DesApplyRunnable implements IWorkspaceRunnable {
IBuilder fBuilder;
IProject fProject;
DesApplyRunnable(IProject project, IBuilder builder){
fProject = project;
fBuilder = builder;
}
@Override
public void run(IProgressMonitor monitor) throws CoreException {
try {
IProjectDescription eDes = fProject.getDescription();
if(BuilderFactory.applyBuilder(eDes, fBuilder) == BuilderFactory.CMD_CHANGED) {
fProject.setDescription(eDes, monitor);
}
} catch (Exception e){
ManagedBuilderCorePlugin.log(e);
}
}
}
static BuildConfigurationData writeConfiguration(ICConfigurationDescription cfgDescription,
BuildConfigurationData base) throws CoreException {
BuildConfigurationData appliedCfg = base;
@ -182,22 +158,6 @@ public class ConfigurationDataProvider extends CConfigurationDataProvider implem
setPersistedFlag(cfgDescription);
cacheNaturesIdsUsedOnCache(cfgDescription);
if(cfgDescription.isActive()){
IConfiguration cfg = appliedCfg.getConfiguration();
IBuilder builder = cfg.getEditableBuilder();
IProject project = context.getProject();
IProjectDescription eDes = context.getEclipseProjectDescription();
switch(BuilderFactory.applyBuilder(eDes, builder)){
case BuilderFactory.CMD_UNDEFINED:
IWorkspaceRunnable applyR = new DesApplyRunnable(project, builder);
context.addWorkspaceRunnable(applyR);
break;
case BuilderFactory.CMD_CHANGED:
context.setEclipseProjectDescription(eDes);
break;
}
}
}
return appliedCfg;
}

View file

@ -648,14 +648,37 @@
</description>
</wizard>
</extension>
<extension
point="org.eclipse.cdt.ui.LanguageSettingsProviderAssociation">
<id-association
id="org.eclipse.cdt.managedbuilder.core.MBSLanguageSettingsProvider"
icon="icons/obj16/mbs.gif"
ui-clear-entries="false"
ui-edit-entries="false">
</id-association>
</extension>
<extension
point="org.eclipse.cdt.ui.LanguageSettingsProviderAssociation">
<id-association
id="org.eclipse.cdt.managedbuilder.core.MBSLanguageSettingsProvider"
icon="icons/obj16/mbs.gif"
ui-clear-entries="false"
ui-edit-entries="false">
</id-association>
</extension>
<extension
point="org.eclipse.cdt.ui.projectTypePages">
<projectTypePage
class="org.eclipse.cdt.managedbuilder.ui.wizards.ToolChainSelectionPage"
id="org.eclipse.cdt.managedbuilder.ui.exeProjectTypePage"
projectType="org.eclipse.cdt.build.core.buildArtefactType.exe">
</projectTypePage>
<projectTypePage
class="org.eclipse.cdt.managedbuilder.ui.wizards.ToolChainSelectionPage"
id="org.eclipse.cdt.managedbuilder.ui.staticLibProjectTypePage"
projectType="org.eclipse.cdt.build.core.buildArtefactType.staticLib">
</projectTypePage>
<projectTypePage
class="org.eclipse.cdt.managedbuilder.ui.wizards.ToolChainSelectionPage"
id="org.eclipse.cdt.managedbuilder.ui.sharedLibProjectTypePage"
projectType="org.eclipse.cdt.build.core.buildArtefactType.sharedLib">
</projectTypePage>
<projectTypePage
class="org.eclipse.cdt.managedbuilder.ui.wizards.ToolChainSelectionPage"
id="org.eclipse.cdt.managedbuilder.ui.makefileProjectTypePage"
projectType="org.eclipse.cdt.build.makefile.projectType">
</projectTypePage>
</extension>
</plugin>

View file

@ -280,6 +280,8 @@ public class Messages extends NLS {
public static String WizardDefaultsTab_0;
public static String WizardDefaultsTab_1;
public static String RefreshPolicyTab_resourcesTreeLabel;
public static String ToolChainSelectionPage_Description;
public static String ToolChainSelectionPage_Title;
static {
// Initialize resource bundle.

View file

@ -301,3 +301,5 @@ NewCfgDialog_3=-- not selected --
NewCfgDialog_4=Import from projects
NewCfgDialog_5=Import predefined
ToolChainSelectionPage_Description=Select the initial toolchain for this project.
ToolChainSelectionPage_Title=Select Tool Chain

View file

@ -0,0 +1,100 @@
/*******************************************************************************
* Copyright (c) 2012 Doug Schaefer and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Doug Schaefer - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.managedbuilder.ui.wizards;
import org.eclipse.cdt.managedbuilder.core.IToolChain;
import org.eclipse.cdt.managedbuilder.core.ManagedBuildManager;
import org.eclipse.cdt.managedbuilder.internal.ui.Messages;
import org.eclipse.cdt.ui.templateengine.Template;
import org.eclipse.cdt.ui.wizards.ProjectTypePage;
import org.eclipse.jface.wizard.IWizard;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.List;
/**
* @since 8.1
*
*/
public class ToolChainSelectionPage extends WizardPage implements ProjectTypePage {
private IWizardPage nextPage;
private String[] toolChainIds;
private String selectedToolChainId;
private List toolChainList;
public ToolChainSelectionPage() {
super("ToolChainSelectionPage"); //$NON-NLS-1$
setTitle(Messages.ToolChainSelectionPage_Title);
setDescription(Messages.ToolChainSelectionPage_Description);
}
@Override
public void createControl(Composite parent) {
Composite comp = new Composite(parent, SWT.NONE);
comp.setLayout(new GridLayout(1, true));
toolChainList = new List(comp, SWT.BORDER | SWT.SINGLE);
toolChainList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
for (String toolChainId : toolChainIds) {
IToolChain toolChain = ManagedBuildManager.getExtensionToolChain(toolChainId);
if (toolChain != null)
toolChainList.add(toolChain.getName());
}
toolChainList.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
if (toolChainList.getSelectionCount() == 0)
selectedToolChainId = null;
else
selectedToolChainId = toolChainIds[toolChainList.getSelectionIndex()];
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
setControl(comp);
}
@Override
public boolean init(Template template, IWizard wizard, IWizardPage nextPage) {
this.nextPage = nextPage;
setWizard(wizard);
toolChainIds = template.getTemplateInfo().getToolChainIds();
// only need this page if there are multiple toolChains to select from.
return toolChainIds != null && toolChainIds.length > 1;
}
@Override
public IWizardPage getNextPage() {
if (nextPage != null)
return nextPage;
return super.getNextPage();
}
@Override
public boolean isPageComplete() {
return selectedToolChainId != null;
}
}

View file

@ -6,7 +6,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Gil Barash - Initial implementation
* Gil Barash - Initial implementation
*******************************************************************************/
package org.eclipse.cdt.codan.internal.checkers.ui.quickfix;
@ -33,7 +33,7 @@ import org.eclipse.ltk.core.refactoring.Change;
public class CaseBreakQuickFixBreak extends AbstractAstRewriteQuickFix {
@Override
public boolean isApplicable(IMarker marker) {
int line = marker.getAttribute(IMarker.LINE_NUMBER, -1) - 1;
int line = marker.getAttribute(IMarker.LINE_NUMBER, 0) - 1;
if (line < 0)
return false;
return true;
@ -45,17 +45,18 @@ public class CaseBreakQuickFixBreak extends AbstractAstRewriteQuickFix {
}
protected IASTStatement getStmtBeforeBreak(IMarker marker, IASTTranslationUnit ast) throws BadLocationException {
int line = marker.getAttribute(IMarker.LINE_NUMBER, -1) - 1;
int line = marker.getAttribute(IMarker.LINE_NUMBER, 0) - 1;
if (line < 0)
return null;
IRegion lineInformation = getDocument().getLineInformation(line);
IASTNodeSelector nodeSelector = ast.getNodeSelector(null);
IASTNode containedNode = nodeSelector.findFirstContainedNode(lineInformation.getOffset(), lineInformation.getLength());
IASTNode beforeBreakNode = null;
if (containedNode != null)
if (containedNode != null) {
beforeBreakNode = CxxAstUtils.getEnclosingStatement(containedNode);
else
} else {
beforeBreakNode = nodeSelector.findEnclosingNode(lineInformation.getOffset(), lineInformation.getLength());
}
if (beforeBreakNode instanceof IASTCompoundStatement) {
while (beforeBreakNode != null) {
if (beforeBreakNode.getParent() instanceof IASTCompoundStatement
@ -79,7 +80,7 @@ public class CaseBreakQuickFixBreak extends AbstractAstRewriteQuickFix {
try {
IASTTranslationUnit ast = getTranslationUnitViaEditor(marker).getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS);
IASTStatement beforeBreak = getStmtBeforeBreak(marker, ast);
if (beforeBreak.getParent() instanceof IASTCompoundStatement) {
if (beforeBreak != null && beforeBreak.getParent() instanceof IASTCompoundStatement) {
IASTCompoundStatement enclosingStatement = (IASTCompoundStatement) beforeBreak.getParent();
IASTStatement after = getAfterStatement(beforeBreak);
ASTRewrite r = ASTRewrite.create(enclosingStatement.getTranslationUnit());

View file

@ -43,12 +43,9 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke
public static final String PARAM_EMPTY_CASE = "empty_case_param"; //$NON-NLS-1$
public static final String PARAM_NO_BREAK_COMMENT = "no_break_comment"; //$NON-NLS-1$
public static final String DEFAULT_NO_BREAK_COMMENT = "no break"; //$NON-NLS-1$
private Boolean _checkLastCase; // Should we check the last case in the switch?
private Boolean _checkEmptyCase; // Should we check an empty case (a case without any statements within it)
private String _noBreakComment; // The comment suppressing this warning
public CaseBreakChecker() {
}
private boolean fCheckLastCase; // Should we check the last case in the switch?
private boolean fCheckEmptyCase; // Should we check an empty case (a case without any statements within it)
private String fNoBreakComment; // The comment suppressing this warning
/**
* This visitor looks for "switch" statements and invokes "SwitchVisitor" on them.
@ -99,10 +96,10 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke
// Next is case or end of switch - means this one is the last
if (prevCase != null && (isCaseStatement(next) || next == null)) {
// Check that current statement end with break or any other exit statement
if (!_checkEmptyCase && isCaseStatement(curr) && next != null) {
if (!fCheckEmptyCase && isCaseStatement(curr) && next != null) {
continue; // Empty case and we don't care
}
if (!_checkLastCase && next == null) {
if (!fCheckLastCase && next == null) {
continue; // Last case and we don't care
}
if (!isProducedByMacroExpansion(prevCase) && isFallThroughStamement(curr)) {
@ -116,7 +113,7 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke
}
if (comment != null) {
String str = getTrimmedComment(comment);
if (str.toLowerCase().contains(_noBreakComment.toLowerCase()))
if (str.toLowerCase().contains(fNoBreakComment.toLowerCase()))
continue;
}
reportProblem(curr, prevCase);
@ -162,7 +159,7 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke
}
}
public void reportProblem(IASTStatement curr, IASTStatement prevCase) {
private void reportProblem(IASTStatement curr, IASTStatement prevCase) {
reportProblem(ER_ID, getProblemLocationAtEndOfNode(curr));
}
@ -227,9 +224,9 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke
@Override
public void processAst(IASTTranslationUnit ast) {
_checkLastCase = (Boolean) getPreference(getProblemById(ER_ID, getFile()), PARAM_LAST_CASE);
_checkEmptyCase = (Boolean) getPreference(getProblemById(ER_ID, getFile()), PARAM_EMPTY_CASE);
_noBreakComment = (String) getPreference(getProblemById(ER_ID, getFile()), PARAM_NO_BREAK_COMMENT);
fCheckLastCase = (Boolean) getPreference(getProblemById(ER_ID, getFile()), PARAM_LAST_CASE);
fCheckEmptyCase = (Boolean) getPreference(getProblemById(ER_ID, getFile()), PARAM_EMPTY_CASE);
fNoBreakComment = (String) getPreference(getProblemById(ER_ID, getFile()), PARAM_NO_BREAK_COMMENT);
SwitchFindingVisitor visitor = new SwitchFindingVisitor();
ast.accept(visitor);
}

View file

@ -32,6 +32,7 @@ import org.eclipse.cdt.core.dom.ast.IASTFunctionDefinition;
import org.eclipse.cdt.core.dom.ast.IASTIdExpression;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.dom.ast.IASTNode.CopyStyle;
import org.eclipse.cdt.core.dom.ast.IASTNodeSelector;
import org.eclipse.cdt.core.dom.ast.IASTParameterDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorMacroExpansion;
@ -170,7 +171,7 @@ public final class CxxAstUtils {
simpleDeclaration.addDeclarator(declarator);
return simpleDeclaration;
} else { // Fallback - return a `void` declaration
IASTDeclarator declarator = factory.newDeclarator(astName.copy());
IASTDeclarator declarator = factory.newDeclarator(astName.copy(CopyStyle.withLocations));
IASTSimpleDeclSpecifier declspec = factory.newSimpleDeclSpecifier();
declspec.setType(Kind.eInt);
IASTSimpleDeclaration simpleDeclaration = factory.newSimpleDeclaration(declspec);
@ -273,9 +274,9 @@ public final class CxxAstUtils {
if (child instanceof IASTParameterDeclaration) {
if (nthParam == targetParameterNum) {
IASTParameterDeclaration pd = (IASTParameterDeclaration) child;
IASTDeclSpecifier declspec = pd.getDeclSpecifier().copy();
IASTDeclarator declarator = pd.getDeclarator().copy();
setNameInNestedDeclarator(declarator, astName.copy());
IASTDeclSpecifier declspec = pd.getDeclSpecifier().copy(CopyStyle.withLocations);
IASTDeclarator declarator = pd.getDeclarator().copy(CopyStyle.withLocations);
setNameInNestedDeclarator(declarator, astName.copy(CopyStyle.withLocations));
IASTSimpleDeclaration declaration = factory.newSimpleDeclaration(declspec);
declaration.addDeclarator(declarator);
return declaration;

View file

@ -6,7 +6,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Anton Gorenkov - initial implementation
* Anton Gorenkov - initial implementation
*******************************************************************************/
package org.eclipse.cdt.codan.core.internal.checkers;
@ -15,7 +15,6 @@ import org.eclipse.cdt.codan.internal.checkers.ClassMembersInitializationChecker
/**
* Test for {@see ClassMembersInitializationChecker} class
*
*/
public class ClassMembersInitializationCheckerTest extends CheckerTestCase {
@Override
@ -183,10 +182,11 @@ public class ClassMembersInitializationCheckerTest extends CheckerTestCase {
// T1 t1;
// T2 t2;
// };
// C::C() : i1(0), t1(T1()) {} // 1 warning for: i2.
// template <typename T1, typename T2>
// C<T1,T2>::C() : i1(0), t1(T1()) {} // 1 warning for: i2.
public void testExternalConstructorOfTemplateClassHandling() {
loadCodeAndRun(getAboveComment());
checkErrorLines(8);
checkErrorLines(9);
}
// class C {
@ -476,5 +476,4 @@ public class ClassMembersInitializationCheckerTest extends CheckerTestCase {
loadCodeAndRun(getAboveComment());
checkErrorLines(8,9,10,11);
}
}

View file

@ -10,14 +10,14 @@
*******************************************************************************/
package org.eclipse.cdt.codan.core.internal.checkers;
import java.io.File;
import java.io.IOException;
import org.eclipse.cdt.codan.core.param.IProblemPreference;
import org.eclipse.cdt.codan.core.test.CheckerTestCase;
import org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectChecker;
import org.eclipse.core.resources.IMarker;
import java.io.File;
import java.io.IOException;
/**
* Test for {@see StatementHasNoEffectChecker} class
*
@ -94,19 +94,18 @@ public class StatementHasNoEffectCheckerTest extends CheckerTestCase {
checkNoErrors();
}
/* first file */
// main() {
// int a;
// +a; // error here on line 3
// }
/* second file */
// foo() {
// int a;
//
// +a; // error here on line 4
// }
/* this test is using two files */
public void test2FilesUnaryExpression() throws IOException {
/* This test is using two files */
CharSequence[] code = getContents(2);
File f1 = loadcode(code[0].toString());
File f2 = loadcode(code[1].toString());

View file

@ -41,7 +41,7 @@ public class TestUtils {
public static String loadFile(InputStream st) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(st));
String buffer;
StringBuffer result = new StringBuffer();
StringBuilder result = new StringBuilder();
while ((buffer = br.readLine()) != null) {
result.append(buffer);
}

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2010, 2011 Tomasz Wesolowski and others
* Copyright (c) 2010, 2012 Tomasz Wesolowski and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -20,41 +20,42 @@ public class CaseBreakQuickFixTest extends QuickFixTestCase {
return new CaseBreakQuickFixBreak();
}
// void func() {
// int a;
// switch(a) {
// case 1:
// hello();
// case 2:
// }
// }
//void func() {
// int a;
// switch(a) {
// case 1:
// hello();
// case 2:
// break;
// }
//}
public void testMiddleCase() throws Exception {
loadcode(getAboveComment());
String result = runQuickFixOneFile();
assertContainedIn("break; case 2:", result);
assertContainedIn("break;\tcase 2:", result);
}
// void func() {
// int a;
// switch(a) {
// case 1:
// hello();
// }
// }
//void func() {
// int a;
// switch(a) {
// case 1:
// hello();
// }
//}
public void testLastCase() throws Exception {
loadcode(getAboveComment());
String result = runQuickFixOneFile();
assertContainedIn("break; }", result);
assertContainedIn("break;\t}", result);
}
// void func() {
// int a;
// switch(a) {
// case 1: {
// hello();
// }
// }
// }
//void func() {
// int a;
// switch(a) {
// case 1: {
// hello();
// }
// }
//}
public void testLastCaseComp() throws Exception {
loadcode(getAboveComment());
String result = runQuickFixOneFile();

View file

@ -16,8 +16,8 @@ import org.eclipse.cdt.codan.ui.AbstractCodanCMarkerResolution;
/**
* @author Tomasz Wesolowski
*/
@SuppressWarnings("restriction")
public class CatchByReferenceQuickFixTest extends QuickFixTestCase {
@Override
public void setUp() throws Exception {
super.setUp();
@ -41,7 +41,6 @@ public class CatchByReferenceQuickFixTest extends QuickFixTestCase {
// } catch (C exception) {
// }
// }
@SuppressWarnings("restriction")
public void testCatchByReference() throws Exception {
setQuickFix(new CatchByReferenceQuickFix());
loadcode(getAboveComment());
@ -56,7 +55,6 @@ public class CatchByReferenceQuickFixTest extends QuickFixTestCase {
// } catch (C) {
// }
// }
@SuppressWarnings("restriction")
public void testCatchByReferenceNoDeclName() throws Exception {
setQuickFix(new CatchByReferenceQuickFix());
loadcode(getAboveComment());
@ -71,7 +69,6 @@ public class CatchByReferenceQuickFixTest extends QuickFixTestCase {
// } catch (C exception) {
// }
// }
@SuppressWarnings("restriction")
public void testCatchByConstReference() throws Exception {
setQuickFix(new CatchByConstReferenceQuickFix());
loadcode(getAboveComment());
@ -86,7 +83,6 @@ public class CatchByReferenceQuickFixTest extends QuickFixTestCase {
// } catch (C) {
// }
// }
@SuppressWarnings("restriction")
public void testCatchByConstReferenceNoDeclName() throws Exception {
setQuickFix(new CatchByConstReferenceQuickFix());
loadcode(getAboveComment());

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2009,2010 QNX Software Systems
* Copyright (c) 2009, 2010 QNX Software Systems
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at

View file

@ -39,17 +39,16 @@ public class SuggestedParenthesisQuickFixTest extends QuickFixTestCase {
// @file:header.h
// int foo();
/* ---- */
// @file:main.c
// #include "header.h"
// main() {
// foo();
// }
/*
* this test is using two files, there was not actually bugs here so
* quick fix is not called
*/
public void test2FilesExample() throws Exception {
/*
* There are no problems in either of the two files, so quick fix is not called.
*/
CharSequence[] code = getContents(2);
File f1 = loadcode(code[0].toString());
File f2 = loadcode(code[1].toString());

View file

@ -6,7 +6,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems (Alena Laskavaia) - initial API and implementation
* QNX Software Systems (Alena Laskavaia) - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.codan.core.model;
@ -16,7 +16,7 @@ import org.eclipse.core.resources.IResource;
/**
* Abstract implementation of a IProblemReporter
*
*
* @since 2.0
*/
public abstract class AbstractProblemReporter implements IProblemReporter {
@ -30,7 +30,7 @@ public abstract class AbstractProblemReporter implements IProblemReporter {
IProblem problem = CheckersRegistry.getInstance().getResourceProfile(file).findProblem(id);
if (problem == null)
throw new IllegalArgumentException("Id is not registered:" + id); //$NON-NLS-1$
if (problem.isEnabled() == false)
if (!problem.isEnabled())
return; // skip
ICodanProblemMarker codanProblemMarker = new CodanProblemMarker(problem, loc, args);
reportProblem(codanProblemMarker);

View file

@ -6,7 +6,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alena Laskavaia - initial API and implementation
* Alena Laskavaia - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.codan.core.model;

View file

@ -6,14 +6,13 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alena Laskavaia - initial API and implementation
* Alena Laskavaia - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.codan.internal.core.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import org.eclipse.cdt.codan.core.CodanCorePlugin;
import org.eclipse.cdt.codan.core.CodanRuntime;
@ -36,16 +35,15 @@ import org.eclipse.core.runtime.IProgressMonitor;
/**
* Problem reported that created eclipse markers
*/
public class CodanMarkerProblemReporter extends AbstractProblemReporter implements
IProblemReporterPersistent, IProblemReporterSessionPersistent {
public class CodanMarkerProblemReporter extends AbstractProblemReporter
implements IProblemReporterPersistent, IProblemReporterSessionPersistent {
private IResource resource;
private IChecker checker;
private ArrayList<ICodanProblemMarker> toAdd = new ArrayList<ICodanProblemMarker>();
/**
* Create instance, which can be use as factory for
* IProblemReporterSessionPersistent or
* as IProblemReporterPersistent.
* IProblemReporterSessionPersistent or as IProblemReporterPersistent.
*/
public CodanMarkerProblemReporter() {
super();
@ -117,9 +115,8 @@ public class CodanMarkerProblemReporter extends AbstractProblemReporter implemen
@Override
public void run(IProgressMonitor monitor) throws CoreException {
Collection<IMarker> markers = findResourceMarkers(file, checker);
for (Iterator<IMarker> iterator = markers.iterator(); iterator.hasNext();) {
IMarker iMarker = iterator.next();
iMarker.delete();
for (IMarker marker : markers) {
marker.delete();
}
}
}, null, IWorkspace.AVOID_UPDATE, null);
@ -143,12 +140,10 @@ public class CodanMarkerProblemReporter extends AbstractProblemReporter implemen
}
ICheckersRegistry reg = CodanRuntime.getInstance().getCheckersRegistry();
Collection<IProblem> problems = reg.getRefProblems(checker);
for (int i = 0; i < markers.length; i++) {
IMarker m = markers[i];
for (IMarker m : markers) {
String id = m.getAttribute(ICodanProblemMarker.ID, ""); //$NON-NLS-1$
for (Iterator<IProblem> iterator = problems.iterator(); iterator.hasNext();) {
IProblem iProblem = iterator.next();
if (iProblem.getId().equals(id)) {
for (IProblem problem : problems) {
if (problem.getId().equals(id)) {
res.add(m);
}
}
@ -176,10 +171,11 @@ public class CodanMarkerProblemReporter extends AbstractProblemReporter implemen
@Override
public void done() {
if (checker != null) {
if (toAdd.size() == 0)
if (toAdd.isEmpty()) {
deleteProblems(false);
else
} else {
reconcileMarkers();
}
toAdd.clear();
}
}
@ -190,8 +186,7 @@ public class CodanMarkerProblemReporter extends AbstractProblemReporter implemen
@Override
public void run(IProgressMonitor monitor) throws CoreException {
Collection<IMarker> markers = findResourceMarkers(resource, checker);
for (Iterator<IMarker> iterator = markers.iterator(); iterator.hasNext();) {
IMarker m = iterator.next();
for (IMarker m : markers) {
ICodanProblemMarker cm = similarMarker(m);
if (cm == null) {
m.delete();
@ -200,8 +195,7 @@ public class CodanMarkerProblemReporter extends AbstractProblemReporter implemen
toAdd.remove(cm);
}
}
for (Iterator<ICodanProblemMarker> iterator = toAdd.iterator(); iterator.hasNext();) {
ICodanProblemMarker cm = iterator.next();
for (ICodanProblemMarker cm : toAdd) {
cm.createMarker();
}
}
@ -244,8 +238,7 @@ public class CodanMarkerProblemReporter extends AbstractProblemReporter implemen
protected ICodanProblemMarker similarMarker(IMarker m) {
ICodanProblemMarker mcm = CodanProblemMarker.createCodanProblemMarkerFromResourceMarker(m);
ArrayList<ICodanProblemMarker> cand = new ArrayList<ICodanProblemMarker>();
for (Iterator<ICodanProblemMarker> iterator = toAdd.iterator(); iterator.hasNext();) {
ICodanProblemMarker cm = iterator.next();
for (ICodanProblemMarker cm : toAdd) {
if (mcm.equals(cm))
return cm;
if (markersAreSimilar(mcm, cm)) {
@ -276,11 +269,6 @@ public class CodanMarkerProblemReporter extends AbstractProblemReporter implemen
return true;
}
/*
* (non-Javadoc)
*
* @see IProblemReporterSessionPersistent#deleteProblems(boolean)
*/
@Override
public void deleteProblems(boolean all) {
if (all)

View file

@ -6,7 +6,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems (Alena Laskavaia) - initial API and implementation
* QNX Software Systems (Alena Laskavaia) - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.codan.internal.core.model;
@ -31,7 +31,7 @@ import org.eclipse.core.runtime.CoreException;
/**
* Instance of a problem. Intermediate representation before problem become a
* marker
*
*
* @since 1.1
*/
public class CodanProblemMarker implements ICodanProblemMarker {
@ -40,11 +40,6 @@ public class CodanProblemMarker implements ICodanProblemMarker {
private IProblem problem;
private Object args[];
@Override
public Object[] getArgs() {
return args;
}
/**
* @param problem
* @param loc
@ -56,41 +51,26 @@ public class CodanProblemMarker implements ICodanProblemMarker {
this.args = args;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.cdt.codan.core.model.ICodanProblemMarker#getLocation()
*/
@Override
public Object[] getArgs() {
return args;
}
@Override
public IProblemLocation getLocation() {
return loc;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.cdt.codan.core.model.ICodanProblemMarker#getProblem()
*/
@Override
public IProblem getProblem() {
return problem;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.cdt.codan.core.model.ICodanProblemMarker#getResource()
*/
@Override
public IResource getResource() {
return loc.getFile();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.cdt.codan.core.model.ICodanProblemMarker#createMarker()
*/
@Override
public IMarker createMarker() throws CoreException {
IResource file = loc.getFile();
@ -112,11 +92,6 @@ public class CodanProblemMarker implements ICodanProblemMarker {
return marker;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.cdt.codan.core.model.ICodanProblemMarker#createMessage()
*/
@Override
public String createMessage() {
String messagePattern = problem.getMessagePattern();
@ -130,10 +105,6 @@ public class CodanProblemMarker implements ICodanProblemMarker {
return message;
}
/**
* @param args2
* @return
*/
private static String serializeArgs(Object[] args) {
if (args != null) {
Properties prop = new Properties();
@ -155,9 +126,9 @@ public class CodanProblemMarker implements ICodanProblemMarker {
}
/**
* Return the argument of a problem that checker passed to "reportProblem"
* Returns the argument of a problem that checker passed to "reportProblem"
* method
*
*
* @param marker - problem marker
* @param index - index of the argument 0 based
* @return problem argument at index, can be null if not set. Can throw AUBE
@ -169,9 +140,9 @@ public class CodanProblemMarker implements ICodanProblemMarker {
}
/**
* Return the arguments of a problem that checker passed to "reportProblem"
* Returns the arguments of a problem that checker passed to "reportProblem"
* method
*
*
* @param marker - problem marker
* @return problem arguments, can not be null. Can be 0 sized array.
*/
@ -194,8 +165,8 @@ public class CodanProblemMarker implements ICodanProblemMarker {
}
/**
* Return problemId from marker
*
* Returns problemId from marker
*
* @param marker
* @return codan problemId
*/
@ -225,8 +196,8 @@ public class CodanProblemMarker implements ICodanProblemMarker {
}
/**
* Attempt to restore CodamProblemMaker from the resource marker
*
* Attempts to restore CodamProblemMaker from the resource marker
*
* @param marker
* @return new instanceof of ICodanProblemMarker or null if marker is not
* codan marker
@ -239,10 +210,6 @@ public class CodanProblemMarker implements ICodanProblemMarker {
return new CodanProblemMarker(problem, loc, getProblemArguments(marker));
}
/**
* @param marker
* @return
*/
public static CodanProblem getProblem(IMarker marker) {
String id = getProblemId(marker);
if (id == null)
@ -255,10 +222,6 @@ public class CodanProblemMarker implements ICodanProblemMarker {
return problem;
}
/**
* @param resource
* @return
*/
public static IProblemProfile getProfile(IResource resource) {
IProblemProfile profile = CheckersRegistry.getInstance().getResourceProfile(resource);
return profile;
@ -276,11 +239,6 @@ public class CodanProblemMarker implements ICodanProblemMarker {
return loc;
}
/**
* @param marker
* @param res
* @throws CoreException
*/
public static void setProblemArguments(IMarker marker, String[] args) throws CoreException {
String propArgs = serializeArgs(args);
marker.setAttribute(PROBLEM_ARGS, propArgs);

View file

@ -6,7 +6,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andrew Gvozdev - initial API and implementation
* Andrew Gvozdev - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.codan.internal.ui;
@ -32,22 +32,22 @@ import org.eclipse.ui.IMarkerResolutionGenerator;
public class CodanProblemMarkerResolutionGenerator implements IMarkerResolutionGenerator {
private static final String EXTENSION_POINT_NAME = "codanMarkerResolution"; //$NON-NLS-1$
private static Map<String, Collection<ConditionalResolution>> resolutions = new HashMap<String, Collection<ConditionalResolution>>();
private static boolean resolutionsLoaded = false;
private static final Map<String, Collection<ConditionalResolution>> resolutions = new HashMap<String, Collection<ConditionalResolution>>();
private static boolean resolutionsLoaded;
static class ConditionalResolution {
IMarkerResolution res;
String messagePattern;
public ConditionalResolution(IMarkerResolution res2, String messagePattern2) {
res = res2;
messagePattern = messagePattern2;
public ConditionalResolution(IMarkerResolution res, String messagePattern) {
this.res = res;
this.messagePattern = messagePattern;
}
}
@Override
public IMarkerResolution[] getResolutions(IMarker marker) {
if (resolutionsLoaded == false) {
if (!resolutionsLoaded) {
readExtensions();
}
String id = marker.getAttribute(ICodanProblemMarker.ID, null);

View file

@ -6,7 +6,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Mike Kucera (IBM) - Initial API and implementation
* Mike Kucera (IBM) - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.parser.tests;
@ -28,7 +28,7 @@ public class ASTComparer extends Assert {
private static Set<String> methodsToIgnore = new HashSet<String>(Arrays.asList(
// Prevent infinite recursion
"getParent",
"getParent",
"getTranslationUnit",
"getLastName",
@ -39,6 +39,7 @@ public class ASTComparer extends Assert {
// Can be different in copy
"isFrozen",
"getContainingFilename",
"getOriginalNode",
// These methods are problematic
"getProblem",
@ -62,18 +63,16 @@ public class ASTComparer extends Assert {
"isLValue"
));
public static void assertCopy(IASTNode node1, IASTNode node2) {
try {
assertCopy(node1, node2, 0);
} catch(Exception e) {
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void assertCopy(IASTNode node1, IASTNode node2, int n) throws Exception {
if(node1 == null && node2 == null)
if (node1 == null && node2 == null)
return;
assertNotNull(node1);
assertNotNull(node2);
@ -86,11 +85,11 @@ public class ASTComparer extends Assert {
BeanInfo beanInfo = Introspector.getBeanInfo(klass1);
for(PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
Method getter = property.getReadMethod();
if(getter == null)
if (getter == null)
continue;
if(methodsToIgnore.contains(getter.getName()))
if (methodsToIgnore.contains(getter.getName()))
continue;
if (getter.getAnnotation(Deprecated.class) != null)
@ -99,48 +98,43 @@ public class ASTComparer extends Assert {
try {
Class returnType = getter.getReturnType();
if(IASTNode.class.isAssignableFrom(returnType)) {
if (IASTNode.class.isAssignableFrom(returnType)) {
//System.out.println(spaces(n) + "Testing1: " + getter.getName());
IASTNode result1 = (IASTNode) getter.invoke(node1);
IASTNode result2 = (IASTNode) getter.invoke(node2);
assertCopy(result1, result2, n+1); // members must be same
}
else if(returnType.isArray() && IASTNode.class.isAssignableFrom(returnType.getComponentType())) {
assertCopy(result1, result2, n + 1); // members must be same
} else if (returnType.isArray() && IASTNode.class.isAssignableFrom(returnType.getComponentType())) {
//System.out.println(spaces(n) + "Testing2: " + getter.getName());
IASTNode[] result1 = (IASTNode[]) getter.invoke(node1);
IASTNode[] result2 = (IASTNode[]) getter.invoke(node2);
if(result1 == null && result2 == null)
if (result1 == null && result2 == null)
continue;
assertNotNull(result1);
assertNotNull(result2);
assertEquals(result1.length, result2.length);
for(int i = 0; i < result1.length; i++)
assertCopy(result1[i], result2[i], n+1);
}
else if((returnType.isPrimitive() || returnType.equals(String.class)) && !returnType.equals(Void.class)) {
assertCopy(result1[i], result2[i], n + 1);
} else if ((returnType.isPrimitive() || returnType.equals(String.class)) && !returnType.equals(Void.class)) {
//System.out.println(spaces(n) + "Testing3: " + getter.getName());
Object result1 = getter.invoke(node1);
Object result2 = getter.invoke(node2);
assertEquals(result1, result2);
}
} catch(AssertionFailedError e) {
} catch (AssertionFailedError e) {
System.out.printf("Failure when calling %s.%s() @(%d,%d)\n",
node1.getClass().getSimpleName(),
getter.getName(),
((ASTNode)node1).getOffset(),
((ASTNode)node1).getLength());
((ASTNode) node1).getOffset(),
((ASTNode) node1).getLength());
throw e;
}
}
}
// private static String spaces(int n) {
// char[] spaces = new char[n*2];
// Arrays.fill(spaces, ' ');
// return new String(spaces);
// }
}

View file

@ -597,11 +597,27 @@ public class AST2BaseTest extends BaseTestCase {
public IASTName findName(String section, int len) {
final int offset = contents.indexOf(section);
assertTrue(offset >= 0);
assertTrue("Section \"" + section + "\" not found", offset >= 0);
IASTNodeSelector selector = tu.getNodeSelector(null);
return selector.findName(offset, len);
}
public IASTName findName(String context, String name) {
if (context == null) {
context = contents;
}
int offset = contents.indexOf(context);
assertTrue("Context \"" + context + "\" not found", offset >= 0);
int nameOffset = context.indexOf(name);
assertTrue("Name \"" + name + "\" not found", nameOffset >= 0);
IASTNodeSelector selector = tu.getNodeSelector(null);
return selector.findName(offset + nameOffset, name.length());
}
public IASTName findName(String name) {
return findName(contents, name);
}
public IASTName findImplicitName(String section, int len) {
final int offset = contents.indexOf(section);
assertTrue(offset >= 0);

View file

@ -56,6 +56,7 @@ public class DOMParserTestSuite extends TestCase {
suite.addTest(LanguageExtensionsTest.suite());
suite.addTest(ASTInactiveCodeTests.suite());
suite.addTest(AccessControlTests.suite());
suite.addTest(VariableReadWriteFlagsTest.suite());
return suite;
}
}

View file

@ -0,0 +1,185 @@
/*******************************************************************************
* Copyright (c) 2012 Google, Inc and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Sergey Prigogin (Google) - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.parser.tests.ast2;
import java.io.IOException;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.internal.core.dom.parser.c.CVariableReadWriteFlags;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVariableReadWriteFlags;
import org.eclipse.cdt.internal.core.parser.ParserException;
import org.eclipse.cdt.internal.core.pdom.dom.PDOMName;
/**
* Unit tests for CPPVariableReadWriteFlags and CVariableReadWriteFlags classes.
*/
public class VariableReadWriteFlagsTest extends AST2BaseTest {
private static final int READ = PDOMName.READ_ACCESS;
private static final int WRITE = PDOMName.WRITE_ACCESS;
protected class AssertionHelper extends BindingAssertionHelper {
AssertionHelper(String contents, boolean isCPP) throws ParserException {
super(contents, isCPP);
}
void assertReadWriteFlags(String context, String name, int expectedFlags) throws Exception {
IASTName variable = findName(context, name);
assertNotNull(variable);
assertEquals(flagsToString(expectedFlags), flagsToString(getReadWriteFlags(variable)));
}
void assertReadWriteFlags(String name, int expectedFlags) throws Exception {
assertReadWriteFlags(null, name, expectedFlags);
}
int getReadWriteFlags(IASTName variable) {
return isCPP ?
CPPVariableReadWriteFlags.getReadWriteFlags(variable) :
CVariableReadWriteFlags.getReadWriteFlags(variable);
}
private String flagsToString(int flags) {
StringBuilder buf = new StringBuilder();
if ((flags & READ) != 0) {
buf.append("READ");
}
if ((flags & WRITE) != 0) {
if (buf.length() != 0)
buf.append(" | ");
buf.append("WRITE");
}
if (buf.length() == 0)
buf.append("0");
return buf.toString();
}
}
public VariableReadWriteFlagsTest() {
}
public VariableReadWriteFlagsTest(String name) {
super(name);
}
public static TestSuite suite() {
return suite(VariableReadWriteFlagsTest.class);
}
protected AssertionHelper getCAssertionHelper() throws ParserException, IOException {
String code= getAboveComment();
return new AssertionHelper(code, false);
}
protected AssertionHelper getCPPAssertionHelper() throws ParserException, IOException {
String code= getAboveComment();
return new AssertionHelper(code, true);
}
// int test(int a) {
// a = 2;
// a *= 3;
// return a + 1;
// }
public void testSimpleAccess() throws Exception {
AssertionHelper a = getCPPAssertionHelper();
a.assertReadWriteFlags("a = 2", "a", WRITE);
a.assertReadWriteFlags("a *= 3", "a", READ | WRITE);
a.assertReadWriteFlags("a + 1", "a", READ);
}
// class C {
// public:
// C(int);
// };
//
// class D {
// public:
// D();
// };
//
// int a;
// int b = 1;
// C c;
// D d;
// C e(1);
// template<typename T> void foo(T p) {
// T f;
// }
public void testVariableDeclaration() throws Exception {
AssertionHelper a = getCPPAssertionHelper();
a.assertReadWriteFlags("int a", "a", 0);
a.assertReadWriteFlags("int b = 1", "b", WRITE);
a.assertReadWriteFlags("C c", "c", 0);
a.assertReadWriteFlags("D d", "d", WRITE);
a.assertReadWriteFlags("C e(1)", "e", WRITE);
a.assertReadWriteFlags("T f", "f", WRITE);
}
// struct A { int x; };
//
// void test(A a, A* ap) {
// a.x = 1;
// (&a)->x = 1;
// ap->x = 1;
// };
public void testFieldAccess() throws Exception {
AssertionHelper a = getCPPAssertionHelper();
a.assertReadWriteFlags("a.x", "a", WRITE);
a.assertReadWriteFlags("a.x", "x", WRITE);
a.assertReadWriteFlags("(&a)->x", "a", WRITE);
a.assertReadWriteFlags("(&a)->x", "x", WRITE);
a.assertReadWriteFlags("ap->x", "ap", READ);
a.assertReadWriteFlags("ap->x", "x", WRITE);
}
// void f(int* x, int& y);
// void g(const int* x, const int& y, int z);
//
// void test(int a, int b, int c) {
// f(&a, b);
// g(&a, b, c);
// };
public void testFunctionCall() throws Exception {
AssertionHelper a = getCPPAssertionHelper();
a.assertReadWriteFlags("f(&a, b)", "a", READ | WRITE);
a.assertReadWriteFlags("f(&a, b)", "b", READ | WRITE);
a.assertReadWriteFlags("f(&a, b)", "f", READ);
a.assertReadWriteFlags("g(&a, b, c)", "a", READ);
a.assertReadWriteFlags("g(&a, b, c)", "b", READ);
a.assertReadWriteFlags("g(&a, b, c)", "c", READ);
}
// struct A {
// void m();
// void mc() const;
// };
//
// void test(A a, A* ap) {
// a.m();
// a.mc();
// (&a)->m();
// (&a)->mc();
// ap->m();
// (*ap).m();
// };
public void testMethodCall() throws Exception {
AssertionHelper a = getCPPAssertionHelper();
a.assertReadWriteFlags("a.m()", "a", READ | WRITE);
a.assertReadWriteFlags("a.m()", "m", READ);
a.assertReadWriteFlags("a.mc()", "a", READ);
a.assertReadWriteFlags("(&a)->m()", "a", READ | WRITE);
a.assertReadWriteFlags("(&a)->m()", "m", READ);
a.assertReadWriteFlags("ap->m()", "ap", READ);
a.assertReadWriteFlags("(*ap).m()", "ap", READ);
}
}

View file

@ -13,8 +13,9 @@ package org.eclipse.cdt.core.parser.tests.rewrite.changegenerator.replace;
import junit.framework.Test;
import org.eclipse.cdt.core.dom.ast.IASTStatement;
import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTNode.CopyStyle;
import org.eclipse.cdt.core.dom.ast.IASTStatement;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTForStatement;
import org.eclipse.cdt.core.parser.tests.rewrite.changegenerator.ChangeGeneratorTest;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPNodeFactory;
@ -60,7 +61,7 @@ public class WhitespaceHandlingTest extends ChangeGeneratorTest {
ICPPASTForStatement forStatement = (ICPPASTForStatement) statement;
CPPNodeFactory nf = CPPNodeFactory.getDefault();
ICPPASTForStatement newFor = forStatement.copy();
ICPPASTForStatement newFor = forStatement.copy(CopyStyle.withLocations);
newFor.setBody(nf.newNullStatement());
ASTModification modification = new ASTModification(ASTModification.ModificationKind.REPLACE, forStatement, newFor, null);

View file

@ -117,7 +117,7 @@ public class TestSourceReader {
if (line.startsWith("//")) {
content.append(line.substring(2) + "\n");
} else {
if (content.length() > 0) {
if (!line.startsWith("@") && content.length() > 0) {
contents.add(content);
if (sections > 0 && contents.size() == sections + 1)
contents.remove(0);
@ -128,7 +128,9 @@ public class TestSourceReader {
if (idx != -1 && !Character.isJavaIdentifierPart(line.charAt(idx + testName.length()))) {
return contents.toArray(new StringBuilder[contents.size()]);
}
contents.clear();
if (!line.startsWith("@")) {
contents.clear();
}
}
}
}

View file

@ -14,6 +14,19 @@
</message_arguments>
</filter>
</resource>
<resource path="parser/org/eclipse/cdt/core/dom/ast/IASTCopyLocation.java" type="org.eclipse.cdt.core.dom.ast.IASTCopyLocation">
<filter id="403853384">
<message_arguments>
<message_argument value="org.eclipse.cdt.core.dom.ast.IASTCopyLocation"/>
</message_arguments>
</filter>
<filter id="406052990">
<message_arguments>
<message_argument value="org.eclipse.cdt.core.dom.ast.IASTCopyLocation"/>
<message_argument value="getOriginalNode()"/>
</message_arguments>
</filter>
</resource>
<resource path="parser/org/eclipse/cdt/core/parser/util/ArrayUtil.java" type="org.eclipse.cdt.core.parser.util.ArrayUtil">
<filter id="420679712">
<message_arguments>

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 Intel Corporation and others.
* Copyright (c) 2007, 2012 Intel Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -7,12 +7,14 @@
*
* Contributors:
* Intel Corporation - Initial API and implementation
* Baltasar Belyavsky (Texas Instruments) - bug 340219: Project metadata files are saved unnecessarily
*******************************************************************************/
package org.eclipse.cdt.core.settings.model.extension;
import org.eclipse.cdt.core.envvar.IEnvironmentContributor;
import org.eclipse.cdt.core.settings.model.ICOutputEntry;
import org.eclipse.cdt.core.settings.model.ICSettingBase;
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.runtime.IPath;
public abstract class CBuildData extends CDataObject {
@ -26,12 +28,22 @@ public abstract class CBuildData extends CDataObject {
public abstract void setBuilderCWD(IPath path);
public abstract ICOutputEntry[] getOutputDirectories();
public abstract void setOutputDirectories(ICOutputEntry[] entries);
public abstract String[] getErrorParserIDs();
public abstract void setErrorParserIDs(String[] ids);
public abstract IEnvironmentContributor getBuildEnvironmentContributor();
/**
* Override to return the build-command overlayed with data (eg. builder-arguments) managed by the build-system.
*
* @since 5.4
*/
public ICommand getBuildSpecCommand() {
return null;
}
}

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2007, 2010 Intel Corporation and others.
* Copyright (c) 2007, 2012 Intel Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -8,6 +8,7 @@
* Contributors:
* Intel Corporation - Initial API and implementation
* James Blackburn (Broadcom Corp.)
* Baltasar Belyavsky (Texas Instruments) - bug 340219: Project metadata files are saved unnecessarily
*******************************************************************************/
package org.eclipse.cdt.internal.core.settings.model;
@ -50,7 +51,6 @@ public class CProjectDescription implements ICProjectDescription, ICDataProxyCon
private boolean fIsReadOnly;
private boolean fIsModified;
private HashMap<QualifiedName, Object> fPropertiesMap;
// private boolean fNeedsActiveCfgIdPersistence;
private boolean fIsLoading;
private boolean fIsApplying;
private boolean fIsCreating;
@ -549,17 +549,10 @@ public class CProjectDescription implements ICProjectDescription, ICDataProxyCon
return cfg;
}
@Override
public boolean isModified() {
boolean needsDescriptionPersistence() {
if(fIsModified)
return true;
if(fActiveCfgInfo.fIsCfgModified)
return true;
if(fSettingCfgInfo.fIsCfgModified)
return true;
if(fPrefs.isModified())
return true;
@ -573,6 +566,20 @@ public class CProjectDescription implements ICProjectDescription, ICDataProxyCon
return false;
}
@Override
public boolean isModified() {
if(needsDescriptionPersistence())
return true;
if(needsActiveCfgPersistence())
return true;
if(needsSettingCfgPersistence())
return true;
return false;
}
private void setModified(boolean modified){
fIsModified = modified;
@ -665,13 +672,6 @@ public class CProjectDescription implements ICProjectDescription, ICDataProxyCon
}
}
// boolean checkPersistCfgChanges(boolean force){
// boolean stored = false;
// stored |= checkPersistActiveCfg(force);
// stored |= checkPersistSettingCfg(force);
// return stored;
// }
boolean checkPersistActiveCfg(String oldId, boolean force){
return fActiveCfgInfo.store(oldId, force);
}

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2007, 2010 Intel Corporation and others.
* Copyright (c) 2007, 2012 Intel Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -8,6 +8,7 @@
* Contributors:
* Intel Corporation - Initial API and implementation
* James Blackburn (Broadcom Corp.)
* Baltasar Belyavsky (Texas Instruments) - bug 340219: Project metadata files are saved unnecessarily
*******************************************************************************/
package org.eclipse.cdt.internal.core.settings.model;
@ -65,14 +66,14 @@ public class SetCProjectDescriptionOperation extends CModelOperation {
AbstractCProjectDescriptionStorage.fireAboutToApplyEvent(fSetDescription, fOldDescriptionCache);
CProjectDescription fNewDescriptionCache = null;
SettingsContext context = new SettingsContext(project);
boolean modified = false;
boolean needsSerialization = false;
if(fSetDescription != null){
ICStorageElement newEl = null;
ICSettingsStorage newStorage = null;
try {
ICStorageElement base = fSetDescription.getRootStorageElement();
modified = fSetDescription.isModified();
needsSerialization = fSetDescription.needsDescriptionPersistence();
// el = base;
// FIXME JBB there is deep magic going on here. The project descriptions are being
// changed in non-obvious ways
@ -94,13 +95,11 @@ public class SetCProjectDescriptionOperation extends CModelOperation {
boolean envStates[] = getEnvStates(fNewDescriptionCache);
try {
fPrjDescStorage.setThreadLocalProjectDesc(fNewDescriptionCache);
modified |= fNewDescriptionCache.applyDatas(context);
fNewDescriptionCache.applyDatas(context);
} finally {
fPrjDescStorage.setThreadLocalProjectDesc(null);
setEnvStates(fNewDescriptionCache, envStates);
}
} else {
modified = fOldDescriptionCache != null;
}
ICDescriptionDelta delta = mngr.createDelta(fNewDescriptionCache, fOldDescriptionCache);
@ -143,7 +142,7 @@ public class SetCProjectDescriptionOperation extends CModelOperation {
try {
IWorkspaceRunnable toRun = null;
if(fNewDescriptionCache != null && !CProjectDescriptionManager.checkFlags(fFlags, ICProjectDescriptionManager.SET_NO_SERIALIZE)){
if(modified || isPersistentCoreSettingChanged(event)){
if(needsSerialization || isPersistentCoreSettingChanged(event)){
toRun = fPrjDescStorage.createDesSerializationRunnable();
if (toRun != null)
context.addWorkspaceRunnable(toRun);
@ -182,7 +181,8 @@ public class SetCProjectDescriptionOperation extends CModelOperation {
return true;
int flags = delta.getChangeFlags();
if(flags != 0 && flags != ICDescriptionDelta.ACTIVE_CFG)
// check for any flag except ACTIVE_CFG and SETTING_CFG
if((flags & ~(ICDescriptionDelta.ACTIVE_CFG | ICDescriptionDelta.SETTING_CFG)) != 0)
return true;
return false;

View file

@ -11,7 +11,6 @@
*******************************************************************************/
package org.eclipse.cdt.core.dom.ast;
/**
* This interface represents a binary expression.
*
@ -36,15 +35,14 @@ public interface IASTBinaryExpression extends IASTExpression {
"IASTBinaryExpression.OPERAND_TWO - IASTExpression for RHS"); //$NON-NLS-1$
/**
* Set the operator.
* Sets the operator.
*
* @param op
* Value to set.
* @param op value to set.
*/
public void setOperator(int op);
/**
* Get the operator.
* Returns the operator.
*
* @return int value as operator
*/
@ -244,7 +242,6 @@ public interface IASTBinaryExpression extends IASTExpression {
* @param expression
* <code>IASTExpression</code> value.
*/
public void setOperand1(IASTExpression expression);
/**

View file

@ -6,7 +6,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Markus Schorn (Wind River Systems) - Initial API and implementation
* Markus Schorn (Wind River Systems) - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.dom.ast;
@ -25,7 +25,7 @@ public interface IASTBinaryTypeIdExpression extends IASTExpression {
public static enum Operator {__is_base_of}
/**
* Get the operator for the expression.
* Returns the operator for the expression.
*/
public Operator getOperator();
@ -40,22 +40,23 @@ public interface IASTBinaryTypeIdExpression extends IASTExpression {
public IASTTypeId getOperand2();
/**
* Set the operator for the expression.
* Sets the operator for the expression.
*/
public void setOperator(Operator value);
/**
* Set the first operand.
* Sets the first operand.
*/
public void setOperand1(IASTTypeId typeId);
/**
* Set the second operand.
* Sets the second operand.
*/
public void setOperand2(IASTTypeId typeId);
@Override
public IASTBinaryTypeIdExpression copy();
@Override
public IASTBinaryTypeIdExpression copy(CopyStyle style);
}

View file

@ -18,6 +18,10 @@ package org.eclipse.cdt.core.dom.ast;
* @noimplement This interface is not intended to be implemented by clients.
*/
public interface IASTComment extends IASTNode {
/**
* @since 5.4
*/
public final IASTComment[] EMPTY_COMMENT_ARRAY = {};
/**
* Set the comment.
@ -39,5 +43,4 @@ public interface IASTComment extends IASTNode {
* @return true if this is a blockcomment
*/
public boolean isBlockComment();
}

View file

@ -7,17 +7,19 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software (IFS)- initial API and implementation
* Institute for Software (IFS)- initial API and implementation
******************************************************************************/
package org.eclipse.cdt.core.dom.ast;
/**
* @author Emanuel Graf IFS
* @noextend This interface is not intended to be extended by clients.
* @noimplement This interface is not intended to be implemented by clients.
* @since 5.3
*
*/
public interface IASTCopyLocation extends IASTNodeLocation {
/**
* @noreference This method is not intended to be referenced by clients.
*/
public IASTNode getOriginalNode();
}

View file

@ -11,7 +11,6 @@
*******************************************************************************/
package org.eclipse.cdt.core.dom.ast;
/**
* This is the root class of expressions.
*
@ -28,7 +27,7 @@ public interface IASTExpression extends IASTInitializerClause {
*/
LVALUE,
/**
* Expiring value as introduced by c++ 0x.
* Expiring value as introduced by c++11.
*/
XVALUE,
/**
@ -42,6 +41,7 @@ public interface IASTExpression extends IASTInitializerClause {
public boolean isRValue() {
return this != LVALUE;
}
/**
* A generalized lvalue is either an lvalue or an xvalue.
*/
@ -53,7 +53,7 @@ public interface IASTExpression extends IASTInitializerClause {
/**
* Empty expression array.
*/
public static final IASTExpression[] EMPTY_EXPRESSION_ARRAY = new IASTExpression[0];
public static final IASTExpression[] EMPTY_EXPRESSION_ARRAY = {};
public IType getExpressionType();

View file

@ -6,20 +6,19 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Doug Schaefer (IBM) - Initial API and implementation
* Doug Schaefer (IBM) - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.dom.ast;
/**
* This interface represents expressions that access a field reference. e.g. a.b =>
* a is the expression, b is the field name. e.g. a()->def => a() is the
* This interface represents expressions that access a field reference. e.g. a.b => a
* is the expression, b is the field name. e.g. a()->def => a() is the
* expression, def is the field name.
*
* @noextend This interface is not intended to be extended by clients.
* @noimplement This interface is not intended to be implemented by clients.
*/
public interface IASTFieldReference extends IASTExpression, IASTNameOwner {
/**
* <code>FIELD_OWNER</code> represents the relationship between a
* <code>IASTFieldReference</code> and its <code>IASTExpression</code>
@ -37,46 +36,44 @@ public interface IASTFieldReference extends IASTExpression, IASTNameOwner {
"IASTFieldReference.FIELD_NAME - IASTName for IASTFieldReference"); //$NON-NLS-1$
/**
* This returns an expression for the object containing the field.
* Returns an expression for the object containing the field.
*
* @return the field owner
*/
public IASTExpression getFieldOwner();
/**
* Set the expression for the object containing the field.
* Sets the expression for the object containing the field.
*
* @param expression
*/
public void setFieldOwner(IASTExpression expression);
/**
* This returns the name of the field being dereferenced.
* Returns the name of the field being dereferenced.
*
* @return the name of the field (<code>IASTName</code>)
*/
public IASTName getFieldName();
/**
* Set the name of the field.
* Sets the name of the field.
*
* @param name
* <code>IASTName</code>
* @param name the new name
*/
public void setFieldName(IASTName name);
/**
* This returns true of this is the arrow operator and not the dot operator.
* Returns true of this is the arrow operator and not the dot operator.
*
* @return is this a pointer dereference
*/
public boolean isPointerDereference();
/**
* Set whether or not this is a pointer dereference (default == no).
* Sets whether or not this is a pointer dereference (default == no).
*
* @param value
* boolean
* @param value the new value
*/
public void setIsPointerDereference(boolean value);
@ -91,5 +88,4 @@ public interface IASTFieldReference extends IASTExpression, IASTNameOwner {
*/
@Override
public IASTFieldReference copy(CopyStyle style);
}

View file

@ -6,7 +6,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Doug Schaefer (IBM) - Initial API and implementation
* Doug Schaefer (IBM) - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.dom.ast;
@ -17,7 +17,6 @@ package org.eclipse.cdt.core.dom.ast;
* @noimplement This interface is not intended to be implemented by clients.
*/
public interface IASTFileLocation extends IASTNodeLocation {
/**
* The name of the file.
*

View file

@ -6,7 +6,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Doug Schaefer (IBM) - Initial API and implementation
* Doug Schaefer (IBM) - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.dom.ast;
@ -17,7 +17,6 @@ package org.eclipse.cdt.core.dom.ast;
* @noimplement This interface is not intended to be implemented by clients.
*/
public interface IASTIdExpression extends IASTExpression, IASTNameOwner {
/**
* <code>ID_NAME</code> represents the relationship between an
* <code>IASTIdExpression</code> and a <code>IASTName</code>.

View file

@ -6,8 +6,8 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
* Markus Schorn (Wind River Systems)
* IBM - Initial API and implementation
* Markus Schorn (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.core.dom.ast;
@ -16,10 +16,8 @@ package org.eclipse.cdt.core.dom.ast;
*/
@Deprecated
public interface IASTMacroExpansion extends IASTNodeLocation {
/**
* The macro definition used for the expansion
*
*/
public IASTPreprocessorMacroDefinition getMacroDefinition();

View file

@ -6,7 +6,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Markus Schorn - initial API and implementation
* Markus Schorn - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.dom.ast;
@ -18,7 +18,6 @@ package org.eclipse.cdt.core.dom.ast;
* @noimplement This interface is not intended to be implemented by clients.
*/
public interface IASTMacroExpansionLocation extends IASTNodeLocation {
/**
* Returns the expansion node enclosing this location. This will be the outermost
* macro expansion that can actually be found in the code.

View file

@ -277,4 +277,11 @@ public interface IASTNode {
* if this node or one of its descendants does not support copying
*/
public IASTNode copy(CopyStyle style);
/**
* If the node is a copy of some other node, returns the original node.
* Otherwise returns the node itself.
* @since 5.4
*/
public IASTNode getOriginalNode();
}

View file

@ -6,7 +6,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Doug Schaefer (IBM) - Initial API and implementation
* Doug Schaefer (IBM) - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.dom.ast;
@ -18,6 +18,8 @@ package org.eclipse.cdt.core.dom.ast;
* @noimplement This interface is not intended to be implemented by clients.
*/
public interface IASTNodeLocation {
/** @since 5.4 */
public static final IASTNodeLocation[] EMPTY_ARRAY = {};
/**
* This is the offset within either the file or a macro-expansion.
@ -33,5 +35,4 @@ public interface IASTNodeLocation {
* Return a file location that best maps into this location.
*/
public IASTFileLocation asFileLocation();
}

View file

@ -17,7 +17,6 @@ package org.eclipse.cdt.core.dom.ast;
* @noimplement This interface is not intended to be implemented by clients.
*/
public interface IASTUnaryExpression extends IASTExpression {
/**
* Prefix increment.
* <code>op_prefixIncr</code> ++exp
@ -32,7 +31,7 @@ public interface IASTUnaryExpression extends IASTExpression {
/**
* Operator plus.
* <code>op_plus</code> ==> + exp
* <code>op_plus</code> ==> +exp
*/
public static final int op_plus = 2;

View file

@ -6,9 +6,9 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* John Camelon (IBM) - Initial API and implementation
* Mike Kucera (IBM)
* Sergey Prigogin (Google)
* John Camelon (IBM) - Initial API and implementation
* Mike Kucera (IBM)
* Sergey Prigogin (Google)
*******************************************************************************/
package org.eclipse.cdt.core.dom.ast.cpp;
@ -22,7 +22,6 @@ import org.eclipse.cdt.core.dom.ast.IASTImplicitNameOwner;
* @noimplement This interface is not intended to be implemented by clients.
*/
public interface ICPPASTBinaryExpression extends IASTBinaryExpression, IASTImplicitNameOwner {
/**
* <code>op_pmdot</code> pointer-to-member field dereference.
*/

View file

@ -6,8 +6,8 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* John Camelon (IBM) - Initial API and implementation
* Mike Kucera (IBM)
* John Camelon (IBM) - Initial API and implementation
* Mike Kucera (IBM)
*******************************************************************************/
package org.eclipse.cdt.core.dom.ast.cpp;
@ -23,7 +23,6 @@ import org.eclipse.cdt.core.dom.ast.IType;
* @noimplement This interface is not intended to be implemented by clients.
*/
public interface ICPPASTFieldReference extends IASTFieldReference, IASTImplicitNameOwner {
/**
* Was template keyword used?
*

View file

@ -20,7 +20,6 @@ import org.eclipse.cdt.core.dom.ast.IPointerType;
* @noimplement This interface is not intended to be implemented by clients.
*/
public interface ICPPFunctionType extends IFunctionType {
/**
* Returns <code>true</code> for a constant method
*/
@ -37,7 +36,6 @@ public interface ICPPFunctionType extends IFunctionType {
*/
public boolean takesVarArgs();
/**
* @deprecated function types don't relate to this pointers at all.
* @noreference This method is not intended to be referenced by clients and should be removed.

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2007, 2011 Wind River Systems, Inc. and others.
* Copyright (c) 2007, 2012 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -260,9 +260,10 @@ public final class ASTRewrite {
}
/**
* Returns comments for the given node.
*
* @param node the node
* @param pos the position
* @param pos the position of the comments
* @return All comments assigned to the node at this position
* @since 5.3
*/

View file

@ -20,7 +20,6 @@ package org.eclipse.cdt.core.dom.rewrite;
* @noextend This interface is not intended to be extended by clients.
*/
public interface ITrackedNodePosition {
/**
* Returns the original or modified start position of the tracked node depending if called before
* or after the rewrite is applied. <code>-1</code> is returned for removed nodes.

View file

@ -8,6 +8,7 @@
* Contributors:
* John Camelon - Initial API and implementation
* Markus Schorn (Wind River Systems)
* Sergey Prigoin (Google)
*******************************************************************************/
package org.eclipse.cdt.internal.core.dom.parser;
@ -35,7 +36,6 @@ import org.eclipse.cdt.internal.core.parser.scanner.Token;
*/
public abstract class ASTNode implements IASTNode {
protected static final ICPPFunction UNINITIALIZED_FUNCTION = new CPPFunction(null);
private static final IASTNodeLocation[] EMPTY_LOCATION_ARRAY = {};
private IASTNode parent;
private ASTNodeProperty property;
@ -138,18 +138,18 @@ public abstract class ASTNode implements IASTNode {
@Override
public IASTNodeLocation[] getNodeLocations() {
if (locations != null)
return locations;
if (length == 0) {
locations= EMPTY_LOCATION_ARRAY;
} else {
final IASTTranslationUnit tu= getTranslationUnit();
if (tu != null) {
ILocationResolver l= (ILocationResolver) tu.getAdapter(ILocationResolver.class);
if (l != null) {
locations= l.getLocations(getOffset(), length);
}
}
if (locations == null) {
if (length != 0) {
final IASTTranslationUnit tu= getTranslationUnit();
if (tu != null) {
ILocationResolver l= (ILocationResolver) tu.getAdapter(ILocationResolver.class);
if (l != null) {
locations= l.getLocations(getOffset(), length);
}
}
}
if (locations == null)
locations= IASTNodeLocation.EMPTY_ARRAY;
}
return locations;
}
@ -259,7 +259,7 @@ public abstract class ASTNode implements IASTNode {
ASTNode astNode= (ASTNode) node;
final int offset = getOffset();
final int nodeOffset= astNode.getOffset();
return offset <= nodeOffset && nodeOffset+astNode.length <= offset+length;
return offset <= nodeOffset && nodeOffset + astNode.length <= offset + length;
}
return false;
}
@ -267,7 +267,7 @@ public abstract class ASTNode implements IASTNode {
@Override
public IToken getSyntax() throws ExpansionOverlapsBoundaryException {
final int offset = getOffset();
return getSyntax(offset, offset+length, 0);
return getSyntax(offset, offset + length, 0);
}
@Override
@ -279,7 +279,7 @@ public abstract class ASTNode implements IASTNode {
@Override
public IToken getTrailingSyntax() throws ExpansionOverlapsBoundaryException {
int right= getBoundary(1);
return getSyntax(getOffset()+length, right, 1);
return getSyntax(getOffset() + length, right, 1);
}
/**
@ -296,15 +296,14 @@ public abstract class ASTNode implements IASTNode {
ASTNode astNode= (ASTNode) sib;
int offset= astNode.getOffset();
if (direction < 0) {
offset+= astNode.getLength();
offset += astNode.getLength();
}
return offset;
}
// no parent
// No parent.
throw new UnsupportedOperationException();
}
private IToken getSyntax(int fromSequenceNumber, int nextSequenceNumber, int direction) throws ExpansionOverlapsBoundaryException {
final IASTTranslationUnit tu= getTranslationUnit();
if (!(tu instanceof ASTNode))
@ -315,7 +314,7 @@ public abstract class ASTNode implements IASTNode {
throw new UnsupportedOperationException();
int endSequenceNumber= lr.convertToSequenceEndNumber(nextSequenceNumber);
IASTFileLocation total= lr.getMappedFileLocation(fromSequenceNumber, endSequenceNumber-fromSequenceNumber);
IASTFileLocation total= lr.getMappedFileLocation(fromSequenceNumber, endSequenceNumber - fromSequenceNumber);
IASTFileLocation myfloc= getFileLocation();
if (total == null || myfloc == null)
throw new UnsupportedOperationException();
@ -324,13 +323,13 @@ public abstract class ASTNode implements IASTNode {
throw new ExpansionOverlapsBoundaryException();
if (fromSequenceNumber > 0) {
IASTFileLocation fl= lr.getMappedFileLocation(fromSequenceNumber-1, endSequenceNumber-fromSequenceNumber+1);
IASTFileLocation fl= lr.getMappedFileLocation(fromSequenceNumber-1, endSequenceNumber - fromSequenceNumber + 1);
if (fl.getFileName().equals(total.getFileName()) && fl.getNodeOffset() == total.getNodeOffset())
throw new ExpansionOverlapsBoundaryException();
}
if (endSequenceNumber < ((ASTNode) tu).getOffset() + ((ASTNode) tu).getLength()) {
IASTFileLocation fl= lr.getMappedFileLocation(fromSequenceNumber, nextSequenceNumber-fromSequenceNumber+1);
IASTFileLocation fl= lr.getMappedFileLocation(fromSequenceNumber, nextSequenceNumber - fromSequenceNumber + 1);
if (fl.getFileName().equals(total.getFileName()) && fl.getNodeLength() == total.getNodeLength())
throw new ExpansionOverlapsBoundaryException();
}
@ -345,7 +344,7 @@ public abstract class ASTNode implements IASTNode {
try {
Token result= null;
Token last= null;
for (;;) {
while (true) {
Token t= lex.nextToken();
switch (t.getType()) {
case IToken.tEND_OF_INPUT:
@ -366,12 +365,24 @@ public abstract class ASTNode implements IASTNode {
}
}
} catch (OffsetLimitReachedException e) {
// does not happen without using content assist limit
// Does not happen without using content assist limit.
}
return null;
}
protected void setCopyLocation(IASTNode originalNode) {
locations = new IASTNodeLocation[] {new ASTCopyLocation(originalNode)};
locations = new IASTNodeLocation[] { new ASTCopyLocation(originalNode) };
}
@Override
public IASTNode getOriginalNode() {
IASTNode node = this;
while (true) {
IASTNodeLocation[] locations = node.getNodeLocations();
if (locations.length == 0 || !(locations[0] instanceof ASTCopyLocation))
break;
node = ((ASTCopyLocation) locations[0]).getOriginalNode();
}
return node;
}
}

View file

@ -6,7 +6,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Markus Schorn - initial API and implementation
* Markus Schorn - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.dom.parser;
@ -57,15 +57,14 @@ public abstract class VariableReadWriteFlags {
protected static final int READ = PDOMName.READ_ACCESS;
protected static final int WRITE = PDOMName.WRITE_ACCESS;
protected VariableReadWriteFlags() {
}
protected int rwAnyNode(IASTNode node, int indirection) {
final IASTNode parent = node.getParent();
if (parent instanceof IASTExpression) {
return rwInExpression((IASTExpression) parent, node, indirection);
} else if (parent instanceof IASTStatement) {
return rwInStatement((IASTStatement) parent, node, indirection);
} else if (parent instanceof IASTDeclarator) {
return rwInDeclarator((IASTDeclarator) parent, indirection);
} else if (parent instanceof IASTEqualsInitializer) {
return rwInEqualsInitializer((IASTEqualsInitializer) parent, indirection);
} else if (parent instanceof IASTArrayModifier) {
@ -76,6 +75,12 @@ public abstract class VariableReadWriteFlags {
return READ | WRITE; // fallback
}
protected int rwInDeclarator(IASTDeclarator parent, int indirection) {
if (parent.getInitializer() != null)
return WRITE;
return 0;
}
protected int rwInEqualsInitializer(IASTEqualsInitializer parent, int indirection) {
IASTNode grand= parent.getParent();
if (grand instanceof IASTDeclarator) {
@ -105,9 +110,15 @@ public abstract class VariableReadWriteFlags {
}
protected int rwInExpression(IASTExpression expr, IASTNode node, int indirection) {
if (expr instanceof IASTIdExpression) {
return rwAnyNode(expr, indirection);
}
if (expr instanceof IASTBinaryExpression) {
return rwInBinaryExpression(node, (IASTBinaryExpression) expr, indirection);
}
if (expr instanceof IASTFieldReference) {
return rwInFieldReference(node, (IASTFieldReference) expr, indirection);
}
if (expr instanceof IASTCastExpression) { // must be ahead of unary
return rwAnyNode(expr, indirection);
}
@ -116,7 +127,7 @@ public abstract class VariableReadWriteFlags {
}
if (expr instanceof IASTArraySubscriptExpression) {
if (indirection > 0 && node.getPropertyInParent() == IASTArraySubscriptExpression.ARRAY) {
return rwAnyNode(expr, indirection-1);
return rwAnyNode(expr, indirection - 1);
}
return READ;
}
@ -134,21 +145,12 @@ public abstract class VariableReadWriteFlags {
}
return 0;
}
if (expr instanceof IASTFieldReference) {
if (node.getPropertyInParent() == IASTFieldReference.FIELD_NAME) {
return rwAnyNode(expr, indirection);
}
return READ;
}
if (expr instanceof IASTFunctionCallExpression) {
if (node.getPropertyInParent() == IASTFunctionCallExpression.FUNCTION_NAME) {
return READ;
return rwInFunctionName((IASTExpression) node);
}
return rwArgumentForFunctionCall((IASTFunctionCallExpression) expr, node, indirection);
}
if (expr instanceof IASTIdExpression) {
return rwAnyNode(expr, indirection);
}
if (expr instanceof IASTProblemExpression) {
return READ | WRITE;
}
@ -159,7 +161,25 @@ public abstract class VariableReadWriteFlags {
return READ | WRITE; // fall back
}
protected int rwArgumentForFunctionCall(final IASTFunctionCallExpression funcCall, IASTNode argument, int indirection) {
protected int rwInFieldReference(IASTNode node, IASTFieldReference expr, int indirection) {
if (node.getPropertyInParent() == IASTFieldReference.FIELD_NAME) {
if (expr.getPropertyInParent() != IASTFunctionCallExpression.FUNCTION_NAME)
return rwAnyNode(expr, indirection);
} else { // IASTFieldReference.FIELD_OWNER
if (expr.isPointerDereference())
--indirection;
if (indirection >= 0)
return rwAnyNode(expr, indirection);
}
return READ;
}
protected int rwInFunctionName(IASTExpression node) {
return READ;
}
protected int rwArgumentForFunctionCall(final IASTFunctionCallExpression funcCall,
IASTNode argument, int indirection) {
final IASTInitializerClause[] args = funcCall.getArguments();
for (int i = 0; i < args.length; i++) {
if (args[i] == argument) {
@ -176,7 +196,6 @@ public abstract class VariableReadWriteFlags {
return READ | WRITE; // fallback
}
protected int rwArgumentForFunctionCall(IFunctionType type, int parameterIdx, int indirection) {
IType[] ptypes= type.getParameterTypes();
if (ptypes != null && ptypes.length > parameterIdx) {
@ -192,18 +211,16 @@ public abstract class VariableReadWriteFlags {
if (node.getPropertyInParent() == IASTCaseStatement.EXPRESSION) {
return READ;
}
}
else if (stmt instanceof IASTDoStatement) {
} else if (stmt instanceof IASTDoStatement) {
if (node.getPropertyInParent() == IASTDoStatement.CONDITION) {
return READ;
}
}
else if (stmt instanceof IASTExpressionStatement) {
} else if (stmt instanceof IASTExpressionStatement) {
IASTNode parent= stmt.getParent();
while (parent instanceof IASTCompoundStatement) {
IASTCompoundStatement compound= (IASTCompoundStatement) parent;
IASTStatement[] statements= compound.getStatements();
if (statements[statements.length-1] != stmt) {
if (statements[statements.length - 1] != stmt) {
return 0;
}
stmt= compound;
@ -220,24 +237,19 @@ public abstract class VariableReadWriteFlags {
if (node.getPropertyInParent() == ICPPASTRangeBasedForStatement.INITIALIZER) {
return READ;
}
}
else if (stmt instanceof IASTIfStatement) {
} else if (stmt instanceof IASTIfStatement) {
if (node.getPropertyInParent() == IASTIfStatement.CONDITION) {
return READ;
}
}
else if (stmt instanceof IASTProblemStatement) {
} else if (stmt instanceof IASTProblemStatement) {
return READ | WRITE;
}
else if (stmt instanceof IASTReturnStatement) {
} else if (stmt instanceof IASTReturnStatement) {
return indirection == 0 ? READ : WRITE;
}
else if (stmt instanceof IASTSwitchStatement) {
} else if (stmt instanceof IASTSwitchStatement) {
if (node.getPropertyInParent() == IASTSwitchStatement.CONTROLLER_EXP) {
return READ;
}
}
else if (stmt instanceof IASTWhileStatement) {
} else if (stmt instanceof IASTWhileStatement) {
if (node.getPropertyInParent() == IASTWhileStatement.CONDITIONEXPRESSION) {
return READ;
}
@ -251,11 +263,11 @@ public abstract class VariableReadWriteFlags {
return rwAnyNode(expr, indirection);
case IASTUnaryExpression.op_amper:
return rwAnyNode(expr, indirection+1);
return rwAnyNode(expr, indirection + 1);
case IASTUnaryExpression.op_star:
if (indirection > 0) {
return rwAnyNode(expr, indirection-1);
return rwAnyNode(expr, indirection - 1);
}
return READ;

View file

@ -46,7 +46,7 @@ public class CASTArrayDeclarator extends CASTDeclarator implements IASTArrayDecl
CASTArrayDeclarator copy = new CASTArrayDeclarator();
copyBaseDeclarator(copy, style);
for (IASTArrayModifier modifier : getArrayModifiers())
copy.addArrayModifier(modifier == null ? null : modifier.copy());
copy.addArrayModifier(modifier == null ? null : modifier.copy(style));
if (style == CopyStyle.withLocations) {
copy.setCopyLocation(this);
}

View file

@ -40,7 +40,7 @@ public class CASTCaseStatement extends ASTNode implements IASTCaseStatement, IAS
@Override
public CASTCaseStatement copy(CopyStyle style) {
CASTCaseStatement copy = new CASTCaseStatement(expression == null ? null : expression.copy());
CASTCaseStatement copy = new CASTCaseStatement(expression == null ? null : expression.copy(style));
copy.setOffsetAndLength(this);
if (style == CopyStyle.withLocations) {
copy.setCopyLocation(this);

View file

@ -100,7 +100,7 @@ public class CASTDesignatedInitializer extends ASTNode implements ICASTDesignate
return (IASTInitializer) rhs;
}
if (rhs instanceof IASTExpression) {
CASTEqualsInitializer init = new CASTEqualsInitializer(((IASTExpression)rhs).copy());
CASTEqualsInitializer init = new CASTEqualsInitializer(((IASTExpression) rhs).copy());
init.setParent(this);
init.setPropertyInParent(OPERAND);
return init;

View file

@ -6,10 +6,10 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* John Camelon (IBM Rational Software) - Initial API and implementation
* Yuan Zhang / Beth Tibbitts (IBM Research)
* Bryan Wilkinson (QNX)
* Markus Schorn (Wind River Systems)
* John Camelon (IBM Rational Software) - Initial API and implementation
* Yuan Zhang / Beth Tibbitts (IBM Research)
* Bryan Wilkinson (QNX)
* Markus Schorn (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.core.dom.parser.c;
@ -30,21 +30,19 @@ import org.eclipse.cdt.internal.core.dom.parser.ProblemType;
/**
* Field reference in C.
*/
public class CASTFieldReference extends ASTNode implements IASTFieldReference, IASTAmbiguityParent, IASTCompletionContext {
public class CASTFieldReference extends ASTNode
implements IASTFieldReference, IASTAmbiguityParent, IASTCompletionContext {
private IASTExpression owner;
private IASTName name;
private boolean ptr;
public CASTFieldReference() {
}
public CASTFieldReference(IASTName name, IASTExpression owner) {
this(name, owner, false);
}
public CASTFieldReference(IASTName name, IASTExpression owner, boolean ptr) {
setFieldOwner(owner);
setFieldName(name);
@ -111,41 +109,40 @@ public class CASTFieldReference extends ASTNode implements IASTFieldReference, I
}
@Override
public boolean accept( ASTVisitor action ){
if( action.shouldVisitExpressions ){
switch( action.visit( this ) ){
case ASTVisitor.PROCESS_ABORT : return false;
case ASTVisitor.PROCESS_SKIP : return true;
default : break;
public boolean accept(ASTVisitor action) {
if (action.shouldVisitExpressions) {
switch (action.visit(this)) {
case ASTVisitor.PROCESS_ABORT: return false;
case ASTVisitor.PROCESS_SKIP: return true;
default: break;
}
}
if( owner != null ) if( !owner.accept( action ) ) return false;
if( name != null ) if( !name.accept( action ) ) return false;
if (owner != null && !owner.accept(action)) return false;
if (name != null && !name.accept(action)) return false;
if( action.shouldVisitExpressions ){
switch( action.leave( this ) ){
case ASTVisitor.PROCESS_ABORT : return false;
case ASTVisitor.PROCESS_SKIP : return true;
default : break;
if (action.shouldVisitExpressions) {
switch (action.leave(this)) {
case ASTVisitor.PROCESS_ABORT: return false;
case ASTVisitor.PROCESS_SKIP: return true;
default: break;
}
}
return true;
}
@Override
public int getRoleForName(IASTName n ) {
if( n == this.name )
public int getRoleForName(IASTName n) {
if (n == this.name)
return r_reference;
return r_unclear;
}
@Override
public void replace(IASTNode child, IASTNode other) {
if( child == owner)
{
other.setPropertyInParent( child.getPropertyInParent() );
other.setParent( child.getParent() );
if (child == owner) {
other.setPropertyInParent(child.getPropertyInParent());
other.setParent(child.getParent());
owner = (IASTExpression) other;
}
}
@ -159,7 +156,6 @@ public class CASTFieldReference extends ASTNode implements IASTFieldReference, I
return new ProblemType(ISemanticProblem.TYPE_UNKNOWN_FOR_EXPRESSION);
}
@Override
public boolean isLValue() {
if (isPointerDereference())

View file

@ -6,7 +6,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Markus Schorn - initial API and implementation
* Markus Schorn - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.dom.parser.c;

View file

@ -44,8 +44,8 @@ public class CPPASTBinaryTypeIdExpression extends ASTNode implements IASTBinaryT
@Override
public CPPASTBinaryTypeIdExpression copy(CopyStyle style) {
CPPASTBinaryTypeIdExpression copy = new CPPASTBinaryTypeIdExpression(fOperator,
fOperand1 == null ? null : fOperand1.copy(),
fOperand2 == null ? null : fOperand2.copy());
fOperand1 == null ? null : fOperand1.copy(style),
fOperand2 == null ? null : fOperand2.copy(style));
copy.setOffsetAndLength(this);
if (style == CopyStyle.withLocations) {
copy.setCopyLocation(this);

View file

@ -18,7 +18,11 @@ import static org.eclipse.cdt.core.dom.ast.IASTExpression.ValueCategory.PRVALUE;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.glvalueType;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.prvalueType;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.typeFromFunctionCall;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.*;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.ALLCVQ;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.CVTYPE;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.REF;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.TDEF;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.getUltimateTypeUptoPointers;
import java.util.ArrayList;
import java.util.Collection;
@ -53,15 +57,13 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPSemantics;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CVQualifier;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil;
public class CPPASTFieldReference extends ASTNode implements ICPPASTFieldReference, IASTAmbiguityParent,
ICPPASTCompletionContext {
public class CPPASTFieldReference extends ASTNode
implements ICPPASTFieldReference, IASTAmbiguityParent, ICPPASTCompletionContext {
private boolean isTemplate;
private IASTExpression owner;
private IASTName name;
private boolean isDeref;
private IASTImplicitName[] implicitNames = null;
private IASTImplicitName[] implicitNames;
public CPPASTFieldReference() {
}
@ -148,15 +150,15 @@ public class CPPASTFieldReference extends ASTNode implements ICPPASTFieldReferen
if (!isDeref)
return implicitNames = IASTImplicitName.EMPTY_NAME_ARRAY;
// collect the function bindings
// Collect the function bindings
List<ICPPFunction> functionBindings = new ArrayList<ICPPFunction>();
getFieldOwnerType(functionBindings);
if (functionBindings.isEmpty())
return implicitNames = IASTImplicitName.EMPTY_NAME_ARRAY;
// create a name to wrap each binding
// Create a name to wrap each binding
implicitNames = new IASTImplicitName[functionBindings.size()];
int i=-1;
int i= -1;
for (ICPPFunction op : functionBindings) {
if (op != null && !(op instanceof CPPImplicitFunction)) {
CPPASTImplicitName operatorName = new CPPASTImplicitName(OverloadableOperator.ARROW, this);
@ -280,7 +282,6 @@ public class CPPASTFieldReference extends ASTNode implements ICPPASTFieldReferen
}
return fieldType;
}
@Override
public ValueCategory getValueCategory() {

View file

@ -14,8 +14,15 @@ package org.eclipse.cdt.internal.core.dom.parser.cpp;
import static org.eclipse.cdt.core.dom.ast.IASTExpression.ValueCategory.LVALUE;
import static org.eclipse.cdt.core.dom.ast.IASTExpression.ValueCategory.PRVALUE;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.*;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.*;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.prvalueType;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.typeFromFunctionCall;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.typeFromReturnType;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.valueCategoryFromFunctionCall;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.valueCategoryFromReturnType;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.CVTYPE;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.REF;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.TDEF;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.getNestedType;
import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.DOMException;
@ -46,17 +53,14 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPTemplates;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.LookupData;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil;
public class CPPASTFunctionCallExpression extends ASTNode implements
ICPPASTFunctionCallExpression, IASTAmbiguityParent {
public class CPPASTFunctionCallExpression extends ASTNode
implements ICPPASTFunctionCallExpression, IASTAmbiguityParent {
private IASTExpression functionName;
private IASTInitializerClause[] fArguments;
private IASTImplicitName[] implicitNames;
private ICPPFunction overload= UNINITIALIZED_FUNCTION;
public CPPASTFunctionCallExpression() {
setArguments(null);
}
@ -144,7 +148,7 @@ public class CPPASTFunctionCallExpression extends ASTNode implements
}
}
// create separate implicit names for the two brackets
// Create separate implicit names for the two brackets
CPPASTImplicitName n1 = new CPPASTImplicitName(OverloadableOperator.PAREN, this);
n1.setBinding(overload);
@ -158,16 +162,18 @@ public class CPPASTFunctionCallExpression extends ASTNode implements
IToken lparen = functionName.getTrailingSyntax();
IToken rparen = lparen.getNext();
if (lparen.getType() == IToken.tLPAREN)
if (lparen.getType() == IToken.tLPAREN) {
n1.setOffsetAndLength(idEndOffset + lparen.getOffset(), 1);
else
} else {
n1.setOffsetAndLength(idEndOffset + lparen.getEndOffset(), 0);
}
if (rparen.getType() == IToken.tRPAREN)
if (rparen.getType() == IToken.tRPAREN) {
n2.setOffsetAndLength(idEndOffset + rparen.getOffset(), 1);
else
} else {
n2.setOffsetAndLength(idEndOffset + rparen.getEndOffset(), 0);
} catch(ExpansionOverlapsBoundaryException e) {
}
} catch (ExpansionOverlapsBoundaryException e) {
n1.setOffsetAndLength(idEndOffset, 0);
n2.setOffsetAndLength(idEndOffset, 0);
}

View file

@ -69,7 +69,7 @@ public class CPPASTIdExpression extends ASTNode implements IASTIdExpression, ICP
@Override
public CPPASTIdExpression copy(CopyStyle style) {
CPPASTIdExpression copy = new CPPASTIdExpression(name == null ? null : name.copy());
CPPASTIdExpression copy = new CPPASTIdExpression(name == null ? null : name.copy(style));
copy.setOffsetAndLength(this);
if (style == CopyStyle.withLocations) {
copy.setCopyLocation(this);

View file

@ -51,8 +51,8 @@ public class CPPASTLiteralExpression extends ASTNode implements ICPPASTLiteralEx
@Override
public CPPASTLiteralExpression copy(CopyStyle style) {
CPPASTLiteralExpression copy = new CPPASTLiteralExpression(kind, value == null ? null
: value.clone());
CPPASTLiteralExpression copy = new CPPASTLiteralExpression(kind,
value == null ? null : value.clone());
copy.setOffsetAndLength(this);
if (style == CopyStyle.withLocations) {
copy.setCopyLocation(this);

View file

@ -152,7 +152,8 @@ public class CPPASTRangeBasedForStatement extends ASTNode implements ICPPASTRang
CPPASTName name = new CPPASTName(CPPVisitor.BEGIN);
name.setOffset(position.getOffset());
CPPASTIdExpression fname = new CPPASTIdExpression(name);
IASTExpression expr= new CPPASTFunctionCallExpression(fname, new IASTInitializerClause[] {forInit.copy()});
IASTExpression expr= new CPPASTFunctionCallExpression(fname,
new IASTInitializerClause[] { forInit.copy() });
expr.setParent(this);
expr.setPropertyInParent(ICPPASTRangeBasedForStatement.INITIALIZER);

View file

@ -113,12 +113,10 @@ import org.eclipse.cdt.core.parser.IScanner;
import org.eclipse.cdt.internal.core.dom.parser.NodeFactory;
import org.eclipse.cdt.internal.core.parser.scanner.CPreprocessor;
/**
* Abstract factory implementation that creates C++ AST nodes.
*/
public class CPPNodeFactory extends NodeFactory implements ICPPNodeFactory {
private static final CPPNodeFactory DEFAULT_INSTANCE = new CPPNodeFactory();
public static CPPNodeFactory getDefault() {

View file

@ -870,6 +870,42 @@ public class ClassTypeHelper {
return null;
}
/**
* Returns <code>true</code> if and only if the given class has a trivial default constructor.
* A default constructor is trivial if:
* <ul>
* <li>it is implicitly defined by the compiler, and</li>
* <li>every direct base class has trivial default constructor, and</li>
* <li>for every nonstatic data member that has class type or array of class type, that type
* has trivial default constructor.</li>
* </ul>
* Similar to <code>std::tr1::has_trivial_default_constructor</code>.
*
* @param classTarget the class to check
* @return <code>true</code> if the class has a trivial default constructor
*/
public static boolean hasTrivialDefaultConstructor(ICPPClassType classTarget) {
for (ICPPConstructor ctor : classTarget.getConstructors()) {
if (!ctor.isImplicit() && ctor.getParameters().length == 0)
return false;
}
for (ICPPClassType baseClass : getAllBases(classTarget)) {
if (!classTarget.isSameType(baseClass) && !hasTrivialDefaultConstructor(baseClass))
return false;
}
for (ICPPField field : classTarget.getDeclaredFields()) {
if (!field.isStatic()) {
IType type = field.getType();
type = SemanticUtil.getNestedType(type, TDEF | CVTYPE | ARRAY);
if (type instanceof ICPPClassType && !classTarget.isSameType(type) &&
!hasTrivialDefaultConstructor((ICPPClassType) type)) {
return false;
}
}
}
return true;
}
/**
* Returns <code>true</code> if and only if the given class has a trivial destructor.
* A destructor is trivial if:

View file

@ -6,12 +6,14 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Markus Schorn - initial API and implementation
* Patrick Hofer - [Bug 328528]
* Markus Schorn - initial API and implementation
* Patrick Hofer - [Bug 328528]
*******************************************************************************/
package org.eclipse.cdt.internal.core.dom.parser.cpp.semantics;
import org.eclipse.cdt.core.dom.ast.IASTDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTExpression;
import org.eclipse.cdt.core.dom.ast.IASTIdExpression;
import org.eclipse.cdt.core.dom.ast.IASTImplicitName;
import org.eclipse.cdt.core.dom.ast.IASTImplicitNameOwner;
import org.eclipse.cdt.core.dom.ast.IASTName;
@ -24,10 +26,14 @@ import org.eclipse.cdt.core.dom.ast.IType;
import org.eclipse.cdt.core.dom.ast.IVariable;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTConstructorInitializer;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTUnaryExpression;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassType;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPConstructor;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPFunctionType;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPReferenceType;
import org.eclipse.cdt.internal.core.dom.parser.ITypeContainer;
import org.eclipse.cdt.internal.core.dom.parser.VariableReadWriteFlags;
import org.eclipse.cdt.internal.core.dom.parser.cpp.ClassTypeHelper;
import org.eclipse.cdt.internal.core.dom.parser.cpp.ICPPUnknownType;
/**
* Helper class to determine whether a variable is accessed for reading and/or writing.
@ -50,6 +56,17 @@ public final class CPPVariableReadWriteFlags extends VariableReadWriteFlags {
return super.rwAnyNode(node, indirection);
}
@Override
protected int rwInDeclarator(IASTDeclarator parent, int indirection) {
IType type = CPPVisitor.createType(parent);
if (type instanceof ICPPUnknownType ||
type instanceof ICPPClassType &&
!ClassTypeHelper.hasTrivialDefaultConstructor((ICPPClassType) type)) {
return WRITE;
}
return super.rwInDeclarator(parent, indirection);
}
private int rwInCtorInitializer(IASTNode node, int indirection, ICPPASTConstructorInitializer parent) {
IASTNode grand= parent.getParent();
if (grand instanceof IASTDeclarator) {
@ -91,6 +108,16 @@ public final class CPPVariableReadWriteFlags extends VariableReadWriteFlags {
return super.rwInUnaryExpression(node, expr, indirection);
}
@Override
protected int rwInFunctionName(IASTExpression node) {
if (!(node instanceof IASTIdExpression)) {
IType type= node.getExpressionType();
if (type instanceof ICPPFunctionType && !((ICPPFunctionType) type).isConst())
return READ | WRITE;
}
return READ;
}
@Override
protected int rwAssignmentToType(IType type, int indirection) {
if (indirection == 0) {
@ -99,7 +126,7 @@ public final class CPPVariableReadWriteFlags extends VariableReadWriteFlags {
}
type= ((ICPPReferenceType) type).getType();
}
while(indirection > 0 && (type instanceof ITypeContainer)) {
while (indirection > 0 && (type instanceof ITypeContainer)) {
if (type instanceof IPointerType) {
indirection--;
}

View file

@ -61,7 +61,7 @@ public class ASTLiteralNode implements IASTNode {
@Override
public IASTNodeLocation[] getNodeLocations() {
return null;
return IASTNodeLocation.EMPTY_ARRAY;
}
@Override
@ -131,4 +131,9 @@ public class ASTLiteralNode implements IASTNode {
public boolean isActive() {
return true;
}
@Override
public IASTNode getOriginalNode() {
return this;
}
}

View file

@ -23,6 +23,7 @@ import org.eclipse.cdt.core.dom.ast.IASTDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTExpression;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTNamedTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTNode.CopyStyle;
import org.eclipse.cdt.core.dom.ast.IASTParameterDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTPointer;
import org.eclipse.cdt.core.dom.ast.IASTPointerOperator;
@ -164,7 +165,7 @@ public class DeclarationGeneratorImpl extends DeclarationGenerator {
arrayType = (IArrayType) type;
IASTExpression arraySizeExpression = arrayType.getArraySizeExpression();
arrayDeclarator.addArrayModifier(factory.newArrayModifier(arraySizeExpression == null
? null : arraySizeExpression.copy()));
? null : arraySizeExpression.copy(CopyStyle.withLocations)));
type = arrayType.getType();
}
returnedDeclarator = arrayDeclarator;
@ -291,7 +292,7 @@ public class DeclarationGeneratorImpl extends DeclarationGenerator {
int nbQualifiedNames = fullQualifiedName.getNames().length;
if (nbQualifiedNames > 1) {
for (int i = 0; i < nbQualifiedNames - 1; i++) {
newQualifiedName.addName(fullQualifiedName.getNames()[i].copy());
newQualifiedName.addName(fullQualifiedName.getNames()[i].copy(CopyStyle.withLocations));
}
}
newQualifiedName.addName(tempId);
@ -309,7 +310,7 @@ public class DeclarationGeneratorImpl extends DeclarationGenerator {
private ICPPASTTemplateId getTemplateId(ICPPTemplateInstance type, IASTName templateName) {
ICPPNodeFactory cppFactory = (ICPPNodeFactory) factory;
ICPPASTTemplateId tempId = cppFactory.newTemplateId(templateName.copy());
ICPPASTTemplateId tempId = cppFactory.newTemplateId(templateName.copy(CopyStyle.withLocations));
for (ICPPTemplateArgument arg : type.getTemplateArguments()) {
IASTDeclSpecifier argDeclSpec = createDeclSpecFromType(arg.isTypeValue() ?
arg.getTypeValue() : arg.getTypeOfNonTypeValue());

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik
* Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
@ -19,7 +19,6 @@ import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTArrayModifier;
import org.eclipse.cdt.core.dom.ast.IASTComment;
import org.eclipse.cdt.core.dom.ast.IASTCompoundStatement;
import org.eclipse.cdt.core.dom.ast.IASTCopyLocation;
import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTDeclarator;
@ -27,7 +26,6 @@ import org.eclipse.cdt.core.dom.ast.IASTExpression;
import org.eclipse.cdt.core.dom.ast.IASTInitializer;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.dom.ast.IASTNodeLocation;
import org.eclipse.cdt.core.dom.ast.IASTParameterDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTPointerOperator;
import org.eclipse.cdt.core.dom.ast.IASTStatement;
@ -130,11 +128,9 @@ public class ASTWriterVisitor extends ASTVisitor {
private List<IASTComment> getLeadingComments(IASTNode node) {
List<IASTComment> leadingComments = commentMap.getLeadingCommentsForNode(node);
IASTNodeLocation[] locs = node.getNodeLocations();
if (locs != null && locs.length > 0 && locs[0] instanceof IASTCopyLocation) {
IASTCopyLocation copyLoc = (IASTCopyLocation) locs[0];
leadingComments.addAll(commentMap.getLeadingCommentsForNode(copyLoc.getOriginalNode()));
}
IASTNode originalNode = node.getOriginalNode();
if (originalNode != node)
leadingComments.addAll(commentMap.getLeadingCommentsForNode(originalNode));
return leadingComments;
}

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 Institute for Software, HSR Hochschule fuer Technik
* Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
@ -8,6 +8,7 @@
*
* Contributors:
* Institute for Software - initial API and implementation
* Sergey Prigogin (Google)
*******************************************************************************/
package org.eclipse.cdt.internal.core.dom.rewrite.astwriter;
@ -18,7 +19,6 @@ import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import org.eclipse.cdt.core.dom.ast.IASTCopyLocation;
import org.eclipse.cdt.core.dom.ast.IASTFileLocation;
import org.eclipse.cdt.core.dom.ast.IASTMacroExpansionLocation;
import org.eclipse.cdt.core.dom.ast.IASTNode;
@ -41,9 +41,9 @@ import org.eclipse.core.runtime.CoreException;
* @author Emanuel Graf IFS
*/
public class MacroExpansionHandler {
private int lastMacroExpOffset;
private final Scribe scribe;
private IASTTranslationUnit tu;
private int lastMacroExpOffset;
private IASTTranslationUnit ast;
private Map<String, List<IIndexName>> macroExpansion = new TreeMap<String, List<IIndexName>>();
public MacroExpansionHandler(Scribe scribe) {
@ -81,11 +81,11 @@ public class MacroExpansionHandler {
protected boolean checkisMacroExpansionNode(IASTNode node, boolean write) {
IASTTranslationUnit unit = node.getTranslationUnit();
if (tu == null || !tu.equals(unit)) {
if (ast == null || !ast.equals(unit)) {
initEmptyMacros(unit);
}
IASTNodeLocation[] locs = getNodeLocations(node);
if (locs != null && locs.length ==1) {
if (locs != null && locs.length == 1) {
if (locs[0] instanceof IASTMacroExpansionLocation) {
IASTMacroExpansionLocation macroNode = (IASTMacroExpansionLocation) locs[0];
@ -94,7 +94,7 @@ public class MacroExpansionHandler {
}
if (write) {
lastMacroExpOffset = macroNode.asFileLocation().getNodeOffset();
node = getOriginalNode(node);
node = node.getOriginalNode();
scribe.print(node.getRawSignature());
}
return true;
@ -105,24 +105,13 @@ public class MacroExpansionHandler {
return false;
}
private IASTNode getOriginalNode(IASTNode node) {
IASTNodeLocation[] locs = node.getNodeLocations();
if (locs != null && locs.length == 1 && locs[0] instanceof IASTCopyLocation) {
node = ((IASTCopyLocation) locs[0]).getOriginalNode();
}
return node;
}
private IASTNodeLocation[] getNodeLocations(IASTNode node) {
IASTNodeLocation[] locs = node.getNodeLocations();
if (locs != null && locs.length == 1 && locs[0] instanceof IASTCopyLocation) {
locs = ((IASTCopyLocation) locs[0]).getOriginalNode().getNodeLocations();
}
return locs;
return node.getOriginalNode().getNodeLocations();
}
private void handleEmptyMacroExpansion(IASTNode node) {
if (node.getTranslationUnit() == null)return;
if (node.getTranslationUnit() == null)
return;
String file = node.getContainingFilename();
List<IIndexName> exps = macroExpansion.get(file);
if (exps != null && !exps.isEmpty()) {
@ -144,46 +133,40 @@ public class MacroExpansionHandler {
}
private IASTFileLocation getFileLocation(IASTNode node) {
IASTFileLocation fileLocation = node.getFileLocation();
if (fileLocation == null) {
IASTNodeLocation[] locs = node.getNodeLocations();
if (locs != null && locs.length > 0 && locs[0] instanceof IASTCopyLocation) {
fileLocation = ((IASTCopyLocation) locs[0]).getOriginalNode().getFileLocation();
}
}
return fileLocation;
return node.getOriginalNode().getFileLocation();
}
private void initEmptyMacros(IASTTranslationUnit unit) {
if (unit != null) {
tu = unit;
IIndex index = tu.getIndex();
ast = unit;
IIndex index = ast.getIndex();
if (index != null) {
macroExpansion = new TreeMap<String, List<IIndexName>>();
IASTPreprocessorMacroDefinition[] md = tu.getMacroDefinitions();
IASTPreprocessorMacroDefinition[] md = ast.getMacroDefinitions();
TreeSet<String>paths = new TreeSet<String>();
for (IASTPreprocessorIncludeStatement is :tu.getIncludeDirectives()) {
for (IASTPreprocessorIncludeStatement is :ast.getIncludeDirectives()) {
if (!is.isSystemInclude()) {
paths.add(is.getContainingFilename());
}
}
paths.add(tu.getContainingFilename());
paths.add(ast.getContainingFilename());
for (IASTPreprocessorMacroDefinition iastPreprocessorMacroDefinition : md) {
if (iastPreprocessorMacroDefinition.getExpansion().length() == 0) {
try {
IIndexMacro[] macroBinding = index.findMacros(iastPreprocessorMacroDefinition.getName().toCharArray(),
IIndexMacro[] macroBinding = index.findMacros(
iastPreprocessorMacroDefinition.getName().toCharArray(),
IndexFilter.ALL, null);
if (macroBinding.length > 0) {
IIndexName[] refs = index.findReferences(macroBinding[0]);
for (IIndexName iIndexName : refs) {
String filename2 = iIndexName.getFileLocation().getFileName();
List<IIndexName> fileList = macroExpansion.get(filename2);
if (paths.contains(filename2)) {
String filename = iIndexName.getFileLocation().getFileName();
List<IIndexName> fileList = macroExpansion.get(filename);
if (paths.contains(filename)) {
if (fileList == null) {
fileList = new ArrayList<IIndexName>();
macroExpansion.put(filename2, fileList);
macroExpansion.put(filename, fileList);
}
fileList.add(iIndexName);
}

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik
* Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
@ -8,15 +8,14 @@
*
* Contributors:
* Institute for Software - initial API and implementation
* Sergey Prigogin (Google)
*******************************************************************************/
package org.eclipse.cdt.internal.core.dom.rewrite.astwriter;
import java.util.List;
import org.eclipse.cdt.core.dom.ast.IASTComment;
import org.eclipse.cdt.core.dom.ast.IASTCopyLocation;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.dom.ast.IASTNodeLocation;
import org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.NodeCommentMap;
/**
@ -108,11 +107,9 @@ public class NodeWriter {
private List<IASTComment> getTrailingComments(IASTNode node) {
List<IASTComment> trailingComments = commentMap.getTrailingCommentsForNode(node);
IASTNodeLocation[] locs = node.getNodeLocations();
if (locs != null && locs.length > 0 && locs[0] instanceof IASTCopyLocation) {
IASTCopyLocation loc = (IASTCopyLocation) locs[0];
trailingComments.addAll(commentMap.getTrailingCommentsForNode(loc.getOriginalNode()));
}
IASTNode originalNode = node.getOriginalNode();
if (originalNode != node)
trailingComments.addAll(commentMap.getTrailingCommentsForNode(originalNode));
return trailingComments;
}
@ -122,11 +119,9 @@ public class NodeWriter {
private List<IASTComment> getFreestandingComments(IASTNode node) {
List<IASTComment> freestandingComments = commentMap.getFreestandingCommentsForNode(node);
IASTNodeLocation[] locs = node.getNodeLocations();
if (locs != null && locs.length > 0 && locs[0] instanceof IASTCopyLocation) {
IASTCopyLocation loc = (IASTCopyLocation) locs[0];
freestandingComments.addAll(commentMap.getFreestandingCommentsForNode(loc.getOriginalNode()));
}
IASTNode originalNode = node.getOriginalNode();
if (originalNode != node)
freestandingComments.addAll(commentMap.getFreestandingCommentsForNode(originalNode));
return freestandingComments;
}

View file

@ -51,7 +51,9 @@ import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTFunctionDefinition;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNamespaceDefinition;
import org.eclipse.cdt.core.formatter.CodeFormatter;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.internal.core.dom.rewrite.ASTModification;
import org.eclipse.cdt.internal.core.dom.rewrite.ASTModification.ModificationKind;
import org.eclipse.cdt.internal.core.dom.rewrite.ASTModificationMap;
@ -63,7 +65,6 @@ import org.eclipse.cdt.internal.core.dom.rewrite.astwriter.ProblemRuntimeExcepti
import org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.NodeCommentMap;
import org.eclipse.cdt.internal.core.dom.rewrite.util.FileHelper;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
@ -122,10 +123,12 @@ public class ChangeGenerator extends ASTVisitor {
change = new CompositeChange(ChangeGeneratorMessages.ChangeGenerator_compositeChange);
classifyModifications();
rootNode.accept(pathProvider);
for (IFile currentFile : changes.keySet()) {
MultiTextEdit edit = changes.get(currentFile);
edit = formatChangedCode(edit, rootNode.getTranslationUnit().getRawSignature(), currentFile.getProject());
TextFileChange subchange= ASTRewriteAnalyzer.createCTextFileChange(currentFile);
for (IFile file : changes.keySet()) {
MultiTextEdit edit = changes.get(file);
IASTTranslationUnit ast = rootNode.getTranslationUnit();
ITranslationUnit tu = (ITranslationUnit) CoreModel.getDefault().create(file);
edit = formatChangedCode(edit, ast.getRawSignature(), tu);
TextFileChange subchange= ASTRewriteAnalyzer.createCTextFileChange(file);
subchange.setEdit(edit);
change.add(subchange);
}
@ -317,11 +320,11 @@ public class ChangeGenerator extends ASTVisitor {
*
* @param multiEdit The text edit produced by refactoring.
* @param code The code being modified.
* @param project The project containing the code.
* @param tu The translation unit 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) {
private MultiTextEdit formatChangedCode(MultiTextEdit multiEdit, String code, ITranslationUnit tu) {
IDocument document = new Document(code);
try {
// Apply refactoring changes to a temporary document.
@ -364,8 +367,9 @@ public class ChangeGenerator extends ASTVisitor {
}
// Calculate formatting changes for the regions after the refactoring changes.
ICProject proj = CCorePlugin.getDefault().getCoreModel().create(project);
Map<String, String> options = proj.getOptions(true);
ICProject project = tu.getCProject();
Map<String, Object> options = new HashMap<String, Object>(project.getOptions(true));
options.put(DefaultCodeFormatterConstants.FORMATTER_TRANSLATION_UNIT, tu);
// Allow all comments to be indented.
options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_NEVER_INDENT_LINE_COMMENTS_ON_FIRST_COLUMN,
DefaultCodeFormatterConstants.FALSE);

View file

@ -164,9 +164,9 @@ class ASTBuiltinName extends ASTPreprocessorDefinition {
@Override
public IASTNodeLocation[] getNodeLocations() {
if (fFileLocation == null) {
return new IASTNodeLocation[0];
return IASTNodeLocation.EMPTY_ARRAY;
}
return new IASTNodeLocation[]{fFileLocation};
return new IASTNodeLocation[] { fFileLocation };
}
@Override

View file

@ -59,7 +59,7 @@ abstract class ASTPreprocessorNode extends ASTNode {
setParent(parent);
setPropertyInParent(property);
setOffset(startNumber);
setLength(endNumber-startNumber);
setLength(endNumber - startNumber);
}
protected char[] getSource(int offset, int length) {
@ -597,9 +597,9 @@ class ASTFunctionStyleMacroDefinition extends ASTMacroDefinition implements IAST
}
}
class ASTUndef extends ASTPreprocessorNode implements IASTPreprocessorUndefStatement {
private final ASTPreprocessorName fName;
public ASTUndef(IASTTranslationUnit parent, char[] name, int startNumber, int nameNumber, int nameEndNumber, IBinding binding, boolean isActive) {
super(parent, IASTTranslationUnit.PREPROCESSOR_STATEMENT, startNumber, nameEndNumber);
fName= new ASTPreprocessorName(this, IASTPreprocessorStatement.MACRO_NAME, nameNumber, nameEndNumber, name, binding);
@ -686,7 +686,7 @@ class ASTFileLocation implements IASTFileLocation {
@Override
public int getEndingLineNumber() {
int end= fLength > 0 ? fOffset+fLength-1 : fOffset;
int end= fLength > 0 ? fOffset + fLength - 1 : fOffset;
return fLocationCtx.getLineNumber(end);
}
@ -701,7 +701,7 @@ class ASTFileLocation implements IASTFileLocation {
@Override
public String toString() {
return getFileName() + "[" + fOffset + "," + (fOffset+fLength) + ")"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
return getFileName() + "[" + fOffset + "," + (fOffset + fLength) + "]"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
}
public int getSequenceNumber() {
@ -709,7 +709,7 @@ class ASTFileLocation implements IASTFileLocation {
}
public int getSequenceEndNumber() {
return fLocationCtx.getSequenceNumberForOffset(fOffset+fLength, true);
return fLocationCtx.getSequenceNumberForOffset(fOffset + fLength, true);
}
public LocationCtxFile getLocationContext() {
@ -723,7 +723,6 @@ class ASTFileLocation implements IASTFileLocation {
}
class ASTMacroExpansion extends ASTPreprocessorNode implements IASTPreprocessorMacroExpansion {
private LocationCtxMacroExpansion fContext;
public ASTMacroExpansion(IASTNode parent, int startNumber, int endNumber) {
@ -765,7 +764,6 @@ class ASTMacroExpansion extends ASTPreprocessorNode implements IASTPreprocessorM
@SuppressWarnings("deprecation")
class ASTMacroExpansionLocation implements IASTMacroExpansionLocation, org.eclipse.cdt.core.dom.ast.IASTMacroExpansion {
private LocationCtxMacroExpansion fContext;
private int fOffset;
private int fLength;
@ -817,7 +815,7 @@ class ASTMacroExpansionLocation implements IASTMacroExpansionLocation, org.eclip
@Override
public String toString() {
return fContext.getMacroDefinition().getName().toString() + "[" + fOffset + "," + (fOffset+fLength) + ")"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
return fContext.getMacroDefinition().getName().toString() + "[" + fOffset + "," + (fOffset+fLength) + "]"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
}
public IASTImageLocation getImageLocation() {
@ -872,7 +870,6 @@ class ASTFileLocationForBuiltins implements IASTFileLocation {
}
}
class ASTImageLocation extends ASTFileLocationForBuiltins implements IASTImageLocation {
private final int fKind;

View file

@ -6,7 +6,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Markus Schorn - initial API and implementation
* Markus Schorn - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.parser.scanner;
@ -20,7 +20,6 @@ final class IncludeSearchPathElement {
public static final String FRAMEWORK_VAR = "__framework__"; //$NON-NLS-1$
public static final String FILE_VAR = "__header__"; //$NON-NLS-1$
private final String fPath;
private final boolean fForQuoteIncludesOnly;
private final boolean fIsFrameworkDirectory;
@ -47,7 +46,7 @@ final class IncludeSearchPathElement {
return null;
}
String framework = includeDirective.substring(0, firstSep);
String file= includeDirective.substring(firstSep+1);
String file= includeDirective.substring(firstSep + 1);
if (file.length() == 0)
return null;
@ -70,7 +69,15 @@ final class IncludeSearchPathElement {
private void replace(StringBuilder buf, String find, final String replace) {
int idx= buf.indexOf(find);
if (idx >= 0) {
buf.replace(idx, idx+find.length(), replace);
buf.replace(idx, idx + find.length(), replace);
}
}
/**
* For debugging only.
*/
@Override
public String toString() {
return fPath;
}
}

View file

@ -241,7 +241,7 @@ class LocationCtxContainer extends LocationCtx {
if (idx < 0) {
return -idx;
}
return idx+1;
return idx + 1;
}
private int[] computeLineOffsets() {
@ -255,7 +255,6 @@ class LocationCtxContainer extends LocationCtx {
int[] result= new int[offsets.size()];
for (int i = 0; i < result.length; i++) {
result[i]= offsets.get(i).intValue();
}
return result;
}

View file

@ -34,7 +34,7 @@ class LocationCtxMacroExpansion extends LocationCtx {
fLength= length;
fLocationInfos= imageLocations;
fExpansionName= expansionName;
if (expansionName.getParent() instanceof ASTMacroExpansion == false) {
if (!(expansionName.getParent() instanceof ASTMacroExpansion)) {
throw new IllegalArgumentException(expansionName.toString() + " is not a macro expansion name"); //$NON-NLS-1$
}
}

View file

@ -280,6 +280,11 @@ public class PDOMASTAdapter {
public boolean isQualified() {
return fDelegate.isQualified();
}
@Override
public IASTNode getOriginalNode() {
return this;
}
}
private static class AnonymousEnumeration implements IEnumeration {

View file

@ -0,0 +1,18 @@
/*******************************************************************************
* Copyright (c) 2012 Ericsson and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Marc Khouzam (Ericsson) - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core;
/**
*/
public interface ICPUInfo {
public String getId();
public String getNumOfCores();
}

View file

@ -0,0 +1,18 @@
/*******************************************************************************
* Copyright (c) 2012 Ericsson and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Marc Khouzam (Ericsson) - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core;
/**
*/
public interface ICoreInfo {
public String getId();
public String getPhysicalId();
}

View file

@ -23,9 +23,11 @@ import org.eclipse.cdt.core.formatter.CodeFormatter;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterOptions;
import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ILanguage;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.model.IWorkingCopy;
import org.eclipse.cdt.core.parser.FileContent;
import org.eclipse.cdt.core.parser.IScannerInfo;
import org.eclipse.cdt.core.parser.IncludeFileContentProvider;
@ -34,8 +36,9 @@ import org.eclipse.cdt.core.parser.ScannerInfo;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.Region;
import org.eclipse.text.edits.TextEdit;
public class CCodeFormatter extends CodeFormatter {
private DefaultCodeFormatterOptions preferences;
@ -120,90 +123,22 @@ public class CCodeFormatter extends CodeFormatter {
}
@Override
public TextEdit format(int kind, String source, int offset, int length, int indentationLevel, String lineSeparator) {
TextEdit edit= null;
ITranslationUnit tu= (ITranslationUnit) options.get(DefaultCodeFormatterConstants.FORMATTER_TRANSLATION_UNIT);
if (tu == null) {
IFile file= (IFile) options.get(DefaultCodeFormatterConstants.FORMATTER_CURRENT_FILE);
if (file != null) {
tu= (ITranslationUnit) CoreModel.getDefault().create(file);
}
}
if (lineSeparator != null) {
preferences.line_separator = lineSeparator;
} else {
preferences.line_separator = System.getProperty("line.separator"); //$NON-NLS-1$
}
public TextEdit format(int kind, String source, int offset, int length, int indentationLevel,
String lineSeparator) {
preferences.initial_indentation_level = indentationLevel;
if (tu != null) {
IIndex index;
try {
index = CCorePlugin.getIndexManager().getIndex(tu.getCProject());
index.acquireReadLock();
} catch (CoreException e) {
throw new AbortFormatting(e);
} catch (InterruptedException e) {
return null;
}
IASTTranslationUnit ast;
try {
try {
ast= tu.getAST(index, ITranslationUnit.AST_SKIP_ALL_HEADERS);
} catch (CoreException exc) {
throw new AbortFormatting(exc);
}
CodeFormatterVisitor codeFormatter = new CodeFormatterVisitor(preferences, offset, length);
edit= codeFormatter.format(source, ast);
IStatus status= codeFormatter.getStatus();
if (!status.isOK()) {
CCorePlugin.log(status);
}
} finally {
index.releaseReadLock();
}
} else {
IncludeFileContentProvider contentProvider = IncludeFileContentProvider.getSavedFilesProvider();
IScannerInfo scanInfo = new ScannerInfo();
FileContent content = FileContent.create("<text>", source.toCharArray()); //$NON-NLS-1$
ILanguage language= (ILanguage) options.get(DefaultCodeFormatterConstants.FORMATTER_LANGUAGE);
if (language == null) {
language= GPPLanguage.getDefault();
}
IASTTranslationUnit ast;
try {
ast= language.getASTTranslationUnit(content, scanInfo, contentProvider, null, 0,
ParserUtil.getParserLogService());
CodeFormatterVisitor codeFormatter = new CodeFormatterVisitor(preferences, offset, length);
edit= codeFormatter.format(source, ast);
IStatus status= codeFormatter.getStatus();
if (!status.isOK()) {
CCorePlugin.log(status);
}
} catch (CoreException e) {
throw new AbortFormatting(e);
}
}
return edit;
return format(kind, source, new IRegion[] { new Region(offset, length) }, lineSeparator)[0];
}
@Override
public TextEdit[] format(int kind, String source, IRegion[] regions, String lineSeparator) {
TextEdit[] edits= new TextEdit[regions.length];
ITranslationUnit tu= (ITranslationUnit) options.get(DefaultCodeFormatterConstants.FORMATTER_TRANSLATION_UNIT);
if (tu == null) {
IFile file= (IFile) options.get(DefaultCodeFormatterConstants.FORMATTER_CURRENT_FILE);
if (file != null) {
tu= (ITranslationUnit) CoreModel.getDefault().create(file);
}
}
if (lineSeparator != null) {
preferences.line_separator = lineSeparator;
} else {
preferences.line_separator = System.getProperty("line.separator"); //$NON-NLS-1$
}
ITranslationUnit tu = getTranslationUnit(source);
if (tu != null) {
IIndex index;
try {
@ -217,20 +152,11 @@ public class CCodeFormatter extends CodeFormatter {
IASTTranslationUnit ast;
try {
try {
ast= tu.getAST(index, ITranslationUnit.AST_SKIP_ALL_HEADERS);
} catch (CoreException exc) {
throw new AbortFormatting(exc);
}
for (int i = 0; i < regions.length; i++) {
IRegion region = regions[i];
CodeFormatterVisitor codeFormatter =
new CodeFormatterVisitor(preferences, region.getOffset(), region.getLength());
edits[i] = codeFormatter.format(source, ast);
IStatus status= codeFormatter.getStatus();
if (!status.isOK()) {
CCorePlugin.log(status);
}
ast= tu.getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS);
} catch (CoreException e) {
throw new AbortFormatting(e);
}
formatRegions(source, regions, edits, ast);
} finally {
index.releaseReadLock();
}
@ -247,20 +173,47 @@ public class CCodeFormatter extends CodeFormatter {
try {
ast= language.getASTTranslationUnit(content, scanInfo, contentProvider, null, 0,
ParserUtil.getParserLogService());
for (int i = 0; i < regions.length; i++) {
IRegion region = regions[i];
CodeFormatterVisitor codeFormatter =
new CodeFormatterVisitor(preferences, region.getOffset(), region.getLength());
edits[i]= codeFormatter.format(source, ast);
IStatus status= codeFormatter.getStatus();
if (!status.isOK()) {
CCorePlugin.log(status);
}
}
formatRegions(source, regions, edits, ast);
} catch (CoreException e) {
throw new AbortFormatting(e);
}
}
return edits;
}
private void formatRegions(String source, IRegion[] regions, TextEdit[] edits,
IASTTranslationUnit ast) {
for (int i = 0; i < regions.length; i++) {
IRegion region = regions[i];
CodeFormatterVisitor codeFormatter =
new CodeFormatterVisitor(preferences, region.getOffset(), region.getLength());
edits[i] = codeFormatter.format(source, ast);
IStatus status= codeFormatter.getStatus();
if (!status.isOK()) {
CCorePlugin.log(status);
}
}
}
private ITranslationUnit getTranslationUnit(String source) {
ITranslationUnit tu= (ITranslationUnit) options.get(DefaultCodeFormatterConstants.FORMATTER_TRANSLATION_UNIT);
if (tu == null) {
IFile file= (IFile) options.get(DefaultCodeFormatterConstants.FORMATTER_CURRENT_FILE);
if (file != null) {
tu= (ITranslationUnit) CoreModel.getDefault().create(file);
}
}
if (tu != null && source != null) {
try {
// Create a private working copy and set it contents to source.
if (tu.isWorkingCopy())
tu = ((IWorkingCopy) tu).getOriginalElement();
tu = tu.getWorkingCopy();
tu.getBuffer().setContents(source);
} catch (CModelException e) {
throw new AbortFormatting(e);
}
}
return tu;
}
}

View file

@ -12,10 +12,17 @@
*******************************************************************************/
package org.eclipse.cdt.ui.tests.refactoring.extractfunction;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.Test;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ltk.core.refactoring.Refactoring;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.PreferenceConstants;
import org.eclipse.cdt.ui.tests.refactoring.RefactoringTestBase;
import org.eclipse.cdt.internal.ui.refactoring.NameInformation;
@ -31,6 +38,10 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase {
private ExtractFunctionInformation refactoringInfo;
private String extractedFunctionName = "extracted";
private String returnValue;
// Map from old names to new ones.
private Map<String, String> parameterRename = new HashMap<String, String>();
// New positions of parameters, or null.
private int[] parameterOrder;
private VisibilityEnum visibility = VisibilityEnum.v_private;
private boolean virtual;
private boolean replaceDuplicates = true;
@ -47,6 +58,26 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase {
return suite(ExtractFunctionRefactoringTest.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
resetPreferences();
}
@Override
public void tearDown() throws Exception {
super.tearDown();
resetPreferences();
}
private void resetPreferences() {
getPreferenceStore().setToDefault(PreferenceConstants.FUNCTION_PASS_OUTPUT_PARAMETERS_BY_POINTER);
}
private IPreferenceStore getPreferenceStore() {
return CUIPlugin.getDefault().getPreferenceStore();
}
@Override
protected Refactoring createRefactoring() {
refactoringInfo = new ExtractFunctionInformation();
@ -61,14 +92,32 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase {
if (refactoringInfo.getMandatoryReturnVariable() == null) {
if (returnValue != null) {
for (NameInformation nameInfo : refactoringInfo.getParameters()) {
nameInfo.setReturnValue(returnValue.equals(String.valueOf(nameInfo.getName().getSimpleID())));
nameInfo.setReturnValue(returnValue.equals(getName(nameInfo)));
}
}
}
if (!parameterRename.isEmpty()) {
for (NameInformation nameInfo : refactoringInfo.getParameters()) {
String newName = parameterRename.get(getName(nameInfo));
if (newName != null)
nameInfo.setNewName(newName);
}
}
if (parameterOrder != null) {
List<NameInformation> parameters = refactoringInfo.getParameters();
NameInformation[] originalParameters = parameters.toArray(new NameInformation[parameters.size()]);
for (int i = 0; i < parameterOrder.length; i++) {
parameters.set(parameterOrder[i], originalParameters[i]);
}
}
refactoringInfo.setVisibility(visibility);
refactoringInfo.setVirtual(virtual);
}
private String getName(NameInformation nameInfo) {
return String.valueOf(nameInfo.getName().getSimpleID());
}
//A.h
//#ifndef A_H_
//#define A_H_
@ -536,7 +585,7 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase {
//A.cpp
//#include "A.h"
//
//#define ZWO 2
//#define TWO 2
//
//A::A() {
//}
@ -547,7 +596,7 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase {
//int A::foo() {
// int i = 2;
// /*$*/++i;
// i += ZWO;
// i += TWO;
// help();/*$$*/
// return i;
//}
@ -558,7 +607,7 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase {
//====================
//#include "A.h"
//
//#define ZWO 2
//#define TWO 2
//
//A::A() {
//}
@ -568,7 +617,7 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase {
//
//int A::extracted(int i) {
// ++i;
// i += ZWO;
// i += TWO;
// help();
// return i;
//}
@ -698,7 +747,7 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase {
//
//private:
// int help();
// void extracted(int* i);
// void extracted(int* j);
//};
//
//#endif /*A_H_*/
@ -731,8 +780,8 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase {
//A::~A() {
//}
//
//void A::extracted(int* i) {
// ++*i;
//void A::extracted(int* j) {
// ++*j;
// help();
//}
//
@ -745,7 +794,94 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase {
//int A::help() {
// return 42;
//}
public void testPointer() throws Exception {
public void testRenamedParameter() throws Exception {
parameterRename.put("i", "j");
assertRefactoringSuccess();
}
//A.c
//struct A {
// int i;
// int j;
//};
//
//int test() {
// struct A a = { 1, 2 };
// return /*$*/a.i + a.j/*$$*/;
//}
//====================
//struct A {
// int i;
// int j;
//};
//
//int extracted(const struct A* a) {
// return a->i + a->j;
//}
//
//int test() {
// struct A a = { 1, 2 };
// return extracted(&a);
//}
public void testInputParameterPassedByPointer() throws Exception {
assertRefactoringSuccess();
}
//A.c
//int test() {
// int i = 0;
// int j = 1;
// /*$*/int k = i;
// i = j;
// j = k;/*$$*/
// return i - j;
//}
//====================
//void swap(int* i, int* j) {
// int k = *i;
// *i = *j;
// *j = k;
//}
//
//int test() {
// int i = 0;
// int j = 1;
// swap(&i, &j);
// return i - j;
//}
public void testOutputParameterPassedByPointer() throws Exception {
extractedFunctionName = "swap";
returnValue = NO_RETURN_VALUE;
assertRefactoringSuccess();
}
//A.h
//class A {
//public:
// int method();
// int const_method() const;
//};
//A.cpp
//#include "A.h"
//
//int test() {
// A a, b;
// return /*$*/a.method() + b.const_method()/*$$*/ + a.const_method();
//}
//====================
//#include "A.h"
//
//int extracted(A b, A* a) {
// return a->method() + b.const_method();
//}
//
//int test() {
// A a, b;
// return extracted(b, &a) + a.const_method();
//}
public void testOutputParameterWithMethodCall() throws Exception {
getPreferenceStore().setValue(PreferenceConstants.FUNCTION_PASS_OUTPUT_PARAMETERS_BY_POINTER, true);
assertRefactoringSuccess();
}
@ -2562,91 +2698,6 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase {
public void testDuplicates() throws Exception {
assertRefactoringSuccess();
}
//A.h
//#ifndef A_H_
//#define A_H_
//
//class A {
//public:
// A();
// virtual ~A();
// int foo();
//
//private:
// int help();
//};
//
//#endif /*A_H_*/
//====================
//#ifndef A_H_
//#define A_H_
//
//class A {
//public:
// A();
// virtual ~A();
// int foo();
//
//private:
// int help();
// int extracted(int i);
//};
//
//#endif /*A_H_*/
//A.cpp
//#include "A.h"
//
//A::A() {
//}
//
//A::~A() {
// int oo = 99;
// ++oo;
// help();
//}
//
//int A::foo() {
// int i = 2;
// /*$*/++i;
// help();/*$$*/
// return i;
//}
//
//int A::help() {
// return 42;
//}
//====================
//#include "A.h"
//
//A::A() {
//}
//
//A::~A() {
// int oo = 99;
// oo = extracted(oo);
//}
//
//int A::extracted(int i) {
// ++i;
// help();
// return i;
//}
//
//int A::foo() {
// int i = 2;
// i = extracted(i);
// return i;
//}
//
//int A::help() {
// return 42;
//}
public void testDuplicatesWithDifferentNames() throws Exception {
assertRefactoringSuccess();
}
//A.h
//#ifndef A_H_
//#define A_H_
@ -2930,7 +2981,96 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase {
//int A::help() {
// return 42;
//}
public void testDuplicatesWithDifferentNamesAndReturnType() throws Exception {
public void testDuplicatesWithDifferentNames() throws Exception {
assertRefactoringSuccess();
}
//A.h
//#ifndef A_H_
//#define A_H_
//
//class A {
//public:
// A();
// virtual ~A();
// int foo();
//
//private:
// int help();
//};
//
//#endif /*A_H_*/
//====================
//#ifndef A_H_
//#define A_H_
//
//class A {
//public:
// A();
// virtual ~A();
// int foo();
//
//private:
// int help();
// int extracted(int j, int i);
//};
//
//#endif /*A_H_*/
//A.cpp
//#include "A.h"
//
//A::A() {
//}
//
//A::~A() {
// int aa = 9;
// int bb = 99;
// aa += bb;
// help();
//}
//
//int A::foo() {
// int i = 2;
// int j = 3;
// /*$*/i += j;
// help();/*$$*/
// return i;
//}
//
//int A::help() {
// return 42;
//}
//====================
//#include "A.h"
//
//A::A() {
//}
//
//A::~A() {
// int aa = 9;
// int bb = 99;
// aa = extracted(bb, aa);
//}
//
//int A::extracted(int j, int i) {
// i += j;
// help();
// return i;
//}
//
//int A::foo() {
// int i = 2;
// int j = 3;
// i = extracted(j, i);
// return i;
//}
//
//int A::help() {
// return 42;
//}
public void testDuplicatesWithDifferentNamesAndReordering() throws Exception {
parameterOrder = new int[] { 1, 0 };
assertRefactoringSuccess();
}
@ -3105,7 +3245,7 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase {
//int A::help() {
// return 42;
//}
public void testDuplicateNameUsedAfterwardsInDuplicateButNotInOriginalSelectionThisIsNoDuplicate() throws Exception {
public void testOutputParameterInDuplicateButNotInOriginal() throws Exception {
assertRefactoringSuccess();
}

View file

@ -357,7 +357,7 @@ public class MarkOccurrenceTest extends BaseUITestCase {
fEditor.selectAndReveal(fMatch.getOffset(), fMatch.getLength());
assertOccurrences(2, 1);
assertOccurrences(2, 0);
assertOccurrencesInWidget();
}

View file

@ -635,3 +635,4 @@ extension-point.name = Refresh Exclusion Contributor
# New New Project Wizard
newProjectWizard.name = C/C++ Project (prototype)
projectTypePages = Project Type Pages

View file

@ -28,6 +28,7 @@
<extension-point id="workingSetConfigurations" name="%workingSetConfigurationsExtensionPoint" schema="schema/workingSetConfigurations.exsd"/>
<extension-point id="LanguageSettingsProviderAssociation" name="%LanguageSettingsProviderAssociationExtensionPoint" schema="schema/LanguageSettingsProviderAssociation.exsd"/>
<extension-point id="RefreshExclusionContributor" name="%extension-point.name" schema="schema/RefreshExclusionContributor.exsd"/>
<extension-point id="projectTypePages" name="%ProjectTypePages" schema="schema/projectTypePages.exsd"/>
<extension
point="org.eclipse.core.runtime.adapters">

View file

@ -0,0 +1,118 @@
<?xml version='1.0' encoding='UTF-8'?>
<!-- Schema file written by PDE -->
<schema targetNamespace="org.eclipse.cdt.ui" xmlns="http://www.w3.org/2001/XMLSchema">
<annotation>
<appInfo>
<meta.schema plugin="org.eclipse.cdt.ui" id="projectTypePages" name="%ProjectTypePages"/>
</appInfo>
<documentation>
This extension is used to register a page in the CDT new project wizard to support
specifying additional information based on the project type associated with a template.
</documentation>
</annotation>
<element name="extension">
<annotation>
<appInfo>
<meta.element />
</appInfo>
</annotation>
<complexType>
<sequence>
<element ref="projectTypePage" minOccurs="1" maxOccurs="unbounded"/>
</sequence>
<attribute name="point" type="string" use="required">
<annotation>
<documentation>
</documentation>
</annotation>
</attribute>
<attribute name="id" type="string">
<annotation>
<documentation>
</documentation>
</annotation>
</attribute>
<attribute name="name" type="string">
<annotation>
<documentation>
</documentation>
<appInfo>
<meta.attribute translatable="true"/>
</appInfo>
</annotation>
</attribute>
</complexType>
</element>
<element name="projectTypePage">
<complexType>
<attribute name="id" type="string" use="required">
<annotation>
<documentation>
</documentation>
</annotation>
</attribute>
<attribute name="projectType" type="string" use="required">
<annotation>
<documentation>
</documentation>
</annotation>
</attribute>
<attribute name="class" type="string">
<annotation>
<documentation>
</documentation>
<appInfo>
<meta.attribute kind="java" basedOn=":org.eclipse.cdt.ui.wizards.ProjectTypePage"/>
</appInfo>
</annotation>
</attribute>
</complexType>
</element>
<annotation>
<appInfo>
<meta.section type="since"/>
</appInfo>
<documentation>
[Enter the first release in which this extension point appears.]
</documentation>
</annotation>
<annotation>
<appInfo>
<meta.section type="examples"/>
</appInfo>
<documentation>
[Enter extension point usage example here.]
</documentation>
</annotation>
<annotation>
<appInfo>
<meta.section type="apiinfo"/>
</appInfo>
<documentation>
[Enter API information here.]
</documentation>
</annotation>
<annotation>
<appInfo>
<meta.section type="implementation"/>
</appInfo>
<documentation>
[Enter information about supplied implementation of this extension point.]
</documentation>
</annotation>
</schema>

View file

@ -71,6 +71,13 @@ public final class CUIMessages extends NLS {
public static String FileTransferDragAdapter_refreshing;
public static String FileTransferDragAdapter_problem;
public static String FileTransferDragAdapter_problemTitle;
public static String NewCDTProjectWizard_mainPageDesc;
public static String NewCDTProjectWizard_mainPageTitle;
public static String NewCDTProjectWizard_refPageDesc;
public static String NewCDTProjectWizard_refPageTitle;
public static String NewCDTProjectWizard_templatePageDesc;
public static String NewCDTProjectWizard_templatePageTitle;
public static String NewCDTProjectWizard_windowTitle;
static {
NLS.initializeMessages(BUNDLE_NAME, CUIMessages.class);

View file

@ -73,3 +73,11 @@ CStructureCreatorVisitor_translationUnitName=Translation Unit
FileTransferDragAdapter_refreshing=Refreshing...
FileTransferDragAdapter_problem=Problem while moving or copying files.
FileTransferDragAdapter_problemTitle=Drag & Drop
NewCDTProjectWizard_mainPageDesc=Create a new C/C++ Project
NewCDTProjectWizard_mainPageTitle=Project
NewCDTProjectWizard_refPageDesc=Select referenced projects
NewCDTProjectWizard_refPageTitle=Project References
NewCDTProjectWizard_templatePageDesc=Select a project template for the new project
NewCDTProjectWizard_templatePageTitle=Project Template
NewCDTProjectWizard_windowTitle=New C/C++ Project

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2000, 2009 IBM Corporation and others.
* Copyright (c) 2000, 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -45,7 +45,7 @@ public class SemanticHighlightingManager implements IPropertyChangeListener {
/**
* Highlighting style.
*/
static class HighlightingStyle {
public static class HighlightingStyle {
/** Text attribute */
private TextAttribute fTextAttribute;
@ -94,7 +94,7 @@ public class SemanticHighlightingManager implements IPropertyChangeListener {
/**
* Highlighted Positions.
*/
static class HighlightedPosition extends Position {
public static class HighlightedPosition extends Position {
/** Highlighting of the position */
private HighlightingStyle fStyle;
@ -260,30 +260,30 @@ public class SemanticHighlightingManager implements IPropertyChangeListener {
}
/** Semantic highlighting presenter */
private SemanticHighlightingPresenter fPresenter;
protected SemanticHighlightingPresenter fPresenter;
/** Semantic highlighting reconciler */
private SemanticHighlightingReconciler fReconciler;
/** Semantic highlightings */
private SemanticHighlighting[] fSemanticHighlightings;
protected SemanticHighlighting[] fSemanticHighlightings;
/** Highlightings */
private HighlightingStyle[] fHighlightings;
protected HighlightingStyle[] fHighlightings;
/** The editor */
private CEditor fEditor;
/** The source viewer */
private CSourceViewer fSourceViewer;
protected CSourceViewer fSourceViewer;
/** The color manager */
private IColorManager fColorManager;
protected IColorManager fColorManager;
/** The preference store */
private IPreferenceStore fPreferenceStore;
protected IPreferenceStore fPreferenceStore;
/** The source viewer configuration */
private CSourceViewerConfiguration fConfiguration;
protected CSourceViewerConfiguration fConfiguration;
/** The presentation reconciler */
private CPresentationReconciler fPresentationReconciler;
protected CPresentationReconciler fPresentationReconciler;
/** The hard-coded ranges */
private HighlightedRange[][] fHardcodedRanges;
protected HighlightedRange[][] fHardcodedRanges;
/**
* Install the semantic highlighting on the given editor infrastructure
@ -347,7 +347,7 @@ public class SemanticHighlightingManager implements IPropertyChangeListener {
*
* @return the hard-coded positions
*/
private HighlightedPosition[] createHardcodedPositions() {
protected HighlightedPosition[] createHardcodedPositions() {
List<HighlightedPosition> positions= new ArrayList<HighlightedPosition>();
for (int i= 0; i < fHardcodedRanges.length; i++) {
HighlightedRange range= null;
@ -421,14 +421,14 @@ public class SemanticHighlightingManager implements IPropertyChangeListener {
/**
* @return <code>true</code> iff semantic highlighting is enabled in the preferences
*/
private boolean isEnabled() {
protected boolean isEnabled() {
return SemanticHighlightings.isEnabled(fPreferenceStore);
}
/**
* Initialize semantic highlightings.
*/
private void initializeHighlightings() {
protected void initializeHighlightings() {
fSemanticHighlightings= SemanticHighlightings.getSemanticHighlightings();
fHighlightings= new HighlightingStyle[fSemanticHighlightings.length];
@ -461,7 +461,7 @@ public class SemanticHighlightingManager implements IPropertyChangeListener {
/**
* Dispose the semantic highlightings.
*/
private void disposeHighlightings() {
protected void disposeHighlightings() {
for (int i= 0, n= fSemanticHighlightings.length; i < n; i++)
removeColor(SemanticHighlightings.getColorPreferenceKey(fSemanticHighlightings[i]));
@ -481,10 +481,11 @@ public class SemanticHighlightingManager implements IPropertyChangeListener {
* Handle the given property change event
*
* @param event The event
* @return
*/
private void handlePropertyChangeEvent(PropertyChangeEvent event) {
protected boolean handlePropertyChangeEvent(PropertyChangeEvent event) {
if (fPreferenceStore == null)
return; // Uninstalled during event notification
return false; // Uninstalled during event notification
if (fConfiguration != null)
fConfiguration.handlePropertyChangeEvent(event);
@ -497,7 +498,7 @@ public class SemanticHighlightingManager implements IPropertyChangeListener {
}
if (!isEnabled())
return;
return false;
boolean refreshNeeded= false;
@ -555,6 +556,8 @@ public class SemanticHighlightingManager implements IPropertyChangeListener {
if (refreshNeeded && fReconciler != null)
fReconciler.refresh();
return refreshNeeded;
}
private void adaptToEnablementChange(HighlightingStyle highlighting, PropertyChangeEvent event) {

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2000, 2009 IBM Corporation and others.
* Copyright (c) 2000, 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -287,18 +287,18 @@ public class SemanticHighlightingReconciler implements ICReconcilingListener {
/** The C editor this semantic highlighting reconciler is installed on */
private CEditor fEditor;
/** The semantic highlighting presenter */
private SemanticHighlightingPresenter fPresenter;
protected SemanticHighlightingPresenter fPresenter;
/** Semantic highlightings */
private SemanticHighlighting[] fSemanticHighlightings;
protected SemanticHighlighting[] fSemanticHighlightings;
/** Highlightings */
private HighlightingStyle[] fHighlightings;
/** Background job's added highlighted positions */
private List<HighlightedPosition> fAddedPositions= new ArrayList<HighlightedPosition>();
protected List<HighlightedPosition> fAddedPositions= new ArrayList<HighlightedPosition>();
/** Background job's removed highlighted positions */
private List<HighlightedPosition> fRemovedPositions= new ArrayList<HighlightedPosition>();
protected List<HighlightedPosition> fRemovedPositions= new ArrayList<HighlightedPosition>();
/** Number of removed positions */
private int fNOfRemovedPositions;
protected int fNOfRemovedPositions;
/** Background job */
private Job fJob;
@ -313,9 +313,9 @@ public class SemanticHighlightingReconciler implements ICReconcilingListener {
private boolean fIsReconciling= false;
/** The semantic highlighting presenter - cache for background thread, only valid during {@link #reconciled(IASTTranslationUnit, boolean, IProgressMonitor)} */
private SemanticHighlightingPresenter fJobPresenter;
protected SemanticHighlightingPresenter fJobPresenter;
/** Semantic highlightings - cache for background thread, only valid during {@link #reconciled(IASTTranslationUnit, boolean, IProgressMonitor)} */
private SemanticHighlighting[] fJobSemanticHighlightings;
protected SemanticHighlighting[] fJobSemanticHighlightings;
/** Highlightings - cache for background thread, only valid during {@link #reconciled(IASTTranslationUnit, boolean, IProgressMonitor)} */
private HighlightingStyle[] fJobHighlightings;
@ -389,7 +389,7 @@ public class SemanticHighlightingReconciler implements ICReconcilingListener {
/**
* Start reconciling positions.
*/
private void startReconcilingPositions() {
protected void startReconcilingPositions() {
fJobPresenter.addAllPositions(fRemovedPositions);
fNOfRemovedPositions= fRemovedPositions.size();
}
@ -452,7 +452,7 @@ public class SemanticHighlightingReconciler implements ICReconcilingListener {
/**
* Stop reconciling positions.
*/
private void stopReconcilingPositions() {
protected void stopReconcilingPositions() {
fRemovedPositions.clear();
fNOfRemovedPositions= 0;
fAddedPositions.clear();

View file

@ -23,14 +23,21 @@ import org.eclipse.cdt.ui.PreferenceConstants;
import org.eclipse.cdt.internal.ui.dialogs.IStatusChangeListener;
/**
* Configures C Editor typing preferences.
* Configures elements of C/C++ code style affecting refactoring.
*/
class CodeStyleBlock extends OptionsConfigurationBlock {
private static final Key CLASS_MEMBER_ASCENDING_VISIBILITY_ORDER = getCDTUIKey(PreferenceConstants.CLASS_MEMBER_ASCENDING_VISIBILITY_ORDER);
private static final Key CLASS_MEMBER_ASCENDING_VISIBILITY_ORDER =
getCDTUIKey(PreferenceConstants.CLASS_MEMBER_ASCENDING_VISIBILITY_ORDER);
private static final Key FUNCTION_OUTPUT_PARAMETERS_BEFORE_INPUT =
getCDTUIKey(PreferenceConstants.FUNCTION_OUTPUT_PARAMETERS_BEFORE_INPUT);
private static final Key FUNCTION_PASS_OUTPUT_PARAMETERS_BY_POINTER =
getCDTUIKey(PreferenceConstants.FUNCTION_PASS_OUTPUT_PARAMETERS_BY_POINTER);
private static Key[] getAllKeys() {
return new Key[] {
CLASS_MEMBER_ASCENDING_VISIBILITY_ORDER,
FUNCTION_OUTPUT_PARAMETERS_BEFORE_INPUT,
FUNCTION_PASS_OUTPUT_PARAMETERS_BY_POINTER,
};
}
@ -52,6 +59,12 @@ class CodeStyleBlock extends OptionsConfigurationBlock {
Composite composite = addSubsection(control, PreferencesMessages.CodeStyleBlock_class_member_order);
fillClassMemberOrderSection(composite);
composite = addSubsection(control, PreferencesMessages.CodeStyleBlock_function_parameter_order);
fillFunctionParameterOrderSection(composite);
composite = addSubsection(control, PreferencesMessages.CodeStyleBlock_function_output_parameter_style);
fillFunctionOutputParameterStyleSection(composite);
scrolled.setContent(control);
final Point size= control.computeSize(SWT.DEFAULT, SWT.DEFAULT);
scrolled.setMinSize(size.x, size.y);
@ -69,6 +82,28 @@ class CodeStyleBlock extends OptionsConfigurationBlock {
CLASS_MEMBER_ASCENDING_VISIBILITY_ORDER, TRUE_FALSE, 0);
}
private void fillFunctionParameterOrderSection(Composite composite) {
GridLayout layout= new GridLayout();
layout.numColumns= 3;
composite.setLayout(layout);
addRadioButton(composite, PreferencesMessages.CodeStyleBlock_input_output,
FUNCTION_OUTPUT_PARAMETERS_BEFORE_INPUT, FALSE_TRUE, 0);
addRadioButton(composite, PreferencesMessages.CodeStyleBlock_output_input,
FUNCTION_OUTPUT_PARAMETERS_BEFORE_INPUT, TRUE_FALSE, 0);
}
private void fillFunctionOutputParameterStyleSection(Composite composite) {
GridLayout layout= new GridLayout();
layout.numColumns= 3;
composite.setLayout(layout);
addRadioButton(composite, PreferencesMessages.CodeStyleBlock_pass_by_reference,
FUNCTION_PASS_OUTPUT_PARAMETERS_BY_POINTER, FALSE_TRUE, 0);
addRadioButton(composite, PreferencesMessages.CodeStyleBlock_pass_by_pointer,
FUNCTION_PASS_OUTPUT_PARAMETERS_BY_POINTER, TRUE_FALSE, 0);
}
@Override
protected void validateSettings(Key changedKey, String oldValue, String newValue) {
}

View file

@ -198,6 +198,12 @@ public final class PreferencesMessages extends NLS {
public static String CodeStyleBlock_class_member_order;
public static String CodeStyleBlock_public_private;
public static String CodeStyleBlock_private_public;
public static String CodeStyleBlock_function_parameter_order;
public static String CodeStyleBlock_input_output;
public static String CodeStyleBlock_output_input;
public static String CodeStyleBlock_function_output_parameter_style;
public static String CodeStyleBlock_pass_by_reference;
public static String CodeStyleBlock_pass_by_pointer;
public static String TodoTaskPreferencePage_title;
public static String TodoTaskPreferencePage_description;

View file

@ -231,8 +231,14 @@ CodeFormatterPreferencePage_description=A&ctive profile:
# Code Style
CodeStylePreferencePage_title=Code Style
CodeStyleBlock_class_member_order=Class member visiblity order:
CodeStyleBlock_public_private=P&ublic, protected, private
CodeStyleBlock_private_public=P&rivate, protected, public
CodeStyleBlock_public_private=Pu&blic, protected, private
CodeStyleBlock_private_public=Pri&vate, protected, public
CodeStyleBlock_function_parameter_order=Function parameter order:
CodeStyleBlock_input_output=&Input parameters first
CodeStyleBlock_output_input=&Output parameters first
CodeStyleBlock_function_output_parameter_style=Output parameters of C++ functions:
CodeStyleBlock_pass_by_reference=Pass by &reference
CodeStyleBlock_pass_by_pointer=Pass by poi&nter
# Task tags.
TodoTaskPreferencePage_title=Task Tags

View file

@ -21,7 +21,6 @@ import org.eclipse.cdt.core.dom.ast.IASTArrayDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTArrayModifier;
import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTFileLocation;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.dom.ast.IASTNode.CopyStyle;
@ -30,6 +29,7 @@ import org.eclipse.cdt.core.dom.ast.IASTPointerOperator;
import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration;
import org.eclipse.cdt.core.dom.ast.INodeFactory;
import org.eclipse.cdt.core.dom.ast.IType;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPNodeFactory;
import org.eclipse.cdt.core.dom.rewrite.TypeHelper;
import org.eclipse.cdt.core.model.ITranslationUnit;
@ -40,13 +40,16 @@ import org.eclipse.cdt.internal.core.dom.rewrite.astwriter.ASTWriterVisitor;
* Additional information about an IASTName in code being refactored.
*/
public class NameInformation {
public static enum Indirection { NONE, POINTER, REFERENCE }
public static final int INDEX_FOR_ADDED = -1;
private final IASTName name;
private IASTName declarationName;
private final List<IASTName> references;
private List<IASTName> referencesAfterCached;
private int lastCachedReferencesHash;
private final List<IASTName> referencesBeforeSelection;
private final List<IASTName> referencesInSelection;
private final List<IASTName> referencesAfterSelection;
private boolean isOutput;
private boolean mustBeReturnValue;
private boolean isWriteAccess;
@ -57,11 +60,15 @@ public class NameInformation {
private boolean isDeleted;
private String defaultValue;
private String newTypeName;
private Indirection indirection;
public NameInformation(IASTName name) {
this.name = name;
this.newName = String.valueOf(name.getSimpleID());
references = new ArrayList<IASTName>();
referencesBeforeSelection = new ArrayList<IASTName>();
referencesInSelection = new ArrayList<IASTName>();
referencesAfterSelection = new ArrayList<IASTName>();
}
public static NameInformation createInfoForAddedParameter(String type, String name,
@ -99,6 +106,7 @@ public class NameInformation {
void setOutput(boolean isOutput) {
this.isOutput = isOutput;
indirection = null;
}
public boolean isOutputParameter() {
@ -111,6 +119,7 @@ public class NameInformation {
public void setMustBeReturnValue(boolean mustBeReturnValue) {
this.mustBeReturnValue = mustBeReturnValue;
indirection = null;
}
public boolean isReturnValue() {
@ -120,6 +129,7 @@ public class NameInformation {
public void setReturnValue(boolean isReturnValue) {
Assert.isTrue(isReturnValue || !mustBeReturnValue);
this.isReturnValue = isReturnValue;
indirection = null;
}
public String getNewName() {
@ -136,6 +146,7 @@ public class NameInformation {
void setWriteAccess(boolean isWriteAceess) {
this.isWriteAccess = isWriteAceess;
indirection = null;
}
public boolean isDeleted() {
@ -182,6 +193,7 @@ public class NameInformation {
void setDeclarationName(IASTName declarationName) {
Assert.isTrue(declarationName.getParent() instanceof IASTDeclarator);
this.declarationName = declarationName;
indirection = null;
}
public IASTName getName() {
@ -189,11 +201,19 @@ public class NameInformation {
}
public boolean isRenamed() {
return name == null ? newName != null : String.valueOf(name.getSimpleID()).equals(name);
return name == null ? newName != null : !String.valueOf(name.getSimpleID()).equals(newName);
}
void addReference(IASTName name) {
void addReference(IASTName name, int startOffset, int endOffset) {
references.add(name);
int nodeOffset = name.getFileLocation().getNodeOffset();
if (nodeOffset >= endOffset) {
referencesAfterSelection.add(name);
} else if (nodeOffset >= startOffset) {
referencesInSelection.add(name);
} else {
referencesBeforeSelection.add(name);
}
}
public String getTypeName() {
@ -224,22 +244,20 @@ public class NameInformation {
return writer.toString();
}
public List<IASTName> getReferencesAfterSelection(int endOffset) {
if (referencesAfterCached == null || lastCachedReferencesHash != references.hashCode()) {
lastCachedReferencesHash = references.hashCode();
referencesAfterCached = new ArrayList<IASTName>();
for (IASTName ref : references) {
IASTFileLocation loc = ref.getFileLocation();
if (loc.getNodeOffset() >= endOffset) {
referencesAfterCached.add(ref);
}
}
}
return referencesAfterCached;
public List<IASTName> getReferencesBeforeSelection() {
return referencesBeforeSelection;
}
public boolean isReferencedAfterSelection(int endOffset) {
return !getReferencesAfterSelection(endOffset).isEmpty();
public List<IASTName> getReferencesInSelection() {
return referencesInSelection;
}
public List<IASTName> getReferencesAfterSelection() {
return referencesAfterSelection;
}
public boolean isReferencedAfterSelection() {
return !referencesAfterSelection.isEmpty();
}
public IASTParameterDeclaration getParameterDeclaration(INodeFactory nodeFactory) {
@ -251,29 +269,47 @@ public class NameInformation {
IASTDeclSpecifier declSpec = safeCopy(getDeclSpecifier());
IASTDeclarator declarator = createDeclarator(nodeFactory, sourceDeclarator, paramName);
if (isOutputParameter()) {
if (nodeFactory instanceof ICPPNodeFactory && !passOutputByPointer) {
declarator.addPointerOperator(((ICPPNodeFactory) nodeFactory).newReferenceOperator(false));
} else {
declarator.addPointerOperator(nodeFactory.newPointer());
}
} else if (declSpec != null && !isWriteAccess) {
IType type = TypeHelper.createType(sourceDeclarator);
if (TypeHelper.shouldBePassedByReference(type, declarationName.getTranslationUnit())) {
if (nodeFactory instanceof ICPPNodeFactory) {
declarator.addPointerOperator(((ICPPNodeFactory) nodeFactory).newReferenceOperator(false));
} else {
declarator.addPointerOperator(nodeFactory.newPointer());
}
declSpec.setConst(true);
}
Indirection indirection = getIndirection();
if (indirection == Indirection.POINTER) {
declarator.addPointerOperator(nodeFactory.newPointer());
} else if (indirection == Indirection.REFERENCE) {
declarator.addPointerOperator(((ICPPNodeFactory) nodeFactory).newReferenceOperator(false));
}
if (indirection != Indirection.NONE && !isWriteAccess && declSpec != null) {
declSpec.setConst(true);
}
declarator.setNestedDeclarator(sourceDeclarator.getNestedDeclarator());
return nodeFactory.newParameterDeclaration(declSpec, declarator);
}
public Indirection getIndirection() {
if (indirection == null) {
indirection = Indirection.NONE;
boolean isCpp = declarationName.getTranslationUnit() instanceof ICPPASTTranslationUnit;
if (isOutputParameter()) {
if (isCpp && !passOutputByPointer) {
indirection = Indirection.REFERENCE;
} else {
indirection = Indirection.POINTER;
}
} else {
IType type = TypeHelper.createType(getDeclarator());
if (TypeHelper.shouldBePassedByReference(type, declarationName.getTranslationUnit())) {
if (isCpp) {
if (!isWriteAccess) {
indirection = Indirection.REFERENCE;
}
} else {
indirection = Indirection.POINTER;
}
}
}
}
return indirection;
}
private IASTDeclarator createDeclarator(INodeFactory nodeFactory, IASTDeclarator sourceDeclarator,
String name) {
IASTName astName = name != null ?
@ -311,5 +347,6 @@ public class NameInformation {
public void setPassOutputByPointer(boolean passOutputByPointer) {
this.passOutputByPointer = passOutputByPointer;
indirection = null;
}
}

View file

@ -28,6 +28,7 @@ import org.eclipse.core.runtime.preferences.IPreferencesService;
import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.DOMException;
import org.eclipse.cdt.core.dom.ast.IASTDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTFieldReference;
import org.eclipse.cdt.core.dom.ast.IASTMacroExpansionLocation;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTNode;
@ -73,6 +74,8 @@ public class NodeContainer {
return;
}
names = new ArrayList<NameInformation>();
final int startOffset = getStartOffset();
final int endOffset = getEndOffset();
IPreferencesService preferences = Platform.getPreferencesService();
final boolean passOutputByPointer = preferences.getBoolean(CUIPlugin.PLUGIN_ID,
@ -87,34 +90,36 @@ public class NodeContainer {
@Override
public int visit(IASTName name) {
IBinding binding = name.resolveBinding();
if (binding instanceof ICPPBinding && !(binding instanceof ICPPTemplateTypeParameter)) {
ICPPBinding cppBinding = (ICPPBinding) binding;
try {
if (!cppBinding.isGloballyQualified()) {
NameInformation nameInfo = new NameInformation(name);
nameInfo.setPassOutputByPointer(passOutputByPointer);
IASTName[] refs = name.getTranslationUnit().getReferences(binding);
for (IASTName ref : refs) {
nameInfo.addReference(ref);
if (name.getPropertyInParent() != IASTFieldReference.FIELD_NAME) {
IBinding binding = name.resolveBinding();
if (binding instanceof ICPPBinding && !(binding instanceof ICPPTemplateTypeParameter)) {
ICPPBinding cppBinding = (ICPPBinding) binding;
try {
if (!cppBinding.isGloballyQualified()) {
NameInformation nameInfo = new NameInformation(name);
nameInfo.setPassOutputByPointer(passOutputByPointer);
IASTName[] refs = name.getTranslationUnit().getReferences(binding);
for (IASTName ref : refs) {
nameInfo.addReference(ref, startOffset, endOffset);
}
names.add(nameInfo);
}
names.add(nameInfo);
} catch (DOMException e) {
ILog logger = CUIPlugin.getDefault().getLog();
IStatus status = new Status(IStatus.WARNING, CUIPlugin.PLUGIN_ID,
e.getMessage(), e);
logger.log(status);
}
} catch (DOMException e) {
ILog logger = CUIPlugin.getDefault().getLog();
IStatus status = new Status(IStatus.WARNING,
CUIPlugin.PLUGIN_ID, IStatus.OK, e.getMessage(), e);
logger.log(status);
} else if (binding instanceof IVariable) {
NameInformation nameInformation = new NameInformation(name);
IASTName[] refs = name.getTranslationUnit().getReferences(binding);
for (IASTName ref : refs) {
nameInformation.addReference(ref, startOffset, endOffset);
}
names.add(nameInformation);
}
} else if (binding instanceof IVariable) {
NameInformation nameInformation = new NameInformation(name);
IASTName[] refs = name.getTranslationUnit().getReferences(binding);
for (IASTName ref : refs) {
nameInformation.addReference(ref);
}
names.add(nameInformation);
}
return super.visit(name);
}
@ -152,12 +157,11 @@ public class NodeContainer {
Set<IASTName> declarations = new HashSet<IASTName>();
interfaceNames = new ArrayList<NameInformation>();
int endOffset = getEndOffset();
for (NameInformation nameInfo : names) {
IASTName declarationName = nameInfo.getDeclarationName();
if (declarations.add(declarationName)) {
if (isDeclaredInSelection(nameInfo)) {
if (nameInfo.isReferencedAfterSelection(endOffset)) {
if (nameInfo.isReferencedAfterSelection()) {
nameInfo.setMustBeReturnValue(true);
interfaceNames.add(nameInfo);
}
@ -173,7 +177,7 @@ public class NodeContainer {
}
}
}
if (nameInfo.isWriteAccess() && nameInfo.isReferencedAfterSelection(endOffset)) {
if (nameInfo.isWriteAccess() && nameInfo.isReferencedAfterSelection()) {
nameInfo.setOutput(true);
}
}

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik
* Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
@ -8,11 +8,13 @@
*
* Contributors:
* Institute for Software - initial API and implementation
* Sergey Prigogin (Google)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.extractfunction;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.eclipse.text.edits.TextEditGroup;
@ -24,7 +26,6 @@ import org.eclipse.cdt.core.dom.ast.IASTExpression;
import org.eclipse.cdt.core.dom.ast.IASTExpressionStatement;
import org.eclipse.cdt.core.dom.ast.IASTFunctionCallExpression;
import org.eclipse.cdt.core.dom.ast.IASTIdExpression;
import org.eclipse.cdt.core.dom.ast.IASTLiteralExpression;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.dom.ast.IASTNode.CopyStyle;
@ -44,7 +45,6 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTBinaryExpression;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTFieldReference;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTFunctionDefinition;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTIdExpression;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTLiteralExpression;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTReturnStatement;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTSimpleDeclSpecifier;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTSimpleDeclaration;
@ -57,31 +57,33 @@ import org.eclipse.cdt.internal.ui.refactoring.NameInformation;
*
* @author Mirko Stocker
*/
public class ExtractExpression extends ExtractedFunctionConstructionHelper {
final static char[] ZERO= { '0' };
public class ExpressionExtractor extends FunctionExtractor {
@Override
public void constructMethodBody(IASTCompoundStatement compound, List<IASTNode> list,
ASTRewrite rewrite, TextEditGroup group) {
CPPASTReturnStatement statement = new CPPASTReturnStatement();
IASTExpression nullReturnExp =
new CPPASTLiteralExpression(IASTLiteralExpression.lk_integer_constant, ZERO);
statement.setReturnValue(nullReturnExp);
ASTRewrite nestedRewrite = rewrite.insertBefore(compound, null, statement, group);
nestedRewrite.replace(nullReturnExp, getExpression(list), group);
public boolean canChooseReturnValue() {
return false;
}
private IASTExpression getExpression(List<IASTNode> list) {
if (list.size() > 1) {
CPPASTBinaryExpression bExp = new CPPASTBinaryExpression();
bExp.setParent(list.get(0).getParent());
bExp.setOperand1((IASTExpression) list.get(0).copy(CopyStyle.withLocations));
bExp.setOperator(((IASTBinaryExpression) list.get(1).getParent()).getOperator());
bExp.setOperand2(getExpression(list.subList(1, list.size())));
return bExp;
@Override
public void constructMethodBody(IASTCompoundStatement compound, List<IASTNode> nodes,
List<NameInformation> parameters, ASTRewrite rewrite, TextEditGroup group) {
CPPASTReturnStatement statement = new CPPASTReturnStatement();
statement.setReturnValue(getExpression(nodes));
ASTRewrite subRewrite = rewrite.insertBefore(compound, null, statement, group);
Map<IASTName, NameInformation> changedParameters = getChangedParameterReferences(parameters);
INodeFactory nodeFactory = nodes.get(0).getTranslationUnit().getASTNodeFactory();
adjustParameterReferences(statement, changedParameters, nodeFactory, subRewrite, group);
}
private IASTExpression getExpression(List<IASTNode> nodes) {
if (nodes.size() > 1) {
CPPASTBinaryExpression expression = new CPPASTBinaryExpression();
expression.setParent(nodes.get(0).getParent());
expression.setOperand1((IASTExpression) nodes.get(0).copy(CopyStyle.withLocations));
expression.setOperator(((IASTBinaryExpression) nodes.get(1).getParent()).getOperator());
expression.setOperand2(getExpression(nodes.subList(1, nodes.size())));
return expression;
} else {
return (IASTExpression) list.get(0).copy(CopyStyle.withLocations);
return (IASTExpression) nodes.get(0).copy(CopyStyle.withLocations);
}
}

View file

@ -61,6 +61,7 @@ import org.eclipse.cdt.core.dom.ast.IASTReturnStatement;
import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTStandardFunctionDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTStatement;
import org.eclipse.cdt.core.dom.ast.IASTUnaryExpression;
import org.eclipse.cdt.core.dom.ast.IBasicType;
import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.IField;
@ -101,7 +102,6 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTQualifiedName;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTReturnStatement;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTSimpleDeclaration;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTemplateDeclaration;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPNodeFactory;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil;
import org.eclipse.cdt.internal.core.dom.rewrite.astwriter.ASTWriterVisitor;
@ -113,6 +113,7 @@ import org.eclipse.cdt.internal.ui.refactoring.MethodContext;
import org.eclipse.cdt.internal.ui.refactoring.MethodContext.ContextType;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
import org.eclipse.cdt.internal.ui.refactoring.NameInformation;
import org.eclipse.cdt.internal.ui.refactoring.NameInformation.Indirection;
import org.eclipse.cdt.internal.ui.refactoring.NodeContainer;
import org.eclipse.cdt.internal.ui.refactoring.utils.ASTHelper;
import org.eclipse.cdt.internal.ui.refactoring.utils.CPPASTAllVisitor;
@ -138,8 +139,8 @@ public class ExtractFunctionRefactoring extends CRefactoring {
HashMap<String, Integer> nameTrail;
private ExtractedFunctionConstructionHelper extractedFunctionConstructionHelper;
private final INodeFactory nodeFactory = CPPNodeFactory.getDefault();
private FunctionExtractor extractor;
private INodeFactory nodeFactory;
DefaultCodeFormatterOptions formattingOptions;
public ExtractFunctionRefactoring(IFile file, ISelection selection,
@ -167,6 +168,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
return status;
}
nodeFactory = ast.getASTNodeFactory();
container = findExtractableNodes();
sm.worked(1);
@ -202,7 +204,9 @@ public class ExtractFunctionRefactoring extends CRefactoring {
if (initStatus.hasFatalError())
return initStatus;
if (info.getMandatoryReturnVariable() == null) {
extractor = FunctionExtractor.createFor(container.getNodesToWrite());
if (extractor.canChooseReturnValue() && info.getMandatoryReturnVariable() == null) {
chooseReturnVariable();
}
@ -212,9 +216,6 @@ public class ExtractFunctionRefactoring extends CRefactoring {
PreferenceConstants.getPreferenceScopes(project.getProject()));
info.sortParameters(outFirst);
extractedFunctionConstructionHelper =
ExtractedFunctionConstructionHelper.createFor(container.getNodesToWrite());
boolean isExtractExpression = container.getNodesToWrite().get(0) instanceof IASTExpression;
info.setExtractExpression(isExtractExpression);
@ -354,7 +355,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
}
}
private void createMethodCalls(final IASTName astMethodName, MethodContext context,
private void createMethodCalls(IASTName methodName, MethodContext context,
ModificationCollector collector) throws CoreException {
String title;
if (context.getType() == MethodContext.ContextType.METHOD) {
@ -363,7 +364,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
title = Messages.ExtractFunctionRefactoring_CreateFunctionCall;
}
IASTNode methodCall = getMethodCall(astMethodName);
IASTNode methodCall = getMethodCall(methodName);
IASTNode firstNodeToWrite = container.getNodesToWrite().get(0);
ASTRewrite rewriter = collector.rewriterForTranslationUnit(
@ -377,7 +378,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
insertCallIntoTree(methodCall, container.getNodesToWrite(), rewriter, editGroup);
if (info.isReplaceDuplicates()) {
replaceSimilar(collector, astMethodName);
replaceSimilar(collector, methodName);
}
for (IASTNode node : container.getNodesToWrite()) {
@ -415,7 +416,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
return binExp;
}
private void createMethodDefinition(final IASTName astMethodName, MethodContext context,
private void createMethodDefinition(final IASTName methodName, MethodContext context,
IASTNode firstNode, ModificationCollector collector) {
IASTFunctionDefinition node = NodeHelper.findFunctionDefinitionInAncestors(firstNode);
if (node != null) {
@ -427,7 +428,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
}
ASTRewrite rewriter = collector.rewriterForTranslationUnit(node.getTranslationUnit());
addMethod(astMethodName, context, rewriter, node, new TextEditGroup(title));
addMethod(methodName, context, rewriter, node, new TextEditGroup(title));
}
}
@ -618,17 +619,17 @@ public class ExtractFunctionRefactoring extends CRefactoring {
return true;
}
private void addMethod(IASTName astMethodName, MethodContext context, ASTRewrite rewriter,
private void addMethod(IASTName methodName, MethodContext context, ASTRewrite rewrite,
IASTNode insertPoint, TextEditGroup group) {
ICPPASTQualifiedName qname = new CPPASTQualifiedName();
if (context.getType() == ContextType.METHOD) {
if (context.getMethodQName() != null) {
for (int i = 0; i < (context.getMethodQName().getNames().length - 1); i++) {
for (int i = 0; i < context.getMethodQName().getNames().length - 1; i++) {
qname.addName(new CPPASTName(context.getMethodQName().getNames()[i].toCharArray()));
}
}
}
qname.addName(astMethodName);
qname.addName(methodName);
IASTFunctionDefinition func = new CPPASTFunctionDefinition();
func.setParent(ast);
@ -637,32 +638,33 @@ public class ExtractFunctionRefactoring extends CRefactoring {
func.setDeclSpecifier(returnType);
IASTStandardFunctionDeclarator createdFunctionDeclarator =
extractedFunctionConstructionHelper.createFunctionDeclarator(qname,
extractor.createFunctionDeclarator(qname,
info.getDeclarator(), info.getReturnVariable(), container.getNodesToWrite(),
info.getParameters(), ast.getASTNodeFactory());
info.getParameters(), nodeFactory);
func.setDeclarator(createdFunctionDeclarator);
IASTCompoundStatement compound = new CPPASTCompoundStatement();
func.setBody(compound);
ASTRewrite subRW;
if (insertPoint.getParent() instanceof ICPPASTTemplateDeclaration) {
ASTRewrite subRewrite;
IASTNode parent = insertPoint.getParent();
if (parent instanceof ICPPASTTemplateDeclaration) {
ICPPASTTemplateDeclaration parentTemplate = (ICPPASTTemplateDeclaration) parent;
CPPASTTemplateDeclaration templateDeclaration = new CPPASTTemplateDeclaration();
templateDeclaration.setParent(ast);
for (ICPPASTTemplateParameter param : ((ICPPASTTemplateDeclaration) insertPoint.getParent()).getTemplateParameters()) {
for (ICPPASTTemplateParameter param : parentTemplate.getTemplateParameters()) {
templateDeclaration.addTemplateParameter(param.copy(CopyStyle.withLocations));
}
templateDeclaration.setDeclaration(func);
subRW = rewriter.insertBefore(insertPoint.getParent().getParent(), insertPoint.getParent(),
templateDeclaration, group);
subRewrite = rewrite.insertBefore(parent.getParent(), parent, templateDeclaration, group);
} else {
subRW = rewriter.insertBefore(insertPoint.getParent(), insertPoint, func, group);
subRewrite = rewrite.insertBefore(parent, insertPoint, func, group);
}
extractedFunctionConstructionHelper.constructMethodBody(compound,
container.getNodesToWrite(), subRW, group);
extractor.constructMethodBody(compound, container.getNodesToWrite(),
info.getParameters(), subRewrite, group);
// Set return value
NameInformation returnVariable = info.getReturnVariable();
@ -675,7 +677,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
expr.setName(new CPPASTName(returnVariable.getNewName().toCharArray()));
}
returnStmt.setReturnValue(expr);
subRW.insertBefore(compound, null, returnStmt, group);
subRewrite.insertBefore(compound, null, returnStmt, group);
}
}
@ -686,7 +688,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
private IASTDeclSpecifier getReturnType() {
IASTNode firstNodeToWrite = container.getNodesToWrite().get(0);
NameInformation returnVariable = info.getReturnVariable();
return extractedFunctionConstructionHelper.determineReturnType(firstNodeToWrite,
return extractor.determineReturnType(firstNodeToWrite,
returnVariable);
}
@ -755,28 +757,28 @@ public class ExtractFunctionRefactoring extends CRefactoring {
return getReturnAssignment(stmt, callExpression, retName);
}
private IASTNode getMethodCall(IASTName astMethodName) {
IASTExpressionStatement stmt = new CPPASTExpressionStatement();
private IASTNode getMethodCall(IASTName methodName) {
IASTExpressionStatement statement = new CPPASTExpressionStatement();
IASTFunctionCallExpression callExpression = new CPPASTFunctionCallExpression();
IASTIdExpression idExpression = new CPPASTIdExpression();
idExpression.setName(new CPPASTName(astMethodName.toCharArray()));
idExpression.setName(new CPPASTName(methodName.toCharArray()));
List<IASTInitializerClause> args = getCallParameters();
callExpression.setArguments(args.toArray(new IASTInitializerClause[args.size()]));
callExpression.setFunctionNameExpression(idExpression);
if (info.getReturnVariable() == null) {
return getReturnAssignment(stmt, callExpression);
return getReturnAssignment(statement, callExpression);
}
IASTName retname = newName(info.getReturnVariable().getName());
return getReturnAssignment(stmt, callExpression, retname);
IASTName retName = newName(info.getReturnVariable().getName());
return getReturnAssignment(statement, callExpression, retName);
}
private IASTNode getReturnAssignment(IASTExpressionStatement stmt,
IASTFunctionCallExpression callExpression, IASTName retname) {
if (info.getReturnVariable().equals(info.getMandatoryReturnVariable())) {
IASTSimpleDeclaration orgDecl = NodeHelper.findSimpleDeclarationInParents(info
.getReturnVariable().getDeclarationName());
IASTSimpleDeclaration orgDecl = NodeHelper.findSimpleDeclarationInParents(
info.getReturnVariable().getDeclarationName());
IASTSimpleDeclaration decl = new CPPASTSimpleDeclaration();
decl.setDeclSpecifier(orgDecl.getDeclSpecifier().copy(CopyStyle.withLocations));
@ -810,15 +812,15 @@ public class ExtractFunctionRefactoring extends CRefactoring {
private IASTNode getReturnAssignment(IASTExpressionStatement stmt,
IASTExpression callExpression) {
IASTNode node = container.getNodesToWrite().get(0);
return extractedFunctionConstructionHelper.createReturnAssignment(node, stmt, callExpression);
return extractor.createReturnAssignment(node, stmt, callExpression);
}
private IASTSimpleDeclaration getDeclaration(IASTName name) {
IASTSimpleDeclaration simpleDecl = new CPPASTSimpleDeclaration();
IASTStandardFunctionDeclarator declarator =
extractedFunctionConstructionHelper.createFunctionDeclarator(name,
extractor.createFunctionDeclarator(name,
info.getDeclarator(), info.getReturnVariable(), container.getNodesToWrite(),
info.getParameters(), ast.getASTNodeFactory());
info.getParameters(), nodeFactory);
simpleDecl.addDeclarator(declarator);
return simpleDecl;
}
@ -831,9 +833,9 @@ public class ExtractFunctionRefactoring extends CRefactoring {
}
simpleDecl.setParent(ast);
IASTStandardFunctionDeclarator declarator =
extractedFunctionConstructionHelper.createFunctionDeclarator(name,
extractor.createFunctionDeclarator(name,
info.getDeclarator(), info.getReturnVariable(), container.getNodesToWrite(),
info.getParameters(), ast.getASTNodeFactory());
info.getParameters(), nodeFactory);
simpleDecl.addDeclarator(declarator);
return simpleDecl;
}
@ -881,8 +883,10 @@ public class ExtractFunctionRefactoring extends CRefactoring {
if (!container.isDeclaredInSelection(nameInfo)) {
IASTName declaration = nameInfo.getDeclarationName();
if (declarations.add(declaration)) {
IASTIdExpression expression = new CPPASTIdExpression();
expression.setName(newName(declaration));
IASTExpression expression = nodeFactory.newIdExpression(newName(declaration));
if (nameInfo.getIndirection() == Indirection.POINTER) {
expression = nodeFactory.newUnaryExpression(IASTUnaryExpression.op_amper, expression);
}
args.add(expression);
}
}

Some files were not shown because too many files have changed in this diff Show more