1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-06-30 21:55:31 +02:00

Merge branch 'master' into sd90

This commit is contained in:
Andrew Gvozdev 2011-08-22 11:12:35 -04:00
commit 862d87074c
36 changed files with 577 additions and 456 deletions

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2004, 2010 IBM Corporation and others.
* Copyright (c) 2004, 2011 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
@ -10,6 +10,7 @@
* Martin Oberhuber (Wind River Systems) - bug 155096
* Gerhard Schaber (Wind River Systems)
* Markus Schorn (Wind River Systems)
* Martin Oberhuber (Wind River) - bug 345750: discover drive-relative paths
*******************************************************************************/
package org.eclipse.cdt.make.internal.core.scannerconfig.gnu;
@ -225,16 +226,14 @@ public class GCCPerFileBOPConsoleParserUtility extends AbstractGCCBOPConsolePars
public IPath getAbsolutePath(String filePath) {
IPath pFilePath;
if (filePath.startsWith("/")) { //$NON-NLS-1$
return convertCygpath(new Path(filePath));
}
else if (filePath.startsWith("\\") || //$NON-NLS-1$
pFilePath = convertCygpath(new Path(filePath));
} else if (filePath.startsWith("\\") || //$NON-NLS-1$
(!filePath.startsWith(".") && //$NON-NLS-1$
filePath.length() > 2 && filePath.charAt(1) == ':' &&
(filePath.charAt(2) == '\\' || filePath.charAt(2) == '/'))) {
// absolute path
pFilePath = new Path(filePath);
}
else {
} else {
// relative path
IPath cwd = getWorkingDirectory();
if (!cwd.isAbsolute()) {
@ -250,6 +249,10 @@ public class GCCPerFileBOPConsoleParserUtility extends AbstractGCCBOPConsolePars
}
pFilePath = cwd.append(filePath);
}
if (pFilePath.getDevice()==null) {
pFilePath = pFilePath.setDevice(getWorkingDirectory().getDevice());
}
return pFilePath;
}

View file

@ -422,6 +422,10 @@ public class CCommandDSC {
IPath ppath = new Path(path);
if (project != null && !ppath.isAbsolute()) {
IResource res = project.findMember(ppath);
if (res == null) {
// To calculate path only; this does not create any file
res = project.getFile(path);
}
if (res != null) {
ppath = res.getLocation();
if (ppath != null) {

View file

@ -135,6 +135,8 @@ public class CfgScannerConfigInfoFactory2 {
boolean isPerRcType = cfg.isPerRcTypeDiscovery();
Map<InfoContext, IScannerConfigBuilderInfo2> baseMap = container.getInfoMap();
if(!isPerRcType){
// Discovery profile scope = configuration wide
CfgInfoContext c = new CfgInfoContext(cfg);
InfoContext baseContext = c.toInfoContext();
IScannerConfigBuilderInfo2 info = container.getInfo(baseContext);
@ -164,8 +166,10 @@ public class CfgScannerConfigInfoFactory2 {
}
map.put(new CfgInfoContext(cfg), info);
} else {
Map<CfgInfoContext, IScannerConfigBuilderInfo2> configMap = getConfigInfoMap(baseMap);
// Discovery profile scope = per language
Map<CfgInfoContext, IScannerConfigBuilderInfo2> configMap = getConfigInfoMap(baseMap);
IResourceInfo[] rcInfos = cfg.getResourceInfos();
for (IResourceInfo rcInfo : rcInfos) {
ITool tools[];
@ -188,7 +192,26 @@ public class CfgScannerConfigInfoFactory2 {
if(superContext != null && superContext.getResourceInfo() != null){
info = configMap.get(superContext);
}
String id = CfgScannerConfigUtil.getDefaultProfileId(context, true);
// Files with custom properties don't have a persisted entry in the config
// info map; we create an ephemeral entry instead. We need to assign that file
// the scanner profile that's used for non-custom files of the same
// inputType/tool (and configuration, of course). Unfortunately, identifying
// a match is inefficient, but in practice, projects don't have tons of
// customized files. See Bug 354194
String id = null;
for (Entry<CfgInfoContext, IScannerConfigBuilderInfo2> entry : configMap.entrySet()) {
CfgInfoContext cfgInfoCxt = entry.getKey();
if (match(cfgInfoCxt.getInputType(), context.getInputType()) &&
match(cfgInfoCxt.getTool(), context.getTool().getSuperClass()) &&
cfgInfoCxt.getConfiguration().equals(context.getConfiguration())) {
id = entry.getValue().getSelectedProfileId();
}
}
if (id == null) {
id = CfgScannerConfigUtil.getDefaultProfileId(context, true);
}
InfoContext baseContext = context.toInfoContext();
if(info == null){
if(id != null){
@ -203,6 +226,13 @@ public class CfgScannerConfigInfoFactory2 {
info = container.createInfo(baseContext, info);
}
}
// Make sure to remove the ephemeral info map entry from the
// container, otherwise it will not be ephemeral but rather a
// permanent and stagnant part of the project description. It was
// added to the container only so we could obtain an
// IScannerConfigBuilderInfo2. Now that we have the info object,
// revert the container. See Bug 354194
container.removeInfo(context.toInfoContext());
}
if(info != null){
map.put(context, info);
@ -347,4 +377,25 @@ public class CfgScannerConfigInfoFactory2 {
}
}
}
private static boolean match(ITool t1, ITool t2){
if (t1 == null || t2 == null)
return false;
if (t1.getId().equals(t2.getId())) {
return true;
}
return match(t1.getSuperClass(), t2.getSuperClass());
}
private static boolean match(IInputType i1, IInputType i2){
if (i1 == null || i2 == null)
return false;
if (i1.getId().equals(i2.getId())) {
return true;
}
return match(i1.getSuperClass(), i2.getSuperClass());
}
}

View file

@ -418,14 +418,41 @@ public class AST2CPPImplicitNameTests extends AST2BaseTest {
IBinding f= bh.assertNonProblem("operator delete(void * b)", 15);
IASTImplicitName[] names = bh.getImplicitNames("delete a;", 6);
assertEquals(2, names.length);
assertEquals(2, names.length);
assertTrue(((ICPPMethod) names[0].resolveBinding()).isDestructor());
assertSame(m, names[1].resolveBinding());
names = bh.getImplicitNames("delete b;", 6);
assertEquals(2, names.length);
assertTrue(((ICPPMethod) names[0].resolveBinding()).isDestructor());
assertEquals(2, names.length);
assertSame(f, names[1].resolveBinding());
}
// typedef int size_t;
// struct A {
// void* operator new(size_t a);
// };
// struct B {};
// void* operator new(size_t b);
//
// void test() {
// A *a = new A;
// B* b = new B;
// }
public void testOverloadedNew_Bug354585() throws Exception {
BindingAssertionHelper bh= new BindingAssertionHelper(getAboveComment(), true);
IBinding m= bh.assertNonProblem("operator new(size_t a)", 12);
IBinding f= bh.assertNonProblem("operator new(size_t b)", 12);
IASTImplicitName[] names = bh.getImplicitNames("new A;", 3);
assertEquals(1, names.length);
assertSame(m, names[0].resolveBinding());
names = bh.getImplicitNames("new B;", 3);
assertEquals(1, names.length);
assertSame(f, names[0].resolveBinding());
}
// struct X {}
// int test(X* x) {
// X* xs = new X[5];

View file

@ -9463,4 +9463,21 @@ public class AST2CPPTests extends AST2BaseTest {
public void testTypedefAsClassNameWithFunctionPtrArgument_350345() throws Exception {
parseAndCheckBindings();
}
// int func1(int input) {
// return input;
// }
// void dut() {
// int const_zero;
// int lll = (func1(func1(const_zero))) + func1(const_zero);
// int kkk = (func1(func1(const_zero))) + func1(const_zero);
// }
//
// void f3(int (x), int y=x);
// void f2(int (x), int y=x) {
// x= 1;
// }
public void testAmbiguityResolution_Bug354599() throws Exception {
parseAndCheckBindings();
}
}

View file

@ -326,5 +326,19 @@ public class PreprocessorBugsTests extends PreprocessorTestsBase {
validateEOF();
validateProblemCount(0);
}
// #define foo(x) (## x)
// void test foo(void); // Valid for Microsoft's compiler, expands to (void)
public void testInvalidTokenPasting_Bug354553() throws Exception {
initializeScanner();
validateToken(IToken.t_void);
validateIdentifier("test");
validateToken(IToken.tLPAREN);
validateToken(IToken.t_void);
validateToken(IToken.tRPAREN);
validateToken(IToken.tSEMI);
validateEOF();
validateProblem(0, IProblem.PREPROCESSOR_MACRO_PASTING_ERROR, "foo");
validateProblemCount(1);
}
}

View file

@ -227,6 +227,8 @@ public class PreprocessorTests extends PreprocessorTestsBase {
validateString("a");
validateToken(IToken.tSEMI);
validateString("a");
validateIdentifier("b");
validateToken(IToken.tSEMI);
validateEOF();
validateProblemCount(1);

View file

@ -551,10 +551,11 @@ public class IndexBugsTests extends BaseTestCase {
fIndex.releaseReadLock();
}
}
public void test164360_1() throws Exception {
waitForIndexer();
IFile include= TestSourceReader.createFile(fCProject.getProject(), "test164360.h", "");
TestScannerProvider.sIncludeFiles= new String[]{include.getLocation().toOSString()};
TestScannerProvider.sIncludeFiles= new String[] { include.getLocation().toOSString() };
IFile file= TestSourceReader.createFile(fCProject.getProject(), "test164360.cpp", "");
TestSourceReader.waitUntilFileIsIndexed(fIndex, file, INDEX_WAIT_TIME);
@ -696,8 +697,7 @@ public class IndexBugsTests extends BaseTestCase {
if (bindings[0] instanceof ICompositeType) {
struct= bindings[0];
typedef= bindings[1];
}
else {
} else {
struct= bindings[1];
typedef= bindings[0];
}
@ -730,8 +730,7 @@ public class IndexBugsTests extends BaseTestCase {
if (bindings[0] instanceof ICPPClassType) {
struct= bindings[0];
typedef= bindings[1];
}
else {
} else {
struct= bindings[1];
typedef= bindings[0];
}
@ -1149,8 +1148,7 @@ public class IndexBugsTests extends BaseTestCase {
assertEquals(1, bindings.length);
IIndexBinding binding = bindings[0];
assertTrue(binding instanceof IVariable);
IIndexName[] names = index.findNames(binding,
IIndex.FIND_ALL_OCCURRENCES);
IIndexName[] names = index.findNames(binding, IIndex.FIND_ALL_OCCURRENCES);
assertEquals(1, names.length);
assertEquals(f4.getFullPath().toString(), names[0].getFile().getLocation().getFullPath());

View file

@ -6,8 +6,8 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Markus Schorn - initial API and implementation
* Andrew Ferguson (Symbian)
* Markus Schorn - initial API and implementation
* Andrew Ferguson (Symbian)
*******************************************************************************/
package org.eclipse.cdt.internal.index.tests;
@ -35,37 +35,31 @@ import org.eclipse.cdt.core.index.IIndexBinding;
public class IndexCBindingResolutionBugs extends IndexBindingResolutionTestBase {
public static class SingleProject extends IndexCBindingResolutionBugs {
public SingleProject() {setStrategy(new SinglePDOMTestStrategy(false));}
public static TestSuite suite() {return suite(SingleProject.class);}
public SingleProject() { setStrategy(new SinglePDOMTestStrategy(false)); }
public static TestSuite suite() { return suite(SingleProject.class); }
}
public static class ProjectWithDepProj extends IndexCBindingResolutionBugs {
public ProjectWithDepProj() {setStrategy(new ReferencedProject(false));}
public static TestSuite suite() {return suite(ProjectWithDepProj.class);}
public ProjectWithDepProj() { setStrategy(new ReferencedProject(false)); }
public static TestSuite suite() { return suite(ProjectWithDepProj.class); }
}
public static void addTests(TestSuite suite) {
suite.addTest(SingleProject.suite());
suite.addTest(ProjectWithDepProj.suite());
}
// #include <stdio.h>
// void func1(void)
// {
// void func1(void) {
// int i = 0;
// for (i=0; i<10;i++)
// {
// for (i=0; i<10;i++) {
// printf("%i", i);
// }
//
// }
// #include "header.h"
//
// int main(void)
// {
// while (1)
// {
// int main(void) {
// while (1) {
// func1();
// }
// return 0;
@ -86,8 +80,7 @@ public class IndexCBindingResolutionBugs extends IndexBindingResolutionTestBase
// #include "header.h"
//
// int main(void)
// {
// int main(void) {
// void* v= func1;
// }
public void testBug181735() throws DOMException {
@ -151,7 +144,7 @@ public class IndexCBindingResolutionBugs extends IndexBindingResolutionTestBase
IVariable v= (IVariable) b0;
IType type= v.getType();
assertTrue(type instanceof IBasicType);
assertTrue(((IBasicType) type).getType() == IBasicType.t_char);
assertTrue(((IBasicType) type).getKind() == IBasicType.Kind.eChar);
}
// int globalFunc();
@ -165,7 +158,7 @@ public class IndexCBindingResolutionBugs extends IndexBindingResolutionTestBase
IFunction f= (IFunction) b0;
IType type= f.getType().getReturnType();
assertTrue(type instanceof IBasicType);
assertTrue(((IBasicType) type).getType() == IBasicType.t_char);
assertTrue(((IBasicType) type).getKind() == IBasicType.Kind.eChar);
}
// struct astruct {
@ -193,7 +186,7 @@ public class IndexCBindingResolutionBugs extends IndexBindingResolutionTestBase
assertEquals("additionalMember", additionalMember.getName());
IType type= member.getType();
assertTrue(type instanceof IBasicType);
assertTrue(((IBasicType) type).getType() == IBasicType.t_char);
assertTrue(((IBasicType) type).getKind() == IBasicType.Kind.eChar);
}
// enum anenum {
@ -224,7 +217,7 @@ public class IndexCBindingResolutionBugs extends IndexBindingResolutionTestBase
ITypedef t= (ITypedef) b0;
IType type= t.getType();
assertTrue(type instanceof IBasicType);
assertTrue(((IBasicType) type).getType() == IBasicType.t_char);
assertTrue(((IBasicType) type).getKind() == IBasicType.Kind.eChar);
}
// struct st_20070703 {
@ -395,7 +388,7 @@ public class IndexCBindingResolutionBugs extends IndexBindingResolutionTestBase
IParameter[] params= f.getParameters();
assertEquals(1, params.length);
assertTrue(params[0].getType() instanceof IBasicType);
assertEquals(IBasicType.t_int, ((IBasicType)params[0].getType()).getType());
assertEquals(IBasicType.Kind.eInt, ((IBasicType) params[0].getType()).getKind());
}
// typedef struct S S;

View file

@ -20,6 +20,7 @@ import org.eclipse.cdt.core.dom.ast.IASTExpression;
import org.eclipse.cdt.core.dom.ast.IBasicType;
import org.eclipse.cdt.core.dom.ast.IBasicType.Kind;
import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.IField;
import org.eclipse.cdt.core.dom.ast.IFunctionType;
import org.eclipse.cdt.core.dom.ast.IParameter;
import org.eclipse.cdt.core.dom.ast.IScope;
@ -1829,5 +1830,40 @@ public class IndexCPPTemplateResolutionTest extends IndexBindingResolutionTestBa
assertTrue(reference instanceof ICPPSpecialization);
}
// template<typename T> struct Base {
// int bfield;
// void bmethod();
// };
// template<typename T> struct XT : Base<T> {
// int field;
// void method() {};
// friend void f();
// struct Nested {};
// };
// struct TXT : XT<int> {};
// TXT x;
public void testClassSpecialization_Bug354086() throws Exception {
ICPPClassType ct= getBindingFromASTName("TXT", 0, ICPPClassType.class);
ICPPMethod[] methods = ct.getAllDeclaredMethods();
assertEquals(2, methods.length);
methods= ct.getConstructors();
assertEquals(2, methods.length);
methods= ct.getMethods();
assertEquals(14, methods.length);
ICPPBase[] bases = ct.getBases();
assertEquals(1, bases.length);
IField field = ct.findField("bfield");
assertNotNull(field);
IField[] fields = ct.getFields();
assertEquals(2, fields.length);
IBinding[] friends = ct.getFriends();
assertEquals(0, friends.length); // not yet supported
}
}

View file

@ -6,7 +6,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andrew Ferguson (Symbian) - Initial implementation
* Andrew Ferguson (Symbian) - Initial implementation
*******************************************************************************/
package org.eclipse.cdt.internal.index.tests;
@ -96,7 +96,7 @@ public class IndexCompositeTests extends BaseTestCase {
setIndex(cprojA, REFD); assertBCount(1, 1);
setIndex(cprojA, BOTH); assertBCount(2, 2);
} finally {
for(Iterator i = projects.iterator(); i.hasNext(); )
for (Iterator i = projects.iterator(); i.hasNext();)
((ICProject)i.next()).getProject().delete(true, true, new NullProgressMonitor());
}
}
@ -203,7 +203,7 @@ public class IndexCompositeTests extends BaseTestCase {
assertNamespaceXMemberCount(5);
assertFieldCount("C1", 1);
} finally {
for(Iterator i = projects.iterator(); i.hasNext(); )
for (Iterator i = projects.iterator(); i.hasNext();)
((ICProject)i.next()).getProject().delete(true, true, new NullProgressMonitor());
}
}
@ -226,8 +226,6 @@ public class IndexCompositeTests extends BaseTestCase {
public void testTripleUpwardV() throws Exception {
CharSequence[] contents = getContentsForTest(3);
List projects = new ArrayList();
try {
ProjectBuilder pb = new ProjectBuilder("projB"+System.currentTimeMillis(), true);
@ -294,7 +292,7 @@ public class IndexCompositeTests extends BaseTestCase {
assertBCount(7+4+4-2, 7+4+4-2 +2+1+1);
assertNamespaceXMemberCount(4);
} finally {
for(Iterator i = projects.iterator(); i.hasNext(); )
for (Iterator i = projects.iterator(); i.hasNext();)
((ICProject)i.next()).getProject().delete(true, true, new NullProgressMonitor());
}
}
@ -349,7 +347,7 @@ public class IndexCompositeTests extends BaseTestCase {
assertBCount(6, 6+1);
assertNamespaceXMemberCount(1);
setIndex(cprojC, REFD);
assertBCount(6+4+1-1, 6+4+1-1 +1+1+1+1 );
assertBCount(6+4+1-1, 6+4+1-1 +1+1+1+1);
assertNamespaceXMemberCount(4);
setIndex(cprojC, BOTH);
assertBCount(6+4+3-2, 6+4+3-2 +1+2+1);
@ -375,24 +373,22 @@ public class IndexCompositeTests extends BaseTestCase {
assertBCount(3, 3 +1);
assertNamespaceXMemberCount(1);
setIndex(cprojA, REFD);
assertBCount(4+2+3-1-1, 4+2+3-1-1 +2+1 );
assertBCount(4+2+3-1-1, 4+2+3-1-1 +2+1);
assertNamespaceXMemberCount(4);
setIndex(cprojA, BOTH);
assertBCount(6+4+3-2, 6+4+3-2 +1+2+1);
assertNamespaceXMemberCount(4);
} finally {
for(Iterator i = projects.iterator(); i.hasNext(); )
for (Iterator i = projects.iterator(); i.hasNext();)
((ICProject)i.next()).getProject().delete(true, true, new NullProgressMonitor());
}
}
/**
* Asserts binding counts, and returns the index tested against
* @param cprojA the project to obtain the index for
* @param options the options to obtain the index for
* @param global the number of bindings expected to be found at global scope
* @param all the number of bindings expected to be found at all scopes
* @return
* @return the index
* @throws CoreException
*/
private IIndex assertBCount(int global, int all) throws CoreException {
@ -416,7 +412,7 @@ public class IndexCompositeTests extends BaseTestCase {
}
private void setIndex(ICProject project, int options) throws CoreException, InterruptedException {
if(index!=null) {
if (index != null) {
index.releaseReadLock();
}
index = CCorePlugin.getIndexManager().getIndex(project, options);
@ -424,7 +420,7 @@ public class IndexCompositeTests extends BaseTestCase {
}
protected void tearDown() throws Exception {
if(index!=null) {
if (index != null) {
index.releaseReadLock();
}
super.tearDown();
@ -456,16 +452,17 @@ class ProjectBuilder {
}
ICProject create() throws CoreException {
ICProject result = cpp ? CProjectHelper.createCCProject(name, "bin", IPDOMManager.ID_NO_INDEXER)
: CProjectHelper.createCCProject(name, "bin", IPDOMManager.ID_NO_INDEXER);
ICProject result = cpp ?
CProjectHelper.createCCProject(name, "bin", IPDOMManager.ID_NO_INDEXER) :
CProjectHelper.createCCProject(name, "bin", IPDOMManager.ID_NO_INDEXER);
for(Iterator i = path2content.entrySet().iterator(); i.hasNext(); ) {
for (Iterator i = path2content.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
TestSourceReader.createFile(result.getProject(), new Path((String)entry.getKey()), (String) entry.getValue());
}
IProjectDescription desc = result.getProject().getDescription();
desc.setReferencedProjects( (IProject[]) dependencies.toArray(new IProject[dependencies.size()]) );
desc.setReferencedProjects((IProject[]) dependencies.toArray(new IProject[dependencies.size()]));
result.getProject().setDescription(desc, new NullProgressMonitor());
CCorePlugin.getIndexManager().setIndexerId(result, IPDOMManager.ID_FAST_INDEXER);

View file

@ -20,7 +20,6 @@ import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.ICompositeType;
import org.eclipse.cdt.core.dom.ast.IMacroBinding;
import org.eclipse.cdt.core.dom.ast.IScope;
import org.eclipse.cdt.core.dom.ast.IType;
import org.eclipse.cdt.core.parser.ParserLanguage;
import org.eclipse.cdt.core.parser.util.ArrayUtil;
import org.eclipse.cdt.internal.core.dom.Linkage;
@ -111,7 +110,7 @@ public class CASTTranslationUnit extends ASTTranslationUnit implements IASTAmbig
/**
* Maps structs from the index into this AST.
*/
public IType mapToASTType(ICompositeType type) {
public ICompositeType mapToASTType(ICompositeType type) {
return fStructMapper.mapToAST(type);
}
}

View file

@ -19,7 +19,6 @@ import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.ICompositeType;
import org.eclipse.cdt.core.dom.ast.IType;
import org.eclipse.cdt.core.parser.util.CharArrayMap;
/**
@ -56,7 +55,7 @@ public class CStructMapper {
fTranslationUnit= tu;
}
public IType mapToAST(ICompositeType type) {
public ICompositeType mapToAST(ICompositeType type) {
if (fStructs == null) {
fStructs= new CharArrayMap<IASTName>();
fTranslationUnit.accept(new Visitor());

View file

@ -607,9 +607,9 @@ public class CVisitor extends ASTQueries {
}
if (type != null && type instanceof ICompositeType) {
final ICompositeType ct = (ICompositeType) type;
if (type instanceof IIndexBinding) {
type= ((CASTTranslationUnit) fieldReference.getTranslationUnit()).mapToASTType(ct);
ICompositeType ct = (ICompositeType) type;
if (ct instanceof IIndexBinding) {
ct= ((CASTTranslationUnit) fieldReference.getTranslationUnit()).mapToASTType(ct);
}
if (prefix) {
char[] p = fieldReference.getFieldName().toCharArray();

View file

@ -64,7 +64,16 @@ final class CPPASTAmbiguityResolver extends ASTVisitor {
break;
}
if (node instanceof IASTParameterDeclaration) {
repopulateScope((IASTParameterDeclaration) node);
// If the parameter declaration belongs to a function declaration or
// function definition we need to update the scope.
IASTNode parent= node.getParent();
if (parent instanceof IASTDeclarator) {
IASTDeclarator dtor= (IASTDeclarator) parent;
if (dtor == ASTQueries.findTypeRelevantDeclarator(dtor) &&
ASTQueries.findOutermostDeclarator(dtor).getParent() instanceof IASTDeclaration) {
repopulateScope((IASTParameterDeclaration) node);
}
}
break;
}
if (node instanceof IASTExpression) {

View file

@ -52,7 +52,7 @@ public abstract class CPPASTNameBase extends ASTNode implements IASTName {
public final void incResolutionDepth() {
if (fBinding == null && ++fResolutionDepth > MAX_RESOLUTION_DEPTH) {
fBinding = new RecursionResolvingBinding(this);
setBinding(new RecursionResolvingBinding(this));
}
}
@ -69,9 +69,9 @@ public abstract class CPPASTNameBase extends ASTNode implements IASTName {
public IBinding resolvePreBinding() {
if (fBinding == null) {
if (++fResolutionDepth > MAX_RESOLUTION_DEPTH) {
fBinding= new RecursionResolvingBinding(this);
setBinding(new RecursionResolvingBinding(this));
} else {
fBinding= createIntermediateBinding();
setBinding(createIntermediateBinding());
}
}
return fBinding;
@ -80,7 +80,7 @@ public abstract class CPPASTNameBase extends ASTNode implements IASTName {
public IBinding resolveBinding() {
if (fBinding == null) {
if (++fResolutionDepth > MAX_RESOLUTION_DEPTH) {
fBinding= new RecursionResolvingBinding(this);
setBinding(new RecursionResolvingBinding(this));
} else {
fIsFinal= false;
final IBinding b= createIntermediateBinding();
@ -91,7 +91,7 @@ public abstract class CPPASTNameBase extends ASTNode implements IASTName {
pb.setASTNode(this);
}
}
fBinding= b;
setBinding(b);
}
}
if (!fIsFinal)
@ -106,13 +106,14 @@ public abstract class CPPASTNameBase extends ASTNode implements IASTName {
* @see ICPPTwoPhaseBinding
*/
public IBinding getPreBinding() {
final IBinding cand= fBinding;
if (cand == null)
return null;
return fBinding;
}
/**
* If this name has not yet been resolved at all, <code>null</code> will be returned.
* Otherwise the final binding for this name is returned.
* @see ICPPTwoPhaseBinding
*/
public IBinding getBinding() {
final IBinding cand= fBinding;
if (cand == null)
@ -128,15 +129,12 @@ public abstract class CPPASTNameBase extends ASTNode implements IASTName {
if (fBinding instanceof ICPPTwoPhaseBinding) {
ICPPTwoPhaseBinding intermediateBinding= (ICPPTwoPhaseBinding) fBinding;
if (++fResolutionDepth > MAX_RESOLUTION_DEPTH) {
fBinding= new RecursionResolvingBinding(this);
setBinding(new RecursionResolvingBinding(this));
} else {
IBinding finalBinding= intermediateBinding.resolveFinalBinding(astName);
fBinding= finalBinding;
setBinding(intermediateBinding.resolveFinalBinding(astName));
}
}
fIsFinal= true;
fResolutionDepth= 0;
}
public void setBinding(IBinding binding) {

View file

@ -425,7 +425,7 @@ public class ClassTypeHelper {
IField[] fields = ct.getDeclaredFields();
ICPPClassType[] bases = getAllBases(ct);
for (ICPPClassType base : bases) {
fields = (IField[]) ArrayUtil.addAll(IField.class, fields, base.getFields());
fields = (IField[]) ArrayUtil.addAll(IField.class, fields, base.getDeclaredFields());
}
return (IField[]) ArrayUtil.trim(IField.class, fields);
}

View file

@ -2941,20 +2941,19 @@ public class CPPSemantics {
return findOverloadedOperator(exp, args, type, OverloadableOperator.PAREN, LookupMode.NO_GLOBALS);
}
public static ICPPFunction findOverloadedOperator(ICPPASTNewExpression exp) {
OverloadableOperator op = OverloadableOperator.fromNewExpression(exp);
IType type = exp.getExpressionType();
if (!(type instanceof IPointerType))
return null;
type = ((IPointerType) type).getType();
IASTTypeId typeId = exp.getTypeId().copy();
IASTExpression sizeExpression = new CPPASTTypeIdExpression(IASTTypeIdExpression.op_sizeof, typeId);
sizeExpression.setParent(exp);
public static ICPPFunction findOverloadedOperator(ICPPASTNewExpression expr) {
OverloadableOperator op = OverloadableOperator.fromNewExpression(expr);
IType type = getTypeOfPointer(expr.getExpressionType());
if (type == null)
return null;
IASTInitializerClause[] placement = exp.getPlacementArguments();
IASTTypeId typeId = expr.getTypeId().copy();
IASTExpression sizeExpression = new CPPASTTypeIdExpression(IASTTypeIdExpression.op_sizeof, typeId);
sizeExpression.setParent(expr);
IASTInitializerClause[] placement = expr.getPlacementArguments();
List<IASTInitializerClause> args = new ArrayList<IASTInitializerClause>();
args.add(createArgForType(expr, type));
args.add(sizeExpression);
if (placement != null) {
for (IASTInitializerClause p : placement) {
@ -2962,23 +2961,23 @@ public class CPPSemantics {
}
}
IASTInitializerClause[] argArray = args.toArray(new IASTInitializerClause[args.size()]);
return findOverloadedOperator(exp, argArray, type, op, LookupMode.GLOBALS_IF_NO_MEMBERS);
return findOverloadedOperator(expr, argArray, type, op, LookupMode.GLOBALS_IF_NO_MEMBERS);
}
public static ICPPFunction findOverloadedOperator(ICPPASTDeleteExpression exp) {
OverloadableOperator op = OverloadableOperator.fromDeleteExpression(exp);
IType classType = getNestedClassType(exp);
IASTExpression[] args = new IASTExpression[] {createArgForType(exp, classType), exp.getOperand()};
return findOverloadedOperator(exp, args, classType, op, LookupMode.GLOBALS_IF_NO_MEMBERS);
public static ICPPFunction findOverloadedOperator(ICPPASTDeleteExpression expr) {
OverloadableOperator op = OverloadableOperator.fromDeleteExpression(expr);
IType type = getTypeOfPointer(expr.getOperand().getExpressionType());
if (type == null)
return null;
IASTExpression[] args = {createArgForType(expr, type), expr.getOperand()};
return findOverloadedOperator(expr, args, type, op, LookupMode.GLOBALS_IF_NO_MEMBERS);
}
private static ICPPClassType getNestedClassType(ICPPASTDeleteExpression exp) {
IType type = exp.getOperand().getExpressionType();
type = SemanticUtil.getUltimateTypeUptoPointers(type);
private static IType getTypeOfPointer(IType type) {
type = SemanticUtil.getNestedType(type, SemanticUtil.TDEF | SemanticUtil.REF | SemanticUtil.CVTYPE);
if (type instanceof IPointerType) {
IType classType = ((IPointerType) type).getType();
if (classType instanceof ICPPClassType)
return (ICPPClassType) classType;
return getNestedType(((IPointerType) type).getType(), TDEF | REF | CVTYPE);
}
return null;
}
@ -3101,10 +3100,11 @@ public class CPPSemantics {
}
public static ICPPFunction findImplicitlyCalledDestructor(ICPPASTDeleteExpression expr) {
ICPPClassType cls = getNestedClassType(expr);
if (cls == null)
IType t = getTypeOfPointer(expr.getOperand().getExpressionType());
if (!(t instanceof ICPPClassType))
return null;
ICPPClassType cls = (ICPPClassType) t;
IScope scope = cls.getCompositeScope();
if (scope == null)
return null;
@ -3281,8 +3281,15 @@ public class CPPSemantics {
funcName.setParent(parent);
funcName.setPropertyInParent(STRING_LOOKUP_PROPERTY);
LookupData funcData = new LookupData(funcName);
if (operator == OverloadableOperator.DELETE || operator == OverloadableOperator.DELETE_ARRAY) {
// Global new and delete operators do not take an argument for the this pointer.
switch (operator) {
case DELETE: case DELETE_ARRAY:
case NEW: case NEW_ARRAY:
args= ArrayUtil.removeFirst(args);
break;
default:
break;
}
funcData.setFunctionArguments(true, args);
funcData.ignoreMembers = true; // (13.3.1.2.3)

View file

@ -6,7 +6,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andrew Ferguson (Symbian) - Initial implementation
* Andrew Ferguson (Symbian) - Initial implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index.composite.c;
@ -25,7 +25,7 @@ class CompositeCStructure extends CompositeCBinding implements ICompositeType, I
}
public IField findField(String name) {
IField preresult = ((ICompositeType)rbinding).findField(name);
IField preresult = ((ICompositeType) rbinding).findField(name);
return (IField) cf.getCompositeBinding((IIndexFragmentBinding) preresult);
}
@ -34,24 +34,24 @@ class CompositeCStructure extends CompositeCBinding implements ICompositeType, I
}
public IField[] getFields() {
IField[] result = ((ICompositeType)rbinding).getFields();
for(int i=0; i<result.length; i++)
result[i] = (IField) cf.getCompositeBinding((IIndexFragmentBinding)result[i]);
IField[] result = ((ICompositeType) rbinding).getFields();
for(int i= 0; i < result.length; i++)
result[i] = (IField) cf.getCompositeBinding((IIndexFragmentBinding) result[i]);
return result;
}
public int getKey() {
return ((ICompositeType)rbinding).getKey();
return ((ICompositeType) rbinding).getKey();
}
public boolean isSameType(IType type) {
return ((ICompositeType)rbinding).isSameType(type);
return ((ICompositeType) rbinding).isSameType(type);
}
@Override
public Object clone() {fail(); return null;}
public boolean isAnonymous() {
return ((ICompositeType)rbinding).isAnonymous();
return ((ICompositeType) rbinding).isAnonymous();
}
}

View file

@ -12,7 +12,6 @@
package org.eclipse.cdt.internal.core.index.composite.cpp;
import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.IField;
import org.eclipse.cdt.core.dom.ast.IScope;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPBase;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassScope;
@ -25,7 +24,6 @@ import org.eclipse.cdt.core.dom.ast.cpp.ICPPSpecialization;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPTemplateParameterMap;
import org.eclipse.cdt.core.parser.util.ObjectMap;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPTemplateParameterMap;
import org.eclipse.cdt.internal.core.dom.parser.cpp.ClassTypeHelper;
import org.eclipse.cdt.internal.core.dom.parser.cpp.ICPPClassSpecializationScope;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPTemplates;
import org.eclipse.cdt.internal.core.index.IIndexFragment;
@ -105,7 +103,7 @@ public class CompositeCPPClassSpecialization extends CompositeCPPClassType imple
}
@Override
public ICPPBase[] getBases() {
public final ICPPBase[] getBases() {
IScope scope= getCompositeScope();
if (scope instanceof ICPPClassSpecializationScope) {
return ((ICPPClassSpecializationScope) scope).getBases();
@ -114,7 +112,7 @@ public class CompositeCPPClassSpecialization extends CompositeCPPClassType imple
}
@Override
public ICPPConstructor[] getConstructors() {
public final ICPPConstructor[] getConstructors() {
IScope scope= getCompositeScope();
if (scope instanceof ICPPClassSpecializationScope) {
return ((ICPPClassSpecializationScope) scope).getConstructors();
@ -123,7 +121,7 @@ public class CompositeCPPClassSpecialization extends CompositeCPPClassType imple
}
@Override
public ICPPMethod[] getDeclaredMethods() {
public final ICPPMethod[] getDeclaredMethods() {
IScope scope= getCompositeScope();
if (scope instanceof ICPPClassSpecializationScope) {
return ((ICPPClassSpecializationScope) scope).getDeclaredMethods();
@ -132,7 +130,7 @@ public class CompositeCPPClassSpecialization extends CompositeCPPClassType imple
}
@Override
public ICPPField[] getDeclaredFields() {
public final ICPPField[] getDeclaredFields() {
IScope scope= getCompositeScope();
if (scope instanceof ICPPClassSpecializationScope) {
return ((ICPPClassSpecializationScope) scope).getDeclaredFields();
@ -141,7 +139,7 @@ public class CompositeCPPClassSpecialization extends CompositeCPPClassType imple
}
@Override
public IBinding[] getFriends() {
public final IBinding[] getFriends() {
IScope scope= getCompositeScope();
if (scope instanceof ICPPClassSpecializationScope) {
return ((ICPPClassSpecializationScope) scope).getFriends();
@ -150,7 +148,7 @@ public class CompositeCPPClassSpecialization extends CompositeCPPClassType imple
}
@Override
public ICPPClassType[] getNestedClasses() {
public final ICPPClassType[] getNestedClasses() {
IScope scope= getCompositeScope();
if (scope instanceof ICPPClassSpecializationScope) {
return ((ICPPClassSpecializationScope) scope).getNestedClasses();
@ -158,26 +156,6 @@ public class CompositeCPPClassSpecialization extends CompositeCPPClassType imple
return super.getNestedClasses();
}
@Override
public IField findField(String name) {
return ClassTypeHelper.findField(this, name);
}
@Override
public ICPPMethod[] getAllDeclaredMethods() {
return ClassTypeHelper.getAllDeclaredMethods(this);
}
@Override
public IField[] getFields() {
return ClassTypeHelper.getFields(this);
}
@Override
public ICPPMethod[] getMethods() {
return ClassTypeHelper.getMethods(this);
}
@Deprecated
public ObjectMap getArgumentMap() {
return TemplateInstanceUtil.getArgumentMap(cf, rbinding);

View file

@ -21,6 +21,7 @@ import org.eclipse.cdt.core.dom.ast.cpp.ICPPConstructor;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPField;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPMethod;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPScope;
import org.eclipse.cdt.internal.core.dom.parser.cpp.ClassTypeHelper;
import org.eclipse.cdt.internal.core.index.IIndexFragmentBinding;
import org.eclipse.cdt.internal.core.index.IIndexType;
import org.eclipse.cdt.internal.core.index.composite.ICompositesFactory;
@ -35,17 +36,12 @@ class CompositeCPPClassType extends CompositeCPPBinding implements ICPPClassType
fail(); return null;
}
public IField findField(String name) {
IField preResult = ((ICPPClassType)rbinding).findField(name);
return (IField) cf.getCompositeBinding((IIndexFragmentBinding)preResult);
public final IField findField(String name) {
return ClassTypeHelper.findField(this, name);
}
public ICPPMethod[] getAllDeclaredMethods() {
ICPPMethod[] result = ((ICPPClassType)rbinding).getAllDeclaredMethods();
for(int i=0; i<result.length; i++) {
result[i] = (ICPPMethod) cf.getCompositeBinding((IIndexFragmentBinding)result[i]);
}
return result;
public final ICPPMethod[] getAllDeclaredMethods() {
return ClassTypeHelper.getAllDeclaredMethods(this);
}
private class CPPBaseDelegate implements ICPPBase {
@ -129,12 +125,8 @@ class CompositeCPPClassType extends CompositeCPPBinding implements ICPPClassType
return result;
}
public IField[] getFields() {
IField[] result = ((ICPPClassType)rbinding).getFields();
for(int i=0; i<result.length; i++) {
result[i]= (IField) cf.getCompositeBinding((IIndexFragmentBinding)result[i]);
}
return result;
public final IField[] getFields() {
return ClassTypeHelper.getFields(this);
}
public IBinding[] getFriends() {
@ -146,12 +138,8 @@ class CompositeCPPClassType extends CompositeCPPBinding implements ICPPClassType
return result;
}
public ICPPMethod[] getMethods() {
ICPPMethod[] result = ((ICPPClassType)rbinding).getMethods();
for(int i=0; i<result.length; i++) {
result[i] = (ICPPMethod) cf.getCompositeBinding((IIndexFragmentBinding) result[i]);
}
return result;
public final ICPPMethod[] getMethods() {
return ClassTypeHelper.getMethods(this);
}
public ICPPClassType[] getNestedClasses() {

View file

@ -13,6 +13,7 @@ package org.eclipse.cdt.internal.core.parser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
@ -154,6 +155,20 @@ public class InternalParserUtil extends ParserFactory {
InputStream in;
try {
in= file.getContents(true);
if (!(in instanceof FileInputStream)) {
/*
* In general, non-local file-systems will not use FileInputStream. Instead make a
* cached copy of the file and open an input stream to that.
*/
IFileStore store = EFS.getStore(file.getLocationURI());
File fileCache = store.toLocalFile(EFS.CACHE, null);
try {
in = new FileInputStream(fileCache);
} catch (FileNotFoundException e) {
CCorePlugin.log(e);
return null;
}
}
try {
return createFileContent(path, file.getCharset(), in);
} finally {
@ -168,6 +183,7 @@ public class InternalParserUtil extends ParserFactory {
case IResourceStatus.NO_LOCATION_LOCAL:
case IResourceStatus.FAILED_READ_LOCAL:
case IResourceStatus.RESOURCE_NOT_LOCAL:
case IResourceStatus.RESOURCE_NOT_FOUND:
break;
default:
CCorePlugin.log(e);
@ -221,6 +237,9 @@ public class InternalParserUtil extends ParserFactory {
private static InternalFileContent createFileContent(String path, String charset, InputStream in) {
try {
AbstractCharArray chars= FileCharArray.create(path, charset, in);
if (chars == null)
return null;
return new InternalFileContent(path, chars);
} catch (IOException e) {
CCorePlugin.log(e);

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;
@ -111,14 +111,14 @@ abstract class LocationCtx implements ILocationCtx {
* that it is contained in this context.
*/
public ASTFileLocation findMappedFileLocation(int sequenceNumber, int length) {
return fParent.createMappedFileLocation(fOffsetInParent, fEndOffsetInParent-fOffsetInParent);
return fParent.createMappedFileLocation(fOffsetInParent, fEndOffsetInParent - fOffsetInParent);
}
/**
* Returns the file location containing the specified offset range in this context.
*/
public ASTFileLocation createMappedFileLocation(int offset, int length) {
return fParent.createMappedFileLocation(fOffsetInParent, fEndOffsetInParent-fOffsetInParent);
return fParent.createMappedFileLocation(fOffsetInParent, fEndOffsetInParent - fOffsetInParent);
}
/**

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;
@ -56,7 +56,7 @@ class LocationCtxContainer extends LocationCtx {
}
public char[] getSource(int offset, int length) {
if (fSource.isValidOffset(offset+length-1)) {
if (fSource.isValidOffset(offset + length - 1)) {
char[] result= new char[length];
fSource.arraycopy(offset, result, 0, length);
return result;
@ -73,12 +73,11 @@ class LocationCtxContainer extends LocationCtx {
public final int getSequenceNumberForOffset(int offset, boolean checkChildren) {
int result= fSequenceNumber + fChildSequenceLength + offset;
if (checkChildren && fChildren != null) {
for (int i= fChildren.size()-1; i >= 0; i--) {
for (int i= fChildren.size() - 1; i >= 0; i--) {
final LocationCtx child= fChildren.get(i);
if (child.fEndOffsetInParent > offset) { // child was inserted behind the offset, adjust sequence number
result-= child.getSequenceLength();
}
else {
} else {
return result;
}
}
@ -93,7 +92,7 @@ class LocationCtxContainer extends LocationCtx {
@Override
public final LocationCtx findSurroundingContext(int sequenceNumber, int length) {
int testEnd= length > 1 ? sequenceNumber+length-1 : sequenceNumber;
int testEnd= length > 1 ? sequenceNumber + length - 1 : sequenceNumber;
final LocationCtx child= findChildLessOrEqualThan(sequenceNumber, false);
if (child != null && child.fSequenceNumber+child.getSequenceLength() > testEnd) {
return child.findSurroundingContext(sequenceNumber, length);
@ -103,7 +102,7 @@ class LocationCtxContainer extends LocationCtx {
@Override
public final LocationCtxMacroExpansion findEnclosingMacroExpansion(int sequenceNumber, int length) {
int testEnd= length > 1 ? sequenceNumber+length-1 : sequenceNumber;
int testEnd= length > 1 ? sequenceNumber + length - 1 : sequenceNumber;
final LocationCtx child= findChildLessOrEqualThan(sequenceNumber, true);
if (child != null && child.fSequenceNumber+child.getSequenceLength() > testEnd) {
return child.findEnclosingMacroExpansion(sequenceNumber, length);
@ -129,9 +128,9 @@ class LocationCtxContainer extends LocationCtx {
@Override
public ASTFileLocation findMappedFileLocation(int sequenceNumber, int length) {
// try to delegate to a child.
int testEnd= length > 1 ? sequenceNumber+length-1 : sequenceNumber;
int testEnd= length > 1 ? sequenceNumber + length - 1 : sequenceNumber;
final LocationCtx child= findChildLessOrEqualThan(sequenceNumber, false);
if (child != null && child.fSequenceNumber+child.getSequenceLength() > testEnd) {
if (child != null && child.fSequenceNumber + child.getSequenceLength() > testEnd) {
return child.findMappedFileLocation(sequenceNumber, length);
}
return super.findMappedFileLocation(sequenceNumber, length);
@ -139,7 +138,7 @@ class LocationCtxContainer extends LocationCtx {
@Override
public boolean collectLocations(int sequenceNumber, final int length, ArrayList<IASTNodeLocation> locations) {
final int endSequenceNumber= sequenceNumber+length;
final int endSequenceNumber= sequenceNumber + length;
if (fChildren != null) {
int childIdx= Math.max(0, findChildIdxLessOrEqualThan(sequenceNumber, false));
for (; childIdx < fChildren.size(); childIdx++) {
@ -151,18 +150,18 @@ class LocationCtxContainer extends LocationCtx {
final int offset= child.fEndOffsetInParent - (child.fSequenceNumber - sequenceNumber);
// it the child is not affected, we are done.
if (endSequenceNumber <= child.fSequenceNumber) {
addFileLocation(offset, endSequenceNumber-sequenceNumber, locations);
addFileLocation(offset, endSequenceNumber - sequenceNumber, locations);
return true;
}
if (offset < child.fOffsetInParent)
addFileLocation(offset, child.fOffsetInParent-offset, locations);
addFileLocation(offset, child.fOffsetInParent - offset, locations);
sequenceNumber= child.fSequenceNumber;
}
// let the child create locations
final int childEndSequenceNumber= child.fSequenceNumber + child.getSequenceLength();
if (sequenceNumber < childEndSequenceNumber) {
if (child.collectLocations(sequenceNumber, endSequenceNumber-sequenceNumber, locations)) {
if (child.collectLocations(sequenceNumber, endSequenceNumber - sequenceNumber, locations)) {
return true;
}
sequenceNumber= childEndSequenceNumber;
@ -174,10 +173,10 @@ class LocationCtxContainer extends LocationCtx {
final int myEndNumber = fSequenceNumber + getSequenceLength();
final int offset= fSource.getLength() - (myEndNumber - sequenceNumber);
if (endSequenceNumber <= myEndNumber) {
addFileLocation(offset, endSequenceNumber-sequenceNumber, locations);
addFileLocation(offset, endSequenceNumber - sequenceNumber, locations);
return true;
}
addFileLocation(offset, fSource.getLength()-offset, locations);
addFileLocation(offset, fSource.getLength() - offset, locations);
return false;
}
@ -200,20 +199,19 @@ class LocationCtxContainer extends LocationCtx {
int upper= fChildren.size();
int lower= 0;
while (upper > lower) {
int middle= (upper+lower)/2;
int middle= (upper + lower) / 2;
LocationCtx child= fChildren.get(middle);
int childSequenceNumber= child.fSequenceNumber;
if (beforeReplacedChars) {
childSequenceNumber-= child.fEndOffsetInParent-child.fOffsetInParent;
childSequenceNumber-= child.fEndOffsetInParent - child.fOffsetInParent;
}
if (childSequenceNumber <= sequenceNumber) {
lower= middle+1;
}
else {
lower= middle + 1;
} else {
upper= middle;
}
}
return lower-1;
return lower - 1;
}
final LocationCtx findChildLessOrEqualThan(final int sequenceNumber, boolean beforeReplacedChars) {
@ -227,8 +225,7 @@ class LocationCtxContainer extends LocationCtx {
for (LocationCtx ctx : fChildren) {
if (ctx.getInclusionStatement() != null) {
result.add(new ASTInclusionNode(ctx));
}
else {
} else {
ctx.getInclusions(result);
}
}

View file

@ -6,13 +6,14 @@
* 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;
import java.util.ArrayList;
import java.util.Collection;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorMacroExpansion;
/**
@ -24,9 +25,9 @@ class LocationCtxFile extends LocationCtxContainer {
private final ASTInclusionStatement fASTInclude;
private final boolean fIsSource;
public LocationCtxFile(LocationCtxContainer parent, String filename, AbstractCharArray source, int parentOffset,
int parentEndOffset, int sequenceNumber, ASTInclusionStatement inclusionStatement,
boolean isSource) {
public LocationCtxFile(LocationCtxContainer parent, String filename, AbstractCharArray source,
int parentOffset, int parentEndOffset, int sequenceNumber,
ASTInclusionStatement inclusionStatement, boolean isSource) {
super(parent, source, parentOffset, parentEndOffset, sequenceNumber);
fFilename= new String(filename);
fASTInclude= inclusionStatement;
@ -46,12 +47,14 @@ class LocationCtxFile extends LocationCtxContainer {
@Override
public ASTFileLocation findMappedFileLocation(int sequenceNumber, int length) {
// try to delegate to a child.
final int testEnd= length > 1 ? sequenceNumber+length-1 : sequenceNumber;
final int testEnd= length > 1 ? sequenceNumber + length - 1 : sequenceNumber;
final int sequenceEnd= sequenceNumber+length;
final LocationCtx child1= findChildLessOrEqualThan(sequenceNumber, false);
final LocationCtx child2= testEnd == sequenceNumber ? child1 : findChildLessOrEqualThan(testEnd, false);
final LocationCtx child2= testEnd == sequenceNumber ?
child1 : findChildLessOrEqualThan(testEnd, false);
if (child1 == child2 && child1 != null && child1.fSequenceNumber + child1.getSequenceLength() > testEnd) {
if (child1 == child2 && child1 != null &&
child1.fSequenceNumber + child1.getSequenceLength() > testEnd) {
return child1.findMappedFileLocation(sequenceNumber, length);
}
@ -61,29 +64,25 @@ class LocationCtxFile extends LocationCtxContainer {
if (child1 == null) {
startOffset= sequenceNumber-fSequenceNumber;
}
else {
} else {
int childSequenceEnd= child1.fSequenceNumber + child1.getSequenceLength();
if (sequenceNumber < childSequenceEnd) {
startOffset= child1.fOffsetInParent;
}
else { // start beyond child1
startOffset= child1.fEndOffsetInParent + sequenceNumber-childSequenceEnd;
} else { // start beyond child1
startOffset= child1.fEndOffsetInParent + sequenceNumber - childSequenceEnd;
}
}
if (child2 == null) {
endOffset= sequenceEnd-fSequenceNumber;
}
else {
endOffset= sequenceEnd - fSequenceNumber;
} else {
int childSequenceEnd= child2.fSequenceNumber + child2.getSequenceLength();
if (childSequenceEnd < sequenceEnd) { // beyond child2
endOffset= child2.fEndOffsetInParent+sequenceEnd-childSequenceEnd;
}
else {
endOffset= child2.fEndOffsetInParent + sequenceEnd - childSequenceEnd;
} else {
endOffset= child2.fEndOffsetInParent;
}
}
return new ASTFileLocation(this, startOffset, endOffset-startOffset);
return new ASTFileLocation(this, startOffset, endOffset - startOffset);
}
@Override
@ -109,7 +108,8 @@ class LocationCtxFile extends LocationCtxContainer {
return sequenceNumber >= child.fSequenceNumber + child.getSequenceLength();
}
public void collectMacroExpansions(int offset, int length, ArrayList<IASTPreprocessorMacroExpansion> list) {
public void collectMacroExpansions(int offset, int length,
ArrayList<IASTPreprocessorMacroExpansion> list) {
Collection<LocationCtx> children= getChildren();
for (LocationCtx ctx : children) {
// context must start before the end of the search range
@ -119,7 +119,9 @@ class LocationCtxFile extends LocationCtxContainer {
if (ctx instanceof LocationCtxMacroExpansion) {
// expansion must end after the search start
if (ctx.fEndOffsetInParent > offset) {
list.add((IASTPreprocessorMacroExpansion) ((LocationCtxMacroExpansion)ctx).getMacroReference().getParent());
IASTNode macroExpansion =
((LocationCtxMacroExpansion) ctx).getMacroReference().getParent();
list.add((IASTPreprocessorMacroExpansion) macroExpansion);
}
}
}

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;
@ -46,10 +46,10 @@ class LocationCtxMacroExpansion extends LocationCtx {
@Override
public boolean collectLocations(int start, int length, ArrayList<IASTNodeLocation> locations) {
final int offset= start-fSequenceNumber;
final int offset= start - fSequenceNumber;
assert offset >= 0 && length >= 0;
if (offset+length <= fLength) {
if (offset + length <= fLength) {
locations.add(new ASTMacroExpansionLocation(this, offset, length));
return true;
}
@ -87,18 +87,15 @@ class LocationCtxMacroExpansion extends LocationCtx {
if (info.fTokenOffsetInExpansion == nextToCheck) {
if (firstInfo == null || lastInfo == null) {
firstInfo= lastInfo= info;
}
else if (lastInfo.canConcatenate(info)) {
} else if (lastInfo.canConcatenate(info)) {
lastInfo= info;
}
else {
} else {
return null;
}
if (++nextToCheck == end) {
return firstInfo.createLocation(fLocationMap, lastInfo);
}
}
else if (info.fTokenOffsetInExpansion > nextToCheck) {
} else if (info.fTokenOffsetInExpansion > nextToCheck) {
return null;
}
}
@ -109,5 +106,3 @@ class LocationCtxMacroExpansion extends LocationCtx {
return fLocationMap.getNestedMacroReferences((ASTMacroExpansion) fExpansionName.getParent());
}
}

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;
@ -37,13 +37,11 @@ import org.eclipse.cdt.internal.core.dom.parser.ASTProblem;
import org.eclipse.cdt.internal.core.parser.scanner.Lexer.LexerOptions;
/**
* Converts the offsets relative to various contexts to the global sequence number. Also creates and stores
* objects that are needed to conform with the IAST... interfaces.
* Converts the offsets relative to various contexts to the global sequence number. Also creates
* and stores objects that are needed to conform with the IAST... interfaces.
* @since 5.0
*/
public class LocationMap implements ILocationResolver {
private static final IASTName[] EMPTY_NAMES = {};
private final LexerOptions fLexerOptions;
private String fTranslationUnitPath;
private IASTTranslationUnit fTranslationUnit;
@ -82,8 +80,7 @@ public class LocationMap implements ILocationResolver {
ASTMacroDefinition astmacro;
if (macro.isFunctionStyle()) {
astmacro= new ASTFunctionStyleMacroDefinition(fTranslationUnit, macro, nameloc, expansionOffset);
}
else {
} else {
astmacro= new ASTMacroDefinition(fTranslationUnit, macro, nameloc, expansionOffset);
}
fBuiltinMacros.add(astmacro);
@ -176,10 +173,11 @@ public class LocationMap implements ILocationResolver {
int nameNumber= getSequenceNumberForOffset(nameOffset);
int nameEndNumber= getSequenceNumberForOffset(nameEndOffset);
int endNumber= getSequenceNumberForOffset(endOffset);
final int length= endNumber-nameNumber;
final int length= endNumber - nameNumber;
ASTMacroExpansion expansion= new ASTMacroExpansion(fTranslationUnit, nameNumber, endNumber);
ASTMacroReferenceName explicitRef= new ASTMacroReferenceName(expansion, IASTPreprocessorMacroExpansion.EXPANSION_NAME, nameNumber, nameEndNumber, macro, null);
ASTMacroReferenceName explicitRef= new ASTMacroReferenceName(expansion,
IASTPreprocessorMacroExpansion.EXPANSION_NAME, nameNumber, nameEndNumber, macro, null);
addMacroReference(explicitRef);
for (IASTName implicitMacroReference : implicitMacroReferences) {
ASTMacroReferenceName name = (ASTMacroReferenceName) implicitMacroReference;
@ -188,7 +186,9 @@ public class LocationMap implements ILocationResolver {
addMacroReference(name);
}
LocationCtxMacroExpansion expansionCtx= new LocationCtxMacroExpansion(this, (LocationCtxContainer) fCurrentContext, nameOffset, endOffset, endNumber, contextLength, imageLocations, explicitRef);
LocationCtxMacroExpansion expansionCtx= new LocationCtxMacroExpansion(this,
(LocationCtxContainer) fCurrentContext, nameOffset, endOffset, endNumber,
contextLength, imageLocations, explicitRef);
expansion.setContext(expansionCtx);
fCurrentContext= expansionCtx;
fLastChildInsertionOffset= 0;
@ -232,7 +232,8 @@ public class LocationMap implements ILocationResolver {
nameOffset= getSequenceNumberForOffset(nameOffset);
nameEndOffset= getSequenceNumberForOffset(nameEndOffset);
endOffset= getSequenceNumberForOffset(endOffset);
fDirectives.add(new ASTInclusionStatement(fTranslationUnit, startOffset, nameOffset, nameEndOffset, endOffset, name, filename, userInclude, active, heuristic));
fDirectives.add(new ASTInclusionStatement(fTranslationUnit, startOffset, nameOffset,
nameEndOffset, endOffset, name, filename, userInclude, active, heuristic));
}
public void encounteredComment(int offset, int endOffset, boolean isBlockComment) {
@ -244,7 +245,8 @@ public class LocationMap implements ILocationResolver {
public void encounterProblem(int id, char[] arg, int offset, int endOffset) {
offset= getSequenceNumberForOffset(offset);
endOffset= getSequenceNumberForOffset(endOffset);
ASTProblem problem = new ASTProblem(fTranslationUnit, IASTTranslationUnit.SCANNER_PROBLEM, id, arg, false, offset, endOffset);
ASTProblem problem = new ASTProblem(fTranslationUnit, IASTTranslationUnit.SCANNER_PROBLEM,
id, arg, false, offset, endOffset);
fProblems.add(problem);
}
@ -302,7 +304,8 @@ public class LocationMap implements ILocationResolver {
fDirectives.add(new ASTPragmaOperator(fTranslationUnit, startNumber, condNumber, condEndNumber, endNumber));
}
public ASTIfdef encounterPoundIfdef(int startOffset, int condOffset, int condEndOffset, int endOffset, boolean taken, IMacroBinding macro) {
public ASTIfdef encounterPoundIfdef(int startOffset, int condOffset, int condEndOffset,
int endOffset, boolean taken, IMacroBinding macro) {
startOffset= getSequenceNumberForOffset(startOffset);
condOffset= getSequenceNumberForOffset(condOffset);
condEndOffset= getSequenceNumberForOffset(condEndOffset);
@ -313,7 +316,8 @@ public class LocationMap implements ILocationResolver {
return ifdef;
}
public ASTIfndef encounterPoundIfndef(int startOffset, int condOffset, int condEndOffset, int endOffset, boolean taken, IMacroBinding macro) {
public ASTIfndef encounterPoundIfndef(int startOffset, int condOffset, int condEndOffset,
int endOffset, boolean taken, IMacroBinding macro) {
startOffset= getSequenceNumberForOffset(startOffset);
condOffset= getSequenceNumberForOffset(condOffset);
condEndOffset= getSequenceNumberForOffset(condEndOffset);
@ -324,8 +328,8 @@ public class LocationMap implements ILocationResolver {
return ifndef;
}
public ASTIf encounterPoundIf(int startOffset, int condOffset, int condEndOffset, int endOffset, boolean taken,
IASTName[] macrosInDefinedExpression) {
public ASTIf encounterPoundIf(int startOffset, int condOffset, int condEndOffset, int endOffset,
boolean taken, IASTName[] macrosInDefinedExpression) {
startOffset= getSequenceNumberForOffset(startOffset);
condOffset= getSequenceNumberForOffset(condOffset);
condEndOffset= getSequenceNumberForOffset(condEndOffset);
@ -341,7 +345,8 @@ public class LocationMap implements ILocationResolver {
return astif;
}
public void encounterPoundDefine(int startOffset, int nameOffset, int nameEndOffset, int expansionOffset, int endOffset, boolean isActive, IMacroBinding macrodef) {
public void encounterPoundDefine(int startOffset, int nameOffset, int nameEndOffset,
int expansionOffset, int endOffset, boolean isActive, IMacroBinding macrodef) {
startOffset= getSequenceNumberForOffset(startOffset);
nameOffset= getSequenceNumberForOffset(nameOffset);
nameEndOffset= getSequenceNumberForOffset(nameEndOffset);
@ -349,20 +354,23 @@ public class LocationMap implements ILocationResolver {
endOffset= getSequenceNumberForOffset(endOffset);
ASTPreprocessorNode astMacro;
if (!macrodef.isFunctionStyle()) {
astMacro= new ASTMacroDefinition(fTranslationUnit, macrodef, startOffset, nameOffset, nameEndOffset, expansionOffset, endOffset, isActive);
}
else {
astMacro= new ASTFunctionStyleMacroDefinition(fTranslationUnit, macrodef, startOffset, nameOffset, nameEndOffset, expansionOffset, endOffset, isActive);
astMacro= new ASTMacroDefinition(fTranslationUnit, macrodef, startOffset, nameOffset,
nameEndOffset, expansionOffset, endOffset, isActive);
} else {
astMacro= new ASTFunctionStyleMacroDefinition(fTranslationUnit, macrodef, startOffset,
nameOffset, nameEndOffset, expansionOffset, endOffset, isActive);
}
fDirectives.add(astMacro);
}
public void encounterPoundUndef(IMacroBinding definition, int startOffset, int nameOffset, int nameEndOffset, int endOffset, char[] name, boolean isActive) {
public void encounterPoundUndef(IMacroBinding definition, int startOffset, int nameOffset,
int nameEndOffset, int endOffset, char[] name, boolean isActive) {
startOffset= getSequenceNumberForOffset(startOffset);
nameOffset= getSequenceNumberForOffset(nameOffset);
nameEndOffset= getSequenceNumberForOffset(nameEndOffset);
// not using endOffset, compatible with 4.0: endOffset= getSequenceNumberForOffset(endOffset);
final ASTUndef undef = new ASTUndef(fTranslationUnit, name, startOffset, nameOffset, nameEndOffset, definition, isActive);
final ASTUndef undef = new ASTUndef(fTranslationUnit, name, startOffset, nameOffset,
nameEndOffset, definition, isActive);
fDirectives.add(undef);
addMacroReference(undef.getMacroName());
}
@ -462,7 +470,7 @@ public class LocationMap implements ILocationResolver {
int length= 0;
if (nodeLength > 0) {
length= getSequenceNumberForFileOffset(fileName, nodeOffset + nodeLength-1)+1 - sequenceNumber;
length= getSequenceNumberForFileOffset(fileName, nodeOffset + nodeLength - 1) + 1 - sequenceNumber;
if (length < 0) {
return null;
}
@ -506,7 +514,7 @@ public class LocationMap implements ILocationResolver {
// check directives
int from= findLastNodeBefore(fDirectives, sequenceStart);
for (int i= from+1; i < fDirectives.size(); i++) {
for (int i= from + 1; i < fDirectives.size(); i++) {
ASTPreprocessorNode directive= fDirectives.get(i);
if (directive.getOffset() > sequenceEnd) {
break;
@ -516,7 +524,7 @@ public class LocationMap implements ILocationResolver {
// check macro references and expansions
from= findLastMacroReferenceBefore(fMacroReferences, sequenceStart);
for (int i= from+1; i < fMacroReferences.size(); i++) {
for (int i= from + 1; i < fMacroReferences.size(); i++) {
ASTPreprocessorNode macroRef= fMacroReferences.get(i);
if (macroRef.getOffset() > sequenceEnd) {
break;
@ -552,15 +560,14 @@ public class LocationMap implements ILocationResolver {
}
private int findLastNodeBefore(ArrayList<? extends ASTPreprocessorNode> nodes, int sequenceStart) {
int lower=-1;
int upper= nodes.size()-1;
while(lower < upper) {
int middle= (lower+upper+1)/2;
int lower= -1;
int upper= nodes.size() - 1;
while (lower < upper) {
int middle= (lower + upper + 1) / 2;
ASTPreprocessorNode candidate= nodes.get(middle);
if (candidate.getOffset() + candidate.getLength() >= sequenceStart) {
upper= middle-1;
}
else {
upper= middle - 1;
} else {
lower= middle;
}
}
@ -568,19 +575,18 @@ public class LocationMap implements ILocationResolver {
}
private int findLastMacroReferenceBefore(ArrayList<? extends ASTPreprocessorName> nodes, int sequenceStart) {
int lower=-1;
int upper= nodes.size()-1;
while(lower < upper) {
int middle= (lower+upper+1)/2;
int lower= -1;
int upper= nodes.size() - 1;
while (lower < upper) {
int middle= (lower + upper + 1) / 2;
ASTPreprocessorNode candidate= nodes.get(middle);
IASTNode parent= candidate.getParent();
if (parent instanceof ASTMacroExpansion) {
candidate= (ASTMacroExpansion) parent;
}
if (candidate.getOffset() + candidate.getLength() >= sequenceStart) {
upper= middle-1;
}
else {
upper= middle - 1;
} else {
lower= middle;
}
}
@ -591,7 +597,7 @@ public class LocationMap implements ILocationResolver {
LocationCtx ctx= fRootContext;
if (filePath != null) {
LinkedList<LocationCtx> contexts= new LinkedList<LocationCtx>();
while(ctx != null) {
while (ctx != null) {
if (ctx instanceof LocationCtxFile) {
if (filePath.equals(ctx.getFilePath())) {
break;
@ -600,8 +606,7 @@ public class LocationMap implements ILocationResolver {
contexts.addAll(ctx.getChildren());
if (contexts.isEmpty()) {
ctx= null;
}
else {
} else {
ctx= contexts.removeFirst();
}
}
@ -617,7 +622,7 @@ public class LocationMap implements ILocationResolver {
return null;
}
IASTFileLocation from= locations[0].asFileLocation();
IASTFileLocation to= locations[locations.length-1].asFileLocation();
IASTFileLocation to= locations[locations.length - 1].asFileLocation();
if (from == to) {
return from;
}
@ -676,7 +681,7 @@ public class LocationMap implements ILocationResolver {
public IASTName[] getDeclarations(IMacroBinding binding) {
IASTPreprocessorMacroDefinition def = getMacroDefinition(binding);
return def == null ? EMPTY_NAMES : new IASTName[] {def.getName()};
return def == null ? IASTName.EMPTY_NAME_ARRAY: new IASTName[] { def.getName() };
}
IASTPreprocessorMacroDefinition getMacroDefinition(IMacroBinding binding) {

View file

@ -65,8 +65,7 @@ public class MacroExpander {
public void execute(IdentityHashMap<PreprocessorMacro, PreprocessorMacro> forbidden) {
if (fIsStart) {
forbidden.put(fMacro, fMacro);
}
else {
} else {
forbidden.remove(fMacro);
}
}
@ -303,18 +302,15 @@ public class MacroExpander {
}
tracker.endFunctionStyleMacro();
}
}
else {
} else {
if (tracker == null) {
objStyleTokenPaste(macro, result);
}
else {
} else {
if (tracker.isRequestedStep()) {
TokenList replacement= new TokenList();
objStyleTokenPaste(macro, replacement);
tracker.storeObjectStyleMacroReplacement(macro, lastConsumed, replacement, result);
}
else {
} else {
objStyleTokenPaste(macro, result);
}
tracker.endObjectStyleMacro();
@ -349,21 +345,17 @@ public class MacroExpander {
PreprocessorMacro macro= fDictionary.get(image);
if (protect || (tracker != null && tracker.isDone())) {
result.append(t);
}
else if (protectDefinedConstructs && Arrays.equals(image, Keywords.cDEFINED)) {
} else if (protectDefinedConstructs && Arrays.equals(image, Keywords.cDEFINED)) {
t.setType(CPreprocessor.tDEFINED);
result.append(t);
protect= true;
}
// tricky: don't mark function-style macros if you don't find the left parenthesis
else if (macro == null || (macro.isFunctionStyle() && !input.findLParenthesis())) {
} else if (macro == null || (macro.isFunctionStyle() && !input.findLParenthesis())) {
// Tricky: Don't mark function-style macros if you don't find the left parenthesis
result.append(t);
}
else if (forbidden.containsKey(macro)) {
} else if (forbidden.containsKey(macro)) {
t.setType(CPreprocessor.tEXPANDED_IDENTIFIER); // prevent any further expansion
result.append(t);
}
else {
} else {
if (fLocationMap != null) {
ImageLocationInfo info= null;
if (fLexOptions.fCreateImageLocations) {
@ -403,8 +395,7 @@ public class MacroExpander {
final Object s= t.fSource;
if (s instanceof ObjectStyleMacro) {
return new MacroImageLocationInfo((ObjectStyleMacro) s, t.getOffset(), t.getEndOffset());
}
else if (s instanceof CPreprocessor) {
} else if (s instanceof CPreprocessor) {
int sequenceNumber= fLocationMap.getSequenceNumberForOffset(t.getOffset());
int sequenceEndNumber= fLocationMap.getSequenceNumberForOffset(t.getEndOffset());
return new ParameterImageLocationInfo(sequenceNumber, sequenceEndNumber);
@ -514,8 +505,7 @@ public class MacroExpander {
spaceMarkers.clear();
idx++;
continue loop;
}
else if (!hasVarargs) {
} else if (!hasVarargs) {
tooManyArgs= true;
break loop;
}
@ -525,8 +515,7 @@ public class MacroExpander {
case CPreprocessor.tSCOPE_MARKER:
if (argCount == 0) {
((ExpansionBoundary) t).execute(forbidden);
}
else {
} else {
result[idx].append(t);
}
continue loop;
@ -556,9 +545,9 @@ public class MacroExpander {
throw new AbortMacroExpansionException();
}
if (tooManyArgs)
if (tooManyArgs) {
handleProblem(IProblem.PREPROCESSOR_MACRO_USAGE_ERROR, macro.getNameCharArray());
else if (idx+1 < requiredArgs) {
} else if (idx+1 < requiredArgs) {
handleProblem(IProblem.PREPROCESSOR_MACRO_USAGE_ERROR, macro.getNameCharArray());
}
return lastToken;
@ -589,8 +578,7 @@ public class MacroExpander {
result.appendAllButLast(arg);
addSpacemarker(result.last(), pasteArg1, result); // start token paste
}
}
else {
} else {
TokenList arg= clone(expandedArgs[idx]);
result.appendAll(arg);
addSpacemarker(t, n, result); // end argument replacement
@ -618,8 +606,7 @@ public class MacroExpander {
Token generated= new TokenWithImage(IToken.tSTRING, null, 0, 0, image);
if (isKind(n, IToken.tPOUNDPOUND)) { // start token paste, same as start stringify
pasteArg1= generated;
}
else {
} else {
result.append(generated);
addSpacemarker(t, n, result); // end stringify
}
@ -654,13 +641,23 @@ public class MacroExpander {
final boolean pasteNext= isKind(n, IToken.tPOUNDPOUND);
generated= tokenpaste(pasteArg1, pasteArg2, macro);
if (generated == null) {
// Cannot perform token paste.
// Use the two tokens instead, see bug 354553.
generated= pasteArg1;
if (rest == null)
rest= new TokenList();
rest.prepend(pasteArg2);
spaceDef0= generated;
spaceDef1= pasteArg2;
}
pasteArg1= null;
if (generated != null) {
if (pasteNext && rest == null) {
pasteArg1= generated; // no need to mark spaces, done ahead
}
else {
} else {
result.append(generated);
addSpacemarker(spaceDef0, spaceDef1, result); // end token paste
}
@ -672,8 +669,7 @@ public class MacroExpander {
result.appendAllButLast(rest);
addSpacemarker(result.last(), pasteArg1, result); // start token paste
}
}
else {
} else {
result.appendAll(rest);
if (idx >= 0) {
addSpacemarker(t, n, result); // end argument replacement
@ -697,8 +693,7 @@ public class MacroExpander {
if (arg.isEmpty()) {
addSpacemarker(l, t, result);
addSpacemarker(nn, nnn, result);
}
else {
} else {
result.append(t);
addSpacemarker(t, n, result);
result.appendAll(arg);
@ -712,8 +707,7 @@ public class MacroExpander {
addSpacemarker(l, t, result);
pasteArg1= t;
}
else {
} else {
result.append(t);
}
break;
@ -722,8 +716,7 @@ public class MacroExpander {
if (isKind(n, IToken.tPOUNDPOUND)) {
addSpacemarker(l, t, result); // start token paste
pasteArg1= t;
}
else {
} else {
result.append(t);
}
break;
@ -767,8 +760,7 @@ public class MacroExpander {
if (isKind(l, IToken.tCOMMA) && macro.hasVarArgs() != FunctionStyleMacro.NO_VAARGS &&
idx == macro.getParameterPlaceholderList().length-1 && !isKind(n.getNext(), IToken.tPOUNDPOUND)) {
result.set(2*idx+1);
}
else {
} else {
result.set(2*idx);
}
t= n; n= (Token) n.getNext();
@ -801,8 +793,7 @@ public class MacroExpander {
if (t != null) {
if (isKind(n, IToken.tPOUNDPOUND)) {
pasteArg1= t;
}
else {
} else {
result.append(t);
addSpacemarker(pasteArg2, n, result); // end token paste
}
@ -814,8 +805,7 @@ public class MacroExpander {
if (isKind(n, IToken.tPOUNDPOUND)) {
addSpacemarker(l, t, result); // start token paste
pasteArg1= t;
}
else {
} else {
result.append(t);
}
break;

View file

@ -57,6 +57,18 @@ class TokenList {
}
}
}
public final void prepend(Token t) {
final Token first= t;
if (first != null) {
final Token last= t;
last.setNext(fFirst);
fFirst= first;
if (fLast == null) {
fLast= last;
}
}
}
public final void prepend(TokenList prepend) {
final Token first= prepend.fFirst;

View file

@ -6,9 +6,9 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Markus Schorn - initial API and implementation
* IBM Corporation
* Sergey Prigogin (Google)
* Markus Schorn - initial API and implementation
* IBM Corporation
* Sergey Prigogin (Google)
*******************************************************************************/
package org.eclipse.cdt.internal.core.pdom;
@ -80,6 +80,7 @@ abstract public class PDOMWriter {
ArrayList<IASTPreprocessorStatement> fMacros= new ArrayList<IASTPreprocessorStatement>();
ArrayList<IASTPreprocessorIncludeStatement> fIncludes= new ArrayList<IASTPreprocessorIncludeStatement>();
}
private boolean fShowProblems;
protected boolean fShowInclusionProblems;
private boolean fShowScannerProblems;

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.pdom.dom;
@ -54,6 +54,7 @@ public class PDOMASTAdapter {
public int getEndingLineNumber() {
return loc.getStartingLineNumber();
}
public String getFileName() {
return loc.getFileName();
}
@ -73,7 +74,6 @@ public class PDOMASTAdapter {
public int getNodeOffset() {
return loc.getNodeOffset();
}
};
}

View file

@ -6,9 +6,9 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX - Initial API and implementation
* Markus Schorn (Wind River Systems)
* Andrew Ferguson (Symbian)
* QNX - Initial API and implementation
* Markus Schorn (Wind River Systems)
* Andrew Ferguson (Symbian)
*******************************************************************************/
package org.eclipse.cdt.internal.core.pdom.dom.c;
@ -91,7 +91,7 @@ public class PDOMCStructure extends PDOMBinding implements ICompositeType, ICCom
@Override
public void accept(IPDOMVisitor visitor) throws CoreException {
super.accept(visitor);
new PDOMNodeLinkedList(getLinkage(), record+MEMBERLIST).accept(visitor);
new PDOMNodeLinkedList(getLinkage(), record + MEMBERLIST).accept(visitor);
}
@Override
@ -197,8 +197,7 @@ public class PDOMCStructure extends PDOMBinding implements ICompositeType, ICCom
} catch (CoreException e) {
if (e.getStatus().equals(Status.OK_STATUS)) {
result= visitor.getField();
}
else {
} else {
CCorePlugin.log(e);
return null;
}

View file

@ -71,21 +71,17 @@ public class CModelUtil {
*/
public static ICContainer getSourceFolder(ICElement element) {
ICContainer folder = null;
if (element != null) {
boolean foundSourceRoot = false;
if (element != null) {
ICElement curr = element;
while (curr != null && !foundSourceRoot) {
if (curr instanceof ICContainer && folder == null) {
folder = (ICContainer)curr;
}
foundSourceRoot = (curr instanceof ISourceRoot);
while (curr != null && !(curr instanceof ISourceRoot)) {
curr = curr.getParent();
}
folder = (ISourceRoot)curr;
if (folder == null) {
ICProject cproject = element.getCProject();
folder = cproject.findSourceRoot(cproject.getProject());
}
}
}
return folder;
}

View file

@ -7,7 +7,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
* Institute for Software - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.extractfunction;
@ -56,59 +56,54 @@ import org.eclipse.cdt.internal.ui.refactoring.NodeContainer.NameInformation;
* Handles the extraction of expression nodes, like return type determination.
*
* @author Mirko Stocker
*
*/
public class ExtractExpression extends ExtractedFunctionConstructionHelper {
final static char[] ZERO= {'0'};
final static char[] ZERO= { '0' };
@Override
public void constructMethodBody(IASTCompoundStatement compound,
List<IASTNode> list, ASTRewrite rewrite, TextEditGroup group) {
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);
}
private IASTExpression getExpression(List<IASTNode> list) {
if(list.size()> 1 ) {
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;
}else {
} else {
return (IASTExpression) list.get(0).copy(CopyStyle.withLocations);
}
}
@Override
public IASTDeclSpecifier determineReturnType(IASTNode extractedNode, NameInformation _) {
List<ITypedef> typdefs = getTypdefs(extractedNode);
List<ITypedef> typedefs = getTypedefs(extractedNode);
if (extractedNode instanceof IASTExpression) {
IASTExpression exp = (IASTExpression) extractedNode;
INodeFactory factory = extractedNode.getTranslationUnit().getASTNodeFactory();
DeclarationGenerator generator = DeclarationGenerator.create(factory);
IType expressionType = exp.getExpressionType();
for (ITypedef typedef : typdefs) {
for (ITypedef typedef : typedefs) {
if (typedef.getType().isSameType(expressionType)) {
return generator.createDeclSpecFromType(typedef);
}
}
return generator.createDeclSpecFromType(expressionType);
} else {// Fallback
} else { // Fallback
return createSimpleDeclSpecifier(Kind.eVoid);
}
}
private List<ITypedef> getTypdefs(IASTNode extractedNode) {
private List<ITypedef> getTypedefs(IASTNode extractedNode) {
final ArrayList<ITypedef> typeDefs = new ArrayList<ITypedef>();
extractedNode.accept(new ASTVisitor() {
{
@ -148,10 +143,10 @@ public class ExtractExpression extends ExtractedFunctionConstructionHelper {
IASTExpression functionNameExpression = callExpression.getFunctionNameExpression();
IASTName functionName = null;
if(functionNameExpression instanceof CPPASTIdExpression) {
if (functionNameExpression instanceof CPPASTIdExpression) {
CPPASTIdExpression idExpression = (CPPASTIdExpression) functionNameExpression;
functionName = idExpression.getName();
} else if(functionNameExpression instanceof CPPASTFieldReference) {
} else if (functionNameExpression instanceof CPPASTFieldReference) {
CPPASTFieldReference fieldReference = (CPPASTFieldReference) functionNameExpression;
functionName = fieldReference.getFieldName();
}
@ -160,28 +155,29 @@ public class ExtractExpression extends ExtractedFunctionConstructionHelper {
@Override
protected boolean isReturnTypeAPointer(IASTNode node) {
if(node instanceof ICPPASTNewExpression) {
if (node instanceof ICPPASTNewExpression) {
return true;
} else if(!(node instanceof IASTFunctionCallExpression)) {
} else if (!(node instanceof IASTFunctionCallExpression)) {
return false;
}
IASTName functionName = findCalledFunctionName((IASTFunctionCallExpression) node);
if(functionName != null) {
if (functionName != null) {
IBinding binding = functionName.resolveBinding();
if (binding instanceof CPPFunction) {
CPPFunction function = (CPPFunction) binding;
if(function.getDefinition() != null) {
if (function.getDefinition() != null) {
IASTNode parent = function.getDefinition().getParent();
if(parent instanceof CPPASTFunctionDefinition) {
if (parent instanceof CPPASTFunctionDefinition) {
CPPASTFunctionDefinition definition = (CPPASTFunctionDefinition) parent;
return definition.getDeclarator().getPointerOperators().length > 0;
}
} else if(hasDeclaration(function)) {
} else if (hasDeclaration(function)) {
IASTNode parent = function.getDeclarations()[0].getParent();
if (parent instanceof CPPASTSimpleDeclaration) {
CPPASTSimpleDeclaration declaration = (CPPASTSimpleDeclaration) parent;
return declaration.getDeclarators().length > 0 && declaration.getDeclarators()[0].getPointerOperators().length > 0;
return declaration.getDeclarators().length > 0 &&
declaration.getDeclarators()[0].getPointerOperators().length > 0;
}
}
}

View file

@ -7,7 +7,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
* Institute for Software - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.extractfunction;
@ -30,14 +30,13 @@ import org.eclipse.cdt.internal.ui.refactoring.NodeContainer;
import org.eclipse.cdt.internal.ui.refactoring.NodeContainer.NameInformation;
final class SimilarFinderVisitor extends ASTVisitor {
private final ExtractFunctionRefactoring refactoring;
private final ExtractFunctionRefactoring refactoring;
private final Vector<IASTNode> trail;
private final IASTName name;
private final List<IASTNode> stmts;
private int i = 0;
private NodeContainer similarContainer;
private final Vector<IASTNode> trail;
private final IASTName name;
private final List<IASTNode> stmts;
private int i;
private NodeContainer similarContainer;
private final List<IASTStatement> stmtToReplace = new ArrayList<IASTStatement>();
private final ModificationCollector collector;
@ -51,95 +50,88 @@ final class SimilarFinderVisitor extends ASTVisitor {
this.stmts = stmts;
this.collector = collector;
this.similarContainer = new NodeContainer();
shouldVisitStatements = true;
}
{
shouldVisitStatements = true;
}
@Override
public int visit(IASTStatement stmt) {
boolean isAllreadyInMainRefactoring = isInSelection(stmt);
@Override
public int visit(IASTStatement stmt) {
boolean isAllreadyInMainRefactoring = isInSelection(stmt);
if( (!isAllreadyInMainRefactoring)
&& this.refactoring.isStatementInTrail(stmt, trail, this.refactoring.getIndex())){
stmtToReplace.add(stmt);
similarContainer.add(stmt);
++i;
if(i==stmts.size()){
//found similar code
boolean similarOnReturnWays = true;
for (NameInformation nameInfo : similarContainer.getAllAfterUsedNames()) {
if(this.refactoring.names.containsKey(nameInfo.getDeclaration().getRawSignature())){
Integer nameOrderNumber = this.refactoring.names.get(nameInfo.getDeclaration().getRawSignature());
if(this.refactoring.nameTrail.containsValue(nameOrderNumber)){
String orgName = null;
boolean found = false;
for (Entry<String, Integer> entry : this.refactoring.nameTrail.entrySet()) {
if(entry.getValue().equals(nameOrderNumber)){
orgName = entry.getKey();
if ((!isAllreadyInMainRefactoring)
&& this.refactoring.isStatementInTrail(stmt, trail, this.refactoring.getIndex())) {
stmtToReplace.add(stmt);
similarContainer.add(stmt);
++i;
if (i == stmts.size()) {
// Found similar code
boolean similarOnReturnWays = true;
for (NameInformation nameInfo : similarContainer.getAllAfterUsedNames()) {
if (this.refactoring.names.containsKey(nameInfo.getDeclaration().getRawSignature())) {
Integer nameOrderNumber = this.refactoring.names.get(nameInfo.getDeclaration().getRawSignature());
if (this.refactoring.nameTrail.containsValue(nameOrderNumber)) {
String orgName = null;
boolean found = false;
for (Entry<String, Integer> entry : this.refactoring.nameTrail.entrySet()) {
if (entry.getValue().equals(nameOrderNumber)) {
orgName = entry.getKey();
}
}
if (orgName != null) {
for (NameInformation orgNameInfo : this.refactoring.container.getAllAfterUsedNamesChoosenByUser()) {
if (orgName.equals(orgNameInfo.getDeclaration().getRawSignature())) {
found = true;
}
}
if(orgName != null){
for (NameInformation orgNameInfo : this.refactoring.container.getAllAfterUsedNamesChoosenByUser()) {
if( orgName.equals(orgNameInfo.getDeclaration().getRawSignature()) ){
found = true;
}
}
}
if(!found){
similarOnReturnWays = false;
}
}
if (!found) {
similarOnReturnWays = false;
}
}
}
if(similarOnReturnWays){
IASTNode call = refactoring.getMethodCall(name,
this.refactoring.nameTrail, this.refactoring.names,
this.refactoring.container, similarContainer);
ASTRewrite rewrite = collector.rewriterForTranslationUnit(stmtToReplace.get(0)
.getTranslationUnit());
TextEditGroup editGroup = new TextEditGroup(Messages.SimilarFinderVisitor_replaceDuplicateCode);
rewrite.replace(stmtToReplace.get(0), call, editGroup);
if (stmtToReplace.size() > 1) {
for (int i = 1; i < stmtToReplace.size(); ++i) {
rewrite.remove(stmtToReplace.get(i), editGroup);
}
}
}
clear();
}
return PROCESS_SKIP;
} else {
if (similarOnReturnWays) {
IASTNode call = refactoring.getMethodCall(name,
this.refactoring.nameTrail, this.refactoring.names,
this.refactoring.container, similarContainer);
ASTRewrite rewrite =
collector.rewriterForTranslationUnit(stmtToReplace.get(0).getTranslationUnit());
TextEditGroup editGroup = new TextEditGroup(Messages.SimilarFinderVisitor_replaceDuplicateCode);
rewrite.replace(stmtToReplace.get(0), call, editGroup);
if (stmtToReplace.size() > 1) {
for (int i = 1; i < stmtToReplace.size(); ++i) {
rewrite.remove(stmtToReplace.get(i), editGroup);
}
}
}
clear();
return super.visit(stmt);
}
return PROCESS_SKIP;
} else {
clear();
return super.visit(stmt);
}
}
private boolean isInSelection(IASTStatement stmt) {
List<IASTNode>nodes = this.refactoring.container.getNodesToWrite();
for (IASTNode node : nodes) {
if(node.equals(stmt)) {
return true;
}
private boolean isInSelection(IASTStatement stmt) {
List<IASTNode>nodes = this.refactoring.container.getNodesToWrite();
for (IASTNode node : nodes) {
if (node.equals(stmt)) {
return true;
}
return false;
}
return false;
}
private void clear() {
i = 0;
this.refactoring.names.clear();
similarContainer = new NodeContainer();
this.refactoring.namesCounter.setObject(ExtractFunctionRefactoring.NULL_INTEGER);
this.refactoring.trailPos.setObject(ExtractFunctionRefactoring.NULL_INTEGER);
private void clear() {
i = 0;
this.refactoring.names.clear();
similarContainer = new NodeContainer();
this.refactoring.namesCounter.setObject(ExtractFunctionRefactoring.NULL_INTEGER);
this.refactoring.trailPos.setObject(ExtractFunctionRefactoring.NULL_INTEGER);
stmtToReplace.clear();
}
}
}
}

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2000, 2008 IBM Corporation and others.
* Copyright (c) 2000, 2011 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
@ -71,13 +71,11 @@ public abstract class AbstractWizardDropDownAction extends Action implements IMe
public Menu getMenu(Control parent) {
synchronized(fLock) {
if (fMenu == null) {
fMenu= new Menu(parent);
IAction[] actions= getActions();
for (int i= 0; i < actions.length; i++) {
ActionContributionItem item= new ActionContributionItem(actions[i]);
item.fill(fMenu, -1);
}
fMenu= new Menu(parent);
IAction[] actions= getActions();
for (int i= 0; i < actions.length; i++) {
ActionContributionItem item= new ActionContributionItem(actions[i]);
item.fill(fMenu, -1);
}
return fMenu;
}
@ -110,13 +108,12 @@ public abstract class AbstractWizardDropDownAction extends Action implements IMe
private IAction[] getActions() {
synchronized(fLock) {
if (fActions == null) {
fActions = getWizardActions();
if (fActions == null)
fActions = NO_ACTIONS;
//TODO provide a way to sort the actions
}
fActions = getWizardActions();
if (fActions == null)
fActions = NO_ACTIONS;
//TODO provide a way to sort the actions
return fActions;
}
}