1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-08-04 23:05:47 +02:00

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

This commit is contained in:
Andrew Gvozdev 2012-01-11 17:18:53 -05:00
commit 9d04a19044
105 changed files with 765 additions and 696 deletions

View file

@ -53,7 +53,7 @@ public class CaseBreakQuickFixBreak extends AbstractAstRewriteQuickFix {
IASTNode containedNode = nodeSelector.findFirstContainedNode(lineInformation.getOffset(), lineInformation.getLength()); IASTNode containedNode = nodeSelector.findFirstContainedNode(lineInformation.getOffset(), lineInformation.getLength());
IASTNode beforeBreakNode = null; IASTNode beforeBreakNode = null;
if (containedNode != null) if (containedNode != null)
beforeBreakNode = CxxAstUtils.getInstance().getEnclosingStatement(containedNode); beforeBreakNode = CxxAstUtils.getEnclosingStatement(containedNode);
else else
beforeBreakNode = nodeSelector.findEnclosingNode(lineInformation.getOffset(), lineInformation.getLength()); beforeBreakNode = nodeSelector.findEnclosingNode(lineInformation.getOffset(), lineInformation.getLength());
if (beforeBreakNode instanceof IASTCompoundStatement) { if (beforeBreakNode instanceof IASTCompoundStatement) {

View file

@ -1,3 +1,13 @@
/*******************************************************************************
* Copyright (c) 2011 Alena Laskavaia 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:
* Alena Laskavaia - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.codan.internal.checkers.ui.quickfix; package org.eclipse.cdt.codan.internal.checkers.ui.quickfix;
import org.eclipse.cdt.codan.core.model.IProblem; import org.eclipse.cdt.codan.core.model.IProblem;

View file

@ -17,7 +17,7 @@ import org.eclipse.core.resources.IMarker;
import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocument;
/** /**
* quick fix for catch by value * Quick fix for catch by value
*/ */
public class CatchByConstReferenceQuickFix extends AbstractCodanCMarkerResolution { public class CatchByConstReferenceQuickFix extends AbstractCodanCMarkerResolution {
@Override @Override

View file

@ -18,7 +18,7 @@ import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocument;
/** /**
* quick fix for catch by value * Quick fix for catch by value
*/ */
public class CatchByReferenceQuickFix extends AbstractCodanCMarkerResolution { public class CatchByReferenceQuickFix extends AbstractCodanCMarkerResolution {
@Override @Override

View file

@ -40,19 +40,18 @@ public class QuickFixCreateField extends AbstractAstRewriteQuickFix {
@Override @Override
public void modifyAST(IIndex index, IMarker marker) { public void modifyAST(IIndex index, IMarker marker) {
CxxAstUtils utils = CxxAstUtils.getInstance();
try { try {
IASTTranslationUnit ast = getTranslationUnitViaEditor(marker).getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS); IASTTranslationUnit ast = getTranslationUnitViaEditor(marker).getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS);
IASTName astName = getASTNameFromMarker(marker, ast); IASTName astName = getASTNameFromMarker(marker, ast);
if (astName == null) { if (astName == null) {
return; return;
} }
IASTDeclaration declaration = utils.createDeclaration(astName, ast.getASTNodeFactory(), index); IASTDeclaration declaration = CxxAstUtils.createDeclaration(astName, ast.getASTNodeFactory(), index);
IASTCompositeTypeSpecifier targetCompositeType = utils.getEnclosingCompositeTypeSpecifier(astName); IASTCompositeTypeSpecifier targetCompositeType = CxxAstUtils.getEnclosingCompositeTypeSpecifier(astName);
if (targetCompositeType == null) { if (targetCompositeType == null) {
// We're not in an inline method; // We're not in an inline method;
// check if we're in a method at all // check if we're in a method at all
targetCompositeType = utils.getCompositeTypeFromFunction(utils.getEnclosingFunction(astName), index); targetCompositeType = CxxAstUtils.getCompositeTypeFromFunction(CxxAstUtils.getEnclosingFunction(astName), index);
if (targetCompositeType == null) { if (targetCompositeType == null) {
return; return;
} }

View file

@ -33,15 +33,8 @@ public class QuickFixCreateLocalVariable extends AbstractAstRewriteQuickFix {
return Messages.QuickFixCreateLocalVariable_0; return Messages.QuickFixCreateLocalVariable_0;
} }
/**
*
* @param ast
* @param astName
* @param r
*/
@Override @Override
public void modifyAST(IIndex index, IMarker marker) { public void modifyAST(IIndex index, IMarker marker) {
CxxAstUtils utils = CxxAstUtils.getInstance();
IASTTranslationUnit ast; IASTTranslationUnit ast;
try { try {
ITranslationUnit tu = getTranslationUnitViaEditor(marker); ITranslationUnit tu = getTranslationUnitViaEditor(marker);
@ -61,9 +54,9 @@ public class QuickFixCreateLocalVariable extends AbstractAstRewriteQuickFix {
} }
ASTRewrite r = ASTRewrite.create(ast); ASTRewrite r = ASTRewrite.create(ast);
INodeFactory factory = ast.getASTNodeFactory(); INodeFactory factory = ast.getASTNodeFactory();
IASTDeclaration declaration = utils.createDeclaration(astName, factory, index); IASTDeclaration declaration = CxxAstUtils.createDeclaration(astName, factory, index);
IASTDeclarationStatement newStatement = factory.newDeclarationStatement(declaration); IASTDeclarationStatement newStatement = factory.newDeclarationStatement(declaration);
IASTNode targetStatement = utils.getEnclosingStatement(astName); IASTNode targetStatement = CxxAstUtils.getEnclosingStatement(astName);
if (targetStatement == null) { if (targetStatement == null) {
return; return;
} }

View file

@ -45,7 +45,6 @@ public class QuickFixCreateParameter extends AbstractAstRewriteQuickFix {
@Override @Override
public void modifyAST(IIndex index, IMarker marker) { public void modifyAST(IIndex index, IMarker marker) {
CxxAstUtils utils = CxxAstUtils.getInstance();
CompositeChange c = new CompositeChange(Messages.QuickFixCreateParameter_0); CompositeChange c = new CompositeChange(Messages.QuickFixCreateParameter_0);
try { try {
ITranslationUnit baseTU = getTranslationUnitViaEditor(marker); ITranslationUnit baseTU = getTranslationUnitViaEditor(marker);
@ -54,11 +53,11 @@ public class QuickFixCreateParameter extends AbstractAstRewriteQuickFix {
if (astName == null) { if (astName == null) {
return; return;
} }
IASTDeclaration declaration = CxxAstUtils.getInstance().createDeclaration(astName, baseAST.getASTNodeFactory(), index); IASTDeclaration declaration = CxxAstUtils.createDeclaration(astName, baseAST.getASTNodeFactory(), index);
// We'll need a FunctionParameterDeclaration later // We'll need a FunctionParameterDeclaration later
final IASTDeclSpecifier finalDeclSpec = (IASTDeclSpecifier) declaration.getChildren()[0]; final IASTDeclSpecifier finalDeclSpec = (IASTDeclSpecifier) declaration.getChildren()[0];
final IASTDeclarator finalDeclarator = (IASTDeclarator) declaration.getChildren()[1]; final IASTDeclarator finalDeclarator = (IASTDeclarator) declaration.getChildren()[1];
IASTFunctionDefinition function = utils.getEnclosingFunction(astName); IASTFunctionDefinition function = CxxAstUtils.getEnclosingFunction(astName);
if (function == null) { if (function == null) {
return; return;
} }
@ -74,7 +73,7 @@ public class QuickFixCreateParameter extends AbstractAstRewriteQuickFix {
HashMap<ITranslationUnit, IASTTranslationUnit> cachedASTs = new HashMap<ITranslationUnit, IASTTranslationUnit>(); HashMap<ITranslationUnit, IASTTranslationUnit> cachedASTs = new HashMap<ITranslationUnit, IASTTranslationUnit>();
HashMap<ITranslationUnit, ASTRewrite> cachedRewrites = new HashMap<ITranslationUnit, ASTRewrite>(); HashMap<ITranslationUnit, ASTRewrite> cachedRewrites = new HashMap<ITranslationUnit, ASTRewrite>();
for (IIndexName iname : declarations) { for (IIndexName iname : declarations) {
ITranslationUnit declTU = utils.getTranslationUnitFromIndexName(iname); ITranslationUnit declTU = CxxAstUtils.getTranslationUnitFromIndexName(iname);
ASTRewrite rewrite; ASTRewrite rewrite;
IASTTranslationUnit declAST; IASTTranslationUnit declAST;
if (!cachedASTs.containsKey(declTU)) { if (!cachedASTs.containsKey(declTU)) {

View file

@ -51,7 +51,7 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.ClassTypeHelper;
*/ */
public class AbstractClassInstantiationChecker extends AbstractIndexAstChecker { public class AbstractClassInstantiationChecker extends AbstractIndexAstChecker {
public static final String ER_ID = "org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation"; //$NON-NLS-1$ public static final String ER_ID = "org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation"; //$NON-NLS-1$
private HashMap<ICPPClassType, ICPPMethod[]> pureVirtualMethodsCache = new HashMap<ICPPClassType, ICPPMethod[]>(); private final HashMap<ICPPClassType, ICPPMethod[]> pureVirtualMethodsCache = new HashMap<ICPPClassType, ICPPMethod[]>();
@Override @Override
public void initPreferences(IProblemWorkingCopy problem) { public void initPreferences(IProblemWorkingCopy problem) {
@ -189,7 +189,7 @@ public class AbstractClassInstantiationChecker extends AbstractIndexAstChecker {
* If it is, reports violations on each pure virtual method * If it is, reports violations on each pure virtual method
*/ */
private void reportProblemsIfAbstract(IType typeToCheck, IASTNode problemNode ) { private void reportProblemsIfAbstract(IType typeToCheck, IASTNode problemNode ) {
IType unwindedType = CxxAstUtils.getInstance().unwindTypedef(typeToCheck); IType unwindedType = CxxAstUtils.unwindTypedef(typeToCheck);
if (!(unwindedType instanceof ICPPClassType) || unwindedType instanceof IProblemBinding) { if (!(unwindedType instanceof ICPPClassType) || unwindedType instanceof IProblemBinding) {
return; return;
} }

View file

@ -71,10 +71,9 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke
* - "exit" * - "exit"
*/ */
protected boolean isBreakOrExitStatement(IASTStatement statement) { protected boolean isBreakOrExitStatement(IASTStatement statement) {
CxxAstUtils utils = CxxAstUtils.getInstance();
return (statement instanceof IASTBreakStatement) || statement instanceof IASTReturnStatement return (statement instanceof IASTBreakStatement) || statement instanceof IASTReturnStatement
|| statement instanceof IASTContinueStatement || statement instanceof IASTGotoStatement || statement instanceof IASTContinueStatement || statement instanceof IASTGotoStatement
|| utils.isThrowStatement(statement) || utils.isExitStatement(statement); || CxxAstUtils.isThrowStatement(statement) || CxxAstUtils.isExitStatement(statement);
} }
@Override @Override

View file

@ -72,7 +72,7 @@ public class CatchByReference extends AbstractIndexAstChecker {
if (spec instanceof IASTNamedTypeSpecifier) { if (spec instanceof IASTNamedTypeSpecifier) {
IASTName tname = ((IASTNamedTypeSpecifier) spec).getName(); IASTName tname = ((IASTNamedTypeSpecifier) spec).getName();
IType typeName = (IType) tname.resolveBinding(); IType typeName = (IType) tname.resolveBinding();
typeName = CxxAstUtils.getInstance().unwindTypedef(typeName); typeName = CxxAstUtils.unwindTypedef(typeName);
if (typeName instanceof IBasicType || typeName instanceof IPointerType || typeName == null) if (typeName instanceof IBasicType || typeName instanceof IPointerType || typeName == null)
continue; continue;
if (typeName instanceof IProblemBinding && !shouldReportForUnknownType()) if (typeName instanceof IProblemBinding && !shouldReportForUnknownType())

View file

@ -179,11 +179,10 @@ public class ProblemBindingChecker extends AbstractIndexAstChecker {
} }
private boolean isInClassContext(IASTName name) { private boolean isInClassContext(IASTName name) {
CxxAstUtils utils = CxxAstUtils.getInstance(); if (CxxAstUtils.getEnclosingCompositeTypeSpecifier(name) != null) {
if (utils.getEnclosingCompositeTypeSpecifier(name) != null) {
return true; return true;
} }
IASTFunctionDefinition function = utils.getEnclosingFunction(name); IASTFunctionDefinition function = CxxAstUtils.getEnclosingFunction(name);
if (function == null) { if (function == null) {
return false; return false;
} }
@ -194,8 +193,7 @@ public class ProblemBindingChecker extends AbstractIndexAstChecker {
} }
private boolean isInFunctionContext(IASTName name) { private boolean isInFunctionContext(IASTName name) {
CxxAstUtils utils = CxxAstUtils.getInstance(); IASTFunctionDefinition function = CxxAstUtils.getEnclosingFunction(name);
IASTFunctionDefinition function = utils.getEnclosingFunction(name);
return (function != null); return (function != null);
} }

View file

@ -204,13 +204,14 @@ public class ReturnChecker extends AbstractAstFunctionChecker {
* @return * @return
*/ */
private boolean isCompoundStatement(IASTStatement last) { private boolean isCompoundStatement(IASTStatement last) {
return last instanceof IASTIfStatement || last instanceof IASTWhileStatement || last instanceof IASTDoStatement return last instanceof IASTIfStatement || last instanceof IASTWhileStatement ||
|| last instanceof IASTForStatement || last instanceof IASTSwitchStatement || last instanceof IASTCompoundStatement; last instanceof IASTDoStatement || last instanceof IASTForStatement ||
last instanceof IASTSwitchStatement || last instanceof IASTCompoundStatement;
} }
protected boolean isFuncExitStatement(IASTStatement statement) { protected boolean isFuncExitStatement(IASTStatement statement) {
CxxAstUtils utils = CxxAstUtils.getInstance(); return statement instanceof IASTReturnStatement || CxxAstUtils.isThrowStatement(statement) ||
return statement instanceof IASTReturnStatement || utils.isThrowStatement(statement) || utils.isExitStatement(statement); CxxAstUtils.isExitStatement(statement);
} }
/** /**
@ -300,7 +301,7 @@ public class ReturnChecker extends AbstractAstFunctionChecker {
type = ((IASTSimpleDeclSpecifier) declSpecifier).getType(); type = ((IASTSimpleDeclSpecifier) declSpecifier).getType();
} else if (declSpecifier instanceof IASTNamedTypeSpecifier) { } else if (declSpecifier instanceof IASTNamedTypeSpecifier) {
IBinding binding = ((IASTNamedTypeSpecifier) declSpecifier).getName().resolveBinding(); IBinding binding = ((IASTNamedTypeSpecifier) declSpecifier).getName().resolveBinding();
IType utype = CxxAstUtils.getInstance().unwindTypedef((IType) binding); IType utype = CxxAstUtils.unwindTypedef((IType) binding);
if (isVoid(utype)) if (isVoid(utype))
return IASTSimpleDeclSpecifier.t_void; return IASTSimpleDeclSpecifier.t_void;
} }

View file

@ -75,7 +75,7 @@ public final class CxxAstUtils {
} }
} }
private class FunctionNameFinderVisitor extends NameFinderVisitor { private static class FunctionNameFinderVisitor extends NameFinderVisitor {
{ {
shouldVisitExpressions = true; shouldVisitExpressions = true;
} }
@ -90,19 +90,11 @@ public final class CxxAstUtils {
} }
} }
private static CxxAstUtils instance; // Not instantiatable. All methods are static.
private CxxAstUtils() { private CxxAstUtils() {
// private constructor
} }
public synchronized static CxxAstUtils getInstance() { public static IType unwindTypedef(IType type) {
if (instance == null)
instance = new CxxAstUtils();
return instance;
}
public IType unwindTypedef(IType type) {
if (!(type instanceof IBinding)) if (!(type instanceof IBinding))
return type; return type;
IBinding typeName = (IBinding) type; IBinding typeName = (IBinding) type;
@ -129,21 +121,21 @@ public final class CxxAstUtils {
return macro != null; return macro != null;
} }
public IASTFunctionDefinition getEnclosingFunction(IASTNode node) { public static IASTFunctionDefinition getEnclosingFunction(IASTNode node) {
while (node != null && !(node instanceof IASTFunctionDefinition)) { while (node != null && !(node instanceof IASTFunctionDefinition)) {
node = node.getParent(); node = node.getParent();
} }
return (IASTFunctionDefinition) node; return (IASTFunctionDefinition) node;
} }
public IASTCompositeTypeSpecifier getEnclosingCompositeTypeSpecifier(IASTNode node) { public static IASTCompositeTypeSpecifier getEnclosingCompositeTypeSpecifier(IASTNode node) {
while (node != null && !(node instanceof IASTCompositeTypeSpecifier)) { while (node != null && !(node instanceof IASTCompositeTypeSpecifier)) {
node = node.getParent(); node = node.getParent();
} }
return (IASTCompositeTypeSpecifier) node; return (IASTCompositeTypeSpecifier) node;
} }
public IASTStatement getEnclosingStatement(IASTNode node) { public static IASTStatement getEnclosingStatement(IASTNode node) {
while (node != null && !(node instanceof IASTStatement)) { while (node != null && !(node instanceof IASTStatement)) {
node = node.getParent(); node = node.getParent();
} }
@ -158,7 +150,7 @@ public final class CxxAstUtils {
* @param index * @param index
* @return * @return
*/ */
public IASTDeclaration createDeclaration(IASTName astName, INodeFactory factory, IIndex index) { public static IASTDeclaration createDeclaration(IASTName astName, INodeFactory factory, IIndex index) {
// Depending on context, either a type or a declaration is easier to // Depending on context, either a type or a declaration is easier to
// infer // infer
IType inferredType = null; IType inferredType = null;
@ -193,7 +185,7 @@ public final class CxxAstUtils {
* *
* @return inferred type or null if couldn't infer * @return inferred type or null if couldn't infer
*/ */
private IType tryInferTypeFromBinaryExpr(IASTName astName) { private static IType tryInferTypeFromBinaryExpr(IASTName astName) {
if (astName.getParent() instanceof IASTIdExpression && astName.getParent().getParent() instanceof IASTBinaryExpression) { if (astName.getParent() instanceof IASTIdExpression && astName.getParent().getParent() instanceof IASTBinaryExpression) {
IASTNode binaryExpr = astName.getParent().getParent(); IASTNode binaryExpr = astName.getParent().getParent();
for (IASTNode node : binaryExpr.getChildren()) { for (IASTNode node : binaryExpr.getChildren()) {
@ -214,7 +206,7 @@ public final class CxxAstUtils {
* *
* @return a generated declaration or null if not suitable * @return a generated declaration or null if not suitable
*/ */
private IASTSimpleDeclaration tryInferTypeFromFunctionCall(IASTName astName, INodeFactory factory, IIndex index) { private static IASTSimpleDeclaration tryInferTypeFromFunctionCall(IASTName astName, INodeFactory factory, IIndex index) {
if (astName.getParent() instanceof IASTIdExpression && astName.getParent().getParent() instanceof IASTFunctionCallExpression if (astName.getParent() instanceof IASTIdExpression && astName.getParent().getParent() instanceof IASTFunctionCallExpression
&& astName.getParent().getPropertyInParent() == IASTFunctionCallExpression.ARGUMENT) { && astName.getParent().getPropertyInParent() == IASTFunctionCallExpression.ARGUMENT) {
IASTFunctionCallExpression call = (IASTFunctionCallExpression) astName.getParent().getParent(); IASTFunctionCallExpression call = (IASTFunctionCallExpression) astName.getParent().getParent();
@ -304,14 +296,14 @@ public final class CxxAstUtils {
return null; return null;
} }
private void setNameInNestedDeclarator(IASTDeclarator declarator, IASTName astName) { private static void setNameInNestedDeclarator(IASTDeclarator declarator, IASTName astName) {
while (declarator.getNestedDeclarator() != null) { while (declarator.getNestedDeclarator() != null) {
declarator = declarator.getNestedDeclarator(); declarator = declarator.getNestedDeclarator();
} }
declarator.setName(astName); declarator.setName(astName);
} }
public ITranslationUnit getTranslationUnitFromIndexName(IIndexName decl) throws CoreException { public static ITranslationUnit getTranslationUnitFromIndexName(IIndexName decl) throws CoreException {
Path path = new Path(decl.getFile().getLocation().getFullPath()); Path path = new Path(decl.getFile().getLocation().getFullPath());
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path); IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
ITranslationUnit tu = (ITranslationUnit) CoreModel.getDefault().create(file); ITranslationUnit tu = (ITranslationUnit) CoreModel.getDefault().create(file);
@ -328,7 +320,7 @@ public final class CxxAstUtils {
* the index to use for name lookup * the index to use for name lookup
* @return Either a type specifier or null * @return Either a type specifier or null
*/ */
public IASTCompositeTypeSpecifier getCompositeTypeFromFunction(final IASTFunctionDefinition function, final IIndex index) { public static IASTCompositeTypeSpecifier getCompositeTypeFromFunction(final IASTFunctionDefinition function, final IIndex index) {
// return value to be set via visitor // return value to be set via visitor
final IASTCompositeTypeSpecifier returnSpecifier[] = { null }; final IASTCompositeTypeSpecifier returnSpecifier[] = { null };
final HashMap<ITranslationUnit, IASTTranslationUnit> astCache = new HashMap<ITranslationUnit, IASTTranslationUnit>(); final HashMap<ITranslationUnit, IASTTranslationUnit> astCache = new HashMap<ITranslationUnit, IASTTranslationUnit>();
@ -389,7 +381,7 @@ public final class CxxAstUtils {
* @param body * @param body
* @return * @return
*/ */
public boolean isThrowStatement(IASTNode body) { public static boolean isThrowStatement(IASTNode body) {
if (!(body instanceof IASTExpressionStatement)) if (!(body instanceof IASTExpressionStatement))
return false; return false;
IASTExpression expression = ((IASTExpressionStatement) body).getExpression(); IASTExpression expression = ((IASTExpressionStatement) body).getExpression();
@ -398,7 +390,7 @@ public final class CxxAstUtils {
return ((IASTUnaryExpression) expression).getOperator() == IASTUnaryExpression.op_throw; return ((IASTUnaryExpression) expression).getOperator() == IASTUnaryExpression.op_throw;
} }
public boolean isExitStatement(IASTNode body) { public static boolean isExitStatement(IASTNode body) {
if (!(body instanceof IASTExpressionStatement)) if (!(body instanceof IASTExpressionStatement))
return false; return false;
IASTExpression expression = ((IASTExpressionStatement) body).getExpression(); IASTExpression expression = ((IASTExpressionStatement) body).getExpression();
@ -407,6 +399,4 @@ public final class CxxAstUtils {
IASTExpression functionNameExpression = ((IASTFunctionCallExpression) expression).getFunctionNameExpression(); IASTExpression functionNameExpression = ((IASTFunctionCallExpression) expression).getFunctionNameExpression();
return functionNameExpression.getRawSignature().equals("exit"); //$NON-NLS-1$ return functionNameExpression.getRawSignature().equals("exit"); //$NON-NLS-1$
} }
} }

View file

@ -31,13 +31,6 @@ import org.eclipse.cdt.core.dom.ast.c.ICBasicType;
* Test CxxAstUtils * Test CxxAstUtils
*/ */
public class CxxAstUtilsTest extends CodanFastCxxAstTestCase { public class CxxAstUtilsTest extends CodanFastCxxAstTestCase {
private CxxAstUtils instance;
@Override
protected void setUp() throws Exception {
instance = CxxAstUtils.getInstance();
}
@Override @Override
public IChecker getChecker() { public IChecker getChecker() {
return null; // not testing checker return null; // not testing checker
@ -65,7 +58,7 @@ public class CxxAstUtilsTest extends CodanFastCxxAstTestCase {
if (spec instanceof IASTNamedTypeSpecifier) { if (spec instanceof IASTNamedTypeSpecifier) {
IASTName tname = ((IASTNamedTypeSpecifier) spec).getName(); IASTName tname = ((IASTNamedTypeSpecifier) spec).getName();
IType typeName = (IType) tname.resolveBinding(); IType typeName = (IType) tname.resolveBinding();
result[0] = instance.unwindTypedef(typeName); result[0] = CxxAstUtils.unwindTypedef(typeName);
} }
} }
return PROCESS_CONTINUE; return PROCESS_CONTINUE;
@ -95,7 +88,7 @@ public class CxxAstUtilsTest extends CodanFastCxxAstTestCase {
@Override @Override
public int visit(IASTStatement stmt) { public int visit(IASTStatement stmt) {
if (stmt instanceof IASTExpressionStatement) { if (stmt instanceof IASTExpressionStatement) {
boolean check = instance.isInMacro(((IASTExpressionStatement) stmt).getExpression()); boolean check = CxxAstUtils.isInMacro(((IASTExpressionStatement) stmt).getExpression());
result[i] = check; result[i] = check;
i++; i++;
} }

View file

@ -5703,4 +5703,14 @@ public class AST2TemplateTests extends AST2BaseTest {
ICPPDeferredClassInstance shortHand= bh.assertNonProblem("derived:", -1); ICPPDeferredClassInstance shortHand= bh.assertNonProblem("derived:", -1);
assertTrue(shortHand.getClassTemplate() instanceof ICPPClassTemplatePartialSpecialization); assertTrue(shortHand.getClassTemplate() instanceof ICPPClassTemplatePartialSpecialization);
} }
// template <typename> class A {};
// template <typename T, typename=void> struct B {};
// template <typename T> struct B<A<T> > {
// typedef int type;
// };
// typedef B<A<int> >::type type; // ERROR HERE
public void testPartialClassTemplateSpecUsingDefaultArgument_367997() throws Exception {
parseAndCheckBindings();
}
} }

View file

@ -12,6 +12,8 @@
*******************************************************************************/ *******************************************************************************/
package org.eclipse.cdt.core.parser.tests.ast2; package org.eclipse.cdt.core.parser.tests.ast2;
import static org.eclipse.cdt.core.parser.ParserLanguage.CPP;
import java.io.IOException; import java.io.IOException;
import junit.framework.TestSuite; import junit.framework.TestSuite;
@ -24,6 +26,7 @@ import org.eclipse.cdt.core.dom.ast.IASTArraySubscriptExpression;
import org.eclipse.cdt.core.dom.ast.IASTBinaryExpression; import org.eclipse.cdt.core.dom.ast.IASTBinaryExpression;
import org.eclipse.cdt.core.dom.ast.IASTCaseStatement; import org.eclipse.cdt.core.dom.ast.IASTCaseStatement;
import org.eclipse.cdt.core.dom.ast.IASTCastExpression; import org.eclipse.cdt.core.dom.ast.IASTCastExpression;
import org.eclipse.cdt.core.dom.ast.IASTComment;
import org.eclipse.cdt.core.dom.ast.IASTCompositeTypeSpecifier; import org.eclipse.cdt.core.dom.ast.IASTCompositeTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTCompoundStatement; import org.eclipse.cdt.core.dom.ast.IASTCompoundStatement;
import org.eclipse.cdt.core.dom.ast.IASTConditionalExpression; import org.eclipse.cdt.core.dom.ast.IASTConditionalExpression;
@ -7387,4 +7390,15 @@ public class AST2Tests extends AST2BaseTest {
assertTrue(v.numericalValue() == 4); assertTrue(v.numericalValue() == 4);
} }
} }
// #define NULL_STATEMENT_MACRO ;;
// void macro_test() {
// NULL_STATEMENT_MACRO //comment
// }
public void testCommentAfterMacroExpansion_367827() throws Exception {
IASTTranslationUnit tu= parse(getAboveComment(), CPP);
IASTComment comment= tu.getComments()[0];
assertEquals("//comment", new String(comment.getComment()));
assertEquals("//comment", comment.getRawSignature());
}
} }

View file

@ -13,9 +13,9 @@ package org.eclipse.cdt.core.parser.tests.rewrite;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.TreeMap; import java.util.TreeMap;
import java.util.Vector;
import org.eclipse.cdt.core.tests.BaseTestFramework; import org.eclipse.cdt.core.tests.BaseTestFramework;
import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFile;
@ -39,7 +39,7 @@ public abstract class RewriteBaseTest extends BaseTestFramework implements ILogL
super(name); super(name);
} }
public RewriteBaseTest(String name, Vector<TestSourceFile> files) { public RewriteBaseTest(String name, List<TestSourceFile> files) {
super(name); super(name);
for (TestSourceFile file : files) { for (TestSourceFile file : files) {
fileMap.put(file.getName(), file); fileMap.put(file.getName(), file);

View file

@ -18,7 +18,7 @@ import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.Vector; import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -59,7 +59,7 @@ public class RewriteTester extends TestSuite {
private static ArrayList<RewriteBaseTest> createTests(BufferedReader inputReader) throws Exception { private static ArrayList<RewriteBaseTest> createTests(BufferedReader inputReader) throws Exception {
String line; String line;
Vector<TestSourceFile> files = new Vector<TestSourceFile>(); List<TestSourceFile> files = new ArrayList<TestSourceFile>();
TestSourceFile actFile = null; TestSourceFile actFile = null;
MatcherState matcherState = MatcherState.skip; MatcherState matcherState = MatcherState.skip;
ArrayList<RewriteBaseTest> testCases = new ArrayList<RewriteBaseTest>(); ArrayList<RewriteBaseTest> testCases = new ArrayList<RewriteBaseTest>();
@ -72,7 +72,7 @@ public class RewriteTester extends TestSuite {
if (!bevorFirstTest) { if (!bevorFirstTest) {
RewriteBaseTest test = createTestClass(className, testName, files); RewriteBaseTest test = createTestClass(className, testName, files);
testCases.add(test); testCases.add(test);
files = new Vector<TestSourceFile>(); files = new ArrayList<TestSourceFile>();
className = null; className = null;
testName = null; testName = null;
} }
@ -114,17 +114,11 @@ public class RewriteTester extends TestSuite {
} }
private static RewriteBaseTest createTestClass(String className, String testName, private static RewriteBaseTest createTestClass(String className, String testName,
Vector<TestSourceFile> files) throws Exception { List<TestSourceFile> files) throws Exception {
try { try {
Class<?> refClass = Class.forName(className); Class<?> refClass = Class.forName(className);
Class<?> paratypes[] = new Class[2]; Constructor<?> ct = refClass.getConstructor(new Class[] { String.class, List.class });
paratypes[0] = testName.getClass(); RewriteBaseTest test = (RewriteBaseTest) ct.newInstance(new Object[] { testName, files });
paratypes[1] = files.getClass();
Constructor<?> ct = refClass.getConstructor(paratypes);
Object arglist[] = new Object[2];
arglist[0] = testName;
arglist[1] = files;
RewriteBaseTest test = (RewriteBaseTest) ct.newInstance(arglist);
for (TestSourceFile file : files) { for (TestSourceFile file : files) {
TextSelection sel = file.getSelection(); TextSelection sel = file.getSelection();
if (sel != null) { if (sel != null) {

View file

@ -15,7 +15,6 @@ import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.TreeSet; import java.util.TreeSet;
import java.util.Vector;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -85,7 +84,7 @@ public class CommentHandlingTest extends RewriteBaseTest {
private static final String TRAILING_COMMENT_TITLE = "<<<=== Trailing Comment Test Section ===>>>"; //$NON-NLS-1$ private static final String TRAILING_COMMENT_TITLE = "<<<=== Trailing Comment Test Section ===>>>"; //$NON-NLS-1$
private static final String FREESTANDING_COMMENT_TITLE = "<<<=== Freestanding Comment Test Section ===>>>"; //$NON-NLS-1$ private static final String FREESTANDING_COMMENT_TITLE = "<<<=== Freestanding Comment Test Section ===>>>"; //$NON-NLS-1$
public CommentHandlingTest(String name, Vector<TestSourceFile> files) { public CommentHandlingTest(String name, List<TestSourceFile> files) {
super(name, files); super(name, files);
} }

View file

@ -477,9 +477,14 @@ public class LocationMapTests extends BaseTestCase {
fLocationMap.encounterPoundDefine(3, 13, 33, 63, 103, true, macro3); fLocationMap.encounterPoundDefine(3, 13, 33, 63, 103, true, macro3);
IASTName name1= fLocationMap.encounterImplicitMacroExpansion(macro1, null); IASTName name1= fLocationMap.encounterImplicitMacroExpansion(macro1, null);
IASTName name2= fLocationMap.encounterImplicitMacroExpansion(macro2, null); IASTName name2= fLocationMap.encounterImplicitMacroExpansion(macro2, null);
fLocationMap.pushMacroExpansion(110, 115, 125, 30, macro3, new IASTName[]{name1, name2}, new ImageLocationInfo[0]); ILocationCtx me = fLocationMap.pushMacroExpansion(110, 115, 125, 30, macro3, new IASTName[]{name1, name2}, new ImageLocationInfo[0]);
fLocationMap.encounteredComment(12, 23, false); // Comment in expansion
checkComment(fLocationMap.getComments()[0], new String(LONGDIGITS, 110, 15), false, FN, 110, 15, 2, 2); fLocationMap.encounteredComment(116, 120, false);
// Comment right after expansion, reported before expansion completes.
fLocationMap.encounteredComment(125, 140, false);
fLocationMap.popContext(me);
checkComment(fLocationMap.getComments()[0], new String(LONGDIGITS, 116, 4), false, FN, 116, 4, 2, 2);
checkComment(fLocationMap.getComments()[1], new String(LONGDIGITS, 125, 15), false, FN, 125, 15, 2, 2);
IASTName[] refs= fLocationMap.getReferences(macro3); IASTName[] refs= fLocationMap.getReferences(macro3);
assertEquals(1, refs.length); assertEquals(1, refs.length);
@ -505,7 +510,6 @@ public class LocationMapTests extends BaseTestCase {
// number: [0,6)[26,30) // number: [0,6)[26,30)
ILocationCtx pre2= fLocationMap.pushPreInclusion(new CharArray("a1a2a3a4a5"), 0, true); ILocationCtx pre2= fLocationMap.pushPreInclusion(new CharArray("a1a2a3a4a5"), 0, true);
assertEquals(FN, fLocationMap.getCurrentFilePath()); assertEquals(FN, fLocationMap.getCurrentFilePath());
fLocationMap.encounteredComment(0,2,true);
// number: [6,15)[25,26) // number: [6,15)[25,26)
ILocationCtx i1= fLocationMap.pushInclusion(0, 2, 4, 6, new CharArray("b1b2b3b4b5"), "pre1", "pre1".toCharArray(), false, false, false); ILocationCtx i1= fLocationMap.pushInclusion(0, 2, 4, 6, new CharArray("b1b2b3b4b5"), "pre1", "pre1".toCharArray(), false, false, false);
assertEquals("pre1", fLocationMap.getCurrentFilePath()); assertEquals("pre1", fLocationMap.getCurrentFilePath());
@ -533,11 +537,10 @@ public class LocationMapTests extends BaseTestCase {
IASTComment[] comments= fLocationMap.getComments(); IASTComment[] comments= fLocationMap.getComments();
checkComment(comments[0], "", true, FN, 0, 0, 1, 1); checkComment(comments[0], "b2", true, "pre1", 2, 2, 1, 1);
checkComment(comments[1], "b2", true, "pre1", 2, 2, 1, 1); checkComment(comments[1], "c2c3", true, "pre11", 2, 4, 1, 1);
checkComment(comments[2], "c2c3", true, "pre11", 2, 4, 1, 1); checkComment(comments[2], "b3", false, "pre1", 4, 2, 1, 1);
checkComment(comments[3], "b3", false, "pre1", 4, 2, 1, 1); checkComment(comments[3], "d1", true, "pre2", 0, 2, 1, 1);
checkComment(comments[4], "d1", true, "pre2", 0, 2, 1, 1);
checkLocation(fLocationMap.getMappedFileLocation(0, 6), FN, 0, 0, 1, 1); checkLocation(fLocationMap.getMappedFileLocation(0, 6), FN, 0, 0, 1, 1);
checkLocation(fLocationMap.getMappedFileLocation(6, 9), "pre1", 0, 9, 1, 1); checkLocation(fLocationMap.getMappedFileLocation(6, 9), "pre1", 0, 9, 1, 1);

View file

@ -41,7 +41,6 @@ import org.eclipse.core.runtime.NullProgressMonitor;
* Test the correctness of C/C++ searches * Test the correctness of C/C++ searches
* *
* @author Vivian Kong * @author Vivian Kong
*
*/ */
public class PDOMSearchTest extends PDOMTestBase { public class PDOMSearchTest extends PDOMTestBase {
final Comparator<IBinding> BINDING_COMPARATOR = new Comparator<IBinding>() { final Comparator<IBinding> BINDING_COMPARATOR = new Comparator<IBinding>() {
@ -72,11 +71,11 @@ public class PDOMSearchTest extends PDOMTestBase {
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
pdom.releaseReadLock(); pdom.releaseReadLock();
} }
/** /**
* Test the members inside namespaces * Test the members inside namespaces
*/ */
public void testNamespaces() throws Exception { public void testNamespaces() throws Exception {
/* Members in the namespace */ /* Members in the namespace */
IBinding[] namespaces = pdom.findBindings(Pattern.compile("namespace1"), false, INDEX_FILTER, NULL_MONITOR); IBinding[] namespaces = pdom.findBindings(Pattern.compile("namespace1"), false, INDEX_FILTER, NULL_MONITOR);
assertEquals(1, namespaces.length); assertEquals(1, namespaces.length);
@ -117,7 +116,6 @@ public class PDOMSearchTest extends PDOMTestBase {
assertEquals(1, defs.length); assertEquals(1, defs.length);
loc = defs[0].getFileLocation(); loc = defs[0].getFileLocation();
assertEquals(offset("Class1.h","namespace namespace1") + 10, loc.getNodeOffset()); //character offset assertEquals(offset("Class1.h","namespace namespace1") + 10, loc.getNodeOffset()); //character offset
} }
public void testClasses() throws Exception { public void testClasses() throws Exception {
@ -223,7 +221,6 @@ public class PDOMSearchTest extends PDOMTestBase {
} }
public void testFunction() throws Exception { public void testFunction() throws Exception {
IBinding[] functions = pdom.findBindings(Pattern.compile("foo2"), false, INDEX_FILTER, NULL_MONITOR); IBinding[] functions = pdom.findBindings(Pattern.compile("foo2"), false, INDEX_FILTER, NULL_MONITOR);
assertEquals(1, functions.length); assertEquals(1, functions.length);
assertTrue(functions[0] instanceof ICPPFunction); assertTrue(functions[0] instanceof ICPPFunction);
@ -233,20 +230,16 @@ public class PDOMSearchTest extends PDOMTestBase {
assertEquals(1, functions.length); assertEquals(1, functions.length);
assertTrue(functions[0] instanceof ICPPFunction); assertTrue(functions[0] instanceof ICPPFunction);
assertEquals("main", getBindingQualifiedName(pdom.getLinkageImpls()[0].adaptBinding(functions[0]))); assertEquals("main", getBindingQualifiedName(pdom.getLinkageImpls()[0].adaptBinding(functions[0])));
} }
public void testMethods() throws Exception { public void testMethods() throws Exception {
IBinding[] methods = pdom.findBindings(Pattern.compile("~Class2"), false, INDEX_FILTER, NULL_MONITOR); IBinding[] methods = pdom.findBindings(Pattern.compile("~Class2"), false, INDEX_FILTER, NULL_MONITOR);
assertEquals(1, methods.length); assertEquals(1, methods.length);
assertTrue(methods[0] instanceof ICPPMethod); assertTrue(methods[0] instanceof ICPPMethod);
assertEquals("Class2::~Class2", getBindingQualifiedName(pdom.getLinkageImpls()[0].adaptBinding(methods[0]))); assertEquals("Class2::~Class2", getBindingQualifiedName(pdom.getLinkageImpls()[0].adaptBinding(methods[0])));
} }
public void testFields() throws Exception { public void testFields() throws Exception {
IBinding[] fields = pdom.findBindings(Pattern.compile("class1x"), false, INDEX_FILTER, NULL_MONITOR); IBinding[] fields = pdom.findBindings(Pattern.compile("class1x"), false, INDEX_FILTER, NULL_MONITOR);
assertEquals(1, fields.length); assertEquals(1, fields.length);
assertTrue(fields[0] instanceof ICPPField); assertTrue(fields[0] instanceof ICPPField);
@ -256,11 +249,9 @@ public class PDOMSearchTest extends PDOMTestBase {
assertEquals(1, fields.length); assertEquals(1, fields.length);
assertTrue(fields[0] instanceof ICPPField); assertTrue(fields[0] instanceof ICPPField);
assertEquals("namespace1::Class1::class1y", getBindingQualifiedName(pdom.getLinkageImpls()[0].adaptBinding(fields[0]))); assertEquals("namespace1::Class1::class1y", getBindingQualifiedName(pdom.getLinkageImpls()[0].adaptBinding(fields[0])));
} }
public void testVariables() throws Exception { public void testVariables() throws Exception {
IBinding[] variables = pdom.findBindings(Pattern.compile("var"), false, INDEX_FILTER, NULL_MONITOR); IBinding[] variables = pdom.findBindings(Pattern.compile("var"), false, INDEX_FILTER, NULL_MONITOR);
assertEquals(1, variables.length); assertEquals(1, variables.length);
assertTrue(variables[0] instanceof ICPPVariable); assertTrue(variables[0] instanceof ICPPVariable);
@ -283,7 +274,6 @@ public class PDOMSearchTest extends PDOMTestBase {
assertEquals(1, defs.length); assertEquals(1, defs.length);
loc = defs[0].getFileLocation(); loc = defs[0].getFileLocation();
assertEquals(offset("main.cpp","int var;") + 4, loc.getNodeOffset()); //character offset assertEquals(offset("main.cpp","int var;") + 4, loc.getNodeOffset()); //character offset
} }
/** /**

View file

@ -22,8 +22,8 @@ import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import java.util.Vector;
/** /**
* Startup class for Eclipse. Creates a class loader using * Startup class for Eclipse. Creates a class loader using
* supplied URL of platform installation, loads and calls * supplied URL of platform installation, loads and calls
@ -181,14 +181,14 @@ protected Object basicRun(String[] args) throws Exception {
private String[] getArrayFromList(String prop) { private String[] getArrayFromList(String prop) {
if (prop == null || prop.trim().equals("")) if (prop == null || prop.trim().equals(""))
return new String[0]; return new String[0];
Vector list = new Vector(); List<String> list = new ArrayList<String>();
StringTokenizer tokens = new StringTokenizer(prop, ","); StringTokenizer tokens = new StringTokenizer(prop, ",");
while (tokens.hasMoreTokens()) { while (tokens.hasMoreTokens()) {
String token = tokens.nextToken().trim(); String token = tokens.nextToken().trim();
if (!token.equals("")) if (!token.equals(""))
list.addElement(token); list.add(token);
} }
return list.isEmpty() ? new String[0] : (String[]) list.toArray(new String[0]); return list.toArray(new String[list.size()]);
} }
/** /**
* Creates and returns a platform <code>BootLoader</code> which can be used to start * Creates and returns a platform <code>BootLoader</code> which can be used to start
@ -404,10 +404,10 @@ public static void endSplash() {
* @exception Exception thrown if a problem occurs during launching * @exception Exception thrown if a problem occurs during launching
*/ */
public static void main(String argString) throws Exception { public static void main(String argString) throws Exception {
Vector list = new Vector(5); List<String> list = new ArrayList<String>(5);
for (StringTokenizer tokens = new StringTokenizer(argString, " "); tokens.hasMoreElements();) for (StringTokenizer tokens = new StringTokenizer(argString, " "); tokens.hasMoreElements();)
list.addElement(tokens.nextElement()); list.add((String) tokens.nextElement());
main((String[]) list.toArray(new String[list.size()])); main(list.toArray(new String[list.size()]));
} }
/** /**

View file

@ -14,18 +14,17 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties; import java.util.Properties;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import java.util.Vector;
/** /**
* Application is responsible for calling core launch api * Application is responsible for calling core launch api
*/ */
public class NewMain extends Main { public class NewMain extends Main {
private static final String DEFAULT_APPLICATION= "org.eclipse.ui.workbench"; private static final String DEFAULT_APPLICATION= "org.eclipse.ui.workbench";
public NewMain(String application, String location, URL pluginPathLocation, String bootLocation, boolean debug) throws IOException { public NewMain(String application, String location, URL pluginPathLocation, String bootLocation, boolean debug) throws IOException {
this.application= application; this.application= application;
this.location= location; this.location= location;
@ -44,17 +43,16 @@ public class NewMain extends Main {
System.exit(0); System.exit(0);
} }
/** /**
* Run this launcher with the arguments specified in the given string. * Run this launcher with the arguments specified in the given string.
* This is a short cut method for people running the launcher from * This is a short cut method for people running the launcher from
* a scrapbook (i.e., swip-and-doit facility). * a scrapbook (i.e., swip-and-doit facility).
*/ */
public static void main(String argString) throws Exception { public static void main(String argString) throws Exception {
Vector list= new Vector(5); List<String> list= new ArrayList<String>(5);
for (StringTokenizer tokens= new StringTokenizer(argString, " "); tokens.hasMoreElements();) for (StringTokenizer tokens= new StringTokenizer(argString, " "); tokens.hasMoreElements();)
list.addElement(tokens.nextElement()); list.add((String) tokens.nextElement());
main((String[]) list.toArray(new String[list.size()])); main(list.toArray(new String[list.size()]));
} }
public static String getLocationFromProperties(String key) { public static String getLocationFromProperties(String key) {

View file

@ -17,6 +17,8 @@ package org.eclipse.cdt.core.dom.ast;
* @noimplement This interface is not intended to be implemented by clients. * @noimplement This interface is not intended to be implemented by clients.
*/ */
public interface IASTLabelStatement extends IASTStatement, IASTNameOwner { public interface IASTLabelStatement extends IASTStatement, IASTNameOwner {
/** @since 5.4 */
public static final IASTStatement[] EMPTY_LABEL_STATEMENT_ARRAY = {};
public static final ASTNodeProperty NAME = new ASTNodeProperty("IASTLabelStatement.NAME - name for IASTLabelStatement"); //$NON-NLS-1$ public static final ASTNodeProperty NAME = new ASTNodeProperty("IASTLabelStatement.NAME - name for IASTLabelStatement"); //$NON-NLS-1$
public static final ASTNodeProperty NESTED_STATEMENT = new ASTNodeProperty( "IASTLabelStatement.NESTED_STATEMENT - statement for IASTLabelStatement" ); //$NON-NLS-1$ public static final ASTNodeProperty NESTED_STATEMENT = new ASTNodeProperty( "IASTLabelStatement.NESTED_STATEMENT - statement for IASTLabelStatement" ); //$NON-NLS-1$

View file

@ -20,7 +20,7 @@ public interface IASTStatement extends IASTNode {
/** /**
* Constant. * Constant.
*/ */
public static final IASTStatement[] EMPTY_STATEMENT_ARRAY = new IASTStatement[0]; public static final IASTStatement[] EMPTY_STATEMENT_ARRAY = {};
/** /**
* @since 5.1 * @since 5.1

View file

@ -26,7 +26,8 @@ import org.eclipse.core.runtime.IAdaptable;
* @noimplement This interface is not intended to be implemented by clients. * @noimplement This interface is not intended to be implemented by clients.
*/ */
public interface IBinding extends IAdaptable { public interface IBinding extends IAdaptable {
public static final IBinding[] EMPTY_BINDING_ARRAY = new IBinding[0]; public static final IBinding[] EMPTY_BINDING_ARRAY = {};
/** /**
* Returns the unqualified name of the binding as a string. * Returns the unqualified name of the binding as a string.
*/ */

View file

@ -16,8 +16,7 @@ package org.eclipse.cdt.core.dom.ast;
* @noimplement This interface is not intended to be implemented by clients. * @noimplement This interface is not intended to be implemented by clients.
*/ */
public interface IField extends IVariable { public interface IField extends IVariable {
public static final IField[] EMPTY_FIELD_ARRAY = {};
public static final IField[] EMPTY_FIELD_ARRAY = new IField[0];
/** /**
* Returns the composite type that owns the field. * Returns the composite type that owns the field.

View file

@ -18,6 +18,9 @@ package org.eclipse.cdt.core.dom.ast;
* @noimplement This interface is not intended to be implemented by clients. * @noimplement This interface is not intended to be implemented by clients.
*/ */
public interface ILabel extends IBinding { public interface ILabel extends IBinding {
/** @since 5.4 */
public static final IBinding[] EMPTY_LABEL_ARRAY = {};
/** /**
* Returns the label statement for this label. * Returns the label statement for this label.
*/ */

View file

@ -15,6 +15,7 @@
package org.eclipse.cdt.core.parser.util; package org.eclipse.cdt.core.parser.util;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.util.Arrays;
import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.Assert;
@ -31,7 +32,7 @@ public abstract class ArrayUtil {
* the given class object. * the given class object.
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
static public <T> T[] append(Class<? extends T> c, T[] array, T obj) { static public <T> T[] append(Class<T> c, T[] array, T obj) {
if (obj == null) if (obj == null)
return array; return array;
if (array == null || array.length == 0) { if (array == null || array.length == 0) {
@ -52,26 +53,6 @@ public abstract class ArrayUtil {
return temp; return temp;
} }
/**
* Assumes that array contains nulls at the end, only.
* @returns index of first null, or -1
*/
private static int findFirstNull(Object[] array) {
boolean haveNull= false;
int left= 0;
int right= array.length - 1;
while (left <= right) {
int mid= (left + right) / 2;
if (array[mid] == null) {
haveNull= true;
right= mid - 1;
} else {
left= mid + 1;
}
}
return haveNull ? right + 1 : -1;
}
/** /**
* Assumes that array contains nulls at the end, only. * Assumes that array contains nulls at the end, only.
* Appends element after the last non-null element. * Appends element after the last non-null element.
@ -103,6 +84,26 @@ public abstract class ArrayUtil {
return temp; return temp;
} }
/**
* Assumes that array contains nulls at the end, only.
* @returns index of first null, or -1
*/
private static int findFirstNull(Object[] array) {
boolean haveNull= false;
int left= 0;
int right= array.length - 1;
while (left <= right) {
int mid= (left + right) / 2;
if (array[mid] == null) {
haveNull= true;
right= mid - 1;
} else {
left= mid + 1;
}
}
return haveNull ? right + 1 : -1;
}
/** /**
* @deprecated Use {@link #appendAt(Class, Object[], int, Object)} instead. * @deprecated Use {@link #appendAt(Class, Object[], int, Object)} instead.
* @since 4.0 * @since 4.0
@ -154,7 +155,7 @@ public abstract class ArrayUtil {
* @param forceNew * @param forceNew
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
static public <T> T[] trim(Class<? extends T> c, T[] array, boolean forceNew) { static public <T> T[] trim(Class<T> c, T[] array, boolean forceNew) {
if (array == null) if (array == null)
return (T[]) Array.newInstance(c, 0); return (T[]) Array.newInstance(c, 0);
@ -173,7 +174,7 @@ public abstract class ArrayUtil {
return temp; return temp;
} }
public static <T> T[] trim(Class<? extends T> c, T[] array) { public static <T> T[] trim(Class<T> c, T[] array) {
return trim(c, array, false); return trim(c, array, false);
} }
@ -188,7 +189,6 @@ public abstract class ArrayUtil {
* @param forceNew * @param forceNew
* @since 5.2 * @since 5.2
*/ */
@SuppressWarnings("unchecked")
static public <T> T[] trim(T[] array, boolean forceNew) { static public <T> T[] trim(T[] array, boolean forceNew) {
int i = array.length; int i = array.length;
if (i == 0 || array[i - 1] != null) { if (i == 0 || array[i - 1] != null) {
@ -200,9 +200,7 @@ public abstract class ArrayUtil {
Assert.isTrue(i >= 0); Assert.isTrue(i >= 0);
} }
T[] temp = (T[]) Array.newInstance(array.getClass().getComponentType(), i); return Arrays.copyOf(array, i);
System.arraycopy(array, 0, temp, 0, i);
return temp;
} }
/** /**
@ -227,7 +225,7 @@ public abstract class ArrayUtil {
* @return The concatenated array, which may be the same as the first parameter. * @return The concatenated array, which may be the same as the first parameter.
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T[] addAll(Class<? extends T> c, T[] dest, T[] source) { public static <T> T[] addAll(Class<T> c, T[] dest, Object[] source) {
if (source == null || source.length == 0) if (source == null || source.length == 0)
return dest; return dest;
@ -254,10 +252,9 @@ public abstract class ArrayUtil {
System.arraycopy(source, 0, dest, firstFree, numToAdd); System.arraycopy(source, 0, dest, firstFree, numToAdd);
return dest; return dest;
} }
T[] temp = (T[]) Array.newInstance(c, firstFree + numToAdd); dest = Arrays.copyOf(dest, firstFree + numToAdd);
System.arraycopy(dest, 0, temp, 0, firstFree); System.arraycopy(source, 0, dest, firstFree, numToAdd);
System.arraycopy(source, 0, temp, firstFree, numToAdd); return dest;
return temp;
} }
/** /**
@ -270,7 +267,7 @@ public abstract class ArrayUtil {
* @since 5.2 * @since 5.2
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T[] addAll(T[] dest, T[] source) { public static <T> T[] addAll(T[] dest, Object[] source) {
if (source == null || source.length == 0) if (source == null || source.length == 0)
return dest; return dest;
@ -299,10 +296,9 @@ public abstract class ArrayUtil {
System.arraycopy(source, 0, dest, firstFree, numToAdd); System.arraycopy(source, 0, dest, firstFree, numToAdd);
return dest; return dest;
} }
T[] temp = (T[]) Array.newInstance(dest.getClass().getComponentType(), firstFree + numToAdd); dest = Arrays.copyOf(dest, firstFree + numToAdd);
System.arraycopy(dest, 0, temp, 0, firstFree); System.arraycopy(source, 0, dest, firstFree, numToAdd);
System.arraycopy(source, 0, temp, firstFree, numToAdd); return dest;
return temp;
} }
/** /**
@ -379,7 +375,7 @@ public abstract class ArrayUtil {
* If there are no nulls in the original array then the original array is returned. * If there are no nulls in the original array then the original array is returned.
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T[] removeNulls(Class<? extends T> c, T[] array) { public static <T> T[] removeNulls(Class<T> c, T[] array) {
if (array == null) if (array == null)
return (T[]) Array.newInstance(c, 0); return (T[]) Array.newInstance(c, 0);
@ -469,7 +465,7 @@ public abstract class ArrayUtil {
* Assumes that array contains nulls at the end, only. * Assumes that array contains nulls at the end, only.
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T[] prepend(Class<? extends T> c, T[] array, T obj) { public static <T> T[] prepend(Class<T> c, T[] array, T obj) {
if (obj == null) if (obj == null)
return array; return array;
if (array == null || array.length == 0) { if (array == null || array.length == 0) {
@ -569,8 +565,8 @@ public abstract class ArrayUtil {
* runtime type. * runtime type.
* @param target the runtime type of the new array * @param target the runtime type of the new array
* @param source the source array * @param source the source array
* @return the current array stored in a new array with the * @return the current array stored in a new array with the specified runtime type,
* specified runtime type, or null if source is null. * or null if source is null.
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <S, T> T[] convert(Class<T> target, S[] source) { public static <S, T> T[] convert(Class<T> target, S[] source) {
@ -584,6 +580,30 @@ public abstract class ArrayUtil {
return result; return result;
} }
/**
* Reverses order of elements in an array.
* @param array the array
* @since 5.4
*/
public static void reverse(Object[] array) {
reverse(array, 0, array.length);
}
/**
* Reverses order of elements in a subsection of an array.
* @param array the array
* @param fromIndex the index of the first affected element (inclusive)
* @param toIndex the index of the last affected element (exclusive)
* @since 5.4
*/
public static void reverse(Object[] array, int fromIndex, int toIndex) {
for (int i = fromIndex, j = toIndex; i < --j; i++) {
Object tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
/** /**
* Returns a new array that contains all of the elements of the * Returns a new array that contains all of the elements of the
* given array except the first one. * given array except the first one.

View file

@ -40,8 +40,12 @@ public abstract class ASTNode implements IASTNode {
private IASTNode parent; private IASTNode parent;
private ASTNodeProperty property; private ASTNodeProperty property;
private int length; /**
* The sequence number of the ast-node as calculated by the location map.
* Do not access directly, because getOffset() may be overloaded for lazy calculations.
*/
private int offset; private int offset;
private int length;
private IASTNodeLocation[] locations; private IASTNodeLocation[] locations;
private IASTFileLocation fileLocation; private IASTFileLocation fileLocation;
@ -112,17 +116,20 @@ public abstract class ASTNode implements IASTNode {
public void setOffset(int offset) { public void setOffset(int offset) {
this.offset = offset; this.offset = offset;
this.locations = null; this.locations = null;
this.fileLocation = null;
} }
public void setLength(int length) { public void setLength(int length) {
this.length = length; this.length = length;
this.locations = null; this.locations = null;
this.fileLocation = null;
} }
public void setOffsetAndLength(int offset, int length) { public void setOffsetAndLength(int offset, int length) {
this.offset = offset; this.offset = offset;
this.length = length; this.length = length;
this.locations = null; this.locations = null;
this.fileLocation = null;
} }
public void setOffsetAndLength(ASTNode node) { public void setOffsetAndLength(ASTNode node) {
@ -140,7 +147,7 @@ public abstract class ASTNode implements IASTNode {
if (tu != null) { if (tu != null) {
ILocationResolver l= (ILocationResolver) tu.getAdapter(ILocationResolver.class); ILocationResolver l= (ILocationResolver) tu.getAdapter(ILocationResolver.class);
if (l != null) { if (l != null) {
locations= l.getLocations(offset, length); locations= l.getLocations(getOffset(), length);
} }
} }
} }
@ -152,7 +159,7 @@ public abstract class ASTNode implements IASTNode {
if (tu != null) { if (tu != null) {
ILocationResolver l= (ILocationResolver) tu.getAdapter(ILocationResolver.class); ILocationResolver l= (ILocationResolver) tu.getAdapter(ILocationResolver.class);
if (l != null) { if (l != null) {
return l.getImageLocation(offset, length); return l.getImageLocation(getOffset(), length);
} }
} }
return null; return null;
@ -177,6 +184,7 @@ public abstract class ASTNode implements IASTNode {
@Override @Override
public String getContainingFilename() { public String getContainingFilename() {
final int offset = getOffset();
if (offset <= 0 && (length == 0 || offset < 0)) { if (offset <= 0 && (length == 0 || offset < 0)) {
final IASTNode parent = getParent(); final IASTNode parent = getParent();
if (parent == null) { if (parent == null) {
@ -195,6 +203,7 @@ public abstract class ASTNode implements IASTNode {
if (fileLocation != null) if (fileLocation != null)
return fileLocation; return fileLocation;
// TODO(sprigogin): The purpose of offset == 0 && length == 0 condition is not clear to me. // TODO(sprigogin): The purpose of offset == 0 && length == 0 condition is not clear to me.
final int offset = getOffset();
if (offset < 0 || (offset == 0 && length == 0 && !(this instanceof IASTTranslationUnit))) { if (offset < 0 || (offset == 0 && length == 0 && !(this instanceof IASTTranslationUnit))) {
return null; return null;
} }
@ -217,7 +226,7 @@ public abstract class ASTNode implements IASTNode {
if (ast != null) { if (ast != null) {
ILocationResolver lr= (ILocationResolver) ast.getAdapter(ILocationResolver.class); ILocationResolver lr= (ILocationResolver) ast.getAdapter(ILocationResolver.class);
if (lr != null) { if (lr != null) {
return lr.isPartOfTranslationUnitFile(offset); return lr.isPartOfTranslationUnitFile(getOffset());
} }
} }
return false; return false;
@ -228,7 +237,7 @@ public abstract class ASTNode implements IASTNode {
if (ast != null) { if (ast != null) {
ILocationResolver lr= (ILocationResolver) ast.getAdapter(ILocationResolver.class); ILocationResolver lr= (ILocationResolver) ast.getAdapter(ILocationResolver.class);
if (lr != null) { if (lr != null) {
return lr.isPartOfSourceFile(offset); return lr.isPartOfSourceFile(getOffset());
} }
} }
return false; return false;
@ -248,27 +257,29 @@ public abstract class ASTNode implements IASTNode {
public boolean contains(IASTNode node) { public boolean contains(IASTNode node) {
if (node instanceof ASTNode) { if (node instanceof ASTNode) {
ASTNode astNode= (ASTNode) node; ASTNode astNode= (ASTNode) node;
return offset <= astNode.offset && final int offset = getOffset();
astNode.offset+astNode.length <= offset+length; final int nodeOffset= astNode.getOffset();
return offset <= nodeOffset && nodeOffset+astNode.length <= offset+length;
} }
return false; return false;
} }
@Override @Override
public IToken getSyntax() throws ExpansionOverlapsBoundaryException { public IToken getSyntax() throws ExpansionOverlapsBoundaryException {
final int offset = getOffset();
return getSyntax(offset, offset+length, 0); return getSyntax(offset, offset+length, 0);
} }
@Override @Override
public IToken getLeadingSyntax() throws ExpansionOverlapsBoundaryException { public IToken getLeadingSyntax() throws ExpansionOverlapsBoundaryException {
int left= getBoundary(-1); int left= getBoundary(-1);
return getSyntax(left, offset, -1); return getSyntax(left, getOffset(), -1);
} }
@Override @Override
public IToken getTrailingSyntax() throws ExpansionOverlapsBoundaryException { public IToken getTrailingSyntax() throws ExpansionOverlapsBoundaryException {
int right= getBoundary(1); int right= getBoundary(1);
return getSyntax(offset+length, right, 1); return getSyntax(getOffset()+length, right, 1);
} }
/** /**

View file

@ -13,7 +13,6 @@
package org.eclipse.cdt.internal.core.dom.parser.c; package org.eclipse.cdt.internal.core.dom.parser.c;
import org.eclipse.cdt.core.dom.ILinkage; import org.eclipse.cdt.core.dom.ILinkage;
import org.eclipse.cdt.core.dom.IName;
import org.eclipse.cdt.core.dom.ast.EScopeKind; import org.eclipse.cdt.core.dom.ast.EScopeKind;
import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTTypeId; import org.eclipse.cdt.core.dom.ast.IASTTypeId;
@ -80,13 +79,13 @@ public class CASTTranslationUnit extends ASTTranslationUnit implements IASTAmbig
if (binding instanceof IMacroBinding) { if (binding instanceof IMacroBinding) {
return getMacroDefinitionsInAST((IMacroBinding) binding); return getMacroDefinitionsInAST((IMacroBinding) binding);
} }
IName[] names = CVisitor.getDeclarations(this, binding); IASTName[] names = CVisitor.getDeclarations(this, binding);
for (int i = 0; i < names.length; i++) { for (int i = 0; i < names.length; i++) {
if (!names[i].isDefinition()) if (!names[i].isDefinition())
names[i] = null; names[i] = null;
} }
// nulls can be anywhere, don't use trim() // nulls can be anywhere, don't use trim()
return (IASTName[])ArrayUtil.removeNulls(IASTName.class, names); return ArrayUtil.removeNulls(IASTName.class, names);
} }
/* /*

View file

@ -95,10 +95,10 @@ public class CCompositeTypeScope extends CScope implements ICCompositeTypeScope
} }
// anonymous structures and unions // anonymous structures and unions
if (declarators.length == 0 && ((IASTSimpleDeclaration) node).getDeclSpecifier() instanceof IASTCompositeTypeSpecifier) { if (declarators.length == 0 && ((IASTSimpleDeclaration) node).getDeclSpecifier() instanceof IASTCompositeTypeSpecifier) {
IASTCompositeTypeSpecifier declSpec = (IASTCompositeTypeSpecifier) ((IASTSimpleDeclaration) node).getDeclSpecifier(); ICASTCompositeTypeSpecifier declSpec = (ICASTCompositeTypeSpecifier) ((IASTSimpleDeclaration) node).getDeclSpecifier();
IASTName n = declSpec.getName(); IASTName n = declSpec.getName();
if (n.toCharArray().length == 0) { if (n.toCharArray().length == 0) {
specStack = (ICASTCompositeTypeSpecifier[]) ArrayUtil.append(ICASTCompositeTypeSpecifier.class, specStack, declSpec); specStack = ArrayUtil.append(ICASTCompositeTypeSpecifier.class, specStack, declSpec);
} }
} }
} }

View file

@ -58,7 +58,7 @@ public class CFunctionScope extends CScope implements ICFunctionScope {
IASTLabelStatement labelStatement = action.labels[i]; IASTLabelStatement labelStatement = action.labels[i];
IBinding binding = labelStatement.getName().resolveBinding(); IBinding binding = labelStatement.getName().resolveBinding();
if (binding != null) if (binding != null)
result = (ILabel[]) ArrayUtil.append( ILabel.class, result, binding ); result = ArrayUtil.append(ILabel.class, result, (ILabel) binding);
} }
} }
return ArrayUtil.trim(ILabel.class, result); return ArrayUtil.trim(ILabel.class, result);
@ -74,7 +74,7 @@ public class CFunctionScope extends CScope implements ICFunctionScope {
@Override @Override
public int visit(IASTStatement statement) { public int visit(IASTStatement statement) {
if (statement instanceof IASTLabelStatement) { if (statement instanceof IASTLabelStatement) {
labels = (IASTLabelStatement[]) ArrayUtil.append( IASTLabelStatement.class, labels, statement ); labels = ArrayUtil.append(IASTLabelStatement.class, labels, (IASTLabelStatement) statement);
} }
return PROCESS_CONTINUE; return PROCESS_CONTINUE;
} }

View file

@ -112,7 +112,7 @@ public class CScope implements ICScope, IASTInternalScope {
private IASTNode physicalNode = null; private IASTNode physicalNode = null;
private boolean isCached = false; private boolean isCached = false;
private CharArrayObjectMap<?> mapsToNameOrBinding[] = { CharArrayObjectMap.EMPTY_MAP, CharArrayObjectMap.EMPTY_MAP }; private final CharArrayObjectMap<?> mapsToNameOrBinding[] = { CharArrayObjectMap.EMPTY_MAP, CharArrayObjectMap.EMPTY_MAP };
private final EScopeKind kind; private final EScopeKind kind;
public CScope(IASTNode physical, EScopeKind eKind) { public CScope(IASTNode physical, EScopeKind eKind) {
@ -134,7 +134,7 @@ public class CScope implements ICScope, IASTInternalScope {
} }
protected static class CollectNamesAction extends ASTVisitor { protected static class CollectNamesAction extends ASTVisitor {
private char[] name; private final char[] name;
private IASTName[] result = null; private IASTName[] result = null;
CollectNamesAction(char[] n) { CollectNamesAction(char[] n) {
@ -376,7 +376,7 @@ public class CScope implements ICScope, IASTInternalScope {
for (Object element : obj) { for (Object element : obj) {
if (element instanceof IBinding) { if (element instanceof IBinding) {
result = (IBinding[]) ArrayUtil.append(IBinding.class, result, element); result = ArrayUtil.append(IBinding.class, result, (IBinding) element);
} else { } else {
IASTName n= null; IASTName n= null;
if (element instanceof IASTName) { if (element instanceof IASTName) {

View file

@ -132,8 +132,8 @@ public class CStructure extends PlatformObject implements ICompositeType, ICInte
@Override @Override
public IScope getScope() throws DOMException { public IScope getScope() throws DOMException {
IASTDeclSpecifier declSpec = (IASTDeclSpecifier) ((definition != null) ? (IASTNode) definition IASTDeclSpecifier declSpec = (IASTDeclSpecifier) ((definition != null) ?
.getParent() : declarations[0].getParent()); (IASTNode) definition.getParent() : declarations[0].getParent());
IScope scope = CVisitor.getContainingScope(declSpec); IScope scope = CVisitor.getContainingScope(declSpec);
while (scope instanceof ICCompositeTypeScope) { while (scope instanceof ICCompositeTypeScope) {
scope = scope.getParent(); scope = scope.getParent();
@ -149,8 +149,8 @@ public class CStructure extends PlatformObject implements ICompositeType, ICInte
IProblemBinding.SEMANTIC_DEFINITION_NOT_FOUND, getNameCharArray()) }; IProblemBinding.SEMANTIC_DEFINITION_NOT_FOUND, getNameCharArray()) };
} }
ICASTCompositeTypeSpecifier compSpec = (ICASTCompositeTypeSpecifier) definition.getParent(); ICASTCompositeTypeSpecifier compSpec = (ICASTCompositeTypeSpecifier) definition.getParent();
IField[] fields = collectFields(compSpec, null); IField[] fields = collectFields(compSpec, IField.EMPTY_FIELD_ARRAY);
return ArrayUtil.trim(IField.class, fields); return ArrayUtil.trim(fields);
} }
private IField[] collectFields(ICASTCompositeTypeSpecifier compSpec, IField[] fields) { private IField[] collectFields(ICASTCompositeTypeSpecifier compSpec, IField[] fields) {
@ -171,7 +171,7 @@ public class CStructure extends PlatformObject implements ICompositeType, ICInte
IASTName name = ASTQueries.findInnermostDeclarator(declarator).getName(); IASTName name = ASTQueries.findInnermostDeclarator(declarator).getName();
IBinding binding = name.resolveBinding(); IBinding binding = name.resolveBinding();
if (binding != null) if (binding != null)
fields = (IField[]) ArrayUtil.append(IField.class, fields, binding); fields = ArrayUtil.append(fields, (IField) binding);
} }
} }
} }

View file

@ -28,7 +28,6 @@ import org.eclipse.cdt.internal.core.dom.parser.VariableReadWriteFlags;
* with the variable. * with the variable.
*/ */
public final class CVariableReadWriteFlags extends VariableReadWriteFlags { public final class CVariableReadWriteFlags extends VariableReadWriteFlags {
private static CVariableReadWriteFlags INSTANCE= new CVariableReadWriteFlags(); private static CVariableReadWriteFlags INSTANCE= new CVariableReadWriteFlags();
public static int getReadWriteFlags(IASTName variable) { public static int getReadWriteFlags(IASTName variable) {
@ -80,8 +79,7 @@ public final class CVariableReadWriteFlags extends VariableReadWriteFlags {
if (indirection == 0) { if (indirection == 0) {
if (type instanceof IQualifierType) { if (type instanceof IQualifierType) {
return ((IQualifierType) type).isConst() ? READ : READ | WRITE; return ((IQualifierType) type).isConst() ? READ : READ | WRITE;
} } else if (type instanceof IPointerType) {
else if (type instanceof IPointerType) {
return ((IPointerType) type).isConst() ? READ : READ | WRITE; return ((IPointerType) type).isConst() ? READ : READ | WRITE;
} }
} }

View file

@ -91,7 +91,7 @@ public class CPPASTFunctionDeclarator extends CPPASTDeclarator implements ICPPAS
if (parameter != null) { if (parameter != null) {
parameter.setParent(this); parameter.setParent(this);
parameter.setPropertyInParent(FUNCTION_PARAMETER); parameter.setPropertyInParent(FUNCTION_PARAMETER);
parameters = (ICPPASTParameterDeclaration[]) ArrayUtil.append(ICPPASTParameterDeclaration.class, parameters, parameter); parameters = ArrayUtil.append(ICPPASTParameterDeclaration.class, parameters, (ICPPASTParameterDeclaration) parameter);
} }
} }

View file

@ -288,20 +288,20 @@ public class CPPClassScope extends CPPScope implements ICPPClassScope {
IBinding binding = null; IBinding binding = null;
if (o instanceof ObjectSet<?>) { if (o instanceof ObjectSet<?>) {
ObjectSet<?> set = (ObjectSet<?>) o; ObjectSet<?> set = (ObjectSet<?>) o;
IBinding[] bs = null; ICPPConstructor[] bs = ICPPConstructor.EMPTY_CONSTRUCTOR_ARRAY;
for (int i = 0; i < set.size(); i++) { for (int i = 0; i < set.size(); i++) {
Object obj = set.keyAt(i); Object obj = set.keyAt(i);
if (obj instanceof IASTName) { if (obj instanceof IASTName) {
IASTName n = (IASTName) obj; IASTName n = (IASTName) obj;
binding = shouldResolve(forceResolve, n, forName) ? n.resolveBinding() : n.getBinding(); binding = shouldResolve(forceResolve, n, forName) ? n.resolveBinding() : n.getBinding();
if (binding instanceof ICPPConstructor) { if (binding instanceof ICPPConstructor) {
bs = ArrayUtil.append(ICPPConstructor.class, bs, binding); bs = ArrayUtil.append(bs, (ICPPConstructor) binding);
} }
} else if (obj instanceof ICPPConstructor) { } else if (obj instanceof ICPPConstructor) {
bs = (IBinding[]) ArrayUtil.append(ICPPConstructor.class, bs, obj); bs = ArrayUtil.append(bs, (ICPPConstructor) obj);
} }
} }
return (ICPPConstructor[]) ArrayUtil.trim(ICPPConstructor.class, bs); return ArrayUtil.trim(ICPPConstructor.class, bs);
} else if (o instanceof IASTName) { } else if (o instanceof IASTName) {
if (shouldResolve(forceResolve, (IASTName) o, forName) || ((IASTName) o).getBinding() != null) { if (shouldResolve(forceResolve, (IASTName) o, forName) || ((IASTName) o).getBinding() != null) {
// always store the name, rather than the binding, such that we can properly flush the scope. // always store the name, rather than the binding, such that we can properly flush the scope.
@ -409,11 +409,11 @@ public class CPPClassScope extends CPPScope implements ICPPClassScope {
* @see chapter 12 of the ISO specification * @see chapter 12 of the ISO specification
*/ */
class ImplicitsAnalysis { class ImplicitsAnalysis {
private boolean hasUserDeclaredConstructor; private final boolean hasUserDeclaredConstructor;
private boolean hasUserDeclaredCopyConstructor; private boolean hasUserDeclaredCopyConstructor;
private boolean hasUserDeclaredCopyAssignmentOperator; private boolean hasUserDeclaredCopyAssignmentOperator;
private boolean hasUserDeclaredDestructor; private final boolean hasUserDeclaredDestructor;
private ICPPClassType classType; private final ICPPClassType classType;
ImplicitsAnalysis(ICPPASTCompositeTypeSpecifier compSpec, ICPPClassType clsType) { ImplicitsAnalysis(ICPPASTCompositeTypeSpecifier compSpec, ICPPClassType clsType) {
classType= clsType; classType= clsType;

View file

@ -33,17 +33,15 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPTemplates;
public class CPPClassTemplatePartialSpecialization extends CPPClassTemplate public class CPPClassTemplatePartialSpecialization extends CPPClassTemplate
implements ICPPClassTemplatePartialSpecialization, ICPPSpecialization { implements ICPPClassTemplatePartialSpecialization, ICPPSpecialization {
private ICPPTemplateArgument[] arguments; private final ICPPTemplateArgument[] arguments;
public CPPClassTemplatePartialSpecialization(ICPPASTTemplateId name) { public CPPClassTemplatePartialSpecialization(ICPPASTTemplateId name, ICPPTemplateArgument[] arguments) {
super(name); super(name);
this.arguments= arguments;
} }
@Override @Override
public ICPPTemplateArgument[] getTemplateArguments() throws DOMException { public ICPPTemplateArgument[] getTemplateArguments() throws DOMException {
if (arguments == null) {
arguments= CPPTemplates.createTemplateArgumentArray((ICPPASTTemplateId) getTemplateName());
}
return arguments; return arguments;
} }

View file

@ -224,7 +224,7 @@ public abstract class CPPTemplateDefinition extends PlatformObject implements IC
for (ICPPASTTemplateParameter param : params) { for (ICPPASTTemplateParameter param : params) {
p= CPPTemplates.getTemplateParameterName(param).resolveBinding(); p= CPPTemplates.getTemplateParameterName(param).resolveBinding();
if (p instanceof ICPPTemplateParameter) { if (p instanceof ICPPTemplateParameter) {
result = (ICPPTemplateParameter[]) ArrayUtil.append(ICPPTemplateParameter.class, result, p); result = ArrayUtil.append(ICPPTemplateParameter.class, result, (ICPPTemplateParameter) p);
} }
} }
templateParameters = ArrayUtil.trim(ICPPTemplateParameter.class, result); templateParameters = ArrayUtil.trim(ICPPTemplateParameter.class, result);

View file

@ -79,14 +79,14 @@ public class CPPTemplateTemplateParameter extends CPPTemplateParameter implement
if (templateParameters == null) { if (templateParameters == null) {
ICPPASTTemplatedTypeTemplateParameter template = (ICPPASTTemplatedTypeTemplateParameter) getPrimaryDeclaration().getParent(); ICPPASTTemplatedTypeTemplateParameter template = (ICPPASTTemplatedTypeTemplateParameter) getPrimaryDeclaration().getParent();
ICPPASTTemplateParameter[] params = template.getTemplateParameters(); ICPPASTTemplateParameter[] params = template.getTemplateParameters();
ICPPTemplateParameter[] result = null; ICPPTemplateParameter[] result = ICPPTemplateParameter.EMPTY_TEMPLATE_PARAMETER_ARRAY;
for (ICPPASTTemplateParameter param : params) { for (ICPPASTTemplateParameter param : params) {
IBinding binding = CPPTemplates.getTemplateParameterName(param).resolvePreBinding(); IBinding binding = CPPTemplates.getTemplateParameterName(param).resolvePreBinding();
if (binding instanceof ICPPTemplateParameter) { if (binding instanceof ICPPTemplateParameter) {
result = (ICPPTemplateParameter[]) ArrayUtil.append(ICPPTemplateParameter.class, result, binding); result = ArrayUtil.append(result, (ICPPTemplateParameter) binding);
} }
} }
templateParameters = ArrayUtil.trim(ICPPTemplateParameter.class, result); templateParameters = ArrayUtil.trim(result);
} }
return templateParameters; return templateParameters;
} }

View file

@ -221,7 +221,7 @@ public class ClassTypeHelper {
for (IASTDeclarator dtor : dtors) { for (IASTDeclarator dtor : dtors) {
binding = ASTQueries.findInnermostDeclarator(dtor).getName().resolveBinding(); binding = ASTQueries.findInnermostDeclarator(dtor).getName().resolveBinding();
if (binding instanceof ICPPField) if (binding instanceof ICPPField)
result = (ICPPField[]) ArrayUtil.append(ICPPField.class, result, binding); result = ArrayUtil.append(ICPPField.class, result, (ICPPField) binding);
} }
} else if (decl instanceof ICPPASTUsingDeclaration) { } else if (decl instanceof ICPPASTUsingDeclaration) {
IASTName n = ((ICPPASTUsingDeclaration)decl).getName(); IASTName n = ((ICPPASTUsingDeclaration)decl).getName();
@ -230,10 +230,10 @@ public class ClassTypeHelper {
IBinding[] bs = ((ICPPUsingDeclaration)binding).getDelegates(); IBinding[] bs = ((ICPPUsingDeclaration)binding).getDelegates();
for (IBinding element : bs) { for (IBinding element : bs) {
if (element instanceof ICPPField) if (element instanceof ICPPField)
result = (ICPPField[]) ArrayUtil.append(ICPPField.class, result, element); result = ArrayUtil.append(ICPPField.class, result, (ICPPField) element);
} }
} else if (binding instanceof ICPPField) { } else if (binding instanceof ICPPField) {
result = (ICPPField[]) ArrayUtil.append(ICPPField.class, result, binding); result = ArrayUtil.append(ICPPField.class, result, (ICPPField) binding);
} }
} }
} }
@ -349,7 +349,7 @@ public class ClassTypeHelper {
for (IASTDeclarator dtor : dtors) { for (IASTDeclarator dtor : dtors) {
binding = ASTQueries.findInnermostDeclarator(dtor).getName().resolveBinding(); binding = ASTQueries.findInnermostDeclarator(dtor).getName().resolveBinding();
if (binding instanceof ICPPMethod) if (binding instanceof ICPPMethod)
result = (ICPPMethod[]) ArrayUtil.append(ICPPMethod.class, result, binding); result = ArrayUtil.append(ICPPMethod.class, result, (ICPPMethod) binding);
} }
} }
} else if (decl instanceof IASTFunctionDefinition) { } else if (decl instanceof IASTFunctionDefinition) {
@ -359,7 +359,7 @@ public class ClassTypeHelper {
dtor = ASTQueries.findInnermostDeclarator(dtor); dtor = ASTQueries.findInnermostDeclarator(dtor);
binding = dtor.getName().resolveBinding(); binding = dtor.getName().resolveBinding();
if (binding instanceof ICPPMethod) { if (binding instanceof ICPPMethod) {
result = (ICPPMethod[]) ArrayUtil.append(ICPPMethod.class, result, binding); result = ArrayUtil.append(ICPPMethod.class, result, (ICPPMethod) binding);
} }
} }
} else if (decl instanceof ICPPASTUsingDeclaration) { } else if (decl instanceof ICPPASTUsingDeclaration) {
@ -369,10 +369,10 @@ public class ClassTypeHelper {
IBinding[] bs = ((ICPPUsingDeclaration)binding).getDelegates(); IBinding[] bs = ((ICPPUsingDeclaration)binding).getDelegates();
for (IBinding element : bs) { for (IBinding element : bs) {
if (element instanceof ICPPMethod) if (element instanceof ICPPMethod)
result = (ICPPMethod[]) ArrayUtil.append(ICPPMethod.class, result, element); result = ArrayUtil.append(ICPPMethod.class, result, (ICPPMethod) element);
} }
} else if (binding instanceof ICPPMethod) { } else if (binding instanceof ICPPMethod) {
result = (ICPPMethod[]) ArrayUtil.append(ICPPMethod.class, result, binding); result = ArrayUtil.append(ICPPMethod.class, result, (ICPPMethod) binding);
} }
} }
} }
@ -418,7 +418,7 @@ public class ClassTypeHelper {
binding = ((ICPPASTElaboratedTypeSpecifier)declSpec).getName().resolveBinding(); binding = ((ICPPASTElaboratedTypeSpecifier)declSpec).getName().resolveBinding();
} }
if (binding instanceof ICPPClassType) if (binding instanceof ICPPClassType)
result = (ICPPClassType[])ArrayUtil.append(ICPPClassType.class, result, binding); result = ArrayUtil.append(ICPPClassType.class, result, (ICPPClassType) binding);
} }
} }
return ArrayUtil.trim(ICPPClassType.class, result); return ArrayUtil.trim(ICPPClassType.class, result);

View file

@ -19,7 +19,17 @@ 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.core.dom.ast.IASTExpression.ValueCategory.PRVALUE;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.typeOrFunctionSet; import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.typeOrFunctionSet;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.valueCat; import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.valueCat;
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.ARRAY;
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.MPTR;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.PTR;
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.calculateInheritanceDepth;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.getNestedType;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.getUltimateTypeUptoPointers;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.isConversionOperator;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -1782,10 +1792,11 @@ public class CPPSemantics {
IBinding[] result = null; IBinding[] result = null;
for (Object binding : bindings) { for (Object binding : bindings) {
if (binding instanceof IASTName) if (binding instanceof IASTName) {
result = ArrayUtil.append(IBinding.class, result, ((IASTName) binding).resolveBinding()); result = ArrayUtil.append(IBinding.class, result, ((IASTName) binding).resolveBinding());
else if (binding instanceof IBinding) } else if (binding instanceof IBinding) {
result = (IBinding[]) ArrayUtil.append(IBinding.class, result, binding); result = ArrayUtil.append(IBinding.class, result, (IBinding) binding);
}
} }
return new CPPCompositeBinding(result); return new CPPCompositeBinding(result);
} }
@ -2019,13 +2030,13 @@ public class CPPSemantics {
} }
} }
IBinding[] bindings = null; IBinding[] bindings = IBinding.EMPTY_BINDING_ARRAY;
if (cmp > 0) { if (cmp > 0) {
bindings = ArrayUtil.append(IBinding.class, bindings, obj); bindings = ArrayUtil.append(bindings, obj);
bindings = ArrayUtil.append(IBinding.class, bindings, type); bindings = ArrayUtil.append(bindings, type);
} else { } else {
bindings = ArrayUtil.append(IBinding.class, bindings, type); bindings = ArrayUtil.append(bindings, type);
bindings = (IBinding[]) ArrayUtil.addAll(IBinding.class, bindings, fns.keyArray()); bindings = ArrayUtil.addAll(bindings, fns.keyArray());
} }
bindings = ArrayUtil.trim(IBinding.class, bindings); bindings = ArrayUtil.trim(IBinding.class, bindings);
ICPPUsingDeclaration composite = new CPPUsingDeclaration(data.astName, bindings); ICPPUsingDeclaration composite = new CPPUsingDeclaration(data.astName, bindings);

View file

@ -531,7 +531,7 @@ public class CPPTemplates {
while (parent.getParent() instanceof ICPPASTTemplateDeclaration) { while (parent.getParent() instanceof ICPPASTTemplateDeclaration) {
parent = parent.getParent(); parent = parent.getParent();
templates = (ICPPASTTemplateDeclaration[]) ArrayUtil.append(ICPPASTTemplateDeclaration.class, templates, parent); templates = ArrayUtil.append(ICPPASTTemplateDeclaration.class, templates, (ICPPASTTemplateDeclaration) parent);
} }
templates = ArrayUtil.trim(ICPPASTTemplateDeclaration.class, templates); templates = ArrayUtil.trim(ICPPASTTemplateDeclaration.class, templates);
@ -677,10 +677,14 @@ public class CPPTemplates {
if (argsAreTrivial(classTemplate.getTemplateParameters(), args)) { if (argsAreTrivial(classTemplate.getTemplateParameters(), args)) {
result= classTemplate; result= classTemplate;
} else { } else {
args= addDefaultArguments(classTemplate, args);
if (args == null) {
return new ProblemBinding(id, IProblemBinding.SEMANTIC_INVALID_TEMPLATE_ARGUMENTS, templateName.toCharArray());
}
ICPPClassTemplatePartialSpecialization partialSpec= findPartialSpecialization(classTemplate, args); ICPPClassTemplatePartialSpecialization partialSpec= findPartialSpecialization(classTemplate, args);
if (isDeclaration || isDefinition) { if (isDeclaration || isDefinition) {
if (partialSpec == null) { if (partialSpec == null) {
partialSpec = new CPPClassTemplatePartialSpecialization(id); partialSpec = new CPPClassTemplatePartialSpecialization(id, args);
if (template instanceof ICPPInternalClassTemplate) if (template instanceof ICPPInternalClassTemplate)
((ICPPInternalClassTemplate) template).addPartialSpecialization(partialSpec); ((ICPPInternalClassTemplate) template).addPartialSpecialization(partialSpec);
return partialSpec; return partialSpec;

View file

@ -35,7 +35,6 @@ import org.eclipse.cdt.internal.core.dom.parser.VariableReadWriteFlags;
* with the variable. * with the variable.
*/ */
public final class CPPVariableReadWriteFlags extends VariableReadWriteFlags { public final class CPPVariableReadWriteFlags extends VariableReadWriteFlags {
private static CPPVariableReadWriteFlags INSTANCE= new CPPVariableReadWriteFlags(); private static CPPVariableReadWriteFlags INSTANCE= new CPPVariableReadWriteFlags();
public static int getReadWriteFlags(IASTName variable) { public static int getReadWriteFlags(IASTName variable) {
@ -109,8 +108,7 @@ public final class CPPVariableReadWriteFlags extends VariableReadWriteFlags {
if (indirection == 0) { if (indirection == 0) {
if (type instanceof IQualifierType) { if (type instanceof IQualifierType) {
return ((IQualifierType) type).isConst() ? READ : READ | WRITE; return ((IQualifierType) type).isConst() ? READ : READ | WRITE;
} } else if (type instanceof IPointerType) {
else if (type instanceof IPointerType) {
return ((IPointerType) type).isConst() ? READ : READ | WRITE; return ((IPointerType) type).isConst() ? READ : READ | WRITE;
} }
} }

View file

@ -13,7 +13,11 @@
*******************************************************************************/ *******************************************************************************/
package org.eclipse.cdt.internal.core.dom.parser.cpp.semantics; package org.eclipse.cdt.internal.core.dom.parser.cpp.semantics;
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.TDEF;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.getNestedType;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.getUltimateTypeUptoPointers;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@ -209,6 +213,7 @@ public class CPPVisitor extends ASTQueries {
private static final char[] PTRDIFF_T = "ptrdiff_t".toCharArray(); //$NON-NLS-1$ private static final char[] PTRDIFF_T = "ptrdiff_t".toCharArray(); //$NON-NLS-1$
private static final char[] TYPE_INFO= "type_info".toCharArray(); //$NON-NLS-1$ private static final char[] TYPE_INFO= "type_info".toCharArray(); //$NON-NLS-1$
private static final char[] INITIALIZER_LIST = "initializer_list".toCharArray(); //$NON-NLS-1$ private static final char[] INITIALIZER_LIST = "initializer_list".toCharArray(); //$NON-NLS-1$
private static final char[][] EMPTY_CHAR_ARRAY_ARRAY = {};
public static final IASTInitializerClause[] NO_ARGS = {}; public static final IASTInitializerClause[] NO_ARGS = {};
// Thread-local set of DeclSpecifiers for which auto types are being created. // Thread-local set of DeclSpecifiers for which auto types are being created.
@ -2301,7 +2306,8 @@ public class CPPVisitor extends ASTQueries {
} }
public static char[][] getQualifiedNameCharArray(IBinding binding) { public static char[][] getQualifiedNameCharArray(IBinding binding) {
char[][] ns = null; char[][] ns = EMPTY_CHAR_ARRAY_ARRAY;
ns = ArrayUtil.append(ns, binding.getNameCharArray());
for (IBinding owner= binding.getOwner(); owner != null; owner= owner.getOwner()) { for (IBinding owner= binding.getOwner(); owner != null; owner= owner.getOwner()) {
char[] n= owner.getNameCharArray(); char[] n= owner.getNameCharArray();
if (n == null) if (n == null)
@ -2311,16 +2317,11 @@ public class CPPVisitor extends ASTQueries {
if (owner instanceof ICPPNamespace && n.length == 0) if (owner instanceof ICPPNamespace && n.length == 0)
continue; continue;
ns = ArrayUtil.append(n.getClass(), ns, n); ns = ArrayUtil.append(ns, n);
} }
final char[] bname = binding.getNameCharArray(); ns = ArrayUtil.trim(ns);
ns = ArrayUtil.trim(bname.getClass(), ns); ArrayUtil.reverse(ns);
char[][] result = new char[ns.length + 1][]; return ns;
for (int i = ns.length - 1; i >= 0; i--) {
result[ns.length - i - 1] = ns[i];
}
result[ns.length]= bname;
return result;
} }
private static IScope getParentScope(IScope scope, IASTTranslationUnit unit) throws DOMException { private static IScope getParentScope(IScope scope, IASTTranslationUnit unit) throws DOMException {

View file

@ -12,7 +12,8 @@
*******************************************************************************/ *******************************************************************************/
package org.eclipse.cdt.internal.core.dom.rewrite.commenthandler; package org.eclipse.cdt.internal.core.dom.rewrite.commenthandler;
import java.util.Vector; import java.util.ArrayList;
import java.util.List;
import org.eclipse.cdt.core.dom.ast.ASTVisitor; import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTComment; import org.eclipse.cdt.core.dom.ast.IASTComment;
@ -63,13 +64,13 @@ public class NodeCommenter {
protected ASTVisitor visitor; protected ASTVisitor visitor;
protected CommentHandler commHandler; protected CommentHandler commHandler;
protected NodeCommentMap commentMap; protected NodeCommentMap commentMap;
protected Vector<IASTNode> children; protected List<IASTNode> children;
public NodeCommenter(ASTVisitor visitor, CommentHandler commHandler, NodeCommentMap commentMap) { public NodeCommenter(ASTVisitor visitor, CommentHandler commHandler, NodeCommentMap commentMap) {
this.visitor = visitor; this.visitor = visitor;
this.commHandler = commHandler; this.commHandler = commHandler;
this.commentMap = commentMap; this.commentMap = commentMap;
this.children = new Vector<IASTNode>(); this.children = new ArrayList<IASTNode>();
} }
protected void writeNodeList(IASTNode[] nodes) { protected void writeNodeList(IASTNode[] nodes) {

View file

@ -50,10 +50,9 @@ public class CompositeCPPClassTemplate extends CompositeCPPClassType
System.arraycopy(ss, 0, preresult[i], 0, ss.length); System.arraycopy(ss, 0, preresult[i], 0, ss.length);
} }
return (ICPPClassTemplatePartialSpecialization[]) ArrayUtil.addAll( return ArrayUtil.addAll(
ICPPClassTemplatePartialSpecialization.class, ICPPClassTemplatePartialSpecialization.EMPTY_PARTIAL_SPECIALIZATION_ARRAY,
ICPPClassTemplatePartialSpecialization.EMPTY_PARTIAL_SPECIALIZATION_ARRAY, cf cf.getCompositeBindings(preresult));
.getCompositeBindings(preresult));
} catch (CoreException ce) { } catch (CoreException ce) {
CCorePlugin.log(ce); CCorePlugin.log(ce);
return ICPPClassTemplatePartialSpecialization.EMPTY_PARTIAL_SPECIALIZATION_ARRAY; return ICPPClassTemplatePartialSpecialization.EMPTY_PARTIAL_SPECIALIZATION_ARRAY;
@ -97,5 +96,4 @@ public class CompositeCPPClassTemplate extends CompositeCPPClassType
ICPPTemplateArgument[] args = CPPTemplates.templateParametersAsArguments(getTemplateParameters()); ICPPTemplateArgument[] args = CPPTemplates.templateParametersAsArguments(getTemplateParameters());
return new CPPDeferredClassInstance(this, args, getCompositeScope()); return new CPPDeferredClassInstance(this, args, getCompositeScope());
} }
} }

View file

@ -22,6 +22,7 @@ import org.eclipse.cdt.core.parser.FileContent;
import org.eclipse.cdt.core.parser.IScannerInfo; import org.eclipse.cdt.core.parser.IScannerInfo;
import org.eclipse.cdt.internal.core.index.IndexFileLocation; import org.eclipse.cdt.internal.core.index.IndexFileLocation;
import org.eclipse.cdt.internal.core.parser.InternalParserUtil; import org.eclipse.cdt.internal.core.parser.InternalParserUtil;
import org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask.UnusedHeaderStrategy;
import org.eclipse.cdt.internal.core.pdom.IndexerInputAdapter; import org.eclipse.cdt.internal.core.pdom.IndexerInputAdapter;
import org.eclipse.cdt.internal.core.pdom.indexer.FileExistsCache; import org.eclipse.cdt.internal.core.pdom.indexer.FileExistsCache;
import org.eclipse.cdt.utils.UNCPathConverter; import org.eclipse.cdt.utils.UNCPathConverter;
@ -178,7 +179,7 @@ public class StandaloneIndexerInputAdapter extends IndexerInputAdapter {
} }
@Override @Override
public AbstractLanguage[] getLanguages(Object tu, boolean bothForHeaders) { public AbstractLanguage[] getLanguages(Object tu, UnusedHeaderStrategy strat) {
ILanguage language = fIndexer.getLanguageMapper().getLanguage(tu.toString()); ILanguage language = fIndexer.getLanguageMapper().getLanguage(tu.toString());
if (language instanceof AbstractLanguage) { if (language instanceof AbstractLanguage) {
return new AbstractLanguage[] {(AbstractLanguage) language}; return new AbstractLanguage[] {(AbstractLanguage) language};

View file

@ -105,21 +105,35 @@ abstract class ASTPreprocessorNode extends ASTNode {
@Override @Override
public String toString() { public String toString() {
return String.valueOf(getSource(getOffset(), getLength())); return String.valueOf(getRawSignatureChars());
} }
} }
class ASTComment extends ASTPreprocessorNode implements IASTComment { class ASTComment extends ASTPreprocessorNode implements IASTComment {
private final boolean fIsBlockComment; private final boolean fIsBlockComment;
public ASTComment(IASTTranslationUnit parent, int startNumber, int endNumber, boolean isBlockComment) { private String fFilePath;
super(parent, IASTTranslationUnit.PREPROCESSOR_STATEMENT, startNumber, endNumber); public ASTComment(IASTTranslationUnit parent, String filePath, int offset, int endOffset, boolean isBlockComment) {
super(parent, IASTTranslationUnit.PREPROCESSOR_STATEMENT, offset, endOffset);
fIsBlockComment= isBlockComment; fIsBlockComment= isBlockComment;
fFilePath= filePath;
}
@Override
public int getOffset() {
if (fFilePath != null) {
// Perform lazy conversion to sequence number
ILocationResolver lr= (ILocationResolver) getTranslationUnit().getAdapter(ILocationResolver.class);
if (lr != null) {
setOffset(lr.getSequenceNumberForFileOffset(fFilePath, super.getOffset()));
fFilePath= null;
}
}
return super.getOffset();
} }
@Override @Override
public char[] getComment() { public char[] getComment() {
return getSource(getOffset(), getLength()); return getRawSignatureChars();
} }
@Override @Override

View file

@ -245,9 +245,7 @@ public class LocationMap implements ILocationResolver {
} }
public void encounteredComment(int offset, int endOffset, boolean isBlockComment) { public void encounteredComment(int offset, int endOffset, boolean isBlockComment) {
offset= getSequenceNumberForOffset(offset); fComments.add(new ASTComment(fTranslationUnit, getCurrentFilePath(), offset, endOffset, isBlockComment));
endOffset= getSequenceNumberForOffset(endOffset);
fComments.add(new ASTComment(fTranslationUnit, offset, endOffset, isBlockComment));
} }
public void encounterProblem(int id, char[] arg, int offset, int endOffset) { public void encounterProblem(int id, char[] arg, int offset, int endOffset) {

View file

@ -71,12 +71,12 @@ import org.eclipse.osgi.util.NLS;
* @since 5.0 * @since 5.0
*/ */
public abstract class AbstractIndexerTask extends PDOMWriter { public abstract class AbstractIndexerTask extends PDOMWriter {
protected static enum UnusedHeaderStrategy { public static enum UnusedHeaderStrategy {
skip, useDefaultLanguage, useAlternateLanguage, useBoth skip, useC, useCPP, useDefaultLanguage, useBoth
} }
private static final int MAX_ERRORS = 500; private static final int MAX_ERRORS = 500;
private static enum UpdateKind {REQUIRED_SOURCE, REQUIRED_HEADER, OTHER_HEADER} private static enum UpdateKind {REQUIRED_SOURCE, REQUIRED_HEADER, ONE_LINKAGE_HEADER, OTHER_HEADER}
private static class LinkageTask { private static class LinkageTask {
final int fLinkageID; final int fLinkageID;
private final Map<IIndexFileLocation, LocationTask> fLocationTasks; private final Map<IIndexFileLocation, LocationTask> fLocationTasks;
@ -87,13 +87,19 @@ public abstract class AbstractIndexerTask extends PDOMWriter {
} }
boolean requestUpdate(IIndexFileLocation ifl, IIndexFragmentFile ifile, Object tu, boolean requestUpdate(IIndexFileLocation ifl, IIndexFragmentFile ifile, Object tu,
UpdateKind kind) { UpdateKind kind, Map<IIndexFileLocation, LocationTask> oneLinkageTasks) {
LocationTask locTask= fLocationTasks.get(ifl); LocationTask locTask= fLocationTasks.get(ifl);
if (locTask == null) { if (locTask == null) {
locTask= new LocationTask(); locTask= new LocationTask();
fLocationTasks.put(ifl, locTask); fLocationTasks.put(ifl, locTask);
} }
return locTask.requestUpdate(ifile, tu, kind); boolean result = locTask.requestUpdate(ifile, tu, kind);
// Store one-linkage tasks.
if (kind == UpdateKind.ONE_LINKAGE_HEADER && locTask.fVersionTasks.isEmpty())
oneLinkageTasks.put(ifl, locTask);
return result;
} }
LocationTask find(IIndexFileLocation ifl) { LocationTask find(IIndexFileLocation ifl) {
@ -282,6 +288,7 @@ public abstract class AbstractIndexerTask extends PDOMWriter {
private List<LinkageTask> fRequestsPerLinkage= new ArrayList<LinkageTask>(); private List<LinkageTask> fRequestsPerLinkage= new ArrayList<LinkageTask>();
private Map<IIndexFile, IndexFileContent> fIndexContentCache= new LRUCache<IIndexFile, IndexFileContent>(500); private Map<IIndexFile, IndexFileContent> fIndexContentCache= new LRUCache<IIndexFile, IndexFileContent>(500);
private Map<IIndexFileLocation, IIndexFile[]> fIndexFilesCache= new LRUCache<IIndexFileLocation, IIndexFile[]>(5000); private Map<IIndexFileLocation, IIndexFile[]> fIndexFilesCache= new LRUCache<IIndexFileLocation, IIndexFile[]>(5000);
private Map<IIndexFileLocation, LocationTask> fOneLinkageTasks= new HashMap<IIndexFileLocation, AbstractIndexerTask.LocationTask>();
private Object[] fFilesToUpdate; private Object[] fFilesToUpdate;
private List<Object> fFilesToRemove = new ArrayList<Object>(); private List<Object> fFilesToRemove = new ArrayList<Object>();
@ -386,6 +393,8 @@ public abstract class AbstractIndexerTask extends PDOMWriter {
* @return array of linkage IDs that shall be parsed * @return array of linkage IDs that shall be parsed
*/ */
protected int[] getLinkagesToParse() { protected int[] getLinkagesToParse() {
if (fIndexHeadersWithoutContext == UnusedHeaderStrategy.useCPP)
return PDOMManager.IDS_FOR_LINKAGES_TO_INDEX_C_FIRST;
return PDOMManager.IDS_FOR_LINKAGES_TO_INDEX; return PDOMManager.IDS_FOR_LINKAGES_TO_INDEX;
} }
@ -494,6 +503,11 @@ public abstract class AbstractIndexerTask extends PDOMWriter {
final List<IIndexFileLocation> filesForLinkage = files.get(linkageID); final List<IIndexFileLocation> filesForLinkage = files.get(linkageID);
if (filesForLinkage != null) { if (filesForLinkage != null) {
parseLinkage(linkageID, filesForLinkage, monitor); parseLinkage(linkageID, filesForLinkage, monitor);
for (Iterator<LocationTask> it = fOneLinkageTasks.values().iterator(); it.hasNext();) {
LocationTask task = it.next();
if (task.isCompleted())
it.remove();
}
fIndexContentCache.clear(); fIndexContentCache.clear();
fIndexFilesCache.clear(); fIndexFilesCache.clear();
} }
@ -569,7 +583,7 @@ public abstract class AbstractIndexerTask extends PDOMWriter {
final boolean forceAll= (fUpdateFlags & IIndexManager.UPDATE_ALL) != 0; final boolean forceAll= (fUpdateFlags & IIndexManager.UPDATE_ALL) != 0;
final boolean checkTimestamps= (fUpdateFlags & IIndexManager.UPDATE_CHECK_TIMESTAMPS) != 0; final boolean checkTimestamps= (fUpdateFlags & IIndexManager.UPDATE_CHECK_TIMESTAMPS) != 0;
final boolean checkFileContentsHash = (fUpdateFlags & IIndexManager.UPDATE_CHECK_CONTENTS_HASH) != 0; final boolean checkFileContentsHash = (fUpdateFlags & IIndexManager.UPDATE_CHECK_CONTENTS_HASH) != 0;
final boolean both = fIndexHeadersWithoutContext == UnusedHeaderStrategy.useBoth;
int count= 0; int count= 0;
int forceFirst= fForceNumberFiles; int forceFirst= fForceNumberFiles;
BitSet linkages= new BitSet(); BitSet linkages= new BitSet();
@ -585,10 +599,14 @@ public abstract class AbstractIndexerTask extends PDOMWriter {
final IIndexFragmentFile[] indexFiles= fIndex.getWritableFiles(ifl); final IIndexFragmentFile[] indexFiles= fIndex.getWritableFiles(ifl);
final boolean isSourceUnit= fResolver.isSourceUnit(tu); final boolean isSourceUnit= fResolver.isSourceUnit(tu);
linkages.clear(); linkages.clear();
if (isRequiredInIndex(tu, ifl, isSourceUnit)) { final boolean regularContent = isRequiredInIndex(tu, ifl, isSourceUnit);
final boolean indexedUnconditionally = fResolver.isIndexedUnconditionally(ifl);
if (regularContent || indexedUnconditionally) {
// Headers or sources required with a specific linkage // Headers or sources required with a specific linkage
final UpdateKind updateKind = isSourceUnit ? UpdateKind.REQUIRED_SOURCE : UpdateKind.REQUIRED_HEADER; final UpdateKind updateKind = isSourceUnit ? UpdateKind.REQUIRED_SOURCE
AbstractLanguage[] langs= fResolver.getLanguages(tu, fIndexHeadersWithoutContext == UnusedHeaderStrategy.useBoth); : regularContent && both ? UpdateKind.REQUIRED_HEADER : UpdateKind.ONE_LINKAGE_HEADER;
if (regularContent || indexFiles.length == 0) {
AbstractLanguage[] langs= fResolver.getLanguages(tu, fIndexHeadersWithoutContext);
for (AbstractLanguage lang : langs) { for (AbstractLanguage lang : langs) {
int linkageID = lang.getLinkageID(); int linkageID = lang.getLinkageID();
boolean foundInLinkage = false; boolean foundInLinkage = false;
@ -610,12 +628,13 @@ public abstract class AbstractIndexerTask extends PDOMWriter {
} }
} }
} }
}
// Handle other files present in index. // Handle other files present in index.
for (IIndexFragmentFile ifile : indexFiles) { for (IIndexFragmentFile ifile : indexFiles) {
if (ifile != null) { if (ifile != null) {
IIndexInclude ctx= ifile.getParsedInContext(); IIndexInclude ctx= ifile.getParsedInContext();
if (ctx == null && !fResolver.isIndexedUnconditionally(ifile.getLocation())) { if (ctx == null && !indexedUnconditionally) {
iFilesToRemove.add(ifile); iFilesToRemove.add(ifile);
count++; count++;
} else { } else {
@ -656,10 +675,6 @@ public abstract class AbstractIndexerTask extends PDOMWriter {
if (fIndexHeadersWithoutContext != UnusedHeaderStrategy.skip) if (fIndexHeadersWithoutContext != UnusedHeaderStrategy.skip)
return true; return true;
// File required because it is open in the editor.
if (fResolver.isIndexedUnconditionally(ifl))
return true;
// Source file // Source file
if (isSourceUnit) { if (isSourceUnit) {
if (fIndexFilesWithoutConfiguration || fResolver.isFileBuildConfigured(tu)) if (fIndexFilesWithoutConfiguration || fResolver.isFileBuildConfigured(tu))
@ -689,7 +704,7 @@ public abstract class AbstractIndexerTask extends PDOMWriter {
private boolean requestUpdate(int linkageID, IIndexFileLocation ifl, IIndexFragmentFile ifile, Object tu, UpdateKind kind) { private boolean requestUpdate(int linkageID, IIndexFileLocation ifl, IIndexFragmentFile ifile, Object tu, UpdateKind kind) {
LinkageTask fileMap= createRequestMap(linkageID); LinkageTask fileMap= createRequestMap(linkageID);
return fileMap.requestUpdate(ifl, ifile, tu, kind); return fileMap.requestUpdate(ifl, ifile, tu, kind, fOneLinkageTasks);
} }
private LinkageTask createRequestMap(int linkageID) { private LinkageTask createRequestMap(int linkageID) {
@ -712,11 +727,13 @@ public abstract class AbstractIndexerTask extends PDOMWriter {
@Override @Override
protected void reportFileWrittenToIndex(FileInAST file, IIndexFragmentFile ifile) throws CoreException { protected void reportFileWrittenToIndex(FileInAST file, IIndexFragmentFile ifile) throws CoreException {
final FileContentKey fck = file.fFileContentKey; final FileContentKey fck = file.fFileContentKey;
final IIndexFileLocation location = fck.getLocation();
boolean wasCounted= false; boolean wasCounted= false;
UpdateKind kind= UpdateKind.OTHER_HEADER; UpdateKind kind= UpdateKind.OTHER_HEADER;
LinkageTask map = findRequestMap(fck.getLinkageID()); LinkageTask map = findRequestMap(fck.getLinkageID());
LocationTask locTask= null;
if (map != null) { if (map != null) {
LocationTask locTask = map.find(fck.getLocation()); locTask = map.find(location);
if (locTask != null) { if (locTask != null) {
kind= locTask.fKind; kind= locTask.fKind;
FileVersionTask v = locTask.findVersion(ifile); FileVersionTask v = locTask.findVersion(ifile);
@ -733,6 +750,21 @@ public abstract class AbstractIndexerTask extends PDOMWriter {
} }
fIndexContentCache.remove(ifile); fIndexContentCache.remove(ifile);
fIndexFilesCache.remove(file.fFileContentKey.getLocation()); fIndexFilesCache.remove(file.fFileContentKey.getLocation());
LocationTask task= fOneLinkageTasks.remove(location);
if (task != null && task != locTask) {
if (task.fKind == UpdateKind.ONE_LINKAGE_HEADER && !task.isCompleted()) {
task.fKind= UpdateKind.OTHER_HEADER;
if (task.isCompleted()) {
if (!wasCounted) {
kind= UpdateKind.ONE_LINKAGE_HEADER;
wasCounted= true;
} else {
reportFile(wasCounted, UpdateKind.ONE_LINKAGE_HEADER);
}
}
}
}
reportFile(wasCounted, kind); reportFile(wasCounted, kind);
} }
@ -989,7 +1021,7 @@ public abstract class AbstractIndexerTask extends PDOMWriter {
} }
private AbstractLanguage getLanguage(Object tu, int linkageID) { private AbstractLanguage getLanguage(Object tu, int linkageID) {
for (AbstractLanguage language : fResolver.getLanguages(tu, true)) { for (AbstractLanguage language : fResolver.getLanguages(tu, UnusedHeaderStrategy.useBoth)) {
if (language.getLinkageID() == linkageID) { if (language.getLinkageID() == linkageID) {
return language; return language;
} }

View file

@ -71,7 +71,7 @@ public abstract class IndexerInputAdapter extends ASTFilePathResolver {
/** /**
* Obtains the languages the input file should be parsed with. * Obtains the languages the input file should be parsed with.
*/ */
public abstract AbstractLanguage[] getLanguages(Object tu, boolean bothForHeaders); public abstract AbstractLanguage[] getLanguages(Object tu, AbstractIndexerTask.UnusedHeaderStrategy strat);
/** /**
* Obtains the scanner configuration for the input file. * Obtains the scanner configuration for the input file.

View file

@ -137,6 +137,9 @@ public class PDOMManager implements IWritableIndexManager, IListener {
public static final int[] IDS_FOR_LINKAGES_TO_INDEX = { public static final int[] IDS_FOR_LINKAGES_TO_INDEX = {
ILinkage.CPP_LINKAGE_ID, ILinkage.C_LINKAGE_ID, ILinkage.FORTRAN_LINKAGE_ID ILinkage.CPP_LINKAGE_ID, ILinkage.C_LINKAGE_ID, ILinkage.FORTRAN_LINKAGE_ID
}; };
public static final int[] IDS_FOR_LINKAGES_TO_INDEX_C_FIRST = {
ILinkage.C_LINKAGE_ID, ILinkage.CPP_LINKAGE_ID, ILinkage.FORTRAN_LINKAGE_ID
};
private final LinkedList<ICProject> fProjectQueue= new LinkedList<ICProject>(); private final LinkedList<ICProject> fProjectQueue= new LinkedList<ICProject>();
private final PDOMSetupJob fSetupJob; private final PDOMSetupJob fSetupJob;

View file

@ -24,6 +24,7 @@ import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.internal.core.index.IWritableIndex; import org.eclipse.cdt.internal.core.index.IWritableIndex;
import org.eclipse.cdt.internal.core.index.IWritableIndexManager; import org.eclipse.cdt.internal.core.index.IWritableIndexManager;
import org.eclipse.cdt.internal.core.model.CProject;
import org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask; import org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask;
import org.eclipse.cdt.internal.core.pdom.ITodoTaskUpdater; import org.eclipse.cdt.internal.core.pdom.ITodoTaskUpdater;
import org.eclipse.cdt.internal.core.pdom.IndexerProgress; import org.eclipse.cdt.internal.core.pdom.IndexerProgress;
@ -80,10 +81,11 @@ public abstract class PDOMIndexerTask extends AbstractIndexerTask implements IPD
boolean i1= checkProperty(IndexerPreferences.KEY_INDEX_UNUSED_HEADERS_WITH_DEFAULT_LANG); boolean i1= checkProperty(IndexerPreferences.KEY_INDEX_UNUSED_HEADERS_WITH_DEFAULT_LANG);
boolean i2= checkProperty(IndexerPreferences.KEY_INDEX_UNUSED_HEADERS_WITH_ALTERNATE_LANG); boolean i2= checkProperty(IndexerPreferences.KEY_INDEX_UNUSED_HEADERS_WITH_ALTERNATE_LANG);
UnusedHeaderStrategy strategy; UnusedHeaderStrategy strategy;
if (i1) { if (i1 == i2) {
strategy= i2 ? UnusedHeaderStrategy.useBoth : UnusedHeaderStrategy.useDefaultLanguage; strategy = i1 ? UnusedHeaderStrategy.useBoth : UnusedHeaderStrategy.skip;
} else { } else {
strategy= i2 ? UnusedHeaderStrategy.useAlternateLanguage: UnusedHeaderStrategy.skip; strategy = i1 == CProject.hasCCNature(getProject().getProject())
? UnusedHeaderStrategy.useCPP : UnusedHeaderStrategy.useC;
} }
setIndexHeadersWithoutContext(strategy); setIndexHeadersWithoutContext(strategy);
} else { } else {

View file

@ -30,6 +30,7 @@ import org.eclipse.cdt.core.parser.IScannerInfo;
import org.eclipse.cdt.core.parser.ScannerInfo; import org.eclipse.cdt.core.parser.ScannerInfo;
import org.eclipse.cdt.internal.core.CCoreInternals; import org.eclipse.cdt.internal.core.CCoreInternals;
import org.eclipse.cdt.internal.core.parser.InternalParserUtil; import org.eclipse.cdt.internal.core.parser.InternalParserUtil;
import org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask.UnusedHeaderStrategy;
import org.eclipse.cdt.internal.core.pdom.IndexerInputAdapter; import org.eclipse.cdt.internal.core.pdom.IndexerInputAdapter;
import org.eclipse.cdt.internal.core.resources.PathCanonicalizationStrategy; import org.eclipse.cdt.internal.core.resources.PathCanonicalizationStrategy;
import org.eclipse.cdt.utils.UNCPathConverter; import org.eclipse.cdt.utils.UNCPathConverter;
@ -193,7 +194,7 @@ public class ProjectIndexerInputAdapter extends IndexerInputAdapter {
} }
@Override @Override
public AbstractLanguage[] getLanguages(Object tuo, boolean bothForHeaders) { public AbstractLanguage[] getLanguages(Object tuo, UnusedHeaderStrategy strategy) {
if (tuo instanceof PotentialTranslationUnit) { if (tuo instanceof PotentialTranslationUnit) {
if (fLangC != null) { if (fLangC != null) {
if (fLangCpp != null) { if (fLangCpp != null) {
@ -211,14 +212,23 @@ public class ProjectIndexerInputAdapter extends IndexerInputAdapter {
try { try {
ILanguage lang= tu.getLanguage(); ILanguage lang= tu.getLanguage();
if (lang instanceof AbstractLanguage) { if (lang instanceof AbstractLanguage) {
if (bothForHeaders && tu.isHeaderUnit()) { final boolean both = strategy == UnusedHeaderStrategy.useBoth;
final boolean useC = strategy == UnusedHeaderStrategy.useC;
final boolean useCpp = strategy == UnusedHeaderStrategy.useCPP;
if ((both || useC || useCpp) && tu.isHeaderUnit()) {
String filename= tu.getElementName(); String filename= tu.getElementName();
if (filename.indexOf('.') >= 0) { if (filename.indexOf('.') >= 0) {
final String contentTypeId= tu.getContentTypeId(); final String contentTypeId= tu.getContentTypeId();
if (contentTypeId.equals(CCorePlugin.CONTENT_TYPE_CXXHEADER) && fLangC != null) { if (contentTypeId.equals(CCorePlugin.CONTENT_TYPE_CXXHEADER) && fLangC != null) {
if (both)
return new AbstractLanguage[] {(AbstractLanguage) lang, fLangC}; return new AbstractLanguage[] {(AbstractLanguage) lang, fLangC};
if (useC)
return new AbstractLanguage[] {fLangC};
} else if (contentTypeId.equals(CCorePlugin.CONTENT_TYPE_CHEADER) && fLangCpp != null) { } else if (contentTypeId.equals(CCorePlugin.CONTENT_TYPE_CHEADER) && fLangCpp != null) {
if (both)
return new AbstractLanguage[] {(AbstractLanguage) lang, fLangCpp}; return new AbstractLanguage[] {(AbstractLanguage) lang, fLangCpp};
if (useCpp)
return new AbstractLanguage[] {fLangCpp};
} }
} }
} }

View file

@ -95,7 +95,7 @@ public class CPPPopulateASTViewAction extends ASTGenericVisitor implements IPopu
if (node instanceof IASTProblemHolder) if (node instanceof IASTProblemHolder)
astProblems = ArrayUtil.append(IASTProblem.class, astProblems, ((IASTProblemHolder) node).getProblem()); astProblems = ArrayUtil.append(IASTProblem.class, astProblems, ((IASTProblemHolder) node).getProblem());
else else
astProblems = (IASTProblem[])ArrayUtil.append(IASTProblem.class, astProblems, node); astProblems = ArrayUtil.append(IASTProblem.class, astProblems, (IASTProblem) node);
} }
if (node instanceof IASTPreprocessorStatement) if (node instanceof IASTPreprocessorStatement)
tree.setFiltersFlag(DOMASTNodeLeaf.FLAG_PREPROCESSOR); tree.setFiltersFlag(DOMASTNodeLeaf.FLAG_PREPROCESSOR);

View file

@ -119,7 +119,7 @@ public class CPopulateASTViewAction extends ASTVisitor implements IPopulateDOMAS
if (node instanceof IASTProblemHolder) if (node instanceof IASTProblemHolder)
astProblems = ArrayUtil.append(IASTProblem.class, astProblems, ((IASTProblemHolder) node).getProblem()); astProblems = ArrayUtil.append(IASTProblem.class, astProblems, ((IASTProblemHolder) node).getProblem());
else else
astProblems = (IASTProblem[])ArrayUtil.append(IASTProblem.class, astProblems, node); astProblems = ArrayUtil.append(IASTProblem.class, astProblems, (IASTProblem) node);
} }
if (node instanceof IASTPreprocessorStatement) if (node instanceof IASTPreprocessorStatement)
tree.setFiltersFlag(DOMASTNodeLeaf.FLAG_PREPROCESSOR); tree.setFiltersFlag(DOMASTNodeLeaf.FLAG_PREPROCESSOR);

View file

@ -51,10 +51,10 @@ import org.eclipse.cdt.core.testplugin.util.TestSourceReader;
import org.eclipse.cdt.ui.testplugin.CTestPlugin; import org.eclipse.cdt.ui.testplugin.CTestPlugin;
import org.eclipse.cdt.ui.tests.BaseUITestCase; import org.eclipse.cdt.ui.tests.BaseUITestCase;
import org.eclipse.cdt.internal.ui.search.PDOMSearchPatternQuery; import org.eclipse.cdt.internal.ui.search.CSearchPatternQuery;
import org.eclipse.cdt.internal.ui.search.PDOMSearchQuery; import org.eclipse.cdt.internal.ui.search.CSearchQuery;
import org.eclipse.cdt.internal.ui.search.PDOMSearchResult; import org.eclipse.cdt.internal.ui.search.CSearchResult;
import org.eclipse.cdt.internal.ui.search.PDOMSearchViewPage; import org.eclipse.cdt.internal.ui.search.CSearchViewPage;
public class BasicSearchTest extends BaseUITestCase { public class BasicSearchTest extends BaseUITestCase {
ICProject fCProject; ICProject fCProject;
@ -109,15 +109,15 @@ public class BasicSearchTest extends BaseUITestCase {
assertTrue(CCorePlugin.getIndexManager().joinIndexer(360000, new NullProgressMonitor())); assertTrue(CCorePlugin.getIndexManager().joinIndexer(360000, new NullProgressMonitor()));
// open a query // open a query
PDOMSearchQuery query= makeProjectQuery("foo"); CSearchQuery query= makeProjectQuery("foo");
PDOMSearchResult result= runQuery(query); CSearchResult result= runQuery(query);
assertEquals(2, result.getElements().length); assertEquals(2, result.getElements().length);
ISearchResultViewPart vp= NewSearchUI.getSearchResultView(); ISearchResultViewPart vp= NewSearchUI.getSearchResultView();
ISearchResultPage page= vp.getActivePage(); ISearchResultPage page= vp.getActivePage();
assertTrue(""+page, page instanceof PDOMSearchViewPage); assertTrue(""+page, page instanceof CSearchViewPage);
PDOMSearchViewPage pdomsvp= (PDOMSearchViewPage) page; CSearchViewPage pdomsvp= (CSearchViewPage) page;
StructuredViewer viewer= pdomsvp.getViewer(); StructuredViewer viewer= pdomsvp.getViewer();
ILabelProvider labpv= (ILabelProvider) viewer.getLabelProvider(); ILabelProvider labpv= (ILabelProvider) viewer.getLabelProvider();
IStructuredContentProvider scp= (IStructuredContentProvider) viewer.getContentProvider(); IStructuredContentProvider scp= (IStructuredContentProvider) viewer.getContentProvider();
@ -152,15 +152,15 @@ public class BasicSearchTest extends BaseUITestCase {
assertTrue(CCorePlugin.getIndexManager().joinIndexer(360000, new NullProgressMonitor())); assertTrue(CCorePlugin.getIndexManager().joinIndexer(360000, new NullProgressMonitor()));
// open a query // open a query
PDOMSearchQuery query= makeProjectQuery("x"); CSearchQuery query= makeProjectQuery("x");
PDOMSearchResult result= runQuery(query); CSearchResult result= runQuery(query);
assertEquals(0, result.getElements().length); assertEquals(0, result.getElements().length);
ISearchResultViewPart vp= NewSearchUI.getSearchResultView(); ISearchResultViewPart vp= NewSearchUI.getSearchResultView();
ISearchResultPage page= vp.getActivePage(); ISearchResultPage page= vp.getActivePage();
assertTrue("" + page, page instanceof PDOMSearchViewPage); assertTrue("" + page, page instanceof CSearchViewPage);
PDOMSearchViewPage pdomsvp= (PDOMSearchViewPage) page; CSearchViewPage pdomsvp= (CSearchViewPage) page;
StructuredViewer viewer= pdomsvp.getViewer(); StructuredViewer viewer= pdomsvp.getViewer();
ILabelProvider labpv= (ILabelProvider) viewer.getLabelProvider(); ILabelProvider labpv= (ILabelProvider) viewer.getLabelProvider();
IStructuredContentProvider scp= (IStructuredContentProvider) viewer.getContentProvider(); IStructuredContentProvider scp= (IStructuredContentProvider) viewer.getContentProvider();
@ -229,8 +229,8 @@ public class BasicSearchTest extends BaseUITestCase {
*/ */
private void coreTestIndexerInProgress(boolean expectComplete) { private void coreTestIndexerInProgress(boolean expectComplete) {
// open a query // open a query
PDOMSearchQuery query= makeProjectQuery("data*"); CSearchQuery query= makeProjectQuery("data*");
PDOMSearchResult result= runQuery(query); CSearchResult result= runQuery(query);
final int maximumHits = INDEXER_IN_PROGRESS_FILE_COUNT * INDEXER_IN_PROGRESS_STRUCT_COUNT; final int maximumHits = INDEXER_IN_PROGRESS_FILE_COUNT * INDEXER_IN_PROGRESS_STRUCT_COUNT;
Object[] elements = result.getElements(); Object[] elements = result.getElements();
@ -241,9 +241,9 @@ public class BasicSearchTest extends BaseUITestCase {
ISearchResultViewPart vp= NewSearchUI.getSearchResultView(); ISearchResultViewPart vp= NewSearchUI.getSearchResultView();
ISearchResultPage page= vp.getActivePage(); ISearchResultPage page= vp.getActivePage();
assertTrue(""+page, page instanceof PDOMSearchViewPage); assertTrue(""+page, page instanceof CSearchViewPage);
PDOMSearchViewPage pdomsvp= (PDOMSearchViewPage) page; CSearchViewPage pdomsvp= (CSearchViewPage) page;
StructuredViewer viewer= pdomsvp.getViewer(); StructuredViewer viewer= pdomsvp.getViewer();
ILabelProvider labpv= (ILabelProvider) viewer.getLabelProvider(); ILabelProvider labpv= (ILabelProvider) viewer.getLabelProvider();
IStructuredContentProvider scp= (IStructuredContentProvider) viewer.getContentProvider(); IStructuredContentProvider scp= (IStructuredContentProvider) viewer.getContentProvider();
@ -281,7 +281,7 @@ public class BasicSearchTest extends BaseUITestCase {
* @param query * @param query
* @return * @return
*/ */
protected PDOMSearchResult runQuery(PDOMSearchQuery query) { protected CSearchResult runQuery(CSearchQuery query) {
final ISearchResult result[]= new ISearchResult[1]; final ISearchResult result[]= new ISearchResult[1];
IQueryListener listener= new IQueryListener() { IQueryListener listener= new IQueryListener() {
@Override @Override
@ -304,9 +304,9 @@ public class BasicSearchTest extends BaseUITestCase {
runnable.run(npm()); runnable.run(npm());
} }
}, query); }, query);
assertTrue(result[0] instanceof PDOMSearchResult); assertTrue(result[0] instanceof CSearchResult);
runEventQueue(500); runEventQueue(500);
return (PDOMSearchResult) result[0]; return (CSearchResult) result[0];
} }
// void foo() {} // void foo() {}
@ -315,7 +315,7 @@ public class BasicSearchTest extends BaseUITestCase {
// foo(); // foo();
// } // }
public void testNewResultsOnSearchAgainA() throws Exception { public void testNewResultsOnSearchAgainA() throws Exception {
PDOMSearchQuery query= makeProjectQuery("foo"); CSearchQuery query= makeProjectQuery("foo");
assertOccurrences(query, 2); assertOccurrences(query, 2);
assertOccurrences(query, 2); assertOccurrences(query, 2);
@ -332,7 +332,7 @@ public class BasicSearchTest extends BaseUITestCase {
// void bar() {foo();foo();foo();} // void bar() {foo();foo();foo();}
public void testNewResultsOnSearchAgainB() throws Exception { public void testNewResultsOnSearchAgainB() throws Exception {
PDOMSearchQuery query= makeProjectQuery("foo"); CSearchQuery query= makeProjectQuery("foo");
assertOccurrences(query, 4); assertOccurrences(query, 4);
assertOccurrences(query, 4); assertOccurrences(query, 4);
@ -355,14 +355,14 @@ public class BasicSearchTest extends BaseUITestCase {
assertOccurrences(query, 3); assertOccurrences(query, 3);
} }
private PDOMSearchQuery makeProjectQuery(String pattern) { private CSearchQuery makeProjectQuery(String pattern) {
String scope1= "Human Readable Description"; String scope1= "Human Readable Description";
return new PDOMSearchPatternQuery(new ICElement[] {fCProject}, scope1, pattern, true, PDOMSearchQuery.FIND_ALL_OCCURRENCES | PDOMSearchPatternQuery.FIND_ALL_TYPES); return new CSearchPatternQuery(new ICElement[] {fCProject}, scope1, pattern, true, CSearchQuery.FIND_ALL_OCCURRENCES | CSearchPatternQuery.FIND_ALL_TYPES);
} }
private void assertOccurrences(PDOMSearchQuery query, int expected) { private void assertOccurrences(CSearchQuery query, int expected) {
query.run(npm()); query.run(npm());
PDOMSearchResult result= (PDOMSearchResult) query.getSearchResult(); CSearchResult result= (CSearchResult) query.getSearchResult();
assertEquals(expected, result.getMatchCount()); assertEquals(expected, result.getMatchCount());
} }
@ -383,7 +383,7 @@ public class BasicSearchTest extends BaseUITestCase {
// f<int>(&a); // f<int>(&a);
// } // }
public void testSearchAndTemplateIDs() throws Exception { public void testSearchAndTemplateIDs() throws Exception {
PDOMSearchQuery query= makeProjectQuery("CT"); CSearchQuery query= makeProjectQuery("CT");
assertOccurrences(query, 5); assertOccurrences(query, 5);
query= makeProjectQuery("f"); query= makeProjectQuery("f");
assertOccurrences(query, 6); assertOccurrences(query, 6);

View file

@ -3069,7 +3069,7 @@
point="org.eclipse.search.searchPages"> point="org.eclipse.search.searchPages">
<page <page
canSearchEnclosingProjects="true" canSearchEnclosingProjects="true"
class="org.eclipse.cdt.internal.ui.search.PDOMSearchPage" class="org.eclipse.cdt.internal.ui.search.CSearchPage"
extensions="c:90,cpp:90, cxx:90, cc:90,C:90, h:90, hh:90, hpp:90, H:90" extensions="c:90,cpp:90, cxx:90, cc:90,C:90, h:90, hh:90, hpp:90, H:90"
icon="icons/obj16/csearch_obj.gif" icon="icons/obj16/csearch_obj.gif"
id="org.eclipse.cdt.ui.pdomSearchPage" id="org.eclipse.cdt.ui.pdomSearchPage"
@ -3248,9 +3248,9 @@
<extension <extension
point="org.eclipse.search.searchResultViewPages"> point="org.eclipse.search.searchResultViewPages">
<viewPage <viewPage
class="org.eclipse.cdt.internal.ui.search.PDOMSearchViewPage" class="org.eclipse.cdt.internal.ui.search.CSearchViewPage"
id="org.eclipse.cdt.ui.pdomSearchViewPage" id="org.eclipse.cdt.ui.pdomSearchViewPage"
searchResultClass="org.eclipse.cdt.internal.ui.search.PDOMSearchResult"/> searchResultClass="org.eclipse.cdt.internal.ui.search.CSearchResult"/>
</extension> </extension>
<extension <extension
@ -3335,7 +3335,7 @@
</page> </page>
<page <page
name="%CodeFormatterPreferencePage.name" name="%codeFormatterPreferencePage.name"
class="org.eclipse.cdt.internal.ui.preferences.CodeFormatterPreferencePage" class="org.eclipse.cdt.internal.ui.preferences.CodeFormatterPreferencePage"
category="org.eclipse.cdt.ui.newui.Page_head_general" category="org.eclipse.cdt.ui.newui.Page_head_general"
id="org.eclipse.cdt.ui.propertyPages.CodeFormatterPreferencePage"> id="org.eclipse.cdt.ui.propertyPages.CodeFormatterPreferencePage">

View file

@ -21,7 +21,7 @@ import org.eclipse.cdt.core.index.IIndexBinding;
import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.search.PDOMSearchQuery; import org.eclipse.cdt.internal.ui.search.CSearchQuery;
/** /**
* @author Doug Schaefer * @author Doug Schaefer
@ -57,7 +57,7 @@ public class FindDeclarationsAction extends IndexAction {
null, null,
cproject, indexView.getLastWriteAccess(cproject), cproject, indexView.getLastWriteAccess(cproject),
(IIndexBinding) binding.fObject, binding.fText, (IIndexBinding) binding.fObject, binding.fText,
PDOMSearchQuery.FIND_DECLARATIONS | PDOMSearchQuery.FIND_DEFINITIONS); CSearchQuery.FIND_DECLARATIONS | CSearchQuery.FIND_DEFINITIONS);
NewSearchUI.activateSearchResultView(); NewSearchUI.activateSearchResultView();
NewSearchUI.runQueryInBackground(query); NewSearchUI.runQueryInBackground(query);

View file

@ -12,7 +12,7 @@
package org.eclipse.cdt.internal.ui.indexview; package org.eclipse.cdt.internal.ui.indexview;
import org.eclipse.cdt.internal.ui.search.PDOMSearchQuery; import org.eclipse.cdt.internal.ui.search.CSearchQuery;
import org.eclipse.cdt.core.index.IIndexBinding; import org.eclipse.cdt.core.index.IIndexBinding;
import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ICProject;
@ -56,7 +56,7 @@ public class FindReferencesAction extends IndexAction {
null, null,
cproject, indexView.getLastWriteAccess(cproject), cproject, indexView.getLastWriteAccess(cproject),
(IIndexBinding) binding.fObject, binding.fText, (IIndexBinding) binding.fObject, binding.fText,
PDOMSearchQuery.FIND_REFERENCES); CSearchQuery.FIND_REFERENCES);
NewSearchUI.activateSearchResultView(); NewSearchUI.activateSearchResultView();
NewSearchUI.runQueryInBackground(query); NewSearchUI.runQueryInBackground(query);

View file

@ -27,14 +27,14 @@ import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.core.CCoreInternals; import org.eclipse.cdt.internal.core.CCoreInternals;
import org.eclipse.cdt.internal.ui.search.PDOMSearchQuery; import org.eclipse.cdt.internal.ui.search.CSearchQuery;
/** /**
* @author Doug Schaefer * @author Doug Schaefer
* *
* This is the search query to be used for searching the PDOM. * This is the search query to be used for searching the PDOM.
*/ */
public class IndexViewSearchQuery extends PDOMSearchQuery { public class IndexViewSearchQuery extends CSearchQuery {
private IIndexBinding fBinding; private IIndexBinding fBinding;
private long fLastWrite; private long fLastWrite;

View file

@ -35,7 +35,6 @@ public final class Messages extends NLS {
public static String Refactoring_CantLoadTU; public static String Refactoring_CantLoadTU;
public static String Refactoring_Ambiguity; public static String Refactoring_Ambiguity;
public static String Refactoring_ParsingError; public static String Refactoring_ParsingError;
public static String NodeContainer_Name;
public static String NO_FILE; public static String NO_FILE;
public static String RefactoringSaveHelper_unexpected_exception; public static String RefactoringSaveHelper_unexpected_exception;
public static String RefactoringSaveHelper_saving; public static String RefactoringSaveHelper_saving;

View file

@ -31,7 +31,6 @@ Refactoring_CantLoadTU=Can not load translation unit.
Refactoring_Ambiguity=Translation unit is ambiguous. Refactoring_Ambiguity=Translation unit is ambiguous.
Refactoring_ParsingError=Unable to parse {0}. Refactoring_ParsingError=Unable to parse {0}.
NO_FILE=File not found. NO_FILE=File not found.
NodeContainer_Name=name:
RefactoringSaveHelper_unexpected_exception=An unexpected exception occurred. See the error log for more details. RefactoringSaveHelper_unexpected_exception=An unexpected exception occurred. See the error log for more details.
RefactoringSaveHelper_saving=Saving Resources RefactoringSaveHelper_saving=Saving Resources
RefactoringSaveHelper_always_save=&Always save all modified resources automatically prior to refactoring RefactoringSaveHelper_always_save=&Always save all modified resources automatically prior to refactoring

View file

@ -50,14 +50,14 @@ import org.eclipse.cdt.internal.core.dom.rewrite.astwriter.ASTWriter;
public class NodeContainer { public class NodeContainer {
public final NameInformation NULL_NAME_INFORMATION = new NameInformation(new CPPASTName()); public final NameInformation NULL_NAME_INFORMATION = new NameInformation(new CPPASTName());
private final ArrayList<IASTNode> vec; private final List<IASTNode> nodes;
private final ArrayList<NameInformation> names; private final List<NameInformation> names;
public class NameInformation { public class NameInformation {
private IASTName name; private IASTName name;
private IASTName declaration; private IASTName declaration;
private final ArrayList<IASTName> references; private final List<IASTName> references;
private ArrayList<IASTName> referencesAfterCached; private List<IASTName> referencesAfterCached;
private int lastCachedReferencesHash; private int lastCachedReferencesHash;
private boolean isReference; private boolean isReference;
private boolean isReturnValue; private boolean isReturnValue;
@ -103,9 +103,8 @@ public class NodeContainer {
references.add(name); references.add(name);
} }
public ArrayList<IASTName> getReferencesAfterSelection() { public List<IASTName> getReferencesAfterSelection() {
if (referencesAfterCached == null if (referencesAfterCached == null || lastCachedReferencesHash != references.hashCode()) {
|| lastCachedReferencesHash != references.hashCode()) {
lastCachedReferencesHash = references.hashCode(); lastCachedReferencesHash = references.hashCode();
referencesAfterCached = new ArrayList<IASTName>(); referencesAfterCached = new ArrayList<IASTName>();
for (IASTName ref : references) { for (IASTName ref : references) {
@ -196,18 +195,17 @@ public class NodeContainer {
return writer.write(declSpec); return writer.write(declSpec);
} }
public boolean isDeclarationInScope() { public boolean isDeclarationExtracted() {
if (declaration != null && declaration.toCharArray().length > 0) { if (declaration != null && declaration.toCharArray().length > 0) {
int declOffset = declaration.getFileLocation().getNodeOffset(); int declOffset = declaration.getFileLocation().getNodeOffset();
return declOffset >= getStartOffset() return declOffset >= getStartOffset() && declOffset <= getEndOffset();
&& declOffset <= getEndOffset();
} }
return true; return true;
} }
@Override @Override
public String toString() { public String toString() {
return Messages.NodeContainer_Name + name + ' ' + isDeclarationInScope(); return name.toString() + ": " + (isDeclarationExtracted() ? "with declaration" : "without declaration"); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
} }
public boolean isReference() { public boolean isReference() {
@ -269,24 +267,24 @@ public class NodeContainer {
public NodeContainer() { public NodeContainer() {
super(); super();
vec = new ArrayList<IASTNode>(); nodes = new ArrayList<IASTNode>();
names = new ArrayList<NameInformation>(); names = new ArrayList<NameInformation>();
} }
public final int size() { public final int size() {
return vec.size(); return nodes.size();
} }
public final boolean isEmpty() { public final boolean isEmpty() {
return vec.isEmpty(); return nodes.isEmpty();
} }
public void add(IASTNode node) { public void add(IASTNode node) {
vec.add(node); nodes.add(node);
} }
public void findAllNames() { public void findAllNames() {
for (IASTNode node : vec) { for (IASTNode node : nodes) {
node.accept(new ASTVisitor() { node.accept(new ASTVisitor() {
{ {
shouldVisitNames = true; shouldVisitNames = true;
@ -343,7 +341,7 @@ public class NodeContainer {
* Returns all local names in the selection which will be used after the * Returns all local names in the selection which will be used after the
* selection expected the ones which are pointers * selection expected the ones which are pointers
*/ */
public ArrayList<NameInformation> getAllAfterUsedNames() { public List<NameInformation> getAllAfterUsedNames() {
ArrayList<IASTName> declarations = new ArrayList<IASTName>(); ArrayList<IASTName> declarations = new ArrayList<IASTName>();
ArrayList<NameInformation> usedAfter = new ArrayList<NameInformation>(); ArrayList<NameInformation> usedAfter = new ArrayList<NameInformation>();
@ -364,13 +362,12 @@ public class NodeContainer {
return usedAfter; return usedAfter;
} }
public ArrayList<NameInformation> getAllAfterUsedNamesChoosenByUser() { public List<NameInformation> getAllAfterUsedNamesChoosenByUser() {
ArrayList<IASTName> declarations = new ArrayList<IASTName>(); ArrayList<IASTName> declarations = new ArrayList<IASTName>();
ArrayList<NameInformation> usedAfter = new ArrayList<NameInformation>(); ArrayList<NameInformation> usedAfter = new ArrayList<NameInformation>();
for (NameInformation nameInf : names) { for (NameInformation nameInf : names) {
if (!declarations.contains(nameInf.getDeclaration())) { if (!declarations.contains(nameInf.getDeclaration())) {
declarations.add(nameInf.getDeclaration()); declarations.add(nameInf.getDeclaration());
if (nameInf.isUserSetIsReference() || nameInf.isUserSetIsReturnValue()) { if (nameInf.isUserSetIsReference() || nameInf.isUserSetIsReturnValue()) {
usedAfter.add(nameInf); usedAfter.add(nameInf);
@ -381,7 +378,7 @@ public class NodeContainer {
return usedAfter; return usedAfter;
} }
public ArrayList<NameInformation> getUsedNamesUnique() { public List<NameInformation> getUsedNamesUnique() {
ArrayList<IASTName> declarations = new ArrayList<IASTName>(); ArrayList<IASTName> declarations = new ArrayList<IASTName>();
ArrayList<NameInformation> usedAfter = new ArrayList<NameInformation>(); ArrayList<NameInformation> usedAfter = new ArrayList<NameInformation>();
@ -411,18 +408,19 @@ public class NodeContainer {
* selection expected the ones which are pointers * selection expected the ones which are pointers
* XXX Was soll dieser Kommentar aussagen? --Mirko * XXX Was soll dieser Kommentar aussagen? --Mirko
*/ */
public ArrayList<NameInformation> getAllDeclaredInScope() { public List<NameInformation> getAllDeclaredInScope() {
ArrayList<IASTName> declarations = new ArrayList<IASTName>(); ArrayList<IASTName> declarations = new ArrayList<IASTName>();
ArrayList<NameInformation> usedAfter = new ArrayList<NameInformation>(); ArrayList<NameInformation> usedAfter = new ArrayList<NameInformation>();
for (NameInformation nameInf : names) { for (NameInformation nameInfo : names) {
if (nameInf.isDeclarationInScope() if (nameInfo.isDeclarationExtracted() &&
&& !declarations.contains(nameInf.getDeclaration()) && nameInf.isUsedAfterReferences()) { !declarations.contains(nameInfo.getDeclaration()) &&
declarations.add(nameInf.getDeclaration()); nameInfo.isUsedAfterReferences()) {
usedAfter.add(nameInf); declarations.add(nameInfo.getDeclaration());
// is return value candidate, set return value to true and reference to false usedAfter.add(nameInfo);
nameInf.setReturnValue(true); // Is return value candidate, set return value to true and reference to false
nameInf.setReference(false); nameInfo.setReturnValue(true);
nameInfo.setReference(false);
} }
} }
@ -430,7 +428,7 @@ public class NodeContainer {
} }
public List<IASTNode> getNodesToWrite() { public List<IASTNode> getNodesToWrite() {
return vec; return nodes;
} }
public int getStartOffset() { public int getStartOffset() {
@ -444,7 +442,7 @@ public class NodeContainer {
private int getOffset(boolean includeComments) { private int getOffset(boolean includeComments) {
int start = Integer.MAX_VALUE; int start = Integer.MAX_VALUE;
for (IASTNode node : vec) { for (IASTNode node : nodes) {
int nodeStart = Integer.MAX_VALUE; int nodeStart = Integer.MAX_VALUE;
IASTNodeLocation[] nodeLocations = node.getNodeLocations(); IASTNodeLocation[] nodeLocations = node.getNodeLocations();
@ -483,7 +481,7 @@ public class NodeContainer {
private int getEndOffset(boolean includeComments) { private int getEndOffset(boolean includeComments) {
int end = 0; int end = 0;
for (IASTNode node : vec) { for (IASTNode node : nodes) {
int fileOffset = 0; int fileOffset = 0;
int length = 0; int length = 0;
@ -514,7 +512,7 @@ public class NodeContainer {
@Override @Override
public String toString() { public String toString() {
return vec.toString(); return nodes.toString();
} }
public List<NameInformation> getNames() { public List<NameInformation> getNames() {

View file

@ -12,6 +12,7 @@
package org.eclipse.cdt.internal.ui.refactoring.extractfunction; package org.eclipse.cdt.internal.ui.refactoring.extractfunction;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT; import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor; import org.eclipse.swt.custom.TableEditor;
@ -38,13 +39,13 @@ public class ChooserComposite extends Composite {
private Button voidReturn; private Button voidReturn;
private final ExtractFunctionInputPage ip; private final ExtractFunctionInputPage page;
public ChooserComposite(Composite parent, final ExtractFunctionInformation info, public ChooserComposite(Composite parent, final ExtractFunctionInformation info,
ExtractFunctionInputPage ip) { ExtractFunctionInputPage page) {
super(parent, SWT.NONE); super(parent, SWT.NONE);
this.ip = ip; this.page = page;
GridLayout layout = new GridLayout(); GridLayout layout = new GridLayout();
setLayout(layout); setLayout(layout);
@ -75,7 +76,7 @@ public class ChooserComposite extends Composite {
addColumnToTable(table, ""); //$NON-NLS-1$ addColumnToTable(table, ""); //$NON-NLS-1$
for (int i = 0; i < info.getAllUsedNames().size(); i++) { for (int i = 0; i < info.getAllUsedNames().size(); i++) {
if (!info.getAllUsedNames().get(i).isDeclarationInScope()) { if (!info.getAllUsedNames().get(i).isDeclarationExtracted()) {
TableItem item = new TableItem(table, SWT.NONE); TableItem item = new TableItem(table, SWT.NONE);
TableEditor editor = new TableEditor(table); TableEditor editor = new TableEditor(table);
@ -212,15 +213,15 @@ public class ChooserComposite extends Composite {
column.setWidth(100); column.setWidth(100);
} }
void onVisibilityOrReturnChange(ArrayList<NameInformation> name) { void onVisibilityOrReturnChange(List<NameInformation> name) {
String variableUsedAfterBlock = null; String variableUsedAfterBlock = null;
for (NameInformation information : name) { for (NameInformation information : name) {
if (information.isUsedAfterReferences() if (information.isUsedAfterReferences() &&
&& !(information.isUserSetIsReference() || information.isUserSetIsReturnValue())) { !(information.isUserSetIsReference() || information.isUserSetIsReturnValue())) {
variableUsedAfterBlock = information.getName().toString(); variableUsedAfterBlock = information.getName().toString();
} }
} }
ip.errorWithAfterUsedVariable(variableUsedAfterBlock); page.errorWithAfterUsedVariable(variableUsedAfterBlock);
} }
} }

View file

@ -53,7 +53,7 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPFunction;
import org.eclipse.cdt.internal.ui.refactoring.NodeContainer.NameInformation; import org.eclipse.cdt.internal.ui.refactoring.NodeContainer.NameInformation;
/** /**
* Handles the extraction of expression nodes, like return type determination. * Handles the extraction of expression nodes, for example, return type determination.
* *
* @author Mirko Stocker * @author Mirko Stocker
*/ */
@ -64,7 +64,8 @@ public class ExtractExpression extends ExtractedFunctionConstructionHelper {
public void constructMethodBody(IASTCompoundStatement compound, List<IASTNode> list, public void constructMethodBody(IASTCompoundStatement compound, List<IASTNode> list,
ASTRewrite rewrite, TextEditGroup group) { ASTRewrite rewrite, TextEditGroup group) {
CPPASTReturnStatement statement = new CPPASTReturnStatement(); CPPASTReturnStatement statement = new CPPASTReturnStatement();
IASTExpression nullReturnExp = new CPPASTLiteralExpression(IASTLiteralExpression.lk_integer_constant, ZERO); IASTExpression nullReturnExp =
new CPPASTLiteralExpression(IASTLiteralExpression.lk_integer_constant, ZERO);
statement.setReturnValue(nullReturnExp); statement.setReturnValue(nullReturnExp);
ASTRewrite nestedRewrite = rewrite.insertBefore(compound, null, statement, group); ASTRewrite nestedRewrite = rewrite.insertBefore(compound, null, statement, group);
@ -154,7 +155,7 @@ public class ExtractExpression extends ExtractedFunctionConstructionHelper {
} }
@Override @Override
protected boolean isReturnTypeAPointer(IASTNode node) { protected boolean hasPointerReturnType(IASTNode node) {
if (node instanceof ICPPASTNewExpression) { if (node instanceof ICPPASTNewExpression) {
return true; return true;
} else if (!(node instanceof IASTFunctionCallExpression)) { } else if (!(node instanceof IASTFunctionCallExpression)) {
@ -186,11 +187,13 @@ public class ExtractExpression extends ExtractedFunctionConstructionHelper {
} }
private static boolean hasDeclaration(CPPFunction function) { private static boolean hasDeclaration(CPPFunction function) {
return function != null && function.getDeclarations() != null && function.getDeclarations().length > 0; return function != null && function.getDeclarations() != null &&
function.getDeclarations().length > 0;
} }
@Override @Override
public IASTNode createReturnAssignment(IASTNode node, IASTExpressionStatement stmt, IASTExpression callExpression) { public IASTNode createReturnAssignment(IASTNode node, IASTExpressionStatement stmt,
IASTExpression callExpression) {
return callExpression; return callExpression;
} }
} }

View file

@ -12,6 +12,7 @@
package org.eclipse.cdt.internal.ui.refactoring.extractfunction; package org.eclipse.cdt.internal.ui.refactoring.extractfunction;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTFunctionDeclarator; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTFunctionDeclarator;
@ -20,15 +21,11 @@ import org.eclipse.cdt.internal.ui.refactoring.NodeContainer.NameInformation;
import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum; import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum;
public class ExtractFunctionInformation { public class ExtractFunctionInformation {
public final int VISIBILITY_PRIVATE = 1;
public final int VISIBILITY_PROTECTED = 3;
public final int VISIBILITY_PUBLIC = 2;
private VisibilityEnum visibility = VisibilityEnum.v_private; private VisibilityEnum visibility = VisibilityEnum.v_private;
private String methodName; private String methodName;
private boolean replaceDuplicates; private boolean replaceDuplicates;
private ArrayList<NameInformation> allAfterUsedNames; private List<NameInformation> allAfterUsedNames;
private ArrayList<NameInformation> allUsedNames; private List<NameInformation> allUsedNames;
private NameInformation inScopeDeclaredVariable; private NameInformation inScopeDeclaredVariable;
private NameInformation returnVariable; private NameInformation returnVariable;
private ICPPASTFunctionDeclarator declarator; private ICPPASTFunctionDeclarator declarator;
@ -65,7 +62,7 @@ public class ExtractFunctionInformation {
this.replaceDuplicates = replaceDuplicates; this.replaceDuplicates = replaceDuplicates;
} }
public ArrayList<NameInformation> getAllAfterUsedNames() { public List<NameInformation> getAllAfterUsedNames() {
if (allAfterUsedNames == null) { if (allAfterUsedNames == null) {
allAfterUsedNames = new ArrayList<NameInformation>(); allAfterUsedNames = new ArrayList<NameInformation>();
for (NameInformation name : getAllUsedNames()) { for (NameInformation name : getAllUsedNames()) {
@ -101,11 +98,11 @@ public class ExtractFunctionInformation {
this.inScopeDeclaredVariable = inScopeDeclaredVariable; this.inScopeDeclaredVariable = inScopeDeclaredVariable;
} }
public ArrayList<NameInformation> getAllUsedNames() { public List<NameInformation> getAllUsedNames() {
return allUsedNames; return allUsedNames;
} }
public void setAllUsedNames(ArrayList<NameInformation> allUsedNames) { public void setAllUsedNames(List<NameInformation> allUsedNames) {
this.allUsedNames = allUsedNames; this.allUsedNames = allUsedNames;
} }

View file

@ -17,7 +17,6 @@ import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Vector;
import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.resources.ResourcesPlugin;
@ -202,7 +201,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
info.getInScopeDeclaredVariable().setUserSetIsReturnValue(true); info.getInScopeDeclaredVariable().setUserSetIsReturnValue(true);
} }
for (int i = 0; i < info.getAllUsedNames().size(); i++) { for (int i = 0; i < info.getAllUsedNames().size(); i++) {
if (!info.getAllUsedNames().get(i).isDeclarationInScope()) { if (!info.getAllUsedNames().get(i).isDeclarationExtracted()) {
NameInformation name = info.getAllUsedNames().get(i); NameInformation name = info.getAllUsedNames().get(i);
if (!name.isReturnValue()) { if (!name.isReturnValue()) {
name.setUserSetIsReference(name.isReference()); name.setUserSetIsReference(name.isReference());
@ -434,7 +433,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
} }
} }
final Vector<IASTNode> initTrail = getTrail(nodesToRewriteWithoutComments); final List<IASTNode> initTrail = getTrail(nodesToRewriteWithoutComments);
final String title; final String title;
if (contextType == MethodContext.ContextType.METHOD) { if (contextType == MethodContext.ContextType.METHOD) {
title = Messages.ExtractFunctionRefactoring_CreateMethodCall; title = Messages.ExtractFunctionRefactoring_CreateMethodCall;
@ -448,8 +447,8 @@ public class ExtractFunctionRefactoring extends CRefactoring {
} }
} }
protected Vector<IASTNode> getTrail(List<IASTNode> stmts) { protected List<IASTNode> getTrail(List<IASTNode> stmts) {
final Vector<IASTNode> trail = new Vector<IASTNode>(); final List<IASTNode> trail = new ArrayList<IASTNode>();
nameTrail = new HashMap<String, Integer>(); nameTrail = new HashMap<String, Integer>();
final Container<Integer> trailCounter = new Container<Integer>(NULL_INTEGER); final Container<Integer> trailCounter = new Container<Integer>(NULL_INTEGER);
@ -465,8 +464,9 @@ public class ExtractFunctionRefactoring extends CRefactoring {
trail.add(node); trail.add(node);
return PROCESS_SKIP; return PROCESS_SKIP;
} else if (node instanceof IASTName) { } else if (node instanceof IASTName) {
if (node instanceof ICPPASTConversionName && node instanceof ICPPASTOperatorName if (node instanceof ICPPASTConversionName &&
&& node instanceof ICPPASTTemplateId) { node instanceof ICPPASTOperatorName &&
node instanceof ICPPASTTemplateId) {
trail.add(node); trail.add(node);
return super.visitAll(node); return super.visitAll(node);
} else { } else {
@ -483,8 +483,8 @@ public class ExtractFunctionRefactoring extends CRefactoring {
} }
trailName.setNameNumber(actCount); trailName.setNameNumber(actCount);
if (info.getReturnVariable() != null if (info.getReturnVariable() != null &&
&& info.getReturnVariable().getName().getRawSignature().equals( info.getReturnVariable().getName().getRawSignature().equals(
name.getRawSignature())) { name.getRawSignature())) {
returnNumber.setObject(Integer.valueOf(actCount)); returnNumber.setObject(Integer.valueOf(actCount));
} }
@ -498,13 +498,12 @@ public class ExtractFunctionRefactoring extends CRefactoring {
} }
} }
}); });
} }
return trail; return trail;
} }
protected boolean isStatementInTrail(IASTStatement stmt, final Vector<IASTNode> trail, IIndex index) { protected boolean isStatementInTrail(IASTStatement stmt, final List<IASTNode> trail, IIndex index) {
final Container<Boolean> same = new Container<Boolean>(Boolean.TRUE); final Container<Boolean> same = new Container<Boolean>(Boolean.TRUE);
final TrailNodeEqualityChecker equalityChecker = new TrailNodeEqualityChecker(names, namesCounter, index); final TrailNodeEqualityChecker equalityChecker = new TrailNodeEqualityChecker(names, namesCounter, index);
@ -591,8 +590,8 @@ public class ExtractFunctionRefactoring extends CRefactoring {
return true; return true;
} }
private void addMethod(IASTName astMethodName, MethodContext context, private void addMethod(IASTName astMethodName, MethodContext context, ASTRewrite rewriter,
ASTRewrite rewriter, IASTNode insertpoint, TextEditGroup group) { IASTNode insertpoint, TextEditGroup group) {
ICPPASTQualifiedName qname = new CPPASTQualifiedName(); ICPPASTQualifiedName qname = new CPPASTQualifiedName();
if (context.getType() == ContextType.METHOD) { if (context.getType() == ContextType.METHOD) {
if (context.getMethodQName() != null) { if (context.getMethodQName() != null) {
@ -609,10 +608,10 @@ public class ExtractFunctionRefactoring extends CRefactoring {
IASTDeclSpecifier returnType = getReturnType(); IASTDeclSpecifier returnType = getReturnType();
func.setDeclSpecifier(returnType); func.setDeclSpecifier(returnType);
IASTStandardFunctionDeclarator createdFunctionDeclarator = extractedFunctionConstructionHelper IASTStandardFunctionDeclarator createdFunctionDeclarator =
.createFunctionDeclarator(qname, info.getDeclarator(), info extractedFunctionConstructionHelper.createFunctionDeclarator(qname,
.getReturnVariable(), container.getNodesToWrite(), info info.getDeclarator(), info.getReturnVariable(), container.getNodesToWrite(),
.getAllUsedNames(), ast.getASTNodeFactory()); info.getAllUsedNames(), ast.getASTNodeFactory());
func.setDeclarator(createdFunctionDeclarator); func.setDeclarator(createdFunctionDeclarator);
IASTCompoundStatement compound = new CPPASTCompoundStatement(); IASTCompoundStatement compound = new CPPASTCompoundStatement();
@ -623,8 +622,8 @@ public class ExtractFunctionRefactoring extends CRefactoring {
CPPASTTemplateDeclaration templateDeclaration = new CPPASTTemplateDeclaration(); CPPASTTemplateDeclaration templateDeclaration = new CPPASTTemplateDeclaration();
templateDeclaration.setParent(ast); templateDeclaration.setParent(ast);
for (ICPPASTTemplateParameter templateParameter : ((ICPPASTTemplateDeclaration) insertpoint.getParent()).getTemplateParameters()) { for (ICPPASTTemplateParameter param : ((ICPPASTTemplateDeclaration) insertpoint.getParent()).getTemplateParameters()) {
templateDeclaration.addTemplateParameter(templateParameter.copy(CopyStyle.withLocations)); templateDeclaration.addTemplateParameter(param.copy(CopyStyle.withLocations));
} }
templateDeclaration.setDeclaration(func); templateDeclaration.setDeclaration(func);
@ -664,8 +663,8 @@ public class ExtractFunctionRefactoring extends CRefactoring {
private IASTDeclSpecifier getReturnType() { private IASTDeclSpecifier getReturnType() {
IASTNode firstNodeToWrite = container.getNodesToWrite().get(0); IASTNode firstNodeToWrite = container.getNodesToWrite().get(0);
NameInformation returnVariable = info.getReturnVariable(); NameInformation returnVariable = info.getReturnVariable();
return extractedFunctionConstructionHelper.determineReturnType(firstNodeToWrite,
return extractedFunctionConstructionHelper.determineReturnType(firstNodeToWrite, returnVariable); returnVariable);
} }
protected IASTNode getMethodCall(IASTName astMethodName, protected IASTNode getMethodCall(IASTName astMethodName,
@ -678,30 +677,28 @@ public class ExtractFunctionRefactoring extends CRefactoring {
idExpression.setName(astMethodName); idExpression.setName(astMethodName);
List<IASTInitializerClause> args = new ArrayList<IASTInitializerClause>(); List<IASTInitializerClause> args = new ArrayList<IASTInitializerClause>();
Vector<IASTName> declarations = new Vector<IASTName>(); List<IASTName> declarations = new ArrayList<IASTName>();
IASTName retName = null; IASTName retName = null;
boolean theRetName = false; boolean theRetName = false;
for (NameInformation nameInfo : myContainer.getNames()) { for (NameInformation nameInfo : myContainer.getNames()) {
Integer trailSeqNumber = trailNameTable.get(nameInfo.getDeclaration().getRawSignature()); Integer trailSeqNumber = trailNameTable.get(nameInfo.getDeclaration().getRawSignature());
String orgName = null; String origName = null;
for (Entry<String, Integer> entry : similarNameTable.entrySet()) { for (Entry<String, Integer> entry : similarNameTable.entrySet()) {
if (entry.getValue().equals(trailSeqNumber)) { if (entry.getValue().equals(trailSeqNumber)) {
orgName = entry.getKey(); origName = entry.getKey();
if (info.getReturnVariable() != null if (info.getReturnVariable() != null &&
&& trailSeqNumber.equals(returnNumber.getObject())) { trailSeqNumber.equals(returnNumber.getObject())) {
theRetName = true; theRetName = true;
} }
} }
} }
if (orgName != null) { if (origName != null) {
boolean found = false; boolean found = false;
for (NameInformation simNameInfo : mySimilarContainer.getNames()) { for (NameInformation simNameInfo : mySimilarContainer.getNames()) {
if (orgName.equals(simNameInfo.getDeclaration() if (origName.equals(simNameInfo.getDeclaration().getRawSignature())) {
.getRawSignature())) { addParameterIfPossible(args, declarations, simNameInfo);
addAParameterIfPossible(args, declarations,
simNameInfo);
found = true; found = true;
if (theRetName) { if (theRetName) {
@ -715,7 +712,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
if (!found) { if (!found) {
// should be a field, use the old name // should be a field, use the old name
IASTIdExpression expression = new CPPASTIdExpression(); IASTIdExpression expression = new CPPASTIdExpression();
CPPASTName fieldName = new CPPASTName(orgName.toCharArray()); CPPASTName fieldName = new CPPASTName(origName.toCharArray());
expression.setName(fieldName); expression.setName(fieldName);
args.add(expression); args.add(expression);
@ -763,7 +760,6 @@ public class ExtractFunctionRefactoring extends CRefactoring {
decl.setDeclSpecifier(orgDecl.getDeclSpecifier().copy(CopyStyle.withLocations)); decl.setDeclSpecifier(orgDecl.getDeclSpecifier().copy(CopyStyle.withLocations));
IASTDeclarator declarator = new CPPASTDeclarator(); IASTDeclarator declarator = new CPPASTDeclarator();
declarator.setName(retname); declarator.setName(retname);
for (IASTPointerOperator pointer : orgDecl.getDeclarators()[0].getPointerOperators()) { for (IASTPointerOperator pointer : orgDecl.getDeclarators()[0].getPointerOperators()) {
@ -792,16 +788,15 @@ public class ExtractFunctionRefactoring extends CRefactoring {
private IASTNode getReturnAssignment(IASTExpressionStatement stmt, private IASTNode getReturnAssignment(IASTExpressionStatement stmt,
IASTExpression callExpression) { IASTExpression callExpression) {
IASTNode node = container.getNodesToWrite().get(0); IASTNode node = container.getNodesToWrite().get(0);
return extractedFunctionConstructionHelper.createReturnAssignment(node, return extractedFunctionConstructionHelper.createReturnAssignment(node, stmt, callExpression);
stmt, callExpression);
} }
private IASTSimpleDeclaration getDeclaration(IASTName name) { private IASTSimpleDeclaration getDeclaration(IASTName name) {
IASTSimpleDeclaration simpleDecl = new CPPASTSimpleDeclaration(); IASTSimpleDeclaration simpleDecl = new CPPASTSimpleDeclaration();
IASTStandardFunctionDeclarator declarator = IASTStandardFunctionDeclarator declarator =
extractedFunctionConstructionHelper.createFunctionDeclarator(name, extractedFunctionConstructionHelper.createFunctionDeclarator(name,
info.getDeclarator(), info.getReturnVariable(), info.getDeclarator(), info.getReturnVariable(), container.getNodesToWrite(),
container.getNodesToWrite(), info.getAllUsedNames(), ast.getASTNodeFactory()); info.getAllUsedNames(), ast.getASTNodeFactory());
simpleDecl.addDeclarator(declarator); simpleDecl.addDeclarator(declarator);
return simpleDecl; return simpleDecl;
} }
@ -813,10 +808,10 @@ public class ExtractFunctionRefactoring extends CRefactoring {
((ICPPASTDeclSpecifier) declSpec).setVirtual(true); ((ICPPASTDeclSpecifier) declSpec).setVirtual(true);
} }
simpleDecl.setParent(ast); simpleDecl.setParent(ast);
IASTStandardFunctionDeclarator declarator = extractedFunctionConstructionHelper IASTStandardFunctionDeclarator declarator =
.createFunctionDeclarator(name, info.getDeclarator(), info extractedFunctionConstructionHelper.createFunctionDeclarator(name,
.getReturnVariable(), container.getNodesToWrite(), info info.getDeclarator(), info.getReturnVariable(), container.getNodesToWrite(),
.getAllUsedNames(), ast.getASTNodeFactory()); info.getAllUsedNames(), ast.getASTNodeFactory());
simpleDecl.addDeclarator(declarator); simpleDecl.addDeclarator(declarator);
return simpleDecl; return simpleDecl;
} }
@ -852,17 +847,17 @@ public class ExtractFunctionRefactoring extends CRefactoring {
public List<IASTInitializerClause> getCallParameters() { public List<IASTInitializerClause> getCallParameters() {
List<IASTInitializerClause> args = new ArrayList<IASTInitializerClause>(); List<IASTInitializerClause> args = new ArrayList<IASTInitializerClause>();
Vector<IASTName> declarations = new Vector<IASTName>(); List<IASTName> declarations = new ArrayList<IASTName>();
for (NameInformation nameInf : container.getNames()) { for (NameInformation nameInfo : container.getNames()) {
addAParameterIfPossible(args, declarations, nameInf); addParameterIfPossible(args, declarations, nameInfo);
} }
return args; return args;
} }
private void addAParameterIfPossible(List<IASTInitializerClause> args, private void addParameterIfPossible(List<IASTInitializerClause> args,
Vector<IASTName> declarations, NameInformation nameInf) { List<IASTName> declarations, NameInformation nameInfo) {
if (!nameInf.isDeclarationInScope()) { if (!nameInfo.isDeclarationExtracted()) {
IASTName declaration = nameInf.getDeclaration(); IASTName declaration = nameInfo.getDeclaration();
if (!declarations.contains(declaration)) { if (!declarations.contains(declaration)) {
declarations.add(declaration); declarations.add(declaration);
IASTIdExpression expression = new CPPASTIdExpression(); IASTIdExpression expression = new CPPASTIdExpression();
@ -875,7 +870,9 @@ public class ExtractFunctionRefactoring extends CRefactoring {
@Override @Override
protected RefactoringDescriptor getRefactoringDescriptor() { protected RefactoringDescriptor getRefactoringDescriptor() {
Map<String, String> arguments = getArgumentMap(); Map<String, String> arguments = getArgumentMap();
RefactoringDescriptor desc = new ExtractFunctionRefactoringDescription(project.getProject().getName(), "Extract Method Refactoring", "Create method " + info.getMethodName(), arguments); //$NON-NLS-1$//$NON-NLS-2$ RefactoringDescriptor desc =
new ExtractFunctionRefactoringDescription(project.getProject().getName(),
"Extract Method Refactoring", "Create method " + info.getMethodName(), arguments); //$NON-NLS-1$//$NON-NLS-2$
return desc; return desc;
} }
@ -884,8 +881,10 @@ public class ExtractFunctionRefactoring extends CRefactoring {
arguments.put(CRefactoringDescription.FILE_NAME, file.getLocationURI().toString()); arguments.put(CRefactoringDescription.FILE_NAME, file.getLocationURI().toString());
arguments.put(CRefactoringDescription.SELECTION, region.getOffset() + "," + region.getLength()); //$NON-NLS-1$ arguments.put(CRefactoringDescription.SELECTION, region.getOffset() + "," + region.getLength()); //$NON-NLS-1$
arguments.put(ExtractFunctionRefactoringDescription.NAME, info.getMethodName()); arguments.put(ExtractFunctionRefactoringDescription.NAME, info.getMethodName());
arguments.put(ExtractFunctionRefactoringDescription.VISIBILITY, info.getVisibility().toString()); arguments.put(ExtractFunctionRefactoringDescription.VISIBILITY,
arguments.put(ExtractFunctionRefactoringDescription.REPLACE_DUPLICATES, Boolean.toString(info.isReplaceDuplicates())); info.getVisibility().toString());
arguments.put(ExtractFunctionRefactoringDescription.REPLACE_DUPLICATES,
Boolean.toString(info.isReplaceDuplicates()));
return arguments; return arguments;
} }
} }

View file

@ -36,13 +36,14 @@ public class ExtractStatement extends ExtractedFunctionConstructionHelper {
@Override @Override
public void constructMethodBody(IASTCompoundStatement compound, List<IASTNode> list, public void constructMethodBody(IASTCompoundStatement compound, List<IASTNode> list,
ASTRewrite rewrite, TextEditGroup group) { ASTRewrite rewrite, TextEditGroup group) {
for (IASTNode each : list) { for (IASTNode node : list) {
rewrite.insertBefore(compound, null, each, group); rewrite.insertBefore(compound, null, node, group);
} }
} }
@Override @Override
public IASTDeclSpecifier determineReturnType(IASTNode extractedNode, NameInformation returnVariable) { public IASTDeclSpecifier determineReturnType(IASTNode extractedNode,
NameInformation returnVariable) {
if (returnVariable != null) { if (returnVariable != null) {
IASTNode decl = ASTHelper.getDeclarationForNode(returnVariable.getDeclaration()); IASTNode decl = ASTHelper.getDeclarationForNode(returnVariable.getDeclaration());
return ASTHelper.getDeclarationSpecifier(decl).copy(CopyStyle.withLocations); return ASTHelper.getDeclarationSpecifier(decl).copy(CopyStyle.withLocations);

View file

@ -55,13 +55,14 @@ public abstract class ExtractedFunctionConstructionHelper {
public abstract IASTNode createReturnAssignment(IASTNode node, IASTExpressionStatement stmt, public abstract IASTNode createReturnAssignment(IASTNode node, IASTExpressionStatement stmt,
IASTExpression callExpression); IASTExpression callExpression);
protected boolean isReturnTypeAPointer(IASTNode node) { protected boolean hasPointerReturnType(IASTNode node) {
return false; return false;
} }
IASTStandardFunctionDeclarator createFunctionDeclarator(IASTName name, IASTStandardFunctionDeclarator createFunctionDeclarator(IASTName name,
IASTStandardFunctionDeclarator functionDeclarator, NameInformation returnVariable, IASTStandardFunctionDeclarator functionDeclarator, NameInformation returnVariable,
List<IASTNode> nodesToWrite, Collection<NameInformation> allUsedNames, INodeFactory nodeFactory) { List<IASTNode> nodesToWrite, Collection<NameInformation> allUsedNames,
INodeFactory nodeFactory) {
IASTStandardFunctionDeclarator declarator = nodeFactory.newFunctionDeclarator(name); IASTStandardFunctionDeclarator declarator = nodeFactory.newFunctionDeclarator(name);
if (functionDeclarator instanceof ICPPASTFunctionDeclarator && if (functionDeclarator instanceof ICPPASTFunctionDeclarator &&
@ -83,17 +84,18 @@ public abstract class ExtractedFunctionConstructionHelper {
declarator.addParameterDeclaration(param); declarator.addParameterDeclaration(param);
} }
if (isReturnTypeAPointer(nodesToWrite.get(0))) { if (hasPointerReturnType(nodesToWrite.get(0))) {
declarator.addPointerOperator(nodeFactory.newPointer()); declarator.addPointerOperator(nodeFactory.newPointer());
} }
return declarator; return declarator;
} }
public Collection<IASTParameterDeclaration> getParameterDeclarations(Collection<NameInformation> allUsedNames, INodeFactory nodeFactory) { public List<IASTParameterDeclaration> getParameterDeclarations(
Collection<IASTParameterDeclaration> result = new ArrayList<IASTParameterDeclaration>(); Collection<NameInformation> allUsedNames, INodeFactory nodeFactory) {
List<IASTParameterDeclaration> result = new ArrayList<IASTParameterDeclaration>();
for (NameInformation name : allUsedNames) { for (NameInformation name : allUsedNames) {
if (!name.isDeclarationInScope()) { if (!name.isDeclarationExtracted()) {
result.add(name.getParameterDeclaration(name.isUserSetIsReference(), nodeFactory)); result.add(name.getParameterDeclaration(name.isUserSetIsReference(), nodeFactory));
} }
} }

View file

@ -14,7 +14,6 @@ package org.eclipse.cdt.internal.ui.refactoring.extractfunction;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Vector;
import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFile;
import org.eclipse.text.edits.TextEditGroup; import org.eclipse.text.edits.TextEditGroup;
@ -32,7 +31,7 @@ import org.eclipse.cdt.internal.ui.refactoring.NodeContainer.NameInformation;
final class SimilarFinderVisitor extends ASTVisitor { final class SimilarFinderVisitor extends ASTVisitor {
private final ExtractFunctionRefactoring refactoring; private final ExtractFunctionRefactoring refactoring;
private final Vector<IASTNode> trail; private final List<IASTNode> trail;
private final IASTName name; private final IASTName name;
private final List<IASTNode> statements; private final List<IASTNode> statements;
private int statementCount; private int statementCount;
@ -42,7 +41,7 @@ final class SimilarFinderVisitor extends ASTVisitor {
private final ModificationCollector collector; private final ModificationCollector collector;
SimilarFinderVisitor(ExtractFunctionRefactoring refactoring, ModificationCollector collector, SimilarFinderVisitor(ExtractFunctionRefactoring refactoring, ModificationCollector collector,
Vector<IASTNode> trail, IFile file, IASTName name, List<IASTNode> statements, List<IASTNode> trail, IFile file, IASTName name, List<IASTNode> statements,
String title) { String title) {
this.refactoring = refactoring; this.refactoring = refactoring;
this.trail = trail; this.trail = trail;

View file

@ -23,11 +23,11 @@ import org.eclipse.cdt.core.index.IIndexFileLocation;
* *
* @author Doug Schaefer * @author Doug Schaefer
*/ */
public class PDOMSearchElement implements IAdaptable { public class CSearchElement implements IAdaptable {
private final IIndexFileLocation location; private final IIndexFileLocation location;
public PDOMSearchElement(IIndexFileLocation loc) { public CSearchElement(IIndexFileLocation loc) {
this.location= loc; this.location= loc;
} }
@ -38,9 +38,9 @@ public class PDOMSearchElement implements IAdaptable {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (!(obj instanceof PDOMSearchElement)) if (!(obj instanceof CSearchElement))
return false; return false;
PDOMSearchElement other = (PDOMSearchElement)obj; CSearchElement other = (CSearchElement)obj;
return location.equals(other.location); return location.equals(other.location);
} }

View file

@ -10,7 +10,6 @@
* Markus Schorn (Wind River Systems) * Markus Schorn (Wind River Systems)
* Sergey Prigogin (Google) * Sergey Prigogin (Google)
*******************************************************************************/ *******************************************************************************/
package org.eclipse.cdt.internal.ui.search; package org.eclipse.cdt.internal.ui.search;
import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.CoreException;
@ -29,12 +28,11 @@ import org.eclipse.cdt.internal.ui.viewsupport.IndexUI;
/** /**
* @author Doug Schaefer * @author Doug Schaefer
*/ */
public class PDOMSearchElementQuery extends PDOMSearchQuery { public class CSearchElementQuery extends CSearchQuery {
private final ISourceReference element;
private ISourceReference element;
private String label; private String label;
public PDOMSearchElementQuery(ICElement[] scope, ISourceReference element, int flags) { public CSearchElementQuery(ICElement[] scope, ISourceReference element, int flags) {
super(scope, flags | IIndex.SEARCH_ACROSS_LANGUAGE_BOUNDARIES); super(scope, flags | IIndex.SEARCH_ACROSS_LANGUAGE_BOUNDARIES);
this.element = element; this.element = element;
this.label= (element instanceof ICElement) ? this.label= (element instanceof ICElement) ?

View file

@ -50,15 +50,13 @@ import org.eclipse.cdt.internal.ui.viewsupport.ColoringLabelProvider;
* URI - for IIndexFileLocations not resolvable to the local filesystem, under URI_CONTAINER<br> * URI - for IIndexFileLocations not resolvable to the local filesystem, under URI_CONTAINER<br>
* @author Doug Schaefer * @author Doug Schaefer
* @author Ed Swartz * @author Ed Swartz
*
*/ */
public class PDOMSearchLabelProvider extends LabelProvider implements IStyledLabelProvider { public class CSearchLabelProvider extends LabelProvider implements IStyledLabelProvider {
protected final CSearchViewPage fPage;
protected final PDOMSearchViewPage fPage;
private final TypeInfoLabelProvider fTypeInfoLabelProvider; private final TypeInfoLabelProvider fTypeInfoLabelProvider;
private final CUILabelProvider fCElementLabelProvider; private final CUILabelProvider fCElementLabelProvider;
public PDOMSearchLabelProvider(PDOMSearchViewPage page) { public CSearchLabelProvider(CSearchViewPage page) {
fTypeInfoLabelProvider= new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_FULLY_QUALIFIED | TypeInfoLabelProvider.SHOW_PARAMETERS); fTypeInfoLabelProvider= new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_FULLY_QUALIFIED | TypeInfoLabelProvider.SHOW_PARAMETERS);
fCElementLabelProvider= new CUILabelProvider(0, CElementImageProvider.SMALL_ICONS); fCElementLabelProvider= new CUILabelProvider(0, CElementImageProvider.SMALL_ICONS);
fPage= page; fPage= page;
@ -152,8 +150,8 @@ public class PDOMSearchLabelProvider extends LabelProvider implements IStyledLab
if (element instanceof TranslationUnit) { if (element instanceof TranslationUnit) {
TranslationUnit translationUnit = (TranslationUnit) element; TranslationUnit translationUnit = (TranslationUnit) element;
AbstractTextSearchResult searchResult = fPage.getInput(); AbstractTextSearchResult searchResult = fPage.getInput();
if (searchResult instanceof PDOMSearchResult) { if (searchResult instanceof CSearchResult) {
PDOMSearchResult pdomSearchResult = (PDOMSearchResult)searchResult; CSearchResult pdomSearchResult = (CSearchResult)searchResult;
return pdomSearchResult.computeContainedMatches(searchResult, translationUnit.getFile()).length; return pdomSearchResult.computeContainedMatches(searchResult, translationUnit.getFile()).length;
} }
} }

View file

@ -9,7 +9,6 @@
* QNX - Initial API and implementation * QNX - Initial API and implementation
* Ed Swartz (Nokia) * Ed Swartz (Nokia)
*******************************************************************************/ *******************************************************************************/
package org.eclipse.cdt.internal.ui.search; package org.eclipse.cdt.internal.ui.search;
import java.util.ArrayList; import java.util.ArrayList;
@ -32,16 +31,13 @@ import org.eclipse.cdt.ui.CUIPlugin;
/** /**
* @author Doug Schaefer * @author Doug Schaefer
*
*/ */
public class PDOMSearchListContentProvider implements public class CSearchListContentProvider implements IStructuredContentProvider, IPDOMSearchContentProvider {
IStructuredContentProvider, IPDOMSearchContentProvider {
private TableViewer viewer; private TableViewer viewer;
private PDOMSearchResult result; private CSearchResult result;
private final PDOMSearchViewPage fPage; private final CSearchViewPage fPage;
PDOMSearchListContentProvider(PDOMSearchViewPage page) { CSearchListContentProvider(CSearchViewPage page) {
fPage= page; fPage= page;
} }
@ -49,15 +45,15 @@ public class PDOMSearchListContentProvider implements
public Object[] getElements(Object inputElement) { public Object[] getElements(Object inputElement) {
Set<String> uncoveredProjects = new HashSet<String>(); Set<String> uncoveredProjects = new HashSet<String>();
PDOMSearchResult result = (PDOMSearchResult) inputElement; CSearchResult result = (CSearchResult) inputElement;
Object[] results = result.getElements(); Object[] results = result.getElements();
List<Object> resultList = new ArrayList<Object>(); List<Object> resultList = new ArrayList<Object>();
// see which projects returned results // see which projects returned results
for (int i = 0; i < results.length; i++) { for (int i = 0; i < results.length; i++) {
if (results[i] instanceof PDOMSearchElement) { if (results[i] instanceof CSearchElement) {
PDOMSearchElement searchElement = (PDOMSearchElement) results[i]; CSearchElement searchElement = (CSearchElement) results[i];
String path = searchElement.getLocation().getFullPath(); String path = searchElement.getLocation().getFullPath();
if (path != null) { if (path != null) {
uncoveredProjects.add(new Path(path).segment(0)); uncoveredProjects.add(new Path(path).segment(0));
@ -74,7 +70,7 @@ public class PDOMSearchListContentProvider implements
} }
// add message for all the projects which have no results // add message for all the projects which have no results
ICProject[] projects = ((PDOMSearchQuery)result.getQuery()).getProjects(); ICProject[] projects = ((CSearchQuery)result.getQuery()).getProjects();
for (int i = 0; i < projects.length; ++i) { for (int i = 0; i < projects.length; ++i) {
ICProject project = projects[i]; ICProject project = projects[i];
boolean foundProject = uncoveredProjects.contains(project.getProject().getName()); boolean foundProject = uncoveredProjects.contains(project.getProject().getName());
@ -113,7 +109,7 @@ public class PDOMSearchListContentProvider implements
@Override @Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
this.viewer = (TableViewer)viewer; this.viewer = (TableViewer)viewer;
result = (PDOMSearchResult)newInput; result = (CSearchResult)newInput;
viewer.refresh(); viewer.refresh();
} }

View file

@ -25,12 +25,12 @@ import org.eclipse.cdt.internal.ui.viewsupport.ColoringLabelProvider;
/** /**
* @author Doug Schaefer * @author Doug Schaefer
*/ */
public class PDOMSearchListLabelProvider extends ColoringLabelProvider { public class CSearchListLabelProvider extends ColoringLabelProvider {
private final PDOMSearchViewPage fPage; private final CSearchViewPage fPage;
private final int fColumnIndex; private final int fColumnIndex;
public PDOMSearchListLabelProvider(PDOMSearchViewPage page, int columnIndex) { public CSearchListLabelProvider(CSearchViewPage page, int columnIndex) {
super(new PDOMSearchLabelProvider(page)); super(new CSearchLabelProvider(page));
fPage = page; fPage = page;
fColumnIndex = columnIndex; fColumnIndex = columnIndex;
} }
@ -39,7 +39,7 @@ public class PDOMSearchListLabelProvider extends ColoringLabelProvider {
public void update(ViewerCell cell) { public void update(ViewerCell cell) {
Object element = cell.getElement(); Object element = cell.getElement();
switch (fColumnIndex) { switch (fColumnIndex) {
case PDOMSearchViewPage.LOCATION_COLUMN_INDEX: case CSearchViewPage.LOCATION_COLUMN_INDEX:
if (element instanceof LineSearchElement) { if (element instanceof LineSearchElement) {
LineSearchElement lineElement = (LineSearchElement) element; LineSearchElement lineElement = (LineSearchElement) element;
String location = IndexLocationFactory.getPath(lineElement.getLocation()).toString(); String location = IndexLocationFactory.getPath(lineElement.getLocation()).toString();
@ -48,7 +48,7 @@ public class PDOMSearchListLabelProvider extends ColoringLabelProvider {
cell.setImage(CDTSharedImages.getImage(CDTSharedImages.IMG_OBJS_SEARCH_LINE)); cell.setImage(CDTSharedImages.getImage(CDTSharedImages.IMG_OBJS_SEARCH_LINE));
} }
break; break;
case PDOMSearchViewPage.DEFINITION_COLUMN_INDEX: case CSearchViewPage.DEFINITION_COLUMN_INDEX:
if (element instanceof LineSearchElement) { if (element instanceof LineSearchElement) {
LineSearchElement lineElement = (LineSearchElement) element; LineSearchElement lineElement = (LineSearchElement) element;
ICElement enclosingElement = lineElement.getMatches()[0].getEnclosingElement(); ICElement enclosingElement = lineElement.getMatches()[0].getEnclosingElement();
@ -60,7 +60,7 @@ public class PDOMSearchListLabelProvider extends ColoringLabelProvider {
} }
} }
break; break;
case PDOMSearchViewPage.MATCH_COLUMN_INDEX: case CSearchViewPage.MATCH_COLUMN_INDEX:
super.update(cell); super.update(cell);
cell.setImage(null); cell.setImage(null);
break; break;

View file

@ -18,25 +18,24 @@ import org.eclipse.cdt.core.index.IIndexFileLocation;
/** /**
* Base class for search matches found by various index searches. * Base class for search matches found by various index searches.
*/ */
public class PDOMSearchMatch extends Match { public class CSearchMatch extends Match {
private boolean fIsPolymorphicCall; private boolean fIsPolymorphicCall;
public PDOMSearchMatch(PDOMSearchElement elem, int offset, int length) { public CSearchMatch(CSearchElement elem, int offset, int length) {
super(elem, offset, length); super(elem, offset, length);
} }
IIndexFileLocation getLocation() { IIndexFileLocation getLocation() {
return ((PDOMSearchElement)getElement()).getLocation(); return ((CSearchElement)getElement()).getLocation();
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj == this) if (obj == this)
return true; return true;
if (!(obj instanceof PDOMSearchMatch)) if (!(obj instanceof CSearchMatch))
return false; return false;
PDOMSearchMatch other = (PDOMSearchMatch)obj; CSearchMatch other = (CSearchMatch)obj;
return getElement().equals(other.getElement()) return getElement().equals(other.getElement())
&& getOffset() == other.getOffset() && getOffset() == other.getOffset()
&& getLength() == other.getLength(); && getLength() == other.getLength();

View file

@ -9,7 +9,6 @@
* Doug Schaefer (QNX) - Initial API and implementation * Doug Schaefer (QNX) - Initial API and implementation
* Markus Schorn (Wind River Systems) * Markus Schorn (Wind River Systems)
*******************************************************************************/ *******************************************************************************/
package org.eclipse.cdt.internal.ui.search; package org.eclipse.cdt.internal.ui.search;
import java.util.HashSet; import java.util.HashSet;
@ -72,10 +71,8 @@ import org.eclipse.cdt.internal.ui.util.RowLayouter;
/** /**
* @author Doug Schaefer * @author Doug Schaefer
*
*/ */
public class PDOMSearchPage extends DialogPage implements ISearchPage { public class CSearchPage extends DialogPage implements ISearchPage {
public static final String EXTENSION_ID = CUIPlugin.PLUGIN_ID + ".pdomSearchPage"; //$NON-NLS-1$ public static final String EXTENSION_ID = CUIPlugin.PLUGIN_ID + ".pdomSearchPage"; //$NON-NLS-1$
//Dialog store id constants //Dialog store id constants
@ -106,18 +103,18 @@ public class PDOMSearchPage extends DialogPage implements ISearchPage {
// These must be in the same order as the Text // These must be in the same order as the Text
private static final Integer[] searchForData = { private static final Integer[] searchForData = {
new Integer(PDOMSearchPatternQuery.FIND_CLASS_STRUCT), new Integer(CSearchPatternQuery.FIND_CLASS_STRUCT),
new Integer(PDOMSearchPatternQuery.FIND_FUNCTION), new Integer(CSearchPatternQuery.FIND_FUNCTION),
new Integer(PDOMSearchPatternQuery.FIND_VARIABLE), new Integer(CSearchPatternQuery.FIND_VARIABLE),
new Integer(PDOMSearchPatternQuery.FIND_UNION), new Integer(CSearchPatternQuery.FIND_UNION),
new Integer(PDOMSearchPatternQuery.FIND_METHOD), new Integer(CSearchPatternQuery.FIND_METHOD),
new Integer(PDOMSearchPatternQuery.FIND_FIELD), new Integer(CSearchPatternQuery.FIND_FIELD),
new Integer(PDOMSearchPatternQuery.FIND_ENUM), new Integer(CSearchPatternQuery.FIND_ENUM),
new Integer(PDOMSearchPatternQuery.FIND_ENUMERATOR), new Integer(CSearchPatternQuery.FIND_ENUMERATOR),
new Integer(PDOMSearchPatternQuery.FIND_NAMESPACE), new Integer(CSearchPatternQuery.FIND_NAMESPACE),
new Integer(PDOMSearchPatternQuery.FIND_TYPEDEF), new Integer(CSearchPatternQuery.FIND_TYPEDEF),
new Integer(PDOMSearchPatternQuery.FIND_MACRO), new Integer(CSearchPatternQuery.FIND_MACRO),
new Integer(PDOMSearchPatternQuery.FIND_ALL_TYPES) new Integer(CSearchPatternQuery.FIND_ALL_TYPES)
}; };
// the index of FIND_ALL_TYPES // the index of FIND_ALL_TYPES
@ -132,10 +129,10 @@ public class PDOMSearchPage extends DialogPage implements ISearchPage {
// Must be in the same order as the text // Must be in the same order as the text
private static Integer[] limitToData = { private static Integer[] limitToData = {
new Integer(PDOMSearchQuery.FIND_DECLARATIONS), new Integer(CSearchQuery.FIND_DECLARATIONS),
new Integer(PDOMSearchQuery.FIND_DEFINITIONS), new Integer(CSearchQuery.FIND_DEFINITIONS),
new Integer(PDOMSearchQuery.FIND_REFERENCES), new Integer(CSearchQuery.FIND_REFERENCES),
new Integer(PDOMSearchQuery.FIND_ALL_OCCURRENCES), new Integer(CSearchQuery.FIND_ALL_OCCURRENCES),
}; };
// The index of FIND_ALL_OCCURANCES // The index of FIND_ALL_OCCURANCES
@ -189,7 +186,7 @@ public class PDOMSearchPage extends DialogPage implements ISearchPage {
// Get search flags // Get search flags
int searchFlags = 0; int searchFlags = 0;
if (searchForButtons[searchAllButtonIndex].getSelection()) { if (searchForButtons[searchAllButtonIndex].getSelection()) {
searchFlags |= PDOMSearchPatternQuery.FIND_ALL_TYPES; searchFlags |= CSearchPatternQuery.FIND_ALL_TYPES;
} else { } else {
for (int i = 0; i < searchForButtons.length; ++i) { for (int i = 0; i < searchForButtons.length; ++i) {
if (searchForButtons[i].getSelection()) if (searchForButtons[i].getSelection())
@ -277,7 +274,7 @@ public class PDOMSearchPage extends DialogPage implements ISearchPage {
null : elements.toArray(new ICElement[elements.size()]); null : elements.toArray(new ICElement[elements.size()]);
try { try {
PDOMSearchPatternQuery job = new PDOMSearchPatternQuery(scope, scopeDescription, patternStr, CSearchPatternQuery job = new CSearchPatternQuery(scope, scopeDescription, patternStr,
isCaseSensitive, searchFlags); isCaseSensitive, searchFlags);
NewSearchUI.activateSearchResultView(); NewSearchUI.activateSearchResultView();
@ -664,7 +661,7 @@ public class PDOMSearchPage extends DialogPage implements ISearchPage {
IDialogSettings settings = getDialogSettings(); IDialogSettings settings = getDialogSettings();
int searchFlags = PDOMSearchPatternQuery.FIND_ALL_TYPES | PDOMSearchQuery.FIND_ALL_OCCURRENCES; int searchFlags = CSearchPatternQuery.FIND_ALL_TYPES | CSearchQuery.FIND_ALL_OCCURRENCES;
try { try {
searchFlags = settings.getInt(STORE_SEARCH_FLAGS); searchFlags = settings.getInt(STORE_SEARCH_FLAGS);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
@ -686,45 +683,45 @@ public class PDOMSearchPage extends DialogPage implements ISearchPage {
ICElement element = (ICElement)obj; ICElement element = (ICElement)obj;
patternCombo.setText(element.getElementName()); patternCombo.setText(element.getElementName());
// Clear the type flags so we can set them correctly for what we have selected // Clear the type flags so we can set them correctly for what we have selected
searchFlags = searchFlags & ~PDOMSearchPatternQuery.FIND_ALL_TYPES; searchFlags = searchFlags & ~CSearchPatternQuery.FIND_ALL_TYPES;
switch (element.getElementType()) { switch (element.getElementType()) {
case ICElement.C_CLASS: case ICElement.C_CLASS:
case ICElement.C_STRUCT: case ICElement.C_STRUCT:
searchFlags |= PDOMSearchPatternQuery.FIND_CLASS_STRUCT; searchFlags |= CSearchPatternQuery.FIND_CLASS_STRUCT;
break; break;
case ICElement.C_FUNCTION: case ICElement.C_FUNCTION:
searchFlags |= PDOMSearchPatternQuery.FIND_FUNCTION; searchFlags |= CSearchPatternQuery.FIND_FUNCTION;
break; break;
case ICElement.C_VARIABLE: case ICElement.C_VARIABLE:
searchFlags |= PDOMSearchPatternQuery.FIND_VARIABLE; searchFlags |= CSearchPatternQuery.FIND_VARIABLE;
break; break;
case ICElement.C_UNION: case ICElement.C_UNION:
searchFlags |= PDOMSearchPatternQuery.FIND_UNION; searchFlags |= CSearchPatternQuery.FIND_UNION;
break; break;
case ICElement.C_METHOD: case ICElement.C_METHOD:
searchFlags |= PDOMSearchPatternQuery.FIND_METHOD; searchFlags |= CSearchPatternQuery.FIND_METHOD;
break; break;
case ICElement.C_FIELD: case ICElement.C_FIELD:
searchFlags |= PDOMSearchPatternQuery.FIND_FIELD; searchFlags |= CSearchPatternQuery.FIND_FIELD;
break; break;
case ICElement.C_ENUMERATION: case ICElement.C_ENUMERATION:
searchFlags |= PDOMSearchPatternQuery.FIND_ENUM; searchFlags |= CSearchPatternQuery.FIND_ENUM;
break; break;
case ICElement.C_ENUMERATOR: case ICElement.C_ENUMERATOR:
searchFlags |= PDOMSearchPatternQuery.FIND_ENUMERATOR; searchFlags |= CSearchPatternQuery.FIND_ENUMERATOR;
break; break;
case ICElement.C_NAMESPACE: case ICElement.C_NAMESPACE:
searchFlags |= PDOMSearchPatternQuery.FIND_NAMESPACE; searchFlags |= CSearchPatternQuery.FIND_NAMESPACE;
break; break;
case ICElement.C_TYPEDEF: case ICElement.C_TYPEDEF:
searchFlags |= PDOMSearchPatternQuery.FIND_TYPEDEF; searchFlags |= CSearchPatternQuery.FIND_TYPEDEF;
break; break;
case ICElement.C_MACRO: case ICElement.C_MACRO:
searchFlags |= PDOMSearchPatternQuery.FIND_MACRO; searchFlags |= CSearchPatternQuery.FIND_MACRO;
break; break;
default: default:
// Not sure, set to all // Not sure, set to all
searchFlags |= PDOMSearchPatternQuery.FIND_ALL_TYPES; searchFlags |= CSearchPatternQuery.FIND_ALL_TYPES;
patternCombo.setText(""); //$NON-NLS-1$ patternCombo.setText(""); //$NON-NLS-1$
} }
} }
@ -740,7 +737,7 @@ public class PDOMSearchPage extends DialogPage implements ISearchPage {
caseSensitiveButton.setSelection(settings.getBoolean(STORE_CASE_SENSITIVE)); caseSensitiveButton.setSelection(settings.getBoolean(STORE_CASE_SENSITIVE));
if ((searchFlags & PDOMSearchPatternQuery.FIND_ALL_TYPES) == PDOMSearchPatternQuery.FIND_ALL_TYPES) { if ((searchFlags & CSearchPatternQuery.FIND_ALL_TYPES) == CSearchPatternQuery.FIND_ALL_TYPES) {
searchForButtons[searchAllButtonIndex].setSelection(true); searchForButtons[searchAllButtonIndex].setSelection(true);
for (int i = 0; i < searchForButtons.length; ++i) { for (int i = 0; i < searchForButtons.length; ++i) {
if (i != searchAllButtonIndex) { if (i != searchAllButtonIndex) {
@ -758,7 +755,7 @@ public class PDOMSearchPage extends DialogPage implements ISearchPage {
} }
} }
if ((searchFlags & PDOMSearchQuery.FIND_ALL_OCCURRENCES) == PDOMSearchQuery.FIND_ALL_OCCURRENCES) { if ((searchFlags & CSearchQuery.FIND_ALL_OCCURRENCES) == CSearchQuery.FIND_ALL_OCCURRENCES) {
limitToButtons[limitToAllButtonIndex].setSelection(true); limitToButtons[limitToAllButtonIndex].setSelection(true);
for (int i = 0; i < limitToButtons.length; ++i) { for (int i = 0; i < limitToButtons.length; ++i) {
if (i != limitToAllButtonIndex) { if (i != limitToAllButtonIndex) {

View file

@ -40,12 +40,10 @@ import org.eclipse.cdt.core.index.IIndexBinding;
import org.eclipse.cdt.core.index.IndexFilter; import org.eclipse.cdt.core.index.IndexFilter;
import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.ICElement;
/** /**
* @author Doug Schaefer * @author Doug Schaefer
*/ */
public class PDOMSearchPatternQuery extends PDOMSearchQuery { public class CSearchPatternQuery extends CSearchQuery {
// First bit after the FINDs in PDOMSearchQuery. // First bit after the FINDs in PDOMSearchQuery.
public static final int FIND_CLASS_STRUCT = 0x10; public static final int FIND_CLASS_STRUCT = 0x10;
public static final int FIND_FUNCTION = 0x20; public static final int FIND_FUNCTION = 0x20;
@ -58,16 +56,16 @@ public class PDOMSearchPatternQuery extends PDOMSearchQuery {
public static final int FIND_NAMESPACE = 0x4000; public static final int FIND_NAMESPACE = 0x4000;
public static final int FIND_TYPEDEF = 0x10000; public static final int FIND_TYPEDEF = 0x10000;
public static final int FIND_MACRO = 0x20000; public static final int FIND_MACRO = 0x20000;
public static final int FIND_ALL_TYPES public static final int FIND_ALL_TYPES =
= FIND_CLASS_STRUCT | FIND_FUNCTION | FIND_VARIABLE FIND_CLASS_STRUCT | FIND_FUNCTION | FIND_VARIABLE |
| FIND_UNION | FIND_METHOD | FIND_FIELD | FIND_ENUM FIND_UNION | FIND_METHOD | FIND_FIELD | FIND_ENUM |
| FIND_ENUMERATOR | FIND_NAMESPACE | FIND_TYPEDEF | FIND_MACRO; FIND_ENUMERATOR | FIND_NAMESPACE | FIND_TYPEDEF | FIND_MACRO;
private String scopeDesc; private final String scopeDesc;
private String patternStr; private final String patternStr;
private Pattern[] pattern; private final Pattern[] pattern;
public PDOMSearchPatternQuery( public CSearchPatternQuery(
ICElement[] scope, ICElement[] scope,
String scopeDesc, String scopeDesc,
String patternStr, String patternStr,

View file

@ -74,7 +74,7 @@ import org.eclipse.cdt.internal.ui.util.Messages;
import org.eclipse.cdt.internal.ui.viewsupport.CElementLabels; import org.eclipse.cdt.internal.ui.viewsupport.CElementLabels;
import org.eclipse.cdt.internal.ui.viewsupport.IndexUI; import org.eclipse.cdt.internal.ui.viewsupport.IndexUI;
public abstract class PDOMSearchQuery implements ISearchQuery { public abstract class CSearchQuery implements ISearchQuery {
public static final int FIND_DECLARATIONS = IIndex.FIND_DECLARATIONS; public static final int FIND_DECLARATIONS = IIndex.FIND_DECLARATIONS;
public static final int FIND_DEFINITIONS = IIndex.FIND_DEFINITIONS; public static final int FIND_DEFINITIONS = IIndex.FIND_DEFINITIONS;
public static final int FIND_REFERENCES = IIndex.FIND_REFERENCES; public static final int FIND_REFERENCES = IIndex.FIND_REFERENCES;
@ -86,15 +86,15 @@ public abstract class PDOMSearchQuery implements ISearchQuery {
CElementLabels.ALL_FULLY_QUALIFIED | CElementLabels.ALL_FULLY_QUALIFIED |
CElementLabels.TEMPLATE_ARGUMENTS; CElementLabels.TEMPLATE_ARGUMENTS;
protected PDOMSearchResult result; protected CSearchResult result;
protected int flags; protected int flags;
protected ICElement[] scope; protected ICElement[] scope;
protected ICProject[] projects; protected ICProject[] projects;
private Set<String> fullPathFilter; private Set<String> fullPathFilter;
protected PDOMSearchQuery(ICElement[] scope, int flags) { protected CSearchQuery(ICElement[] scope, int flags) {
result = new PDOMSearchResult(this); result = new CSearchResult(this);
this.flags = flags; this.flags = flags;
this.scope = scope; this.scope = scope;
@ -319,7 +319,7 @@ public abstract class PDOMSearchQuery implements ISearchQuery {
for (Match lineMatch : searchElement.getMatches()) { for (Match lineMatch : searchElement.getMatches()) {
int offset = lineMatch.getOffset(); int offset = lineMatch.getOffset();
int length = lineMatch.getLength(); int length = lineMatch.getLength();
PDOMSearchMatch match = new PDOMSearchMatch(searchElement, offset, length); CSearchMatch match = new CSearchMatch(searchElement, offset, length);
if (lineMatch.isPolymorphicCall()) if (lineMatch.isPolymorphicCall())
match.setIsPolymorphicCall(); match.setIsPolymorphicCall();
result.addMatch(match); result.addMatch(match);
@ -470,7 +470,7 @@ public abstract class PDOMSearchQuery implements ISearchQuery {
for (Match lineMatch : searchElement.getMatches()) { for (Match lineMatch : searchElement.getMatches()) {
int offset = lineMatch.getOffset(); int offset = lineMatch.getOffset();
int length = lineMatch.getLength(); int length = lineMatch.getLength();
PDOMSearchMatch match = new PDOMSearchMatch(searchElement, offset, length); CSearchMatch match = new CSearchMatch(searchElement, offset, length);
result.addMatch(match); result.addMatch(match);
} }
} }
@ -487,7 +487,7 @@ public abstract class PDOMSearchQuery implements ISearchQuery {
@Override @Override
public final IStatus run(IProgressMonitor monitor) throws OperationCanceledException { public final IStatus run(IProgressMonitor monitor) throws OperationCanceledException {
PDOMSearchResult result= (PDOMSearchResult) getSearchResult(); CSearchResult result= (CSearchResult) getSearchResult();
result.removeAll(); result.removeAll();
result.setIndexerBusy(!CCorePlugin.getIndexManager().isIndexerIdle()); result.setIndexerBusy(!CCorePlugin.getIndexManager().isIndexerIdle());

View file

@ -46,15 +46,15 @@ import org.eclipse.cdt.internal.ui.util.ExternalEditorInput;
/** /**
* @author Doug Schaefer * @author Doug Schaefer
*/ */
public class PDOMSearchResult extends AbstractTextSearchResult implements IEditorMatchAdapter, IFileMatchAdapter { public class CSearchResult extends AbstractTextSearchResult implements IEditorMatchAdapter, IFileMatchAdapter {
private static final String KEY_SHOW_POLYMORPHIC_CALLS = "ShowPolymorphicCalls"; //$NON-NLS-1$ private static final String KEY_SHOW_POLYMORPHIC_CALLS = "ShowPolymorphicCalls"; //$NON-NLS-1$
final static MatchFilter[] ALL_FILTERS = new MatchFilter[] {HidePolymorphicCalls.FILTER}; final static MatchFilter[] ALL_FILTERS = new MatchFilter[] {HidePolymorphicCalls.FILTER};
final static MatchFilter[] NO_FILTERS = {}; final static MatchFilter[] NO_FILTERS = {};
private PDOMSearchQuery query; private CSearchQuery query;
private boolean indexerBusy; private boolean indexerBusy;
public PDOMSearchResult(PDOMSearchQuery query) { public CSearchResult(CSearchQuery query) {
super(); super();
this.query = query; this.query = query;
} }
@ -102,9 +102,9 @@ public class PDOMSearchResult extends AbstractTextSearchResult implements IEdito
@Override @Override
public boolean isShownInEditor(Match match, IEditorPart editor) { public boolean isShownInEditor(Match match, IEditorPart editor) {
final String fileName= getFileName(editor); final String fileName= getFileName(editor);
if (fileName != null && match instanceof PDOMSearchMatch) { if (fileName != null && match instanceof CSearchMatch) {
final IPath filePath= new Path(fileName); final IPath filePath= new Path(fileName);
return filePath.equals(IndexLocationFactory.getAbsolutePath(((PDOMSearchMatch)match).getLocation())); return filePath.equals(IndexLocationFactory.getAbsolutePath(((CSearchMatch)match).getLocation()));
} }
return false; return false;
} }
@ -114,10 +114,10 @@ public class PDOMSearchResult extends AbstractTextSearchResult implements IEdito
List<Match> list = new ArrayList<Match>(); List<Match> list = new ArrayList<Match>();
Object[] elements = result.getElements(); Object[] elements = result.getElements();
for (int i = 0; i < elements.length; ++i) { for (int i = 0; i < elements.length; ++i) {
if (pfilename.equals(IndexLocationFactory.getAbsolutePath(((PDOMSearchElement)elements[i]).getLocation()))) { if (pfilename.equals(IndexLocationFactory.getAbsolutePath(((CSearchElement)elements[i]).getLocation()))) {
Match[] matches = result.getMatches(elements[i]); Match[] matches = result.getMatches(elements[i]);
for (int j = 0; j < matches.length; ++j) { for (int j = 0; j < matches.length; ++j) {
if (matches[j] instanceof PDOMSearchMatch) { if (matches[j] instanceof CSearchMatch) {
list.add(matches[j]); list.add(matches[j]);
} }
} }
@ -159,8 +159,8 @@ public class PDOMSearchResult extends AbstractTextSearchResult implements IEdito
return ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(location.getFullPath())); return ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(location.getFullPath()));
} }
} catch(CoreException ce) { /* fall-through to return null */ } } catch(CoreException ce) { /* fall-through to return null */ }
} else if (element instanceof PDOMSearchElement) { } else if (element instanceof CSearchElement) {
PDOMSearchElement searchElement = (PDOMSearchElement)element; CSearchElement searchElement = (CSearchElement)element;
IIndexFileLocation location = searchElement.getLocation(); IIndexFileLocation location = searchElement.getLocation();
if(location.getFullPath()!=null) { if(location.getFullPath()!=null) {
return ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(location.getFullPath())); return ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(location.getFullPath()));

View file

@ -38,12 +38,12 @@ import org.eclipse.cdt.internal.ui.editor.ASTProvider;
/** /**
* Query for searching the index based on a text selection. * Query for searching the index based on a text selection.
*/ */
public class PDOMSearchTextSelectionQuery extends PDOMSearchQuery { public class CSearchTextSelectionQuery extends CSearchQuery {
private ITranslationUnit tu; private ITranslationUnit tu;
private ITextSelection selection; private ITextSelection selection;
private String label; private String label;
public PDOMSearchTextSelectionQuery(ICElement[] scope, ITranslationUnit tu, ITextSelection selection, int flags) { public CSearchTextSelectionQuery(ICElement[] scope, ITranslationUnit tu, ITextSelection selection, int flags) {
super(scope, flags | IIndex.SEARCH_ACROSS_LANGUAGE_BOUNDARIES); super(scope, flags | IIndex.SEARCH_ACROSS_LANGUAGE_BOUNDARIES);
this.tu = tu; this.tu = tu;
this.selection = selection; this.selection = selection;

View file

@ -42,16 +42,14 @@ import org.eclipse.cdt.internal.core.resources.ResourceLookup;
/** /**
* @author Doug Schaefer * @author Doug Schaefer
*
*/ */
public class PDOMSearchTreeContentProvider implements ITreeContentProvider, IPDOMSearchContentProvider { public class CSearchTreeContentProvider implements ITreeContentProvider, IPDOMSearchContentProvider {
private TreeViewer viewer; private TreeViewer viewer;
private PDOMSearchResult result; private CSearchResult result;
private Map<Object, Set<Object>> tree = new HashMap<Object, Set<Object>>(); private final Map<Object, Set<Object>> tree = new HashMap<Object, Set<Object>>();
private final PDOMSearchViewPage fPage; private final CSearchViewPage fPage;
PDOMSearchTreeContentProvider(PDOMSearchViewPage page) { CSearchTreeContentProvider(CSearchViewPage page) {
fPage= page; fPage= page;
} }
@ -92,7 +90,7 @@ public class PDOMSearchTreeContentProvider implements ITreeContentProvider, IPDO
@Override @Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
this.viewer = (TreeViewer)viewer; this.viewer = (TreeViewer)viewer;
this.result = (PDOMSearchResult) newInput; this.result = (CSearchResult) newInput;
initialize(result); initialize(result);
viewer.refresh(); viewer.refresh();
} }
@ -128,7 +126,7 @@ public class PDOMSearchTreeContentProvider implements ITreeContentProvider, IPDO
return children.add(child); return children.add(child);
} }
private void insertSearchElement(PDOMSearchElement element) { private void insertSearchElement(CSearchElement element) {
IIndexFileLocation location= element.getLocation(); IIndexFileLocation location= element.getLocation();
IFile[] files; IFile[] files;
if(location.getFullPath()!=null) { if(location.getFullPath()!=null) {
@ -181,7 +179,7 @@ public class PDOMSearchTreeContentProvider implements ITreeContentProvider, IPDO
public void elementsChanged(Object[] elements) { public void elementsChanged(Object[] elements) {
if (elements != null) { if (elements != null) {
for (int i = 0; i < elements.length; ++i) { for (int i = 0; i < elements.length; ++i) {
PDOMSearchElement element = (PDOMSearchElement)elements[i]; CSearchElement element = (CSearchElement)elements[i];
if (fPage.getDisplayedMatchCount(element) > 0) { if (fPage.getDisplayedMatchCount(element) > 0) {
insertSearchElement(element); insertSearchElement(element);
} else { } else {
@ -219,7 +217,7 @@ public class PDOMSearchTreeContentProvider implements ITreeContentProvider, IPDO
initialize(result); initialize(result);
} }
private void initialize(final PDOMSearchResult result) { private void initialize(final CSearchResult result) {
this.result = result; this.result = result;
tree.clear(); tree.clear();
if (result != null) { if (result != null) {
@ -230,13 +228,13 @@ public class PDOMSearchTreeContentProvider implements ITreeContentProvider, IPDO
Object[] elements = result.getElements(); Object[] elements = result.getElements();
for (int i = 0; i < elements.length; ++i) { for (int i = 0; i < elements.length; ++i) {
final PDOMSearchElement element = (PDOMSearchElement)elements[i]; final CSearchElement element = (CSearchElement)elements[i];
if (fPage.getDisplayedMatchCount(element) > 0) if (fPage.getDisplayedMatchCount(element) > 0)
insertSearchElement(element); insertSearchElement(element);
} }
// add all the projects which have no results // add all the projects which have no results
ICProject[] projects = ((PDOMSearchQuery)result.getQuery()).getProjects(); ICProject[] projects = ((CSearchQuery)result.getQuery()).getProjects();
for (int i = 0; i < projects.length; ++i) { for (int i = 0; i < projects.length; ++i) {
ICProject project = projects[i]; ICProject project = projects[i];
Object projectResults = tree.get(project); Object projectResults = tree.get(project);

View file

@ -21,9 +21,9 @@ import org.eclipse.cdt.internal.core.model.TranslationUnit;
import org.eclipse.cdt.internal.ui.util.Messages; import org.eclipse.cdt.internal.ui.util.Messages;
public class PDOMSearchTreeLabelProvider extends PDOMSearchLabelProvider { public class CSearchTreeLabelProvider extends CSearchLabelProvider {
public PDOMSearchTreeLabelProvider(PDOMSearchViewPage page) { public CSearchTreeLabelProvider(CSearchViewPage page) {
super(page); super(page);
} }

View file

@ -28,9 +28,9 @@ import org.eclipse.cdt.internal.ui.util.Messages;
* Query for searching unresolved includes in projects. * Query for searching unresolved includes in projects.
* Could be extended to search resources selections. * Could be extended to search resources selections.
*/ */
public class PDOMSearchUnresolvedIncludesQuery extends PDOMSearchQuery { public class CSearchUnresolvedIncludesQuery extends CSearchQuery {
public PDOMSearchUnresolvedIncludesQuery(ICElement[] scope) { public CSearchUnresolvedIncludesQuery(ICElement[] scope) {
super(scope, 0); super(scope, 0);
} }
@ -40,7 +40,7 @@ public class PDOMSearchUnresolvedIncludesQuery extends PDOMSearchQuery {
for (IIndexFile file : index.getAllFiles()) { for (IIndexFile file : index.getAllFiles()) {
for (IIndexInclude include : file.getIncludes()) { for (IIndexInclude include : file.getIncludes()) {
if (include.isActive() && !include.isResolved()) { if (include.isActive() && !include.isResolved()) {
result.addMatch(new PDOMSearchMatch(new ProblemSearchElement( result.addMatch(new CSearchMatch(new ProblemSearchElement(
IProblem.PREPROCESSOR_INCLUSION_NOT_FOUND, include.getFullName(), IProblem.PREPROCESSOR_INCLUSION_NOT_FOUND, include.getFullName(),
include.getIncludedByLocation()), include.getIncludedByLocation()),
include.getNameOffset(), include.getNameLength())); include.getNameOffset(), include.getNameLength()));

View file

@ -21,7 +21,6 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVariableReadWri
import org.eclipse.cdt.internal.core.pdom.dom.PDOMName; import org.eclipse.cdt.internal.core.pdom.dom.PDOMName;
public class CSearchUtil { public class CSearchUtil {
public static int LRU_WORKINGSET_LIST_SIZE= 3; public static int LRU_WORKINGSET_LIST_SIZE= 3;
private static LRUWorkingSets workingSetsCache; private static LRUWorkingSets workingSetsCache;
@ -62,8 +61,7 @@ public class CSearchUtil {
boolean isWrite; boolean isWrite;
if (binding instanceof ICPPVariable) { if (binding instanceof ICPPVariable) {
isWrite = ((CPPVariableReadWriteFlags.getReadWriteFlags(node) & PDOMName.WRITE_ACCESS) != 0); isWrite = ((CPPVariableReadWriteFlags.getReadWriteFlags(node) & PDOMName.WRITE_ACCESS) != 0);
} } else {
else {
isWrite = ((CVariableReadWriteFlags.getReadWriteFlags(node) & PDOMName.WRITE_ACCESS) != 0); isWrite = ((CVariableReadWriteFlags.getReadWriteFlags(node) & PDOMName.WRITE_ACCESS) != 0);
} }
return isWrite; return isWrite;

View file

@ -51,7 +51,7 @@ import org.eclipse.cdt.internal.ui.viewsupport.ColoringLabelProvider;
/** /**
* Implementation of the search view page for index based searches. * Implementation of the search view page for index based searches.
*/ */
public class PDOMSearchViewPage extends AbstractTextSearchViewPage { public class CSearchViewPage extends AbstractTextSearchViewPage {
public static final int LOCATION_COLUMN_INDEX = 0; public static final int LOCATION_COLUMN_INDEX = 0;
public static final int DEFINITION_COLUMN_INDEX = 1; public static final int DEFINITION_COLUMN_INDEX = 1;
public static final int MATCH_COLUMN_INDEX = 2; public static final int MATCH_COLUMN_INDEX = 2;
@ -70,7 +70,7 @@ public class PDOMSearchViewPage extends AbstractTextSearchViewPage {
private IPDOMSearchContentProvider contentProvider; private IPDOMSearchContentProvider contentProvider;
private boolean fShowEnclosingDefinitions; private boolean fShowEnclosingDefinitions;
private ShowEnclosingDefinitionsAction fShowEnclosingDefinitionsAction; private ShowEnclosingDefinitionsAction fShowEnclosingDefinitionsAction;
private int[] fColumnWidths = { 300, 150, 300 }; private final int[] fColumnWidths = { 300, 150, 300 };
private class ShowEnclosingDefinitionsAction extends Action { private class ShowEnclosingDefinitionsAction extends Action {
public ShowEnclosingDefinitionsAction() { public ShowEnclosingDefinitionsAction() {
@ -84,11 +84,11 @@ public class PDOMSearchViewPage extends AbstractTextSearchViewPage {
} }
} }
public PDOMSearchViewPage(int supportedLayouts) { public CSearchViewPage(int supportedLayouts) {
super(supportedLayouts); super(supportedLayouts);
} }
public PDOMSearchViewPage() { public CSearchViewPage() {
super(); super();
} }
@ -196,9 +196,6 @@ public class PDOMSearchViewPage extends AbstractTextSearchViewPage {
* *
*/ */
private class SearchViewerComparator extends ViewerComparator { private class SearchViewerComparator extends ViewerComparator {
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ViewerComparator#compare(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
@Override @Override
public int compare(Viewer viewer, Object e1, Object e2) { public int compare(Viewer viewer, Object e1, Object e2) {
if (e1 instanceof LineSearchElement && e2 instanceof LineSearchElement) { if (e1 instanceof LineSearchElement && e2 instanceof LineSearchElement) {
@ -216,9 +213,6 @@ public class PDOMSearchViewPage extends AbstractTextSearchViewPage {
return super.compare(viewer, e1, e2); return super.compare(viewer, e1, e2);
} }
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ViewerComparator#category(java.lang.Object)
*/
@Override @Override
public int category(Object element) { public int category(Object element) {
// place status messages first // place status messages first
@ -260,10 +254,10 @@ public class PDOMSearchViewPage extends AbstractTextSearchViewPage {
@Override @Override
protected void configureTreeViewer(TreeViewer viewer) { protected void configureTreeViewer(TreeViewer viewer) {
contentProvider = new PDOMSearchTreeContentProvider(this); contentProvider = new CSearchTreeContentProvider(this);
viewer.setComparator(new SearchViewerComparator()); viewer.setComparator(new SearchViewerComparator());
viewer.setContentProvider((PDOMSearchTreeContentProvider)contentProvider); viewer.setContentProvider((CSearchTreeContentProvider)contentProvider);
PDOMSearchTreeLabelProvider innerLabelProvider = new PDOMSearchTreeLabelProvider(this); CSearchTreeLabelProvider innerLabelProvider = new CSearchTreeLabelProvider(this);
ColoringLabelProvider labelProvider = new ColoringLabelProvider(innerLabelProvider); ColoringLabelProvider labelProvider = new ColoringLabelProvider(innerLabelProvider);
viewer.setLabelProvider(labelProvider); viewer.setLabelProvider(labelProvider);
} }
@ -271,9 +265,9 @@ public class PDOMSearchViewPage extends AbstractTextSearchViewPage {
@Override @Override
protected void configureTableViewer(TableViewer viewer) { protected void configureTableViewer(TableViewer viewer) {
createColumns(viewer); createColumns(viewer);
contentProvider = new PDOMSearchListContentProvider(this); contentProvider = new CSearchListContentProvider(this);
viewer.setComparator(new SearchViewerComparator()); viewer.setComparator(new SearchViewerComparator());
viewer.setContentProvider((PDOMSearchListContentProvider)contentProvider); viewer.setContentProvider((CSearchListContentProvider)contentProvider);
} }
@Override @Override
@ -303,7 +297,7 @@ public class PDOMSearchViewPage extends AbstractTextSearchViewPage {
private void createColumns(TableViewer viewer) { private void createColumns(TableViewer viewer) {
for (int i = 0; i < fColumnLabels.length; i++) { for (int i = 0; i < fColumnLabels.length; i++) {
TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE); TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE);
viewerColumn.setLabelProvider(new PDOMSearchListLabelProvider(this, i)); viewerColumn.setLabelProvider(new CSearchListLabelProvider(this, i));
TableColumn tableColumn = viewerColumn.getColumn(); TableColumn tableColumn = viewerColumn.getColumn();
tableColumn.setText(fColumnLabels[i]); tableColumn.setText(fColumnLabels[i]);
tableColumn.setWidth(fColumnWidths[i]); tableColumn.setWidth(fColumnWidths[i]);
@ -321,12 +315,12 @@ public class PDOMSearchViewPage extends AbstractTextSearchViewPage {
@Override @Override
protected void showMatch(Match match, int currentOffset, int currentLength, boolean activate) throws PartInitException { protected void showMatch(Match match, int currentOffset, int currentLength, boolean activate) throws PartInitException {
if (!(match instanceof PDOMSearchMatch)) if (!(match instanceof CSearchMatch))
return; return;
try { try {
Object element= ((PDOMSearchMatch)match).getElement(); Object element= ((CSearchMatch) match).getElement();
IIndexFileLocation ifl= ((PDOMSearchElement)element).getLocation(); IIndexFileLocation ifl= ((CSearchElement) element).getLocation();
IPath path = IndexLocationFactory.getPath(ifl); IPath path = IndexLocationFactory.getPath(ifl);
IEditorPart editor = EditorUtility.openInEditor(path, null, activate); IEditorPart editor = EditorUtility.openInEditor(path, null, activate);
if (editor instanceof ITextEditor) { if (editor instanceof ITextEditor) {

View file

@ -19,7 +19,7 @@ public class HidePolymorphicCalls extends MatchFilter {
@Override @Override
public boolean filters(Match match) { public boolean filters(Match match) {
return match instanceof PDOMSearchMatch && ((PDOMSearchMatch) match).isPolymorphicCall(); return match instanceof CSearchMatch && ((CSearchMatch) match).isPolymorphicCall();
} }
@Override @Override

View file

@ -41,7 +41,7 @@ public interface IPDOMSearchContentProvider {
* TODO: it would be better if IIndexManager told us which projects specifically * TODO: it would be better if IIndexManager told us which projects specifically
* were being indexed at the time, so we could annotate per-project whose results are suspicious * were being indexed at the time, so we could annotate per-project whose results are suspicious
* (which may be none at all for a given search). * (which may be none at all for a given search).
* See the handling of {@link PDOMSearchResult#wasIndexerBusy()}. * See the handling of {@link CSearchResult#wasIndexerBusy()}.
*/ */
static IStatus INCOMPLETE_RESULTS_NODE = static IStatus INCOMPLETE_RESULTS_NODE =
new Status(IStatus.WARNING, CUIPlugin.PLUGIN_ID, new Status(IStatus.WARNING, CUIPlugin.PLUGIN_ID,

View file

@ -31,7 +31,7 @@ import org.eclipse.cdt.internal.core.parser.scanner.InternalFileContent;
/** /**
* Element representing a line with one ore more matches. * Element representing a line with one ore more matches.
*/ */
public class LineSearchElement extends PDOMSearchElement { public class LineSearchElement extends CSearchElement {
public static final class Match { public static final class Match {
private final int fOffset; private final int fOffset;
private final int fLength; private final int fLength;
@ -39,7 +39,8 @@ public class LineSearchElement extends PDOMSearchElement {
private final ICElement fEnclosingElement; private final ICElement fEnclosingElement;
private final boolean fIsWriteAccess; private final boolean fIsWriteAccess;
public Match(int offset, int length, boolean isPolymorphicCall, ICElement enclosingElement, boolean isWriteAccess) { public Match(int offset, int length, boolean isPolymorphicCall, ICElement enclosingElement,
boolean isWriteAccess) {
fOffset = offset; fOffset = offset;
fLength = length; fLength = length;
fIsPolymorphicCall = isPolymorphicCall; fIsPolymorphicCall = isPolymorphicCall;

View file

@ -44,7 +44,7 @@ public class OpenCSearchPageAction implements IWorkbenchWindowActionDelegate {
beep(); beep();
return; return;
} }
NewSearchUI.openSearchDialog(fWindow, PDOMSearchPage.EXTENSION_ID); NewSearchUI.openSearchDialog(fWindow, CSearchPage.EXTENSION_ID);
} }
@Override @Override

View file

@ -15,7 +15,7 @@ import org.eclipse.cdt.core.index.IIndexFileLocation;
/** /**
* Represents a problem in a search. * Represents a problem in a search.
*/ */
public class ProblemSearchElement extends PDOMSearchElement { public class ProblemSearchElement extends CSearchElement {
private final int fProblemID; private final int fProblemID;
private final String fDetail; private final String fDetail;

View file

@ -23,7 +23,7 @@ import org.eclipse.cdt.internal.core.browser.ASTTypeInfo;
/** /**
* Represents a a c/c++-entity in a search. * Represents a a c/c++-entity in a search.
*/ */
public class TypeInfoSearchElement extends PDOMSearchElement { public class TypeInfoSearchElement extends CSearchElement {
private final ITypeInfo typeInfo; private final ITypeInfo typeInfo;
public TypeInfoSearchElement(IIndex index, IIndexName name, IIndexBinding binding) throws CoreException { public TypeInfoSearchElement(IIndex index, IIndexName name, IIndexBinding binding) throws CoreException {

View file

@ -27,9 +27,9 @@ import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.internal.ui.editor.CEditor; import org.eclipse.cdt.internal.ui.editor.CEditor;
import org.eclipse.cdt.internal.ui.search.CSearchMessages; import org.eclipse.cdt.internal.ui.search.CSearchMessages;
import org.eclipse.cdt.internal.ui.search.PDOMSearchElementQuery; import org.eclipse.cdt.internal.ui.search.CSearchElementQuery;
import org.eclipse.cdt.internal.ui.search.PDOMSearchQuery; import org.eclipse.cdt.internal.ui.search.CSearchQuery;
import org.eclipse.cdt.internal.ui.search.PDOMSearchTextSelectionQuery; import org.eclipse.cdt.internal.ui.search.CSearchTextSelectionQuery;
import org.eclipse.cdt.internal.ui.text.CWordFinder; import org.eclipse.cdt.internal.ui.text.CWordFinder;
@ -76,12 +76,12 @@ public abstract class FindAction extends SelectionParseAction {
NewSearchUI.runQueryInBackground(searchJob); NewSearchUI.runQueryInBackground(searchJob);
} }
protected PDOMSearchQuery createQuery(ISourceReference object) { protected CSearchQuery createQuery(ISourceReference object) {
return new PDOMSearchElementQuery(getScope(), object, getLimitTo()); return new CSearchElementQuery(getScope(), object, getLimitTo());
} }
protected PDOMSearchQuery createQuery(ICElement element, ITextSelection selNode) { protected CSearchQuery createQuery(ICElement element, ITextSelection selNode) {
return new PDOMSearchTextSelectionQuery(getScope(), return new CSearchTextSelectionQuery(getScope(),
(ITranslationUnit) element, selNode, getLimitTo()); (ITranslationUnit) element, selNode, getLimitTo());
} }

View file

@ -14,7 +14,7 @@ package org.eclipse.cdt.internal.ui.search.actions;
import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.internal.ui.editor.CEditor; import org.eclipse.cdt.internal.ui.editor.CEditor;
import org.eclipse.cdt.internal.ui.search.CSearchMessages; import org.eclipse.cdt.internal.ui.search.CSearchMessages;
import org.eclipse.cdt.internal.ui.search.PDOMSearchQuery; import org.eclipse.cdt.internal.ui.search.CSearchQuery;
import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.IWorkbenchSite;
@ -56,6 +56,6 @@ public class FindDeclarationsAction extends FindAction {
@Override @Override
protected int getLimitTo() { protected int getLimitTo() {
return PDOMSearchQuery.FIND_DECLARATIONS_DEFINITIONS; return CSearchQuery.FIND_DECLARATIONS_DEFINITIONS;
} }
} }

View file

@ -16,7 +16,7 @@ import org.eclipse.ui.IWorkingSet;
import org.eclipse.cdt.internal.ui.editor.CEditor; import org.eclipse.cdt.internal.ui.editor.CEditor;
import org.eclipse.cdt.internal.ui.search.CSearchMessages; import org.eclipse.cdt.internal.ui.search.CSearchMessages;
import org.eclipse.cdt.internal.ui.search.PDOMSearchQuery; import org.eclipse.cdt.internal.ui.search.CSearchQuery;
public class FindDeclarationsInWorkingSetAction extends FindInWorkingSetAction { public class FindDeclarationsInWorkingSetAction extends FindInWorkingSetAction {
@ -36,6 +36,6 @@ public class FindDeclarationsInWorkingSetAction extends FindInWorkingSetAction {
@Override @Override
protected int getLimitTo() { protected int getLimitTo() {
return PDOMSearchQuery.FIND_DECLARATIONS_DEFINITIONS; return CSearchQuery.FIND_DECLARATIONS_DEFINITIONS;
} }
} }

View file

@ -15,7 +15,7 @@ import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.internal.ui.editor.CEditor; import org.eclipse.cdt.internal.ui.editor.CEditor;
import org.eclipse.cdt.internal.ui.search.CSearchMessages; import org.eclipse.cdt.internal.ui.search.CSearchMessages;
import org.eclipse.cdt.internal.ui.search.PDOMSearchQuery; import org.eclipse.cdt.internal.ui.search.CSearchQuery;
import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResource;
import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.IStructuredSelection;
@ -73,7 +73,7 @@ public class FindDeclarationsProjectAction extends FindAction {
@Override @Override
protected int getLimitTo() { protected int getLimitTo() {
return PDOMSearchQuery.FIND_DECLARATIONS_DEFINITIONS; return CSearchQuery.FIND_DECLARATIONS_DEFINITIONS;
} }
} }

View file

@ -13,7 +13,7 @@ package org.eclipse.cdt.internal.ui.search.actions;
import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.internal.ui.editor.CEditor; import org.eclipse.cdt.internal.ui.editor.CEditor;
import org.eclipse.cdt.internal.ui.search.CSearchMessages; import org.eclipse.cdt.internal.ui.search.CSearchMessages;
import org.eclipse.cdt.internal.ui.search.PDOMSearchQuery; import org.eclipse.cdt.internal.ui.search.CSearchQuery;
import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.IWorkbenchSite;
public class FindRefsAction extends FindAction { public class FindRefsAction extends FindAction {
@ -54,6 +54,6 @@ public class FindRefsAction extends FindAction {
@Override @Override
protected int getLimitTo() { protected int getLimitTo() {
return PDOMSearchQuery.FIND_REFERENCES; return CSearchQuery.FIND_REFERENCES;
} }
} }

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