From 3d08050db856df5bc98ec2fd1959fb48bb153bef Mon Sep 17 00:00:00 2001 From: Chris Recoskie Date: Mon, 22 Aug 2011 13:19:10 -0400 Subject: [PATCH 01/29] Bug 355399 - NPE in ScannerInfoConsoleParserUtility.translateRelativePaths() for remote projects --- .../scannerconfig/gnu/ScannerInfoConsoleParserUtility.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig/gnu/ScannerInfoConsoleParserUtility.java b/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig/gnu/ScannerInfoConsoleParserUtility.java index 6ad7efeff3c..2cd11728e96 100644 --- a/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig/gnu/ScannerInfoConsoleParserUtility.java +++ b/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig/gnu/ScannerInfoConsoleParserUtility.java @@ -23,6 +23,7 @@ import org.eclipse.cdt.internal.core.resources.ResourceLookup; import org.eclipse.cdt.make.core.MakeCorePlugin; import org.eclipse.cdt.make.internal.core.MakeMessages; import org.eclipse.cdt.make.internal.core.scannerconfig.util.TraceUtil; +import org.eclipse.cdt.utils.EFSExtensionManager; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; @@ -220,7 +221,7 @@ public class ScannerInfoConsoleParserUtility extends AbstractGCCBOPConsoleParser // appending fileName to cwd should yield file path filePath = cwd.append(fileName); } - if (!filePath.toString().equalsIgnoreCase(file.getLocation().toString())) { + if (!filePath.toString().equalsIgnoreCase(EFSExtensionManager.getDefault().getPathFromURI(file.getLocationURI()))) { // must be the cwd is wrong // check if file name starts with ".." if (fileName.startsWith("..")) { //$NON-NLS-1$ From 53e62ebcc571214d2a211754092432b4c6bb1939 Mon Sep 17 00:00:00 2001 From: Chris Recoskie Date: Mon, 22 Aug 2011 15:29:57 -0400 Subject: [PATCH 02/29] Bug 355399 - NPE in ScannerInfoConsoleParserUtility.translateRelativePaths() for remote projects --- .../core/scannerconfig/gnu/ScannerInfoConsoleParserUtility.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig/gnu/ScannerInfoConsoleParserUtility.java b/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig/gnu/ScannerInfoConsoleParserUtility.java index 2cd11728e96..1ff5e0f1e53 100644 --- a/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig/gnu/ScannerInfoConsoleParserUtility.java +++ b/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/scannerconfig/gnu/ScannerInfoConsoleParserUtility.java @@ -238,7 +238,7 @@ public class ScannerInfoConsoleParserUtility extends AbstractGCCBOPConsoleParser tPath = tPath.removeFirstSegments(1); } // get the file path from the file - filePath = file.getLocation(); + filePath = new Path(EFSExtensionManager.getDefault().getPathFromURI(file.getLocationURI())); IPath lastFileSegment = filePath.removeFirstSegments(filePath.segmentCount() - tPath.segmentCount()); if (lastFileSegment.matchingFirstSegments(tPath) == tPath.segmentCount()) { cwd = filePath.removeLastSegments(tPath.segmentCount()); From 6f2671b1eeccb5ede9328c1aa89db3e2bf232f8f Mon Sep 17 00:00:00 2001 From: Alena Laskavaia Date: Mon, 22 Aug 2011 22:46:24 -0400 Subject: [PATCH 03/29] Bug 352221 - Quick Fix for "case break" checker --- .../META-INF/MANIFEST.MF | 3 +- .../plugin.xml | 9 ++ .../ui/quickfix/CaseBreakQuickFixBreak.java | 112 ++++++++++++++++++ .../ui/quickfix/CaseBreakQuickFixComment.java | 55 +++++++++ .../checkers/ui/quickfix/Messages.java | 2 + .../checkers/ui/quickfix/messages.properties | 2 + .../internal/checkers/CaseBreakChecker.java | 65 ++++++---- .../checkers/CheckersMessages.properties | 2 +- .../checkers/CaseBreakCheckerTest.java | 70 +++++------ .../core/test/AutomatedIntegrationSuite.java | 2 + .../cdt/codan/core/test/CheckerTestCase.java | 11 +- .../cdt/codan/core/test/CodanTestCase.java | 28 +++-- .../ui/quickfix/CaseBreakQuickFixTest.java | 52 ++++++++ 13 files changed, 345 insertions(+), 68 deletions(-) create mode 100644 codan/org.eclipse.cdt.codan.checkers.ui/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/CaseBreakQuickFixBreak.java create mode 100644 codan/org.eclipse.cdt.codan.checkers.ui/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/CaseBreakQuickFixComment.java create mode 100644 codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/CaseBreakQuickFixTest.java diff --git a/codan/org.eclipse.cdt.codan.checkers.ui/META-INF/MANIFEST.MF b/codan/org.eclipse.cdt.codan.checkers.ui/META-INF/MANIFEST.MF index d08c9b9ea83..01e93429945 100644 --- a/codan/org.eclipse.cdt.codan.checkers.ui/META-INF/MANIFEST.MF +++ b/codan/org.eclipse.cdt.codan.checkers.ui/META-INF/MANIFEST.MF @@ -12,7 +12,8 @@ Require-Bundle: org.eclipse.ui, org.eclipse.cdt.core, org.eclipse.cdt.codan.core.cxx, org.eclipse.cdt.codan.ui.cxx, - org.eclipse.cdt.codan.core + org.eclipse.cdt.codan.core, + org.eclipse.cdt.codan.checkers Bundle-ActivationPolicy: lazy Bundle-RequiredExecutionEnvironment: J2SE-1.5 Bundle-Vendor: %Bundle-Vendor diff --git a/codan/org.eclipse.cdt.codan.checkers.ui/plugin.xml b/codan/org.eclipse.cdt.codan.checkers.ui/plugin.xml index 839147f898d..0d9a0bfa5c2 100644 --- a/codan/org.eclipse.cdt.codan.checkers.ui/plugin.xml +++ b/codan/org.eclipse.cdt.codan.checkers.ui/plugin.xml @@ -37,6 +37,15 @@ class="org.eclipse.cdt.codan.internal.checkers.ui.quickfix.QuickFixCreateParameter" problemId="org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem"> + + + + + diff --git a/codan/org.eclipse.cdt.codan.checkers.ui/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/CaseBreakQuickFixBreak.java b/codan/org.eclipse.cdt.codan.checkers.ui/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/CaseBreakQuickFixBreak.java new file mode 100644 index 00000000000..f00a37497c0 --- /dev/null +++ b/codan/org.eclipse.cdt.codan.checkers.ui/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/CaseBreakQuickFixBreak.java @@ -0,0 +1,112 @@ +/******************************************************************************* + * Copyright (c) 2011 Gil Barash + * 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: + * Gil Barash - Initial implementation + *******************************************************************************/ +package org.eclipse.cdt.codan.internal.checkers.ui.quickfix; + +import org.eclipse.cdt.codan.core.cxx.CxxAstUtils; +import org.eclipse.cdt.codan.internal.checkers.ui.CheckersUiActivator; +import org.eclipse.cdt.codan.ui.AbstractAstRewriteQuickFix; +import org.eclipse.cdt.core.dom.ast.IASTBreakStatement; +import org.eclipse.cdt.core.dom.ast.IASTCompoundStatement; +import org.eclipse.cdt.core.dom.ast.IASTNode; +import org.eclipse.cdt.core.dom.ast.IASTNodeSelector; +import org.eclipse.cdt.core.dom.ast.IASTStatement; +import org.eclipse.cdt.core.dom.ast.IASTSwitchStatement; +import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; +import org.eclipse.cdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.cdt.core.index.IIndex; +import org.eclipse.cdt.core.model.ITranslationUnit; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IRegion; +import org.eclipse.ltk.core.refactoring.Change; + +public class CaseBreakQuickFixBreak extends AbstractAstRewriteQuickFix { + @Override + public boolean isApplicable(IMarker marker) { + int line = marker.getAttribute(IMarker.LINE_NUMBER, -1) - 1; + if (line < 0) + return false; + return true; + } + + public String getLabel() { + return Messages.CaseBreakQuickFixBreak_Label; + } + + protected IASTStatement getStmtBeforeBreak(IMarker marker, IASTTranslationUnit ast) throws BadLocationException { + int line = marker.getAttribute(IMarker.LINE_NUMBER, -1) - 1; + if (line < 0) + return null; + IRegion lineInformation = getDocument().getLineInformation(line); + IASTNodeSelector nodeSelector = ast.getNodeSelector(null); + IASTNode containedNode = nodeSelector.findFirstContainedNode(lineInformation.getOffset(), lineInformation.getLength()); + IASTNode beforeBreakNode = null; + if (containedNode != null) + beforeBreakNode = CxxAstUtils.getInstance().getEnclosingStatement(containedNode); + else + beforeBreakNode = nodeSelector.findEnclosingNode(lineInformation.getOffset(), lineInformation.getLength()); + if (beforeBreakNode instanceof IASTCompoundStatement) { + while (beforeBreakNode != null) { + if (beforeBreakNode.getParent() instanceof IASTCompoundStatement + && beforeBreakNode.getParent().getParent() instanceof IASTSwitchStatement) { + if (beforeBreakNode instanceof IASTCompoundStatement) { + IASTStatement[] statements = ((IASTCompoundStatement) beforeBreakNode).getStatements(); + return statements[statements.length - 1]; // return last one + } + return (IASTStatement) beforeBreakNode; + } + beforeBreakNode = beforeBreakNode.getParent(); + } + } + if (beforeBreakNode instanceof IASTStatement) + return (IASTStatement) beforeBreakNode; + return null; + } + + @Override + public void modifyAST(IIndex index, IMarker marker) { + try { + IASTTranslationUnit ast = getTranslationUnitViaEditor(marker).getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS); + IASTStatement beforeBreak = getStmtBeforeBreak(marker, ast); + if (beforeBreak.getParent() instanceof IASTCompoundStatement) { + IASTCompoundStatement enclosingStatement = (IASTCompoundStatement) beforeBreak.getParent(); + IASTStatement after = getAfterStatement(beforeBreak); + ASTRewrite r = ASTRewrite.create(enclosingStatement.getTranslationUnit()); + IASTBreakStatement breakStatement = ast.getASTNodeFactory().newBreakStatement(); + r.insertBefore(enclosingStatement, after, breakStatement, null); + Change c = r.rewriteAST(); + c.perform(new NullProgressMonitor()); + } + } catch (CoreException e) { + CheckersUiActivator.log(e); + } catch (BadLocationException e) { + CheckersUiActivator.log(e); + } + } + + private IASTStatement getAfterStatement(IASTStatement beforeBreak) { + IASTCompoundStatement enclosingStatement = (IASTCompoundStatement) beforeBreak.getParent(); + IASTStatement after = null; + IASTStatement[] statements = enclosingStatement.getStatements(); + for (int i = 0; i < statements.length; i++) { + IASTStatement st = statements[i]; + if (st == beforeBreak) { + if (i < statements.length - 1) { + after = statements[i + 1]; + break; + } + } + } + return after; + } +} diff --git a/codan/org.eclipse.cdt.codan.checkers.ui/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/CaseBreakQuickFixComment.java b/codan/org.eclipse.cdt.codan.checkers.ui/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/CaseBreakQuickFixComment.java new file mode 100644 index 00000000000..27b95adaf87 --- /dev/null +++ b/codan/org.eclipse.cdt.codan.checkers.ui/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/CaseBreakQuickFixComment.java @@ -0,0 +1,55 @@ +package org.eclipse.cdt.codan.internal.checkers.ui.quickfix; + +import org.eclipse.cdt.codan.core.model.IProblem; +import org.eclipse.cdt.codan.core.param.RootProblemPreference; +import org.eclipse.cdt.codan.internal.checkers.CaseBreakChecker; +import org.eclipse.cdt.codan.ui.AbstractCodanCMarkerResolution; +import org.eclipse.core.resources.IMarker; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.text.edits.InsertEdit; +import org.eclipse.text.edits.MalformedTreeException; + +public class CaseBreakQuickFixComment extends AbstractCodanCMarkerResolution { + public String getLabel() { + return Messages.CaseBreakQuickFixComment_Label; + } + + @Override + public void apply(IMarker marker, IDocument document) { + try { + int line = marker.getAttribute(IMarker.LINE_NUMBER, -1); + if (line < 0) + return; + int offset = document.getLineOffset(line); + String indent = getIndentationStr(document, line); + String comment = getNoBreakComment(marker); + String editStr = String.format("%s/* %s */\n", indent, comment);//$NON-NLS-1$ + InsertEdit edit = new InsertEdit(offset, editStr); + edit.apply(document); + } catch (MalformedTreeException e) { + return; + } catch (BadLocationException e) { + return; + } + } + + private String getIndentationStr(IDocument document, int line) throws BadLocationException { + int prevLine = line - 1; + IRegion lineInformation = document.getLineInformation(prevLine); + String prevLineStr = document.get(lineInformation.getOffset(), lineInformation.getLength()); + int nonSpace = prevLineStr.indexOf(prevLineStr.trim()); + String indent = prevLineStr.substring(0, nonSpace); + return indent; + } + + private String getNoBreakComment(IMarker marker) { + IProblem problem = getProblem(marker); + RootProblemPreference map = (RootProblemPreference) problem.getPreference(); + String comment = (String) map.getChildValue(CaseBreakChecker.PARAM_NO_BREAK_COMMENT); + if (comment == null || comment.trim().length() == 0) + comment = "no break"; //$NON-NLS-1$ + return comment; + } +} diff --git a/codan/org.eclipse.cdt.codan.checkers.ui/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/Messages.java b/codan/org.eclipse.cdt.codan.checkers.ui/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/Messages.java index dee3330d91b..0a7a6864aa0 100644 --- a/codan/org.eclipse.cdt.codan.checkers.ui/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/Messages.java +++ b/codan/org.eclipse.cdt.codan.checkers.ui/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/Messages.java @@ -4,6 +4,8 @@ import org.eclipse.osgi.util.NLS; public class Messages extends NLS { private static final String BUNDLE_NAME = "org.eclipse.cdt.codan.internal.checkers.ui.quickfix.messages"; //$NON-NLS-1$ + public static String CaseBreakQuickFixBreak_Label; + public static String CaseBreakQuickFixComment_Label; public static String QuickFixCreateField_0; public static String QuickFixCreateLocalVariable_0; public static String QuickFixCreateParameter_0; diff --git a/codan/org.eclipse.cdt.codan.checkers.ui/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/messages.properties b/codan/org.eclipse.cdt.codan.checkers.ui/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/messages.properties index da3f433fce7..0afc2cc4215 100644 --- a/codan/org.eclipse.cdt.codan.checkers.ui/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/messages.properties +++ b/codan/org.eclipse.cdt.codan.checkers.ui/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/messages.properties @@ -1,3 +1,5 @@ +CaseBreakQuickFixBreak_Label=Add break statement +CaseBreakQuickFixComment_Label=Add supressing comment QuickFixCreateField_0=Create field QuickFixCreateLocalVariable_0=Create local variable QuickFixCreateParameter_0=Create parameter \ No newline at end of file diff --git a/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/CaseBreakChecker.java b/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/CaseBreakChecker.java index a56b94379f5..dfd564bbb40 100644 --- a/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/CaseBreakChecker.java +++ b/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/CaseBreakChecker.java @@ -1,10 +1,10 @@ /******************************************************************************* - * Copyright (c) 2010,2011 Gil Barash + * Copyright (c) 2010,2011 Gil Barash * 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: * Gil Barash - Initial implementation * Elena laskavaia - Rewrote checker to reduce false positives in complex cases @@ -14,6 +14,8 @@ package org.eclipse.cdt.codan.internal.checkers; import org.eclipse.cdt.codan.core.cxx.CxxAstUtils; import org.eclipse.cdt.codan.core.cxx.model.AbstractIndexAstChecker; import org.eclipse.cdt.codan.core.model.ICheckerWithPreferences; +import org.eclipse.cdt.codan.core.model.IProblemLocation; +import org.eclipse.cdt.codan.core.model.IProblemLocationFactory; import org.eclipse.cdt.codan.core.model.IProblemWorkingCopy; import org.eclipse.cdt.core.dom.ast.ASTVisitor; import org.eclipse.cdt.core.dom.ast.IASTBreakStatement; @@ -23,9 +25,11 @@ import org.eclipse.cdt.core.dom.ast.IASTCompoundStatement; import org.eclipse.cdt.core.dom.ast.IASTContinueStatement; import org.eclipse.cdt.core.dom.ast.IASTDefaultStatement; import org.eclipse.cdt.core.dom.ast.IASTExpressionStatement; +import org.eclipse.cdt.core.dom.ast.IASTFileLocation; import org.eclipse.cdt.core.dom.ast.IASTGotoStatement; import org.eclipse.cdt.core.dom.ast.IASTIfStatement; import org.eclipse.cdt.core.dom.ast.IASTMacroExpansionLocation; +import org.eclipse.cdt.core.dom.ast.IASTNode; import org.eclipse.cdt.core.dom.ast.IASTNodeLocation; import org.eclipse.cdt.core.dom.ast.IASTReturnStatement; import org.eclipse.cdt.core.dom.ast.IASTStatement; @@ -40,7 +44,10 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke public static final String DEFAULT_NO_BREAK_COMMENT = "no break"; //$NON-NLS-1$ private Boolean _checkLastCase; // Should we check the last case in the switch? private Boolean _checkEmptyCase; // Should we check an empty case (a case without any statements within it) - private String _noBreakComment; // The comment suppressing this warning + private String _noBreakComment; // The comment suppressing this warning + + public CaseBreakChecker() { + } /** * This visitor looks for "switch" statements and invokes "SwitchVisitor" on @@ -72,7 +79,7 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke @Override public int visit(IASTStatement statement) { - if (statement instanceof IASTSwitchStatement && !isProducedMyMacroExpansion(statement)) { + if (statement instanceof IASTSwitchStatement && !isProducedByMacroExpansion(statement)) { IASTSwitchStatement switchStmt = (IASTSwitchStatement) statement; IASTStatement body = switchStmt.getBody(); if (body instanceof IASTCompoundStatement) { @@ -110,10 +117,10 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke } if (comment != null) { String str = getTrimmedComment(comment); - if (str.equalsIgnoreCase(_noBreakComment)) + if (str.toLowerCase().contains(_noBreakComment.toLowerCase())) continue; } - reportProblem(ER_ID, prevCase, (Object) null); + reportProblem(curr, prevCase); } } } @@ -136,13 +143,13 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke * @return */ public boolean isFallThroughStamement(IASTStatement body) { - if (body == null) return true; + if (body == null) + return true; if (body instanceof IASTCompoundStatement) { IASTStatement[] statements = ((IASTCompoundStatement) body).getStatements(); if (statements.length > 0) { - return isFallThroughStamement(statements[statements.length - 1]); + return isFallThroughStamement(statements[statements.length - 1]); } - return true; } else if (isBreakOrExitStatement(body)) { return false; @@ -150,26 +157,36 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke return true; } else if (body instanceof IASTIfStatement) { IASTIfStatement ifs = (IASTIfStatement) body; - return isFallThroughStamement(ifs.getThenClause()) || isFallThroughStamement(ifs.getElseClause()) ; + return isFallThroughStamement(ifs.getThenClause()) || isFallThroughStamement(ifs.getElseClause()); } return true; // TODO } - - /** - * Checks if the given statement is a result of macro expansion with a possible - * exception for the trailing semicolon. - * - * @param statement the statement to check. - * @return true if the statement is a result of macro expansion - */ - private boolean isProducedMyMacroExpansion(IASTStatement statement) { - IASTNodeLocation[] locations = statement.getNodeLocations(); - return locations.length > 0 && locations[0] instanceof IASTMacroExpansionLocation && - (locations.length == 1 || locations.length == 2 && locations[1].getNodeLength() == 1); - } } - public CaseBreakChecker() { + public void reportProblem(IASTStatement curr, IASTStatement prevCase) { + reportProblem(ER_ID, getProblemLocationAtEndOfNode(curr)); + } + + private IProblemLocation getProblemLocationAtEndOfNode(IASTNode astNode) { + IASTFileLocation astLocation = astNode.getFileLocation(); + int line = astLocation.getEndingLineNumber(); + IProblemLocationFactory locFactory = getRuntime().getProblemLocationFactory(); + return locFactory.createProblemLocation(getFile(), -1, + -1, line); + } + + /** + * Checks if the given statement is a result of macro expansion with a + * possible + * exception for the trailing semicolon. + * + * @param statement the statement to check. + * @return true if the statement is a result of macro expansion + */ + private boolean isProducedByMacroExpansion(IASTStatement statement) { + IASTNodeLocation[] locations = statement.getNodeLocations(); + return locations.length > 0 && locations[0] instanceof IASTMacroExpansionLocation + && (locations.length == 1 || locations.length == 2 && locations[1].getNodeLength() == 1); } /** diff --git a/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/CheckersMessages.properties b/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/CheckersMessages.properties index b219b977cff..e7f79019b3f 100644 --- a/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/CheckersMessages.properties +++ b/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/CheckersMessages.properties @@ -8,7 +8,7 @@ # Contributors: # Alena Laskavaia - initial API and implementation ############################################################################### -CaseBreakChecker_DefaultNoBreakCommentDescription=Comment text to suppress the problem (regular expression): +CaseBreakChecker_DefaultNoBreakCommentDescription=Comment text to suppress the problem: CaseBreakChecker_EmptyCaseDescription=Check also empty case statement (except if last) CaseBreakChecker_LastCaseDescription=Check also the last case statement ClassMembersInitializationChecker_SkipConstructorsWithFCalls=Skip constructors with initialization function calls diff --git a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/CaseBreakCheckerTest.java b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/CaseBreakCheckerTest.java index 3872ba617e9..083aff6960c 100644 --- a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/CaseBreakCheckerTest.java +++ b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/CaseBreakCheckerTest.java @@ -62,7 +62,7 @@ public class CaseBreakCheckerTest extends CheckerTestCase { // } public void testLastCaseBad() { loadCodeAndRun(getAboveComment()); - checkErrorLines(4); + checkErrorLines(5); } // void foo(void) { @@ -181,7 +181,7 @@ public class CaseBreakCheckerTest extends CheckerTestCase { // } public void testEmptyLastCaseTwoSwitches() { loadCodeAndRun(getAboveComment()); - checkErrorLines(3); + checkErrorLines(7); } // void foo(void) { @@ -222,7 +222,7 @@ public class CaseBreakCheckerTest extends CheckerTestCase { // } public void testLastCaseBadCommentNotLast() { loadCodeAndRun(getAboveComment()); - checkErrorLines(4); + checkErrorLines(7); } // void foo(void) { @@ -246,70 +246,74 @@ public class CaseBreakCheckerTest extends CheckerTestCase { // case 6: // b = 2; // /* no break1 */ + // case 7: + // b = 2; + // /* fallthrough */ // } // } public void testDifferentComments() { loadCodeAndRun(getAboveComment()); - checkErrorLines(16, 19); + checkErrorLines(17,23); } // void foo(void) { // int a, b; // switch( a ) { - // case 1: + // case 1: //err // // lolo - // case 2: - // case 3: + // case 2: //err + // case 3://err // } // // switch( a ) { // case 1: - // b = 2; + // b = 2; // err // // lolo // case 2: - // b = 2; - // case 3: + // b = 2; // err + // case 3: // err // case 4: // break; - // case 5: - // case 6: + // case 5: // err + // case 6: // err // } // // switch( a ) { // case 1: - // b = 2; + // b = 2; // err // // lolo // case 2: - // b = 2; + // b = 2; //err // case 3: // b = 2; // /* no break */ // case 4: - // b = 2; + // b = 2; // err // case 5: // b = 2; // break; // case 6: // b = 2; // /* no break */ - // b = 2; + // b = 2; //err // case 7: - // b = 2; + // b = 2;//err // } // // switch( a ) { // case 1: - // b = 2; + // b = 2; // err // // lolo // case 2: - // b = 2; - // default: + // b = 2; // err + // default: //err // } // } public void testGeneral1() { setEmpty(true); + setLast(true); loadCodeAndRun(getAboveComment()); - checkErrorLines(4, 6, 7, 11, 14, 16, 19, 20, 24, 27, 32, 37, 41, 46, 49, 51); + checkErrorComments(); } // void foo(void) { @@ -339,7 +343,7 @@ public class CaseBreakCheckerTest extends CheckerTestCase { // } public void testGeneralComments1() { loadCodeAndRun(getAboveComment()); - checkErrorLines(8, 12); + checkErrorLines(9, 14); } // void foo(void) { @@ -347,14 +351,14 @@ public class CaseBreakCheckerTest extends CheckerTestCase { // switch( a ) { // case 0: // switch( b ) { - // case 2: - // } + // case 2: // err + // } // err // // case 1: // switch( b ) { // case 2: // break; - // } + // } // err // case 3: // switch( b ) { // case 2: @@ -365,17 +369,17 @@ public class CaseBreakCheckerTest extends CheckerTestCase { // switch( b ) { // case 2: // /* no break */ - // } + // } // err // case 5: // switch( b ) { - // case 2: + // case 2: // err // } // /* no break */ // } // } public void testNestedSwitches() { loadCodeAndRun(getAboveComment()); - checkErrorLines(4, 20, 6, 9, 27); + checkErrorComments(); } // void foo(void) { @@ -441,16 +445,16 @@ public class CaseBreakCheckerTest extends CheckerTestCase { // switch( a ) { // case 1: // while (a--) - // break; + // break; // err // case 2: // while (a--) { // break; - // } + // } // err // } // } public void testEmptyCaseWithLoopBreak() { loadCodeAndRun(getAboveComment()); - checkErrorLines(3, 6); + checkErrorComments(); } // void foo(int a) { @@ -518,7 +522,7 @@ public class CaseBreakCheckerTest extends CheckerTestCase { public void testIfErr() { String code = getAboveComment(); loadCodeAndRun(code); - checkErrorLine(3); + checkErrorLine(7); } // #define DEFINE_BREAK {break;} @@ -568,6 +572,6 @@ public class CaseBreakCheckerTest extends CheckerTestCase { public void testEmptyCompoundStatement() { String code = getAboveComment(); loadCodeAndRun(code); - checkErrorLine(4); + checkErrorLine(6); } } diff --git a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/test/AutomatedIntegrationSuite.java b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/test/AutomatedIntegrationSuite.java index b832bcd40fe..7f700eaea05 100644 --- a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/test/AutomatedIntegrationSuite.java +++ b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/test/AutomatedIntegrationSuite.java @@ -30,6 +30,7 @@ import org.eclipse.cdt.codan.core.internal.checkers.StatementHasNoEffectCheckerT import org.eclipse.cdt.codan.core.internal.checkers.SuggestedParenthesisCheckerTest; import org.eclipse.cdt.codan.core.internal.checkers.SuspiciousSemicolonCheckerTest; import org.eclipse.cdt.codan.core.internal.checkers.UnusedSymbolInFileScopeCheckerTest; +import org.eclipse.cdt.codan.internal.checkers.ui.quickfix.CaseBreakQuickFixTest; import org.eclipse.cdt.codan.internal.checkers.ui.quickfix.CatchByReferenceQuickFixTest; import org.eclipse.cdt.codan.internal.checkers.ui.quickfix.CreateLocalVariableQuickFixTest; import org.eclipse.cdt.codan.internal.checkers.ui.quickfix.SuggestedParenthesisQuickFixTest; @@ -74,6 +75,7 @@ public class AutomatedIntegrationSuite extends TestSuite { suite.addTestSuite(CreateLocalVariableQuickFixTest.class); suite.addTestSuite(SuggestedParenthesisQuickFixTest.class); suite.addTestSuite(CatchByReferenceQuickFixTest.class); + suite.addTestSuite(CaseBreakQuickFixTest.class); return suite; } } diff --git a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/test/CheckerTestCase.java b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/test/CheckerTestCase.java index e135de07b71..391cc8c6591 100644 --- a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/test/CheckerTestCase.java +++ b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/test/CheckerTestCase.java @@ -33,7 +33,7 @@ import org.eclipse.core.runtime.NullProgressMonitor; * method to get source directory for the tests, * default is "src". To make it read comment from java class, you need to * include this source directory (with test java files) into the build bundle. - * + * */ @SuppressWarnings("nls") public class CheckerTestCase extends CodanTestCase { @@ -50,6 +50,13 @@ public class CheckerTestCase extends CodanTestCase { assertEquals(args.length, markers.length); } + public void checkErrorComments() { + for (Object i : errLines) { + checkErrorLine((Integer) i); + } + assertEquals("Expected number of errors "+errLines.size(),errLines.size(), markers.length); + } + public IMarker checkErrorLine(int i, String problemId) { return checkErrorLine(currentFile, i, problemId); } @@ -82,7 +89,7 @@ public class CheckerTestCase extends CodanTestCase { break; } } - assertEquals(Integer.valueOf(expectedLine), line); + assertEquals("Error on line "+expectedLine+" is not found",Integer.valueOf(expectedLine), line); if (file != null) assertEquals(file.getName(), mfile); assertTrue(found); diff --git a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/test/CodanTestCase.java b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/test/CodanTestCase.java index 76b3397fd6e..5ce5343e19d 100644 --- a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/test/CodanTestCase.java +++ b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/test/CodanTestCase.java @@ -10,6 +10,12 @@ *******************************************************************************/ package org.eclipse.cdt.codan.core.test; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; + import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.IPDOMManager; import org.eclipse.cdt.core.model.CModelException; @@ -30,12 +36,6 @@ import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Plugin; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.ArrayList; - /** * TODO: add description */ @@ -47,6 +47,7 @@ public class CodanTestCase extends BaseTestCase { protected File currentFile; protected ICElement currentCElem; protected IFile currentIFile; + protected ArrayList errLines= new ArrayList(); /** * @@ -220,7 +221,9 @@ public class CodanTestCase extends BaseTestCase { private File loadcode(String code, File testFile) { try { tempFiles.add(testFile); - TestUtils.saveFile(new ByteArrayInputStream(code.trim().getBytes()), testFile); + String trim = code.trim(); + loadErrorComments(trim); + TestUtils.saveFile(new ByteArrayInputStream(trim.getBytes()), testFile); currentFile = testFile; try { cproject.getProject().refreshLocal(1, null); @@ -240,6 +243,17 @@ public class CodanTestCase extends BaseTestCase { } } + private void loadErrorComments(String trim) { + String[] lines = trim.split("\n"); + for (int i = 0; i < lines.length; i++) { + String string = lines[i]; + if (string.matches(".*//\\s*err\\s*")) { + + errLines.add(i+1); + } + } + } + public File loadcode_c(String code) { return loadcode(code, true); } diff --git a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/CaseBreakQuickFixTest.java b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/CaseBreakQuickFixTest.java new file mode 100644 index 00000000000..3c057af950e --- /dev/null +++ b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/CaseBreakQuickFixTest.java @@ -0,0 +1,52 @@ +package org.eclipse.cdt.codan.internal.checkers.ui.quickfix; + +import org.eclipse.cdt.codan.ui.AbstractCodanCMarkerResolution; + +@SuppressWarnings("nls") +public class CaseBreakQuickFixTest extends QuickFixTestCase { + @SuppressWarnings("restriction") + @Override + protected AbstractCodanCMarkerResolution createQuickFix() { + return new CaseBreakQuickFixBreak(); + } + + // void func() { + // int a; + // switch(a) { + // case 1: + // hello(); + // case 2: + // } + // } + public void testMiddleCase() { + loadcode(getAboveComment()); + String result = runQuickFixOneFile(); + assertContainedIn("break; case 2:", result); + } + + // void func() { + // int a; + // switch(a) { + // case 1: + // hello(); + // } + // } + public void testLastCase() { + loadcode(getAboveComment()); + String result = runQuickFixOneFile(); + assertContainedIn("break; }", result); + } + // void func() { + // int a; + // switch(a) { + // case 1: { + // hello(); + // } + // } + // } + public void testLastCaseComp() { + loadcode(getAboveComment()); + String result = runQuickFixOneFile(); + assertContainedIn("hello(); break;", result); + } +} From 49342dc9bf9496d5b03737de01449ba4cdfd2950 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Mon, 22 Aug 2011 20:26:21 -0700 Subject: [PATCH 04/29] Fixed warnings. --- .../eclipse/cdt/core/model/tests/CModelIdentifierTests.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/org.eclipse.cdt.core.tests/model/org/eclipse/cdt/core/model/tests/CModelIdentifierTests.java b/core/org.eclipse.cdt.core.tests/model/org/eclipse/cdt/core/model/tests/CModelIdentifierTests.java index 572ff303434..94138184a59 100644 --- a/core/org.eclipse.cdt.core.tests/model/org/eclipse/cdt/core/model/tests/CModelIdentifierTests.java +++ b/core/org.eclipse.cdt.core.tests/model/org/eclipse/cdt/core/model/tests/CModelIdentifierTests.java @@ -36,8 +36,8 @@ import org.eclipse.core.runtime.Path; /** * Tests for CModel identifier API. * - * @see ICElement#getHandleIdentier() - * @see CoreModel.create(String) + * @see ICElement#getHandleIdentifier() + * @see CoreModel#create(String) * * @since 5.0 */ @@ -105,7 +105,7 @@ public class CModelIdentifierTests extends BaseTestCase { String identifier= (String) identifiers.get(i); assertNotNull("Could not create identifier for element: "+ expected, identifier); ICElement actual= CoreModel.create(identifier); - assertNotNull("Cannot create element '" + expected + "' from identifier: "+identifier, actual); + assertNotNull("Cannot create element '" + expected + "' from identifier: " + identifier, actual); assertEquals(expected.getElementName(), actual.getElementName()); assertEquals(expected.getElementType(), actual.getElementType()); assertEquals(expected, actual); From 64c383952a35d928fb255b903e798cadedba2f63 Mon Sep 17 00:00:00 2001 From: Markus Schorn Date: Tue, 23 Aug 2011 15:41:16 +0200 Subject: [PATCH 05/29] Bug 355304: Argument deduction for explicit function template specialization. --- .../core/parser/tests/ast2/AST2CPPTests.java | 12 + .../parser/tests/ast2/AST2TemplateTests.java | 12 + .../pdom/tests/CPPFunctionTemplateTests.java | 17 +- .../core/model/ext/CElementHandle.java | 7 +- .../parser/cpp/CPPTemplateParameterMap.java | 2 +- .../parser/cpp/semantics/CPPSemantics.java | 184 +++++----- .../parser/cpp/semantics/CPPTemplates.java | 101 ++++- .../dom/parser/cpp/semantics/CPPVisitor.java | 55 +-- .../dom/parser/cpp/semantics/Conversions.java | 18 +- .../dom/parser/cpp/semantics/LookupData.java | 155 +++----- .../semantics/TemplateArgumentDeduction.java | 347 +++++++++--------- .../cdt/internal/core/pdom/PDOMWriter.java | 4 +- 12 files changed, 475 insertions(+), 439 deletions(-) diff --git a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2CPPTests.java b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2CPPTests.java index 6b0d18b3fc3..013c8924b4a 100644 --- a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2CPPTests.java +++ b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2CPPTests.java @@ -9480,4 +9480,16 @@ public class AST2CPPTests extends AST2BaseTest { public void testAmbiguityResolution_Bug354599() throws Exception { parseAndCheckBindings(); } + + // void (g)(char); + // void (g )(int); + // void (g )(int); + public void testFunctionRedeclarations() throws Exception { + BindingAssertionHelper bh= getAssertionHelper(); + IFunction g1= bh.assertNonProblem("g)", 1); + IFunction g2= bh.assertNonProblem("g )", 1); + IFunction g3= bh.assertNonProblem("g )", 1); + assertNotSame(g1, g2); + assertSame(g2, g3); + } } diff --git a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2TemplateTests.java b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2TemplateTests.java index bf1f8b09d8f..a5ea4b878a2 100644 --- a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2TemplateTests.java +++ b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2TemplateTests.java @@ -5454,4 +5454,16 @@ public class AST2TemplateTests extends AST2BaseTest { public void testTemplateTemplateParameterMatching_352859() throws Exception { parseAndCheckBindings(); } + + // template T f(); + // template<> int f() { + // return 0; + // } + public void testArgumentDeductionFromReturnTypeOfExplicitSpecialization_355304() throws Exception { + parseAndCheckBindings(); + BindingAssertionHelper bh= new BindingAssertionHelper(getAboveComment(), true); + ICPPFunctionTemplate template= bh.assertNonProblem("f();", 1); + ICPPTemplateInstance inst= bh.assertNonProblem("f() {", 1); + assertSame(template, inst.getTemplateDefinition()); + } } diff --git a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/internal/pdom/tests/CPPFunctionTemplateTests.java b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/internal/pdom/tests/CPPFunctionTemplateTests.java index cdb7fdd4eb8..82e8550af9d 100644 --- a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/internal/pdom/tests/CPPFunctionTemplateTests.java +++ b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/internal/pdom/tests/CPPFunctionTemplateTests.java @@ -11,18 +11,23 @@ *******************************************************************************/ package org.eclipse.cdt.internal.pdom.tests; +import java.util.Arrays; +import java.util.List; + import junit.framework.Test; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.IPDOMManager; import org.eclipse.cdt.core.dom.ast.IBinding; import org.eclipse.cdt.core.dom.ast.cpp.ICPPFunctionTemplate; +import org.eclipse.cdt.core.dom.ast.cpp.ICPPTemplateInstance; import org.eclipse.cdt.core.index.IndexFilter; import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.testplugin.CProjectHelper; import org.eclipse.cdt.core.testplugin.CTestPlugin; import org.eclipse.cdt.core.testplugin.util.TestSourceReader; import org.eclipse.cdt.internal.core.CCoreInternals; +import org.eclipse.cdt.internal.core.dom.parser.cpp.ICPPInstanceCache; import org.eclipse.cdt.internal.core.index.IIndexFragment; import org.eclipse.cdt.internal.core.pdom.PDOM; import org.eclipse.cdt.internal.core.pdom.indexer.IndexerPreferences; @@ -96,7 +101,15 @@ public class CPPFunctionTemplateTests extends PDOMTestBase { ICPPFunctionTemplate fooX= (ICPPFunctionTemplate) bs[b ? 0 : 1]; ICPPFunctionTemplate fooAB= (ICPPFunctionTemplate) bs[b ? 1 : 0]; - assertNameCount(pdom, fooX, IIndexFragment.FIND_REFERENCES, 3); - assertNameCount(pdom, fooAB, IIndexFragment.FIND_REFERENCES, 6); + List instances= Arrays.asList(((ICPPInstanceCache) fooX).getAllInstances()); + assertEquals(3, instances.size()); + for (ICPPTemplateInstance inst : instances) { + assertEquals(1, pdom.findNames(inst, IIndexFragment.FIND_REFERENCES).length); + } + instances= Arrays.asList(((ICPPInstanceCache) fooAB).getAllInstances()); + assertEquals(6, instances.size()); + for (ICPPTemplateInstance inst : instances) { + assertEquals(1, pdom.findNames(inst, IIndexFragment.FIND_REFERENCES).length); + } } } diff --git a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/model/ext/CElementHandle.java b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/model/ext/CElementHandle.java index e7f81ee9fe9..36932ec7aa2 100644 --- a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/model/ext/CElementHandle.java +++ b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/model/ext/CElementHandle.java @@ -49,6 +49,7 @@ abstract class CElementHandle implements ICElementHandle, ISourceReference { private IRegion fRegion; private long fTimestamp; + private int fIndex; public CElementHandle(ICElement parent, int type, String name) { fParent= parent; @@ -57,8 +58,8 @@ abstract class CElementHandle implements ICElementHandle, ISourceReference { // undo this here if (name.length() > 0 && name.charAt(0)=='{') { fName= ""; //$NON-NLS-1$ - } - else { + fIndex= name.hashCode(); + } else { fName= name; } fRegion= new Region(0,0); @@ -313,6 +314,6 @@ abstract class CElementHandle implements ICElementHandle, ISourceReference { } public int getIndex() { - return 0; + return fIndex; } } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPTemplateParameterMap.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPTemplateParameterMap.java index d1ce349769a..3d5bc411e5b 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPTemplateParameterMap.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPTemplateParameterMap.java @@ -163,7 +163,7 @@ public class CPPTemplateParameterMap implements ICPPTemplateParameterMap { } } - public boolean mergeToExplicit(CPPTemplateParameterMap deducedMap) { + public boolean addDeducedArgs(CPPTemplateParameterMap deducedMap) { Integer[] keys= deducedMap.getAllParameterPositions(); for (Integer key : keys) { Object explicit= fMap.get(key); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPSemantics.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPSemantics.java index eb7ec223333..2a087805332 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPSemantics.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPSemantics.java @@ -458,16 +458,12 @@ public class CPPSemantics { } } - // explicit function specializations are found via name resolution, need to + // Some declarations are found via name resolution (e.g. when using a qualified name), // add name as definition and check the declaration specifier. - if (binding instanceof IFunction) { - if (data.forFunctionDeclaration()) { - IASTNode declaration= data.astName; - while (declaration instanceof IASTName) - declaration= declaration.getParent(); - while (declaration instanceof IASTDeclarator) - declaration= declaration.getParent(); - + final IASTDeclaration declaration = data.forDeclaration(); + if (declaration != null) { + // Functions + if (binding instanceof IFunction) { binding= checkDeclSpecifier(binding, data.astName, declaration); if (!(binding instanceof IProblemBinding)) { if (declaration instanceof ICPPASTFunctionDefinition) { @@ -475,24 +471,17 @@ public class CPPSemantics { } } } - } - - // Definitions of static fields are found via name resolution, need to add name to - // the binding to get the right type of arrays that may be declared incomplete. - if (binding instanceof ICPPField && data.astName.isDefinition()) { - IASTNode declaration= data.astName; - while (declaration instanceof IASTName) - declaration= declaration.getParent(); - while (declaration instanceof IASTDeclarator) - declaration= declaration.getParent(); - if (declaration.getPropertyInParent() != IASTCompositeTypeSpecifier.MEMBER_DECLARATION) { - ASTInternal.addDefinition(binding, data.astName); + // Definitions of static fields. + if (binding instanceof ICPPField && data.astName.isDefinition()) { + if (declaration.getPropertyInParent() != IASTCompositeTypeSpecifier.MEMBER_DECLARATION) { + ASTInternal.addDefinition(binding, data.astName); + } } } - + // If we're still null... if (binding == null) { - if (name instanceof ICPPASTQualifiedName && data.forFunctionDeclaration()) { + if (name instanceof ICPPASTQualifiedName && declaration != null) { binding = new ProblemBinding(data.astName, IProblemBinding.SEMANTIC_MEMBER_DECLARATION_NOT_FOUND, data.getFoundBindings()); } else { @@ -601,9 +590,7 @@ public class CPPSemantics { data.forceQualified = true; } - if (parent instanceof ICPPASTFunctionDeclarator) { - data.setFunctionParameters(((ICPPASTFunctionDeclarator) parent).getParameters()); - } else if (parent instanceof IASTIdExpression) { + if (parent instanceof IASTIdExpression) { IASTNode grand= parent.getParent(); while (grand instanceof IASTUnaryExpression && ((IASTUnaryExpression) grand).getOperator() == IASTUnaryExpression.op_bracketedPrimary) { @@ -2276,7 +2263,7 @@ public class CPPSemantics { } private static ICPPFunction[] selectByArgumentCount(LookupData data, ICPPFunction[] functions) throws DOMException { - assert !data.forFunctionDeclaration(); + assert data.forDeclaration() == null; int argumentCount = data.getFunctionArgumentCount(); @@ -2328,16 +2315,6 @@ public class CPPSemantics { return result; } - private static boolean isMatchingFunctionDeclaration(ICPPFunction candidate, LookupData data) { - IASTNode node = data.astName.getParent(); - while (node instanceof IASTName) - node = node.getParent(); - if (node instanceof IASTDeclarator) { - return isSameFunction(candidate, (IASTDeclarator) node); - } - return false; - } - static IBinding resolveFunction(LookupData data, ICPPFunction[] fns, boolean allowUDC) throws DOMException { fns= (ICPPFunction[]) ArrayUtil.trim(ICPPFunction.class, fns); if (fns == null || fns.length == 0) @@ -2348,17 +2325,18 @@ public class CPPSemantics { if (data.forUsingDeclaration()) return new CPPUsingDeclaration(data.astName, fns); - // No arguments to resolve function - if (!data.hasFunctionArguments()) { - return createFunctionSet(data.astName, fns); - } - if (data.astName instanceof ICPPASTConversionName) { return resolveUserDefinedConversion(data, fns); } - if (data.forFunctionDeclaration()) + if (data.forDeclaration() != null) { return resolveFunctionDeclaration(data, fns); + } + + // No arguments to resolve function + if (!data.hasFunctionArguments()) { + return createFunctionSet(data.astName, fns); + } // Reduce our set of candidate functions to only those who have the right number of parameters final IType[] argTypes = data.getFunctionArgumentTypes(); @@ -2519,38 +2497,77 @@ public class CPPSemantics { } } + /** + * Called for declarations with qualified name or template-id. Also for explicit function + * specializations or instantiations. + */ private static IBinding resolveFunctionDeclaration(LookupData data, ICPPFunction[] fns) throws DOMException { - if (data.forExplicitFunctionSpecialization()) { - fns = CPPTemplates.instantiateForFunctionCall(data.astName, - fns, - Arrays.asList(data.getFunctionArgumentTypes()), Arrays.asList(data.getFunctionArgumentValueCategories()), - data.argsContainImpliedObject); + final IASTDeclarator dtor= ASTQueries.findTypeRelevantDeclarator(data.getDeclarator()); + final IType t = CPPVisitor.createType(dtor); + if (!(t instanceof ICPPFunctionType)) + return null; + + final ICPPFunctionType ft= (ICPPFunctionType) t; + + IASTName templateID= data.astName; + if (templateID.getPropertyInParent() == ICPPASTTemplateId.TEMPLATE_NAME) { + templateID= (ICPPASTTemplateId) templateID.getParent(); + } + + // 14.5.4 Friends with template ids require instantiation + boolean isFriend= CPPVisitor.isFriendDeclaration(data.forDeclaration()); + if (!data.forExplicitFunctionSpecialization() + && !(isFriend && templateID instanceof ICPPASTTemplateId)) { + // Search for a matching function + for (ICPPFunction fn : fns) { + if (fn != null && !(fn instanceof IProblemBinding) && !(fn instanceof ICPPUnknownBinding)) { + if (isSameFunction(fn, dtor)) { + return fn; + } + } + } + // 14.5.4 Friends with qualified ids allow for instantiation + if (!data.forExplicitFunctionInstantiation() + && !(isFriend && templateID.getParent() instanceof ICPPASTQualifiedName)) { + return null; + } + } + + // Try to instantiate a template + IASTTranslationUnit tu= data.tu; + ICPPTemplateArgument[] tmplArgs= ICPPTemplateArgument.EMPTY_ARGUMENTS; + if (templateID instanceof ICPPASTTemplateId) { + tmplArgs = CPPTemplates.createTemplateArgumentArray((ICPPASTTemplateId) templateID); } - int argCount = data.getFunctionArgumentCount(); - if (argCount == 1) { - // check for parameter of type void - final IType[] argTypes = data.getFunctionArgumentTypes(); - if (argTypes.length == 1 && SemanticUtil.isVoidType(argTypes[0])) { - argCount= 0; - } - } - - for (ICPPFunction fn : fns) { - if (fn != null && !(fn instanceof IProblemBinding) && !(fn instanceof ICPPUnknownBinding)) { - // The index is optimized to provide the function type, avoid using the parameters - // as long as possible. - final IType[] parameterTypes = fn.getType().getParameterTypes(); - int parCount = parameterTypes.length; - if (parCount == 1 && SemanticUtil.isVoidType(parameterTypes[0])) - parCount= 0; - - if (parCount == argCount && isMatchingFunctionDeclaration(fn, data)) { - return fn; - } - } - } - return null; + ICPPFunctionTemplate bestTemplate= null; + ICPPFunction bestInst= null; + boolean isAmbiguous= false; + for (ICPPFunction fn : fns) { + if (fn instanceof ICPPFunctionTemplate + && !(fn instanceof IProblemBinding) && !(fn instanceof ICPPUnknownBinding)) { + ICPPFunctionTemplate template= (ICPPFunctionTemplate) fn; + ICPPFunction inst= CPPTemplates.instantiateForFunctionDeclaration(template, tmplArgs, ft); + if (inst != null) { + int cmp= CPPTemplates.orderFunctionTemplates(bestTemplate, template, TypeSelection.PARAMETERS_AND_RETURN_TYPE); + if (cmp == 0) + cmp= compareByRelevance(tu, bestTemplate, template); + + if (cmp == 0) + isAmbiguous= true; + + if (cmp < 0) { + isAmbiguous= false; + bestTemplate= template; + bestInst= inst; + } + } + } + } + if (isAmbiguous) + return new ProblemBinding(data.astName, IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, fns); + + return bestInst; } public static void sortAstBeforeIndex(IFunction[] fns) { @@ -2691,14 +2708,15 @@ public class CPPSemantics { return new CPPReferenceType(implicitType, false); } - private static IBinding resolveUserDefinedConversion(LookupData data, IFunction[] fns) { + private static IBinding resolveUserDefinedConversion(LookupData data, ICPPFunction[] fns) { ICPPASTConversionName astName= (ICPPASTConversionName) data.astName; IType t= CPPVisitor.createType(astName.getTypeId()); if (t instanceof ISemanticProblem) { return new ProblemBinding(astName, IProblemBinding.SEMANTIC_INVALID_TYPE, data.getFoundBindings()); } - if (!data.forFunctionDeclaration() || data.forExplicitFunctionSpecialization()) { - CPPTemplates.instantiateConversionTemplates(fns, t); + if (data.forDeclaration() == null || + data.forExplicitFunctionSpecialization() || data.forExplicitFunctionInstantiation()) { + fns= CPPTemplates.instantiateConversionTemplates(fns, t); } IFunction unknown= null; @@ -2896,12 +2914,10 @@ public class CPPSemantics { final ICPPFunctionTemplate template = (ICPPFunctionTemplate) fn; ICPPFunction inst= CPPTemplates.instantiateForAddressOfFunction(template, (ICPPFunctionType) targetType, name); if (inst != null) { - int cmp= -1; - if (result != null) { - cmp= CPPTemplates.orderFunctionTemplates(resultTemplate, template, TypeSelection.PARAMETERS_AND_RETURN_TYPE); - if (cmp == 0) - cmp= compareByRelevance(tu, resultTemplate, template); - } + int cmp= CPPTemplates.orderFunctionTemplates(resultTemplate, template, TypeSelection.PARAMETERS_AND_RETURN_TYPE); + if (cmp == 0) + cmp= compareByRelevance(tu, resultTemplate, template); + if (cmp == 0) isAmbiguous= true; @@ -3627,7 +3643,9 @@ public class CPPSemantics { if (templateDecl != null) { if (templateDecl instanceof ICPPASTTemplateSpecialization) { - if (!(function instanceof ICPPSpecialization)) + if (!(function instanceof ICPPTemplateInstance)) + return false; + if (!((ICPPTemplateInstance) function).isExplicitSpecialization()) return false; } else { if (function instanceof ICPPTemplateDefinition) { @@ -3641,7 +3659,7 @@ public class CPPSemantics { } } else if (function instanceof ICPPTemplateDefinition) { return false; - } + } declarator= ASTQueries.findTypeRelevantDeclarator(declarator); if (declarator instanceof ICPPASTFunctionDeclarator) { diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPTemplates.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPTemplates.java index aef3e512a70..a3cb25d933c 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPTemplates.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPTemplates.java @@ -30,6 +30,7 @@ import org.eclipse.cdt.core.dom.ast.IASTDeclarator; import org.eclipse.cdt.core.dom.ast.IASTElaboratedTypeSpecifier; import org.eclipse.cdt.core.dom.ast.IASTExpression; import org.eclipse.cdt.core.dom.ast.IASTExpression.ValueCategory; +import org.eclipse.cdt.core.dom.ast.IASTFunctionDeclarator; import org.eclipse.cdt.core.dom.ast.IASTFunctionDefinition; import org.eclipse.cdt.core.dom.ast.IASTIdExpression; import org.eclipse.cdt.core.dom.ast.IASTInitializerClause; @@ -51,6 +52,7 @@ import org.eclipse.cdt.core.dom.ast.ITypedef; import org.eclipse.cdt.core.dom.ast.IValue; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTCompositeTypeSpecifier; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTCompositeTypeSpecifier.ICPPASTBaseSpecifier; +import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTDeclSpecifier; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTElaboratedTypeSpecifier; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTExplicitTemplateInstantiation; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTFunctionDefinition; @@ -706,10 +708,17 @@ public class CPPTemplates { parentOfName= parentOfName.getParent(); } - return parentOfName instanceof ICPPASTElaboratedTypeSpecifier || + if (parentOfName instanceof ICPPASTElaboratedTypeSpecifier || parentOfName instanceof ICPPASTCompositeTypeSpecifier || parentOfName instanceof ICPPASTNamedTypeSpecifier || - parentOfName instanceof ICPPASTBaseSpecifier; + parentOfName instanceof ICPPASTBaseSpecifier) + return true; + + if (parentOfName instanceof IASTDeclarator) { + IASTDeclarator rel= ASTQueries.findTypeRelevantDeclarator((IASTDeclarator) parentOfName); + return !(rel instanceof IASTFunctionDeclarator); + } + return false; } @@ -1310,7 +1319,7 @@ public class CPPTemplates { // determine nesting level of parent int level= missingTemplateDecls; - if (!CPPVisitor.isFriendFunctionDeclaration(innerMostTDecl.getDeclaration())) { + if (!isFriendFunctionDeclaration(innerMostTDecl.getDeclaration())) { node= outerMostTDecl.getParent(); while (node != null) { if (node instanceof ICPPASTInternalTemplateDeclaration) { @@ -1335,6 +1344,23 @@ public class CPPTemplates { innerMostTDecl.setAssociatedWithLastName(lastIsTemplate); } + private static boolean isFriendFunctionDeclaration(IASTDeclaration declaration) { + while (declaration instanceof ICPPASTTemplateDeclaration) { + declaration= ((ICPPASTTemplateDeclaration) declaration).getDeclaration(); + } + if (declaration instanceof IASTSimpleDeclaration) { + IASTSimpleDeclaration sdecl = (IASTSimpleDeclaration) declaration; + ICPPASTDeclSpecifier declspec= (ICPPASTDeclSpecifier) sdecl.getDeclSpecifier(); + if (declspec.isFriend()) { + IASTDeclarator[] dtors= sdecl.getDeclarators(); + if (dtors.length == 1 && ASTQueries.findTypeRelevantDeclarator(dtors[0]) instanceof IASTFunctionDeclarator) { + return true; + } + } + } + return false; + } + private static CharArraySet collectTemplateParameterNames(ICPPASTTemplateDeclaration tdecl) { CharArraySet set= new CharArraySet(4); while(true) { @@ -1628,24 +1654,30 @@ public class CPPTemplates { return null; } - static void instantiateConversionTemplates(IFunction[] functions, IType conversionType) { + /** + * 14.8.2.3 Deducing conversion function template arguments + */ + static ICPPFunction[] instantiateConversionTemplates(ICPPFunction[] functions, IType conversionType) { boolean checkedForDependentType= false; - for (int i = 0; i < functions.length; i++) { - IFunction func = functions[i]; - if (func instanceof ICPPFunctionTemplate) { - ICPPFunctionTemplate template= (ICPPFunctionTemplate) func; - functions[i]= null; + ICPPFunction[] result= functions; + int i=0; + boolean done= false; + for (ICPPFunction f : functions) { + ICPPFunction inst = f; + if (f instanceof ICPPFunctionTemplate) { + ICPPFunctionTemplate template= (ICPPFunctionTemplate) f; + inst= null; - // extract template arguments and parameter types. + // Extract template arguments and parameter types. if (!checkedForDependentType) { try { if (isDependentType(conversionType)) { - functions[i]= CPPUnknownFunction.createForSample(template); - return; + inst= CPPUnknownFunction.createForSample(template); + done= true; } checkedForDependentType= true; } catch (DOMException e) { - return; + return functions; } } CPPTemplateParameterMap map= new CPPTemplateParameterMap(1); @@ -1653,16 +1685,48 @@ public class CPPTemplates { ICPPTemplateArgument[] args= TemplateArgumentDeduction.deduceForConversion(template, conversionType, map); if (args != null) { IBinding instance= instantiateFunctionTemplate(template, args, map); - if (instance instanceof IFunction) { - functions[i]= (IFunction) instance; + if (instance instanceof ICPPFunction) { + inst= (ICPPFunction) instance; } } } catch (DOMException e) { // try next candidate } } + if (result != functions || f != inst) { + if (result == functions) { + result= new ICPPFunction[functions.length]; + System.arraycopy(functions, 0, result, 0, i); + } + result[i++]= inst; + } + if (done) + break; } + return result; } + + /** + * 14.8.2.6 Deducing template arguments from a function declaration + * @return + */ + static ICPPFunction instantiateForFunctionDeclaration(ICPPFunctionTemplate template, + ICPPTemplateArgument[] args, ICPPFunctionType functionType) { + CPPTemplateParameterMap map= new CPPTemplateParameterMap(1); + try { + args= TemplateArgumentDeduction.deduceForDeclaration(template, args, functionType, map); + if (args != null) { + IBinding instance= instantiateFunctionTemplate(template, args, map); + if (instance instanceof ICPPFunction) { + return (ICPPFunction) instance; + } + } + } catch (DOMException e) { + // try next candidate + } + return null; + } + /** * 14.8.2.2 Deducing template arguments taking the address of a function template [temp.deduct.funcaddr] @@ -1702,6 +1766,13 @@ public class CPPTemplates { // 14.5.6.2 Partial ordering of function templates static int orderFunctionTemplates(ICPPFunctionTemplate f1, ICPPFunctionTemplate f2, TypeSelection mode) throws DOMException { + if (f1 == f2) + return 0; + if (f1 == null) + return -1; + if (f2 == null) + return 1; + int s1 = compareSpecialization(f1, f2, mode); int s2 = compareSpecialization(f2, f1, mode); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVisitor.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVisitor.java index 049f19d97f4..ebf43313861 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVisitor.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVisitor.java @@ -633,13 +633,7 @@ public class CPPVisitor extends ASTQueries { boolean isFriendDecl= false; ICPPScope scope = (ICPPScope) getContainingNonTemplateScope(name); if (scope instanceof ICPPClassScope) { - if (parent instanceof IASTSimpleDeclaration) { - ICPPASTDeclSpecifier declSpec = (ICPPASTDeclSpecifier) ((IASTSimpleDeclaration) parent).getDeclSpecifier(); - isFriendDecl= declSpec.isFriend(); - } else if (parent instanceof IASTFunctionDefinition) { - ICPPASTDeclSpecifier declSpec = (ICPPASTDeclSpecifier) ((IASTFunctionDefinition) parent).getDeclSpecifier(); - isFriendDecl= declSpec.isFriend(); - } + isFriendDecl = isFriendDeclaration(parent); if (isFriendDecl) { try { while (scope.getKind() == EScopeKind.eClassType) { @@ -753,6 +747,18 @@ public class CPPVisitor extends ASTQueries { return binding; } + public static boolean isFriendDeclaration(IASTNode decl) { + IASTDeclSpecifier declSpec; + if (decl instanceof IASTSimpleDeclaration) { + declSpec = ((IASTSimpleDeclaration) decl).getDeclSpecifier(); + } else if (decl instanceof IASTFunctionDefinition) { + declSpec = ((IASTFunctionDefinition) decl).getDeclSpecifier(); + } else { + return false; + } + return declSpec instanceof ICPPASTDeclSpecifier && ((ICPPASTDeclSpecifier) declSpec).isFriend(); + } + public static boolean isConstructor(IScope containingScope, IASTDeclarator declarator) { if (containingScope == null || !(containingScope instanceof ICPPClassScope)) return false; @@ -2340,7 +2346,6 @@ public class CPPVisitor extends ASTQueries { */ public static IBinding findDeclarationOwner(IASTNode node, boolean allowFunction) { // Search for declaration - boolean isFriend= false; boolean isNonSimpleElabDecl= false; while (!(node instanceof IASTDeclaration)) { if (node == null) @@ -2360,19 +2365,7 @@ public class CPPVisitor extends ASTQueries { node= node.getParent(); } - if (node instanceof IASTSimpleDeclaration) { - final IASTSimpleDeclaration sdecl = (IASTSimpleDeclaration) node; - ICPPASTDeclSpecifier declSpec= (ICPPASTDeclSpecifier) sdecl.getDeclSpecifier(); - if (declSpec.isFriend()) { - isFriend= true; - } - } else if (node instanceof IASTFunctionDefinition) { - IASTFunctionDefinition funcDefinition = (IASTFunctionDefinition) node; - ICPPASTDeclSpecifier declSpec = (ICPPASTDeclSpecifier) funcDefinition.getDeclSpecifier(); - if (declSpec.isFriend()) { - isFriend= true; - } - } + boolean isFriend= isFriendDeclaration(node); // Search for enclosing binding IASTName name= null; @@ -2409,26 +2402,6 @@ public class CPPVisitor extends ASTQueries { return name.resolveBinding(); } - /** - * Check whether a given declaration is a friend function declaration. - */ - public static boolean isFriendFunctionDeclaration(IASTDeclaration declaration) { - while (declaration instanceof ICPPASTTemplateDeclaration) { - declaration= ((ICPPASTTemplateDeclaration) declaration).getDeclaration(); - } - if (declaration instanceof IASTSimpleDeclaration) { - IASTSimpleDeclaration sdecl = (IASTSimpleDeclaration) declaration; - ICPPASTDeclSpecifier declspec= (ICPPASTDeclSpecifier) sdecl.getDeclSpecifier(); - if (declspec.isFriend()) { - IASTDeclarator[] dtors= sdecl.getDeclarators(); - if (dtors.length == 1 && findTypeRelevantDeclarator(dtors[0]) instanceof IASTFunctionDeclarator) { - return true; - } - } - } - return false; - } - public static boolean doesNotSpecifyType(IASTDeclSpecifier declspec) { if (declspec instanceof ICPPASTSimpleDeclSpecifier) { ICPPASTSimpleDeclSpecifier ds= (ICPPASTSimpleDeclSpecifier) declspec; diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/Conversions.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/Conversions.java index 25b732fb3e3..e6e19133d69 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/Conversions.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/Conversions.java @@ -684,10 +684,11 @@ public class Conversions { final IType uqSource= getNestedType(source, TDEF | REF | CVTYPE); if (uqSource instanceof ICPPClassType) { - ICPPMethod[] ops = SemanticUtil.getConversionOperators((ICPPClassType) uqSource); - CPPTemplates.instantiateConversionTemplates(ops, t); - for (final ICPPMethod op : ops) { - if (op != null && !(op instanceof IProblemBinding)) { + ICPPFunction[] ops = SemanticUtil.getConversionOperators((ICPPClassType) uqSource); + ops= CPPTemplates.instantiateConversionTemplates(ops, t); + for (final ICPPFunction f : ops) { + if (f instanceof ICPPMethod && !(f instanceof IProblemBinding)) { + ICPPMethod op= (ICPPMethod) f; if (op.isExplicit()) continue; final IType returnType = op.getType().getReturnType(); @@ -733,12 +734,13 @@ public class Conversions { c.setDeferredUDC(DeferredUDC.INIT_BY_CONVERSION); return c; } - ICPPMethod[] ops = SemanticUtil.getConversionOperators(uqSource); - CPPTemplates.instantiateConversionTemplates(ops, target); + ICPPFunction[] ops = SemanticUtil.getConversionOperators(uqSource); + ops= CPPTemplates.instantiateConversionTemplates(ops, target); FunctionCost cost1= null; Cost cost2= null; - for (final ICPPMethod op : ops) { - if (op != null && !(op instanceof IProblemBinding)) { + for (final ICPPFunction f : ops) { + if (f instanceof ICPPMethod && !(f instanceof IProblemBinding)) { + ICPPMethod op= (ICPPMethod) f; final boolean isExplicitConversion= op.isExplicit(); if (isExplicitConversion /** && !direct **/) continue; diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/LookupData.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/LookupData.java index 41095ccab2a..201d5c4a69d 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/LookupData.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/LookupData.java @@ -14,7 +14,6 @@ *******************************************************************************/ package org.eclipse.cdt.internal.core.dom.parser.cpp.semantics; -import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.valueCategoryFromReturnType; import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.getSimplifiedType; import java.util.Collections; @@ -53,7 +52,6 @@ import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTExplicitTemplateInstantiation; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTFieldReference; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTInitializerList; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNamespaceDefinition; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTParameterDeclaration; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTQualifiedName; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateDeclaration; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateId; @@ -69,7 +67,6 @@ import org.eclipse.cdt.core.parser.util.ArrayUtil; import org.eclipse.cdt.core.parser.util.CharArrayObjectMap; import org.eclipse.cdt.core.parser.util.CharArrayUtils; import org.eclipse.cdt.core.parser.util.ObjectSet; -import org.eclipse.cdt.internal.core.dom.parser.ASTQueries; import org.eclipse.cdt.internal.core.dom.parser.ProblemBinding; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTranslationUnit; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPCompositeBinding; @@ -103,7 +100,6 @@ public class LookupData { /** In list-initialization **/ public boolean fNoNarrowing= false; - private ICPPASTParameterDeclaration[] functionParameters; private IASTInitializerClause[] functionArgs; private IType[] functionArgTypes; private ValueCategory[] functionArgValueCategories; @@ -171,81 +167,58 @@ public class LookupData { return false; } - public boolean forFunctionDeclaration() { - if (astName == null) return false; - if (astName.getPropertyInParent() == CPPSemantics.STRING_LOOKUP_PROPERTY) return false; + /** + * Returns whether the name belongs to a simple declaration or function definition. + */ + public IASTDeclaration forDeclaration() { + IASTNode node = getDeclarator(); + + while (node instanceof IASTDeclarator) + node= node.getParent(); + + if (node instanceof IASTSimpleDeclaration || node instanceof IASTFunctionDefinition) + return (IASTDeclaration) node; - IASTName n = astName; - if (n.getParent() instanceof ICPPASTTemplateId) - n = (IASTName) n.getParent(); - IASTNode p1 = n.getParent(); - if (p1 instanceof ICPPASTQualifiedName) { - if (((ICPPASTQualifiedName) p1).getLastName() != n) - return false; - p1 = p1.getParent(); - } + return null; + } + + public IASTDeclarator getDeclarator() { + IASTName name= astName; + if (name == null || name.getPropertyInParent() == CPPSemantics.STRING_LOOKUP_PROPERTY) + return null; - if (p1 instanceof IASTDeclarator) { - IASTNode p2= ASTQueries.findOutermostDeclarator((IASTDeclarator) p1).getParent(); - if (p2 instanceof IASTSimpleDeclaration) { - if (p2.getParent() instanceof ICPPASTExplicitTemplateInstantiation) - return false; - if (astName instanceof ICPPASTTemplateId && - ((ICPPASTDeclSpecifier)((IASTSimpleDeclaration) p2).getDeclSpecifier()).isFriend()) - return false; - - return true; - } - return p2 instanceof IASTFunctionDefinition; + if (name.getParent() instanceof ICPPASTTemplateId) + name= (IASTName) name.getParent(); + + IASTNode node= name.getParent(); + if (node instanceof ICPPASTQualifiedName) { + if (((ICPPASTQualifiedName) node).getLastName() != name) + return null; + node = node.getParent(); } - return false; + + if (node instanceof IASTDeclarator) + return (IASTDeclarator) node; + + return null; } public boolean forExplicitFunctionSpecialization() { - if (astName == null) return false; - if (astName.getPropertyInParent() == CPPSemantics.STRING_LOOKUP_PROPERTY) return false; - - IASTName n = astName; - if (n.getParent() instanceof ICPPASTTemplateId) - n = (IASTName) n.getParent(); - IASTNode p1 = n.getParent(); - if (p1 instanceof ICPPASTQualifiedName) { - if (((ICPPASTQualifiedName) p1).getLastName() != n) - return false; - p1 = p1.getParent(); - } - - if (p1 instanceof IASTDeclarator) { - IASTNode p2= ASTQueries.findOutermostDeclarator((IASTDeclarator) p1).getParent(); - if (p2 instanceof IASTSimpleDeclaration || p2 instanceof IASTFunctionDefinition) { - ICPPASTTemplateDeclaration tmplDecl = CPPTemplates.getTemplateDeclaration(n); - return tmplDecl instanceof ICPPASTTemplateSpecialization; - } + IASTDeclaration decl= forDeclaration(); + if (decl != null) { + IASTName n = astName; + if (n.getParent() instanceof ICPPASTTemplateId) + n = (IASTName) n.getParent(); + + ICPPASTTemplateDeclaration tmplDecl = CPPTemplates.getTemplateDeclaration(n); + return tmplDecl instanceof ICPPASTTemplateSpecialization; } return false; } public boolean forExplicitFunctionInstantiation() { - if (astName == null) return false; - if (astName.getPropertyInParent() == CPPSemantics.STRING_LOOKUP_PROPERTY) return false; - - IASTName n = astName; - if (n.getParent() instanceof ICPPASTTemplateId) - n = (IASTName) n.getParent(); - IASTNode p1 = n.getParent(); - if (p1 instanceof ICPPASTQualifiedName) { - if (((ICPPASTQualifiedName) p1).getLastName() != n) - return false; - p1 = p1.getParent(); - } - - if (p1 instanceof IASTDeclarator) { - IASTNode p2= ASTQueries.findOutermostDeclarator((IASTDeclarator) p1).getParent(); - if (p2 instanceof IASTDeclaration) { - return p2.getParent() instanceof ICPPASTExplicitTemplateInstantiation; - } - } - return false; + IASTDeclaration decl= forDeclaration(); + return decl != null && decl.getParent() instanceof ICPPASTExplicitTemplateInstantiation; } public boolean qualified() { @@ -414,14 +387,6 @@ public class LookupData { } return CPPVisitor.getImpliedObjectType(scope); } - if (prop == IASTDeclarator.DECLARATOR_NAME) { - if (forExplicitFunctionInstantiation()) { - IScope scope = CPPVisitor.getContainingScope(astName); - if (scope instanceof ICPPClassScope) { - return ((ICPPClassScope) scope).getClassType(); - } - } - } return null; } @@ -491,13 +456,7 @@ public class LookupData { return false; if (p instanceof IASTDeclaration) { if (prop == IASTCompositeTypeSpecifier.MEMBER_DECLARATION) { - if (p instanceof IASTSimpleDeclaration) { - ICPPASTDeclSpecifier declSpec = (ICPPASTDeclSpecifier) ((IASTSimpleDeclaration) p).getDeclSpecifier(); - return declSpec.isFriend(); - } else if (p instanceof IASTFunctionDefinition) { - ICPPASTDeclSpecifier declSpec = (ICPPASTDeclSpecifier) ((IASTFunctionDefinition) p).getDeclSpecifier(); - return declSpec.isFriend(); - } + return CPPVisitor.isFriendDeclaration(p); } else { return false; } @@ -547,14 +506,7 @@ public class LookupData { functionArgTypes[i]= new InitializerListType((ICPPASTInitializerList) e); } } - } else if (functionParameters != null) { - ICPPASTParameterDeclaration[] pdecls= functionParameters; - functionArgTypes= new IType[pdecls.length]; - for (int i = 0; i < pdecls.length; i++) { - functionArgTypes[i] = SemanticUtil.getSimplifiedType(CPPVisitor.createType( - pdecls[i], true)); - } - } + } } return functionArgTypes; } @@ -570,36 +522,19 @@ public class LookupData { functionArgValueCategories[i] = ExpressionTypes.valueCat((IASTExpression) arg); } } - } else { - IType[] argTypes= getFunctionArgumentTypes(); - if (argTypes != null) { - functionArgValueCategories= new ValueCategory[argTypes.length]; - for (int i = 0; i < argTypes.length; i++) { - IType t= argTypes[i]; - functionArgValueCategories[i]= valueCategoryFromReturnType(t); - } - } else { - functionArgValueCategories= new ValueCategory[0]; - } - } + } } return functionArgValueCategories; } - public void setFunctionParameters(ICPPASTParameterDeclaration[] parameters) { - functionParameters= parameters; - } - public int getFunctionArgumentCount() { if (functionArgs != null) return functionArgs.length; - if (functionParameters != null) - return functionParameters.length; return 0; } public boolean hasFunctionArguments() { - return functionArgs != null || functionParameters != null; + return functionArgs != null; } public IBinding[] getFoundBindings() { diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/TemplateArgumentDeduction.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/TemplateArgumentDeduction.java index be23516639f..03346097b98 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/TemplateArgumentDeduction.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/TemplateArgumentDeduction.java @@ -38,6 +38,7 @@ import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassTemplatePartialSpecialization; import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassType; import org.eclipse.cdt.core.dom.ast.cpp.ICPPFunction; import org.eclipse.cdt.core.dom.ast.cpp.ICPPFunctionTemplate; +import org.eclipse.cdt.core.dom.ast.cpp.ICPPFunctionType; import org.eclipse.cdt.core.dom.ast.cpp.ICPPMethod; import org.eclipse.cdt.core.dom.ast.cpp.ICPPParameterPackType; import org.eclipse.cdt.core.dom.ast.cpp.ICPPPointerToMemberType; @@ -67,181 +68,16 @@ public class TemplateArgumentDeduction { static ICPPTemplateArgument[] deduceForFunctionCall(ICPPFunctionTemplate template, ICPPTemplateArgument[] tmplArgs, List fnArgs, List argIsLValue, CPPTemplateParameterMap map) throws DOMException { + final ICPPTemplateParameter[] tmplParams = template.getTemplateParameters(); - final int numTmplParams = tmplParams.length; - final int numTmplArgs = tmplArgs.length; - tmplArgs= SemanticUtil.getSimplifiedArguments(tmplArgs); - ICPPTemplateParameter tmplParam= null; - int packOffset= -1; - for (int i = 0; i < numTmplArgs; i++) { - if (packOffset < 0 || tmplParam == null) { - if (i >= numTmplParams) - return null; - - tmplParam= tmplParams[i]; - if (tmplParam.isParameterPack()) { - packOffset= i; - } - } - ICPPTemplateArgument tmplArg= tmplArgs[i]; - tmplArg= CPPTemplates.matchTemplateParameterAndArgument(tmplParam, tmplArg, map); - if (tmplArg == null) - return null; - - if (packOffset < 0) { - map.put(tmplParam, tmplArg); - } - } - - if (packOffset >= 0) { - final int packSize= tmplArgs.length- packOffset; - ICPPTemplateArgument[] pack= new ICPPTemplateArgument[packSize]; - System.arraycopy(tmplArgs, packOffset, pack, 0, packSize); - map.put(tmplParam, pack); - } + if (!addExplicitArguments(tmplParams, tmplArgs, map)) + return null; if (!deduceFromFunctionArgs(template, fnArgs, argIsLValue, map)) return null; - List result= new ArrayList(numTmplParams); - for (ICPPTemplateParameter tpar : tmplParams) { - if (tpar.isParameterPack()) { - ICPPTemplateArgument[] deducedArgs= map.getPackExpansion(tpar); - if (deducedArgs == null) - return null; - result.addAll(Arrays.asList(deducedArgs)); - } else { - ICPPTemplateArgument deducedArg= map.getArgument(tpar); - if (deducedArg == null) { - deducedArg= tpar.getDefaultValue(); - if (deducedArg == null) - return null; - } - result.add(deducedArg); - } - } - return result.toArray(new ICPPTemplateArgument[result.size()]); - } - - /** - * 14.8.2.2 [temp.deduct.funcaddr] - * Deducing template arguments taking the address of a function template - * @throws DOMException - */ - static ICPPTemplateArgument[] deduceForAddressOf(ICPPFunctionTemplate template, - ICPPTemplateArgument[] tmplArgs, IFunctionType arg, CPPTemplateParameterMap map) throws DOMException { - final ICPPTemplateParameter[] tmplParams = template.getTemplateParameters(); - final int numTmplParams = tmplParams.length; - final int numTmplArgs = tmplArgs.length; - - tmplArgs= SemanticUtil.getSimplifiedArguments(tmplArgs); - ICPPTemplateParameter tmplParam= null; - int packOffset= -1; - for (int i = 0; i < numTmplArgs; i++) { - if (packOffset < 0 || tmplParam == null) { - if (i >= numTmplParams) - return null; - - tmplParam= tmplParams[i]; - if (tmplParam.isParameterPack()) { - packOffset= i; - } - } - ICPPTemplateArgument tmplArg= tmplArgs[i]; - tmplArg= CPPTemplates.matchTemplateParameterAndArgument(tmplParam, tmplArg, map); - if (tmplArg == null) - return null; - - if (packOffset < 0) { - map.put(tmplParam, tmplArg); - } - } - - if (packOffset >= 0) { - final int packSize= tmplArgs.length- packOffset; - ICPPTemplateArgument[] pack= new ICPPTemplateArgument[packSize]; - System.arraycopy(tmplArgs, packOffset, pack, 0, packSize); - map.put(tmplParam, pack); - } - - IType par= template.getType(); - par= CPPTemplates.instantiateType(par, map, -1, null); - if (!CPPTemplates.isValidType(par)) - return null; - - boolean isDependentPar= CPPTemplates.isDependentType(par); - if (isDependentPar) { - TemplateArgumentDeduction deduct= new TemplateArgumentDeduction(tmplParams, map, new CPPTemplateParameterMap(tmplParams.length), 0); - par= SemanticUtil.getNestedType(par, SemanticUtil.TDEF); - if (arg != null && !deduct.fromType(par, arg, false)) - return null; - if (!map.mergeToExplicit(deduct.fDeducedArgs)) - return null; - } - - if (!verifyDeduction(tmplParams, map, true)) - return null; - - if (isDependentPar) - par= CPPTemplates.instantiateType(par, map, -1, null); - - if (arg == null || arg.isSameType(par)) { - List result= new ArrayList(numTmplParams); - for (ICPPTemplateParameter tpar : tmplParams) { - if (tpar.isParameterPack()) { - ICPPTemplateArgument[] deducedArgs= map.getPackExpansion(tpar); - if (deducedArgs == null) - return null; - result.addAll(Arrays.asList(deducedArgs)); - } else { - ICPPTemplateArgument deducedArg= map.getArgument(tpar); - if (deducedArg == null) { - deducedArg= tpar.getDefaultValue(); - if (deducedArg == null) - return null; - } - - result.add(deducedArg); - } - } - return result.toArray(new ICPPTemplateArgument[result.size()]); - } - return null; - } - - /** - * Deduce arguments for a user defined conversion template - * 14.8.2.3 - */ - static ICPPTemplateArgument[] deduceForConversion(ICPPFunctionTemplate template, - IType conversionType, CPPTemplateParameterMap map) throws DOMException { - final ICPPTemplateParameter[] tmplParams = template.getTemplateParameters(); - final int length = tmplParams.length; - - ICPPTemplateArgument[] result = new ICPPTemplateArgument[length]; - IType a= SemanticUtil.getSimplifiedType(conversionType); - IType p= template.getType().getReturnType(); - p= getArgumentTypeForDeduction(p, a instanceof ICPPReferenceType); - a= SemanticUtil.getNestedType(a, SemanticUtil.REF | SemanticUtil.TDEF); - TemplateArgumentDeduction deduct= new TemplateArgumentDeduction(tmplParams, null, map, 0); - if (!deduct.fromType(p, a, false)) { - return null; - } - - for (int i = 0; i < length; i++) { - if (result[i] == null) { - final ICPPTemplateParameter tpar = tmplParams[i]; - ICPPTemplateArgument deducedArg= map.getArgument(tpar); - if (deducedArg == null) { - deducedArg= tpar.getDefaultValue(); - if (deducedArg == null) - return null; - } - result[i]= deducedArg; - } - } - return result; + return createArguments(map, tmplParams); } /** @@ -253,9 +89,6 @@ public class TemplateArgumentDeduction { try { IType[] fnPars = template.getType().getParameterTypes(); final int fnParCount = fnPars.length; - if (fnParCount == 0) - return true; - final ICPPTemplateParameter[] tmplPars = template.getTemplateParameters(); TemplateArgumentDeduction deduct= new TemplateArgumentDeduction(tmplPars, map, new CPPTemplateParameterMap(fnParCount), 0); IType fnParPack= null; @@ -288,7 +121,7 @@ public class TemplateArgumentDeduction { // C++0x: 14.9.2.1-1 if (arg instanceof InitializerListType) { par= SemanticUtil.getNestedType(par, TDEF | REF | CVTYPE); - + // Check if this is a deduced context IType inner= Conversions.getInitListType(par); if (inner != null) { @@ -338,7 +171,7 @@ public class TemplateArgumentDeduction { } } - if (!deduct.fExplicitArgs.mergeToExplicit(deduct.fDeducedArgs)) + if (!map.addDeducedArgs(deduct.fDeducedArgs)) return false; return verifyDeduction(tmplPars, map, true); @@ -346,7 +179,7 @@ public class TemplateArgumentDeduction { } return false; } - + private static boolean deduceFromFunctionArg(IType par, IType arg, ValueCategory valueCat, TemplateArgumentDeduction deduct) throws DOMException { boolean isReferenceTypeParameter= false; if (par instanceof ICPPReferenceType) { @@ -407,6 +240,112 @@ public class TemplateArgumentDeduction { return deduct.fromType(par, arg, true); } + /** + * 14.8.2.2 [temp.deduct.funcaddr] + * Deducing template arguments taking the address of a function template + * @throws DOMException + */ + static ICPPTemplateArgument[] deduceForAddressOf(ICPPFunctionTemplate template, + ICPPTemplateArgument[] tmplArgs, IFunctionType arg, CPPTemplateParameterMap map) throws DOMException { + final ICPPTemplateParameter[] tmplParams = template.getTemplateParameters(); + if (!addExplicitArguments(tmplParams, tmplArgs, map)) + return null; + + IType par= template.getType(); + par= CPPTemplates.instantiateType(par, map, -1, null); + if (!CPPTemplates.isValidType(par)) + return null; + + boolean isDependentPar= CPPTemplates.isDependentType(par); + if (isDependentPar) { + TemplateArgumentDeduction deduct= new TemplateArgumentDeduction(tmplParams, map, new CPPTemplateParameterMap(tmplParams.length), 0); + par= SemanticUtil.getNestedType(par, SemanticUtil.TDEF); + if (arg != null && !deduct.fromType(par, arg, false)) + return null; + if (!map.addDeducedArgs(deduct.fDeducedArgs)) + return null; + } + + if (!verifyDeduction(tmplParams, map, true)) + return null; + + if (isDependentPar) + par= CPPTemplates.instantiateType(par, map, -1, null); + + if (arg == null || arg.isSameType(par)) { + return createArguments(map, tmplParams); + } + return null; + } + + /** + * Deduce arguments for a user defined conversion template + * 14.8.2.3 + */ + static ICPPTemplateArgument[] deduceForConversion(ICPPFunctionTemplate template, + IType conversionType, CPPTemplateParameterMap map) throws DOMException { + final ICPPTemplateParameter[] tmplParams = template.getTemplateParameters(); + final int length = tmplParams.length; + + ICPPTemplateArgument[] result = new ICPPTemplateArgument[length]; + IType a= SemanticUtil.getSimplifiedType(conversionType); + IType p= template.getType().getReturnType(); + p= getArgumentTypeForDeduction(p, a instanceof ICPPReferenceType); + a= SemanticUtil.getNestedType(a, SemanticUtil.REF | SemanticUtil.TDEF); + TemplateArgumentDeduction deduct= new TemplateArgumentDeduction(tmplParams, null, map, 0); + if (!deduct.fromType(p, a, false)) { + return null; + } + + for (int i = 0; i < length; i++) { + if (result[i] == null) { + final ICPPTemplateParameter tpar = tmplParams[i]; + ICPPTemplateArgument deducedArg= map.getArgument(tpar); + if (deducedArg == null) { + deducedArg= tpar.getDefaultValue(); + if (deducedArg == null) + return null; + } + result[i]= deducedArg; + } + } + return result; + } + + /** + * Deduce arguments for a function declaration + * 14.8.2.6 + */ + static ICPPTemplateArgument[] deduceForDeclaration(ICPPFunctionTemplate template, + ICPPTemplateArgument[] args, ICPPFunctionType ftype, CPPTemplateParameterMap map) throws DOMException { + final ICPPTemplateParameter[] tmplParams = template.getTemplateParameters(); + + if (!addExplicitArguments(tmplParams, args, map)) + return null; + + IType a= SemanticUtil.getSimplifiedType(ftype); + IType p= CPPTemplates.instantiateType(template.getType(), map, -1, null); + if (!CPPTemplates.isValidType(p)) + return null; + + TemplateArgumentDeduction deduct= new TemplateArgumentDeduction(tmplParams, map, new CPPTemplateParameterMap(tmplParams.length), 0); + if (!deduct.fromType(p, a, false)) { + return null; + } + + if (!map.addDeducedArgs(deduct.fDeducedArgs)) + return null; + + if (!verifyDeduction(tmplParams, map, true)) + return null; + + IType type= CPPTemplates.instantiateType(p, map, -1, null); + if (!ftype.isSameType(type)) + return null; + + return createArguments(map, tmplParams); + } + /** * Deduces the mapping for the template parameters from the function parameters, * returns false if there is no mapping. @@ -470,6 +409,64 @@ public class TemplateArgumentDeduction { return isMoreCVQualified ? 1 : 0; } + /** + * Adds the explicit arguments to the map. + */ + private static boolean addExplicitArguments(final ICPPTemplateParameter[] tmplParams, + ICPPTemplateArgument[] tmplArgs, CPPTemplateParameterMap map) { + tmplArgs= SemanticUtil.getSimplifiedArguments(tmplArgs); + ICPPTemplateParameter tmplParam= null; + int packOffset= -1; + for (int i = 0; i < tmplArgs.length; i++) { + if (packOffset < 0 || tmplParam == null) { + if (i >= tmplParams.length) + return false; + + tmplParam= tmplParams[i]; + if (tmplParam.isParameterPack()) { + packOffset= i; + } + } + ICPPTemplateArgument tmplArg= tmplArgs[i]; + tmplArg= CPPTemplates.matchTemplateParameterAndArgument(tmplParam, tmplArg, map); + if (tmplArg == null) + return false; + + if (packOffset < 0) { + map.put(tmplParam, tmplArg); + } + } + + if (packOffset >= 0) { + final int packSize= tmplArgs.length- packOffset; + ICPPTemplateArgument[] pack= new ICPPTemplateArgument[packSize]; + System.arraycopy(tmplArgs, packOffset, pack, 0, packSize); + map.put(tmplParam, pack); + } + return true; + } + + private static ICPPTemplateArgument[] createArguments(CPPTemplateParameterMap map, + final ICPPTemplateParameter[] tmplParams) { + List result= new ArrayList(tmplParams.length); + for (ICPPTemplateParameter tpar : tmplParams) { + if (tpar.isParameterPack()) { + ICPPTemplateArgument[] deducedArgs= map.getPackExpansion(tpar); + if (deducedArgs == null) + return null; + result.addAll(Arrays.asList(deducedArgs)); + } else { + ICPPTemplateArgument deducedArg= map.getArgument(tpar); + if (deducedArg == null) { + return null; + } + + result.add(deducedArg); + } + } + return result.toArray(new ICPPTemplateArgument[result.size()]); + } + /** * 14.8.2.1.3 If P is a class and has the form template-id, then A can be a derived class of the deduced A. */ diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/PDOMWriter.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/PDOMWriter.java index 39498fcadf4..b435461ca37 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/PDOMWriter.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/PDOMWriter.java @@ -43,6 +43,7 @@ import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTQualifiedName; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateId; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTUsingDirective; import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassTemplate; +import org.eclipse.cdt.core.dom.ast.cpp.ICPPFunctionTemplate; import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespace; import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespaceAlias; import org.eclipse.cdt.core.dom.ast.cpp.ICPPTemplateParameter; @@ -254,7 +255,8 @@ abstract public class PDOMWriter { try { final IBinding binding = name.resolveBinding(); if (name.getPropertyInParent() == ICPPASTTemplateId.TEMPLATE_NAME && - ((IASTName) name.getParent()).getBinding() == binding) { + (((IASTName) name.getParent()).getBinding() == binding || + binding instanceof ICPPFunctionTemplate)) { na[0]= null; } else if (binding instanceof IProblemBinding) { fStatistics.fProblemBindingCount++; From beeef2d87c0adb73e69502ac3e1761ec43c8a001 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Wed, 24 Aug 2011 19:58:30 -0700 Subject: [PATCH 06/29] Cosmetics. --- .../internal/index/tests/IndexBugsTests.java | 296 +++++++++--------- 1 file changed, 144 insertions(+), 152 deletions(-) diff --git a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/internal/index/tests/IndexBugsTests.java b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/internal/index/tests/IndexBugsTests.java index cbbeb1f6ce3..fd67979eb33 100644 --- a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/internal/index/tests/IndexBugsTests.java +++ b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/internal/index/tests/IndexBugsTests.java @@ -9,7 +9,7 @@ * Markus Schorn - initial API and implementation * Andrew Ferguson (Symbian) * Sergey Prigogin (Google) - *******************************************************************************/ + *******************************************************************************/ package org.eclipse.cdt.internal.index.tests; import java.io.ByteArrayInputStream; @@ -116,28 +116,28 @@ public class IndexBugsTests extends BaseTestCase { protected class BindingAssertionHelper { protected IASTTranslationUnit tu; protected String contents; - + public BindingAssertionHelper(IFile file, String contents, IIndex index) throws CModelException, CoreException { this.contents= contents; this.tu= TestSourceReader.createIndexBasedAST(index, fCProject, file); } - + public IASTTranslationUnit getTranslationUnit() { return tu; } - + public IBinding assertProblem(String section, int len) { IBinding binding= binding(section, len); assertTrue("Non-ProblemBinding for name: " + section.substring(0, len), binding instanceof IProblemBinding); return binding; } - + public T assertNonProblem(String section, int len) { IBinding binding= binding(section, len); if (binding instanceof IProblemBinding) { IProblemBinding problem= (IProblemBinding) binding; - fail("ProblemBinding for name: " + section.substring(0, len) + " (" + renderProblemID(problem.getID())+")"); + fail("ProblemBinding for name: " + section.substring(0, len) + " (" + renderProblemID(problem.getID())+")"); } if (binding == null) { fail("Null binding resolved for name: " + section.substring(0, len)); @@ -146,7 +146,7 @@ public class IndexBugsTests extends BaseTestCase { } public void assertNoName(String section, int len) { - IASTName name= findName(section,len,false); + IASTName name= findName(section, len, false); if (name != null) { String selection = section.substring(0, len); fail("Found unexpected \"" + selection + "\": " + name.resolveBinding()); @@ -158,15 +158,15 @@ public class IndexBugsTests extends BaseTestCase { * it resolves to the given type of binding. */ public IASTImplicitName assertImplicitName(String section, int len, Class bindingClass) { - IASTName name = findName(section,len,true); + IASTName name = findName(section, len, true); final String selection = section.substring(0, len); assertNotNull("did not find \""+selection+"\"", name); - + assertInstance(name, IASTImplicitName.class); IASTImplicitNameOwner owner = (IASTImplicitNameOwner) name.getParent(); IASTImplicitName[] implicits = owner.getImplicitNames(); assertNotNull(implicits); - + if (implicits.length > 1) { boolean found = false; for (IASTImplicitName n : implicits) { @@ -177,27 +177,27 @@ public class IndexBugsTests extends BaseTestCase { } assertTrue(found); } - + assertEquals(selection, name.getRawSignature()); IBinding binding = name.resolveBinding(); assertNotNull(binding); assertInstance(binding, bindingClass); return (IASTImplicitName) name; } - + public void assertNoImplicitName(String section, int len) { - IASTName name = findName(section,len,true); + IASTName name = findName(section, len, true); final String selection = section.substring(0, len); assertNull("found name \""+selection+"\"", name); } - + public IASTImplicitName[] getImplicitNames(String section, int len) { - IASTName name = findName(section,len,true); + IASTName name = findName(section, len, true); IASTImplicitNameOwner owner = (IASTImplicitNameOwner) name.getParent(); IASTImplicitName[] implicits = owner.getImplicitNames(); return implicits; } - + private IASTName findName(String section, int len, boolean implicit) { final int offset = contents.indexOf(section); assertTrue(offset >= 0); @@ -222,7 +222,7 @@ public class IndexBugsTests extends BaseTestCase { } return "Unknown problem ID"; } - + public T assertNonProblem(String section, int len, Class type, Class... cs) { IBinding binding= binding(section, len); assertTrue("ProblemBinding for name: " + section.substring(0, len), @@ -233,16 +233,16 @@ public class IndexBugsTests extends BaseTestCase { } return type.cast(binding); } - + private IBinding binding(String section, int len) { - IASTName name = findName(section, len,false); + IASTName name = findName(section, len, false); final String selection = section.substring(0, len); assertNotNull("Did not find \"" + selection + "\"", name); assertEquals(selection, name.getRawSignature()); - + IBinding binding = name.resolveBinding(); assertNotNull("No binding for " + name.getRawSignature(), binding); - + return name.resolveBinding(); } } @@ -261,7 +261,7 @@ public class IndexBugsTests extends BaseTestCase { waitForIndexer(); fIndex= CCorePlugin.getIndexManager().getIndex(fCProject); } - + @Override protected void tearDown() throws Exception { if (fCProject != null) { @@ -269,11 +269,11 @@ public class IndexBugsTests extends BaseTestCase { } super.tearDown(); } - + protected IProject getProject() { return fCProject.getProject(); } - + protected String[] getContentsForTest(int blocks) throws IOException { CharSequence[] help= TestSourceReader.getContentsForTest( CTestPlugin.getDefault().getBundle(), "parser", getClass(), getName(), blocks); @@ -284,7 +284,7 @@ public class IndexBugsTests extends BaseTestCase { } return result; } - + protected IFile createFile(IContainer container, String fileName, String contents) throws Exception { return TestSourceReader.createFile(container, new Path(fileName), contents); } @@ -304,7 +304,7 @@ public class IndexBugsTests extends BaseTestCase { String[] parts= qname.split("::"); Pattern[] result= new Pattern[parts.length]; for (int i = 0; i < result.length; i++) { - result[i]= Pattern.compile(parts[i]); + result[i]= Pattern.compile(parts[i]); } return result; } @@ -335,7 +335,7 @@ public class IndexBugsTests extends BaseTestCase { IASTName name= ast.getNodeSelector(null).findName(source.indexOf(section), len); assertNotNull("Name not found for \"" + section + "\"", name); assertEquals(section.substring(0, len), name.getRawSignature()); - + IBinding binding = name.resolveBinding(); assertNotNull("No binding for " + section.substring(0, len), binding); assertTrue("ProblemBinding for name: " + section.substring(0, len), @@ -357,7 +357,7 @@ public class IndexBugsTests extends BaseTestCase { // public: // void one() {} // void two() {} - // }; + // }; // class A { // public: @@ -369,29 +369,29 @@ public class IndexBugsTests extends BaseTestCase { // Because of fix for http://bugs.eclipse.org/193779 this test case passes. // However http://bugs.eclipse.org/154563 remains to be fixed. String[] content= getContentsForTest(2); - + IFile file= createFile(getProject(), "header.h", content[0]); waitUntilFileIsIndexed(file, INDEX_WAIT_TIME); - + IIndex index= CCorePlugin.getIndexManager().getIndex(fCProject); index.acquireReadLock(); try { IBinding[] bs= index.findBindings("A".toCharArray(), IndexFilter.ALL, npm()); - assertEquals(1, bs.length); + assertEquals(1, bs.length); assertTrue(bs[0] instanceof ICPPClassType); assertEquals(2, ((ICPPClassType)bs[0]).getDeclaredMethods().length); } finally { index.releaseReadLock(); } - + file= createFile(getProject(), "header.h", content[1]); waitUntilFileIsIndexed(file, INDEX_WAIT_TIME); - + index= CCorePlugin.getIndexManager().getIndex(fCProject); index.acquireReadLock(); try { IBinding[] bs= index.findBindings("A".toCharArray(), IndexFilter.ALL, npm()); - assertEquals(1, bs.length); + assertEquals(1, bs.length); assertTrue(bs[0] instanceof ICPPClassType); assertEquals(3, ((ICPPClassType)bs[0]).getDeclaredMethods().length); } finally { @@ -419,9 +419,9 @@ public class IndexBugsTests extends BaseTestCase { try { IIndexBinding[] bindings= fIndex.findBindings(getPattern("arrayDataSize"), true, IndexFilter.ALL, npm()); assertEquals(1, bindings.length); - + IIndexBinding binding= bindings[0]; - + // check if we have the definition IIndexName[] decls= fIndex.findNames(binding, IIndex.FIND_DEFINITIONS); assertEquals(1, decls.length); @@ -504,7 +504,7 @@ public class IndexBugsTests extends BaseTestCase { // namespace ns162011 { // class Class162011 { - // friend void function162011(Class162011); + // friend void function162011(Class162011); // }; // void function162011(Class162011 x){}; // } @@ -517,7 +517,7 @@ public class IndexBugsTests extends BaseTestCase { int indexOfDef = content.indexOf(funcName, indexOfDecl+1); IFile file= createFile(getProject(), fileName, content); waitUntilFileIsIndexed(file, INDEX_WAIT_TIME); - + // make sure the ast is correct ITranslationUnit tu= (ITranslationUnit) fCProject.findElement(new Path(fileName)); IASTTranslationUnit ast= tu.getAST(); @@ -535,9 +535,9 @@ public class IndexBugsTests extends BaseTestCase { try { IIndexBinding[] bindings= fIndex.findBindings(getPattern("ns162011::function162011"), true, IndexFilter.ALL, npm()); assertEquals(1, bindings.length); - + IIndexBinding binding= bindings[0]; - + // check if we have the declaration IIndexName[] decls= fIndex.findNames(binding, IIndex.FIND_DECLARATIONS); assertEquals(1, decls.length); @@ -630,11 +630,11 @@ public class IndexBugsTests extends BaseTestCase { // // header.h // class E {}; - + // #include "header.h" // E var; - - // // header.h + + // // header.h // enum E {A,B,C}; public void test171834() throws Exception { CModelListener.sSuppressUpdateOfLastRecentlyUsed= false; @@ -659,7 +659,7 @@ public class IndexBugsTests extends BaseTestCase { index.releaseReadLock(); } - InputStream in = new ByteArrayInputStream(testData[2].getBytes()); + InputStream in = new ByteArrayInputStream(testData[2].getBytes()); header.setContents(in, IResource.FORCE, null); TestSourceReader.waitUntilFileIsIndexed(index, header, INDEX_WAIT_TIME); @@ -692,7 +692,7 @@ public class IndexBugsTests extends BaseTestCase { try { IBinding[] bindings= fIndex.findBindings("S20070201".toCharArray(), IndexFilter.getFilter(ILinkage.C_LINKAGE_ID), npm()); assertEquals(2, bindings.length); - + IBinding struct, typedef; if (bindings[0] instanceof ICompositeType) { struct= bindings[0]; @@ -701,7 +701,7 @@ public class IndexBugsTests extends BaseTestCase { struct= bindings[1]; typedef= bindings[0]; } - + assertTrue(struct instanceof ICompositeType); assertTrue(typedef instanceof ITypedef); assertTrue(((ITypedef) typedef).getType() instanceof ICompositeType); @@ -725,7 +725,7 @@ public class IndexBugsTests extends BaseTestCase { try { IBinding[] bindings= fIndex.findBindings("S20070201".toCharArray(), IndexFilter.getFilter(ILinkage.CPP_LINKAGE_ID), npm()); assertEquals(2, bindings.length); - + IBinding struct, typedef; if (bindings[0] instanceof ICPPClassType) { struct= bindings[0]; @@ -734,7 +734,7 @@ public class IndexBugsTests extends BaseTestCase { struct= bindings[1]; typedef= bindings[0]; } - + assertTrue(struct instanceof ICPPClassType); assertTrue(((ICPPClassType)struct).getKey()==ICompositeType.k_struct); assertTrue(typedef instanceof ITypedef); @@ -768,7 +768,7 @@ public class IndexBugsTests extends BaseTestCase { } finally { fIndex.releaseReadLock(); } - + long timestamp= file.getLocalTimeStamp(); content= "int UPDATED20070213;\n" + content.replaceFirst("int", "float"); file= TestSourceReader.createFile(fCProject.getProject(), "test173997.cpp", content); @@ -779,7 +779,7 @@ public class IndexBugsTests extends BaseTestCase { // double check if file was indexed IBinding[] bindings= fIndex.findBindings("UPDATED20070213".toCharArray(), IndexFilter.getFilter(ILinkage.CPP_LINKAGE_ID), npm()); assertEquals(1, bindings.length); - + bindings= fIndex.findBindings("T20070213".toCharArray(), IndexFilter.getFilter(ILinkage.CPP_LINKAGE_ID), npm()); assertEquals(1, bindings.length); assertTrue(bindings[0] instanceof ITypedef); @@ -797,36 +797,36 @@ public class IndexBugsTests extends BaseTestCase { // class A {}; // class B {}; // A var; - + // class A {}; // class B {}; // B var; public void test173997_2() throws Exception { String[] content= getContentsForTest(2); - + IFile file= createFile(getProject(), "header.h", content[0]); waitUntilFileIsIndexed(file, INDEX_WAIT_TIME); - + IIndex index= CCorePlugin.getIndexManager().getIndex(fCProject); index.acquireReadLock(); try { IBinding[] bs= index.findBindings("var".toCharArray(), IndexFilter.ALL, npm()); - assertEquals(1, bs.length); + assertEquals(1, bs.length); assertTrue(bs[0] instanceof ICPPVariable); assertTrue(((ICPPVariable)bs[0]).getType() instanceof ICPPClassType); assertEquals("A", ((ICPPClassType)(((ICPPVariable)bs[0]).getType())).getName()); } finally { index.releaseReadLock(); } - + file= createFile(getProject(), "header.h", content[1]); waitUntilFileIsIndexed(file, INDEX_WAIT_TIME); - + index= CCorePlugin.getIndexManager().getIndex(fCProject); index.acquireReadLock(); try { IBinding[] bs= index.findBindings("var".toCharArray(), IndexFilter.ALL, npm()); - assertEquals(1, bs.length); + assertEquals(1, bs.length); assertTrue(bs[0] instanceof ICPPVariable); assertTrue(((ICPPVariable)bs[0]).getType() instanceof ICPPClassType); assertEquals("B", ((ICPPClassType)(((ICPPVariable)bs[0]).getType())).getName()); @@ -838,7 +838,7 @@ public class IndexBugsTests extends BaseTestCase { // // header.h // template class Test {}; // template void f() {} - + // #include "header.h" // struct A {}; // Test a; @@ -956,7 +956,7 @@ public class IndexBugsTests extends BaseTestCase { /* Check that when a project is deleted, its index contents do not * appear in the initial index of a newly created project of the same name */ - + String pname = "deleteTest"+System.currentTimeMillis(); ICProject cproject = CProjectHelper.createCCProject(pname, "bin", IPDOMManager.ID_FAST_INDEXER); IIndex index = CCorePlugin.getIndexManager().getIndex(cproject); @@ -994,8 +994,8 @@ public class IndexBugsTests extends BaseTestCase { File newLocation = CProjectHelper.freshDir(); IProjectDescription description = cproject.getProject().getDescription(); description.setLocationURI(newLocation.toURI()); - cproject.getProject().move(description, IResource.FORCE | IResource.SHALLOW, new NullProgressMonitor()); - + cproject.getProject().move(description, IResource.FORCE | IResource.SHALLOW, new NullProgressMonitor()); + index = CCorePlugin.getIndexManager().getIndex(cproject); index.acquireReadLock(); try { @@ -1031,23 +1031,23 @@ public class IndexBugsTests extends BaseTestCase { return !(binding instanceof IFunction); } }; - + IBinding[] bindings= fIndex.findBindingsForPrefix(new char[] {'a'}, true, NON_FUNCTIONS, null); - assertEquals(3,bindings.length); - + assertEquals(3, bindings.length); + bindings= fIndex.findBindingsForPrefix(new char[] {'a'}, false, NON_FUNCTIONS, null); - assertEquals(6,bindings.length); - + assertEquals(6, bindings.length); + bindings= fIndex.findBindingsForPrefix(new char[] {'a','A'}, true, NON_FUNCTIONS, null); - assertEquals(1,bindings.length); - + assertEquals(1, bindings.length); + bindings= fIndex.findBindingsForPrefix(new char[] {'a','A'}, false, NON_FUNCTIONS, null); assertEquals(2, bindings.length); } finally { fIndex.releaseReadLock(); - } + } } - + // class a { class b { class c { void f(); }; }; }; public void testFilterFindBindingsFQCharArray() throws Exception { waitForIndexer(); @@ -1064,27 +1064,27 @@ public class IndexBugsTests extends BaseTestCase { return !(binding instanceof ICPPClassType); } }; - + IBinding[] bindings= fIndex.findBindings(new char[][]{{'a'},{'b'},{'c'},{'f'}}, NON_CLASS, npm()); - assertEquals(1,bindings.length); + assertEquals(1, bindings.length); } finally { fIndex.releaseReadLock(); - } + } } - + // typedef struct { // float fNumber; // int iIdx; // } StructA_T; - + // #include "../__bugsTest__/common.h" // StructA_T gvar1; - + // #include "../__bugsTest__/common.h" // StructA_T gvar2; public void testFileInMultipleFragments_bug192352() throws Exception { String[] contents= getContentsForTest(3); - + ICProject p2 = CProjectHelper.createCCProject("__bugsTest_2_", "bin", IPDOMManager.ID_FAST_INDEXER); try { IFile f1= TestSourceReader.createFile(fCProject.getProject(), "common.h", contents[0]); @@ -1109,22 +1109,22 @@ public class IndexBugsTests extends BaseTestCase { CProjectHelper.delete(p2); } } - + // #ifndef _h1 // #define _h1 // #define M v // #endif - + // #ifndef _h1 // #include "header1.h" // #endif - + // #include "header1.h" // #include "header2.h" - + // #include "header2.h" // int M; - + // #include "header2.h" // #ifndef _h1 // #include "header1.h" @@ -1140,7 +1140,7 @@ public class IndexBugsTests extends BaseTestCase { IFile f4= TestSourceReader.createFile(fCProject.getProject(), "src2.cpp", contents[3]); IFile f5= TestSourceReader.createFile(fCProject.getProject(), "src3.cpp", contents[4]); waitForIndexer(); - + IIndex index= indexManager.getIndex(fCProject); index.acquireReadLock(); try { @@ -1151,7 +1151,7 @@ public class IndexBugsTests extends BaseTestCase { IIndexName[] names = index.findNames(binding, IIndex.FIND_ALL_OCCURRENCES); assertEquals(1, names.length); assertEquals(f4.getFullPath().toString(), names[0].getFile().getLocation().getFullPath()); - + IIndexFile idxFile= index.getFile(ILinkage.CPP_LINKAGE_ID, IndexLocationFactory.getWorkspaceIFL(f5)); IIndexInclude[] includes= idxFile.getIncludes(); assertEquals(2, includes.length); @@ -1163,10 +1163,9 @@ public class IndexBugsTests extends BaseTestCase { index.releaseReadLock(); } } - - + // #define MAC(...) Bug200239 - + // #include "header.h" // int MAC(1); // void func() { @@ -1190,9 +1189,9 @@ public class IndexBugsTests extends BaseTestCase { fIndex.releaseReadLock(); } } - + // #define GMAC(x...) Bug200239 - + // #include "header.h" // int GMAC(1); // void func() { @@ -1217,7 +1216,6 @@ public class IndexBugsTests extends BaseTestCase { } } - // typedef bug200553_A bug200553_B; // typedef bug200553_B bug200553_A; public void testTypedefRecursionCpp_Bug200553() throws Exception { @@ -1266,7 +1264,7 @@ public class IndexBugsTests extends BaseTestCase { } assertTrue(maxDepth > 0); } - + // typedef bug200553_A bug200553_B; // typedef bug200553_B bug200553_A; public void testTypedefRecursionC_Bug200553() throws Exception { @@ -1306,7 +1304,7 @@ public class IndexBugsTests extends BaseTestCase { fIndex.releaseReadLock(); } } - + // #ifndef GUARD // #include "source.cpp" // #endif @@ -1315,7 +1313,7 @@ public class IndexBugsTests extends BaseTestCase { final IIndexManager indexManager = CCorePlugin.getIndexManager(); IFile f1= TestSourceReader.createFile(fCProject.getProject(), "source.cpp", contents[0]); waitForIndexer(); - + final ITranslationUnit tu= (ITranslationUnit) fCProject.findElement(new Path("source.cpp")); Thread th= new Thread() { @Override @@ -1324,7 +1322,7 @@ public class IndexBugsTests extends BaseTestCase { tu.getAST(fIndex, ITranslationUnit.AST_CONFIGURE_USING_SOURCE_CONTEXT); } catch (CoreException e) { CCorePlugin.log(e); - } + } } }; fIndex.acquireReadLock(); @@ -1357,9 +1355,9 @@ public class IndexBugsTests extends BaseTestCase { fIndex.releaseReadLock(); } } - + // static inline void staticInHeader() {}; - + // #include "header.h" // void f1() { // staticInHeader(); @@ -1384,9 +1382,9 @@ public class IndexBugsTests extends BaseTestCase { fIndex.releaseReadLock(); } } - + // static const int staticConstInHeader= 12; - + // #include "header.h" // void f1() { // int a= staticConstInHeader; @@ -1413,7 +1411,7 @@ public class IndexBugsTests extends BaseTestCase { } // static inline void staticInHeader() {}; - + // #include "header.h" // void f1() { // staticInHeader(); @@ -1438,9 +1436,9 @@ public class IndexBugsTests extends BaseTestCase { fIndex.releaseReadLock(); } } - + // static const int staticConstInHeader= 12; - + // #include "header.h" // void f1() { // int a= staticConstInHeader; @@ -1467,7 +1465,7 @@ public class IndexBugsTests extends BaseTestCase { } // int ok; - + // #include "header.x" public void testNonStandardSuffix_Bug205778() throws Exception { String[] contents= getContentsForTest(2); @@ -1484,14 +1482,14 @@ public class IndexBugsTests extends BaseTestCase { fIndex.releaseReadLock(); } } - + // inline void MyClass::method() {} - + // class MyClass { // void method(); // }; // #include "MyClass_inline.h" - + // #include "MyClass.h" public void testAddingMemberBeforeContainer_Bug203170() throws Exception { String[] contents= getContentsForTest(3); @@ -1512,14 +1510,13 @@ public class IndexBugsTests extends BaseTestCase { fIndex.releaseReadLock(); } } - - + // typedef int unrelated; - + // class unrelated { // public: int b; // }; - + // #include "h1.h" // void test() { // unrelated a; @@ -1546,7 +1543,7 @@ public class IndexBugsTests extends BaseTestCase { } // #undef BBB - + // #define BBB // #include "header.h" // #ifdef BBB @@ -1574,9 +1571,9 @@ public class IndexBugsTests extends BaseTestCase { fIndex.releaseReadLock(); } } - + // #define BUG ok - + // int BUG; // #include "common.h" @@ -1601,7 +1598,7 @@ public class IndexBugsTests extends BaseTestCase { } // #include "h2.h" - + // int BUG; // #define BUG ok @@ -1625,7 +1622,6 @@ public class IndexBugsTests extends BaseTestCase { } } - // #include // #define _CONCAT(x,y) x##y // #define CONCAT(x,y) _CONCAT(x,y) @@ -1638,7 +1634,7 @@ public class IndexBugsTests extends BaseTestCase { TestSourceReader.createFile(fCProject.getProject(), "f1/g/source.cpp", contents + "int CONCAT(one, ID);\n"); TestSourceReader.createFile(fCProject.getProject(), "f2/g/source.cpp", contents + "int CONCAT(two, ID);\n"); TestSourceReader.createFile(fCProject.getProject(), "f1/g/h/source.cpp", contents + "int CONCAT(three, ID);\n"); - + waitForIndexer(); fIndex.acquireReadLock(); try { @@ -1652,7 +1648,7 @@ public class IndexBugsTests extends BaseTestCase { fIndex.releaseReadLock(); } } - + public void testIncludeHeuristicsFlag_Bug213562() throws Exception { final IIndexManager indexManager = CCorePlugin.getIndexManager(); TestSourceReader.createFile(fCProject.getProject(), "f1/header.h", ""); @@ -1673,8 +1669,7 @@ public class IndexBugsTests extends BaseTestCase { fIndex.releaseReadLock(); } } - - + // #include "dir" // #include "header.h" public void testInclusionOfFolders_Bug243682() throws Exception { @@ -1696,9 +1691,8 @@ public class IndexBugsTests extends BaseTestCase { } finally { fIndex.releaseReadLock(); } - } - - + } + // #ifndef B_H // #include "b.h" // #endif @@ -1760,7 +1754,7 @@ public class IndexBugsTests extends BaseTestCase { fIndex.releaseReadLock(); } } - + // namespace ns { // template class X {}; // } @@ -1788,8 +1782,7 @@ public class IndexBugsTests extends BaseTestCase { fIndex.releaseReadLock(); } } - - + // #include "B.cpp" // static int STATIC; @@ -1812,9 +1805,9 @@ public class IndexBugsTests extends BaseTestCase { fIndex.releaseReadLock(); } } - + // int a; - + // #include "a.h" // void test() {a=0;} public void testDeclarationForBinding_Bug254844() throws Exception { @@ -1857,7 +1850,7 @@ public class IndexBugsTests extends BaseTestCase { // int i; // }; // } - + // #include "a.h" // using ns::A; // void test() { @@ -1870,7 +1863,7 @@ public class IndexBugsTests extends BaseTestCase { // struct A { // int j; // }; - + // #include "b.h" // void test() { // A a; @@ -1908,14 +1901,14 @@ public class IndexBugsTests extends BaseTestCase { // namespace ns { // enum E1 { e = 1 }; // } - + // #include "a.h" // using namespace ns; // int i = e; // // b.h // enum E2 { e = 2 }; - + // #include "b.h" // int i = e; public void testDisambiguationByReachability_268704_2() throws Exception { @@ -2016,7 +2009,7 @@ public class IndexBugsTests extends BaseTestCase { // // header.h // namespace ns2 { class A {}; } - + // #include "header.h" // namespace ns1 { // class B : public ns2::A {}; @@ -2049,7 +2042,7 @@ public class IndexBugsTests extends BaseTestCase { // // a.h // #undef AAA - + // // b.h // #include "a.h" // #define AAA @@ -2083,7 +2076,7 @@ public class IndexBugsTests extends BaseTestCase { // // a.h // #undef AAA - + // // b.h // #define AAA // #include "a.h" @@ -2153,7 +2146,7 @@ public class IndexBugsTests extends BaseTestCase { index.releaseReadLock(); } } - + // template void f(T t) throw (T) {} public void testFunctionTemplateWithThrowsException_293021() throws Exception { waitForIndexer(); @@ -2176,19 +2169,19 @@ public class IndexBugsTests extends BaseTestCase { index.releaseReadLock(); } } - + // // a.h // class P {}; - + // // b.h // namespace P {class C {};} // // source1.cpp - // #include "a.h" + // #include "a.h" // P p; // // source2.cpp - // #include "b.h" + // #include "b.h" // P::C c; public void testDisambiguateClassVsNamespace_297686() throws Exception { waitForIndexer(); @@ -2221,12 +2214,12 @@ public class IndexBugsTests extends BaseTestCase { // // a.h // struct Error{}; - + // // b.h // void Error(int errCode) {} // // source1.cpp - // #include "a.h" + // #include "a.h" // Error d; // // source2.cpp @@ -2261,7 +2254,7 @@ public class IndexBugsTests extends BaseTestCase { public void testUpdateNonSrcFolderHeader_283080() throws Exception { IIndexBinding[] r; - + final IProject prj = fCProject.getProject(); final IFolder src= prj.getFolder("src"); final IFolder h= prj.getFolder("h"); @@ -2278,7 +2271,7 @@ public class IndexBugsTests extends BaseTestCase { CCorePlugin.getDefault().setProjectDescription(prj, desc); TestSourceReader.createFile(h, "a.h", "int version1;"); waitForIndexer(fCProject); - + final IIndex index= CCorePlugin.getIndexManager().getIndex(fCProject); index.acquireReadLock(); try { @@ -2287,7 +2280,7 @@ public class IndexBugsTests extends BaseTestCase { } finally { index.releaseReadLock(); } - + IFile s= TestSourceReader.createFile(h, "a.h", "int version2;"); waitForIndexer(fCProject); index.acquireReadLock(); @@ -2307,7 +2300,7 @@ public class IndexBugsTests extends BaseTestCase { } finally { index.releaseReadLock(); } - + s= TestSourceReader.createFile(h, "a.h", "int version3;"); waitUntilFileIsIndexed(s, INDEX_WAIT_TIME); index.acquireReadLock(); @@ -2323,12 +2316,12 @@ public class IndexBugsTests extends BaseTestCase { public void testUpdateForContentTypeChange_283080() throws Exception { IIndexBinding[] r; - + final IProject prj = fCProject.getProject(); IFile file= TestSourceReader.createFile(prj, "a.cpp", "// \u0110 \n int a;"); file.setCharset("US-ASCII", new NullProgressMonitor()); waitForIndexer(fCProject); - + final IIndex index= CCorePlugin.getIndexManager().getIndex(fCProject); int offset1= 0; index.acquireReadLock(); @@ -2341,7 +2334,7 @@ public class IndexBugsTests extends BaseTestCase { } finally { index.releaseReadLock(); } - + file.setCharset("UTF-8", new NullProgressMonitor()); waitForIndexer(fCProject); int offset2= 0; @@ -2355,13 +2348,13 @@ public class IndexBugsTests extends BaseTestCase { } finally { index.releaseReadLock(); } - + assertTrue(offset1 != offset2); } public void testUpdateOnFolderRemove_343538() throws Exception { IIndexBinding[] r; - + final IProject prj = fCProject.getProject(); final IFolder root= prj.getFolder("root"); root.create(true, false, null); @@ -2376,7 +2369,7 @@ public class IndexBugsTests extends BaseTestCase { TestSourceReader.createFile(child1, "a.c", "void bug343538() {}"); TestSourceReader.createFile(child2, "b.c", "void bug343538();"); waitForIndexer(fCProject); - + final IIndex index= CCorePlugin.getIndexManager().getIndex(fCProject); index.acquireReadLock(); try { @@ -2387,7 +2380,7 @@ public class IndexBugsTests extends BaseTestCase { } finally { index.releaseReadLock(); } - + // Collect files and folders final Set files = new HashSet(); final Set folders = new HashSet(); @@ -2430,5 +2423,4 @@ public class IndexBugsTests extends BaseTestCase { index.releaseReadLock(); } } - } \ No newline at end of file From e5c813169a1553fb637400384a0cc4b2d27dc429 Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Thu, 25 Aug 2011 09:08:13 -0400 Subject: [PATCH 07/29] Bug 349736: DSF-GDB breakpoint deleted when modifying thread filter --- .../ui/breakpoints/GdbThreadFilterEditor.java | 32 ++++++++++++------- .../gdb/internal/ui/breakpoints/Messages.java | 5 ++- .../ui/breakpoints/Messages.properties | 3 ++ .../dsf/mi/service/MIBreakpointsManager.java | 2 +- 4 files changed, 29 insertions(+), 13 deletions(-) diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/GdbThreadFilterEditor.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/GdbThreadFilterEditor.java index d3206875d7d..3b4ae72dd26 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/GdbThreadFilterEditor.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/GdbThreadFilterEditor.java @@ -24,16 +24,16 @@ import org.eclipse.cdt.dsf.concurrent.Query; import org.eclipse.cdt.dsf.datamodel.DMContexts; import org.eclipse.cdt.dsf.datamodel.IDMContext; import org.eclipse.cdt.dsf.debug.service.IProcesses; -import org.eclipse.cdt.dsf.debug.service.IRunControl; +import org.eclipse.cdt.dsf.debug.service.IProcesses.IProcessDMContext; import org.eclipse.cdt.dsf.debug.service.IProcesses.IThreadDMContext; import org.eclipse.cdt.dsf.debug.service.IProcesses.IThreadDMData; +import org.eclipse.cdt.dsf.debug.service.IRunControl; import org.eclipse.cdt.dsf.debug.service.IRunControl.IContainerDMContext; import org.eclipse.cdt.dsf.debug.service.IRunControl.IExecutionDMContext; import org.eclipse.cdt.dsf.debug.service.command.ICommandControlService; import org.eclipse.cdt.dsf.gdb.breakpoints.CBreakpointGdbThreadsFilterExtension; import org.eclipse.cdt.dsf.gdb.internal.ui.GdbUIPlugin; import org.eclipse.cdt.dsf.gdb.launching.GdbLaunch; -import org.eclipse.cdt.dsf.gdb.service.IGDBBackend; import org.eclipse.cdt.dsf.mi.service.IMIExecutionDMContext; import org.eclipse.cdt.dsf.mi.service.IMIProcesses; import org.eclipse.cdt.dsf.service.DsfServicesTracker; @@ -256,7 +256,7 @@ public class GdbThreadFilterEditor { private void createThreadViewer(Composite parent) { Label label = new Label(parent, SWT.NONE); - label.setText("&Restrict to Selected Targets and Threads:"); //$NON-NLS-1$ + label.setText(Messages.GdbThreadFilterEditor_RestrictToSelected); label.setFont(parent.getFont()); label.setLayoutData(new GridData()); GridData data = new GridData(GridData.FILL_BOTH); @@ -388,7 +388,7 @@ public class GdbThreadFilterEditor { IContainerDMContext[] containerDmcs = (IContainerDMContext[])getData(); rm.setData(containerDmcs); } else { - rm.setStatus(getFailStatus(IDsfStatusConstants.INVALID_STATE, "Wront type of container contexts.")); //$NON-NLS-1$ + rm.setStatus(getFailStatus(IDsfStatusConstants.INVALID_STATE, "Wrong type of container contexts.")); //$NON-NLS-1$ } rm.done(); } @@ -458,7 +458,7 @@ public class GdbThreadFilterEditor { class ContainerLabelQuery extends Query { @Override - protected void execute(DataRequestMonitor rm) { + protected void execute(final DataRequestMonitor rm) { if (!session.isActive()) { rm.setStatus(getFailStatus(IDsfStatusConstants.INVALID_STATE, "Container's session not active.")); //$NON-NLS-1$ rm.done(); @@ -466,13 +466,22 @@ public class GdbThreadFilterEditor { } DsfServicesTracker tracker = new DsfServicesTracker(GdbUIPlugin.getBundleContext(), session.getId()); - IGDBBackend backend = tracker.getService(IGDBBackend.class); - if (backend != null) { - rm.setData(backend.getProgramPath().toOSString()); + IProcesses processService = tracker.getService(IProcesses.class); + IProcessDMContext procDmc = DMContexts.getAncestorOfType(container, IProcessDMContext.class); + if (processService != null && procDmc != null) { + processService.getExecutionData( + procDmc, + new DataRequestMonitor(ImmediateExecutor.getInstance(), rm) { + @Override + public void handleSuccess() { + rm.setData(getData().getName()); + rm.done(); + } + }); } else { - rm.setStatus(getFailStatus(IDsfStatusConstants.INVALID_STATE, "GDB Backend not accessible.")); //$NON-NLS-1$ + rm.setStatus(getFailStatus(IDsfStatusConstants.INVALID_STATE, "Processes service not accessible.")); //$NON-NLS-1$ + rm.done(); } - rm.done(); tracker.dispose(); } } @@ -511,7 +520,8 @@ public class GdbThreadFilterEditor { ImmediateExecutor.getInstance(), rm) { @Override protected void handleSuccess() { - final StringBuilder builder = new StringBuilder("Thread["); //$NON-NLS-1$ + final StringBuilder builder = new StringBuilder(Messages.GdbThreadFilterEditor_Thread); + builder.append("["); //$NON-NLS-1$ builder.append(((IMIExecutionDMContext)thread).getThreadId()); builder.append("] "); //$NON-NLS-1$ builder.append(getData().getId()); diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/Messages.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/Messages.java index 2eeb0e892b3..38b8bed6d9c 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/Messages.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/Messages.java @@ -31,7 +31,10 @@ public class Messages extends NLS { public static String TracepointPropertyPage_PassCount; public static String TracepointPropertyPage_Class; public static String TracepointPropertyPage_Enabled; - + + public static String GdbThreadFilterEditor_Thread; + public static String GdbThreadFilterEditor_RestrictToSelected; + static { // initialize resource bundle NLS.initializeMessages(Messages.class.getName(), Messages.class); diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/Messages.properties b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/Messages.properties index 010a6b7dbd6..95a0dd2ac43 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/Messages.properties +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/Messages.properties @@ -29,3 +29,6 @@ TracepointPropertyPage_IgnoreCount=&Ignore count: TracepointPropertyPage_PassCount=&Pass count: TracepointPropertyPage_Class=Class: TracepointPropertyPage_Enabled=Enabled + +GdbThreadFilterEditor_Thread=Thread +GdbThreadFilterEditor_RestrictToSelected=&Restrict to Selected Processes and Threads: \ No newline at end of file diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/mi/service/MIBreakpointsManager.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/mi/service/MIBreakpointsManager.java index 3b3f673684e..8350f969927 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/mi/service/MIBreakpointsManager.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/mi/service/MIBreakpointsManager.java @@ -1669,7 +1669,7 @@ public class MIBreakpointsManager extends AbstractDsfService implements IBreakpo // Extract the thread IDs (if there is none, we are covered) for (IContainerDMContext ctxt : targets) { - if (DMContexts.isAncestorOf(ctxt, context)) { + if (ctxt.equals(context) || DMContexts.isAncestorOf(ctxt, context)) { threads.add(filterExtension.getThreadFilters(ctxt)); } } From dda266c4787b7a03111f4e500b5438106a9851b0 Mon Sep 17 00:00:00 2001 From: Marc-Andre Laperle Date: Sun, 28 Aug 2011 14:38:02 -0400 Subject: [PATCH 08/29] Bug 355006 - NPE using Implement method on template function --- .../resources/refactoring/ImplementMethod.rts | 19 +++++++++++++++++++ .../ImplementMethodRefactoring.java | 13 +++++++------ .../ui/refactoring/utils/NodeHelper.java | 17 +++++++++++------ 3 files changed, 37 insertions(+), 12 deletions(-) diff --git a/core/org.eclipse.cdt.ui.tests/resources/refactoring/ImplementMethod.rts b/core/org.eclipse.cdt.ui.tests/resources/refactoring/ImplementMethod.rts index ba804a149a3..7fc4d475cc9 100644 --- a/core/org.eclipse.cdt.ui.tests/resources/refactoring/ImplementMethod.rts +++ b/core/org.eclipse.cdt.ui.tests/resources/refactoring/ImplementMethod.rts @@ -838,3 +838,22 @@ void TestClass::foo() { } +//!Bug 355006 - NPE implementing template function +//#org.eclipse.cdt.ui.tests.refactoring.implementmethod.ImplementMethodRefactoringTest +//@.config +filename=A.h +infos=1 +//@A.h + +/*$*/template void func(T&);/*$$*/ + +//= + +template void func(T&); + +template inline void func(T& ) +{ +} + + + diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/implementmethod/ImplementMethodRefactoring.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/implementmethod/ImplementMethodRefactoring.java index bf101d1f1e6..510c842227f 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/implementmethod/ImplementMethodRefactoring.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/implementmethod/ImplementMethodRefactoring.java @@ -260,15 +260,16 @@ public class ImplementMethodRefactoring extends CRefactoring2 { IASTFunctionDefinition functionDefinition = nodeFactory.newFunctionDefinition(declSpecifier, createdMethodDeclarator, nodeFactory.newCompoundStatement()); functionDefinition.setParent(unit); - if (NodeHelper.isContainedInTemplateDeclaration(declarationParent)) { - ICPPASTTemplateDeclaration templateDeclaration = nodeFactory.newTemplateDeclaration(functionDefinition); - templateDeclaration.setParent(unit); + ICPPASTTemplateDeclaration templateDeclaration = NodeHelper.findContainedTemplateDecalaration(declarationParent); + if (templateDeclaration != null) { + ICPPASTTemplateDeclaration newTemplateDeclaration = nodeFactory.newTemplateDeclaration(functionDefinition); + newTemplateDeclaration.setParent(unit); - for (ICPPASTTemplateParameter templateParameter : ((ICPPASTTemplateDeclaration) declarationParent.getParent().getParent() ).getTemplateParameters()) { - templateDeclaration.addTemplateParameter(templateParameter.copy(CopyStyle.withLocations)); + for (ICPPASTTemplateParameter templateParameter : templateDeclaration.getTemplateParameters()) { + newTemplateDeclaration.addTemplateParameter(templateParameter.copy(CopyStyle.withLocations)); } - return templateDeclaration; + return newTemplateDeclaration; } return functionDefinition; } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/utils/NodeHelper.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/utils/NodeHelper.java index fac66b73716..3aad6f7f999 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/utils/NodeHelper.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/utils/NodeHelper.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2009 Institute for Software, HSR Hochschule fuer Technik + * Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik * Rapperswil, University of applied sciences and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 @@ -212,11 +212,16 @@ public class NodeHelper { } public static boolean isContainedInTemplateDeclaration(IASTNode node) { - if (node == null) { - return false; - } else if (node instanceof ICPPASTTemplateDeclaration) { - return true; + return findContainedTemplateDecalaration(node) != null; + } + + public static ICPPASTTemplateDeclaration findContainedTemplateDecalaration(IASTNode node) { + while (node != null) { + if (node instanceof ICPPASTTemplateDeclaration) { + return (ICPPASTTemplateDeclaration) node; + } + node = node.getParent(); } - return isContainedInTemplateDeclaration(node.getParent()); + return null; } } From c0b9f79b300f27293e507c7c050afe4befa86928 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Sun, 28 Aug 2011 19:31:15 -0700 Subject: [PATCH 09/29] Bug 356037 - "No break at the end of case" warning for a case statement produced by macro expansion. --- .../OSGI-INF/l10n/bundle.properties | 6 +- .../internal/checkers/CaseBreakChecker.java | 32 +++-- .../checkers/CaseBreakCheckerTest.java | 116 ++++++++---------- 3 files changed, 72 insertions(+), 82 deletions(-) diff --git a/codan/org.eclipse.cdt.codan.checkers/OSGI-INF/l10n/bundle.properties b/codan/org.eclipse.cdt.codan.checkers/OSGI-INF/l10n/bundle.properties index 3d003daed30..c5ebf9beed5 100644 --- a/codan/org.eclipse.cdt.codan.checkers/OSGI-INF/l10n/bundle.properties +++ b/codan/org.eclipse.cdt.codan.checkers/OSGI-INF/l10n/bundle.properties @@ -52,7 +52,7 @@ problem.name.FormatString = Format String Vulnerability checker.name.AssignmentToItself = Assignment to itself problem.messagePattern.AssignmentToItself = Assignment to itself ''{0}'' problem.name.AssignmentToItself = Assignment to itself -problem.description.AssignmentToItself = Finds expression where left and right side of the assignment is the same, i.e. 'var = var' +problem.description.AssignmentToItself = Finds expression where left and right sides of the assignment are the same, i.e. 'var = var' checker.name.ReturnStyle = Return with parenthesis problem.name.ReturnStyle = Return with parenthesis problem.messagePattern.ReturnStyle = Return statement has invalid style. Return value should be surrounded by parenthesis @@ -60,10 +60,10 @@ problem.description.ReturnStyle = Checks for return statements that do no return checker.name.SuspiciousSemicolon = Suspicious semicolon problem.name.SuspiciousSemicolon = Suspicious semicolon problem.messagePattern.SuspiciousSemicolon = Suspicious semicolon -problem.description.SuspiciousSemicolon = A semicolon is used as a null statement in a condition. For example, 'if(expression);' +problem.description.SuspiciousSemicolon = A semicolon is used as a null statement in a condition. For example, 'if (expression);' checker.name.CaseBreak = No break at end of case problem.description.CaseBreak = Looks for "case" statements which end without a "break" statement -problem.messagePattern.CaseBreak = No break at the end of this case +problem.messagePattern.CaseBreak = No break at the end of case binding.checker.name = Problem Binding Checker problem.description.G = Name resolution problem found by the indexer problem.messagePattern.G = Symbol ''{0}'' could not be resolved diff --git a/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/CaseBreakChecker.java b/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/CaseBreakChecker.java index dfd564bbb40..20da627cbc6 100644 --- a/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/CaseBreakChecker.java +++ b/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/CaseBreakChecker.java @@ -1,13 +1,14 @@ /******************************************************************************* - * Copyright (c) 2010,2011 Gil Barash + * Copyright (c) 2010, 2011 Gil Barash * 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: - * Gil Barash - Initial implementation - * Elena laskavaia - Rewrote checker to reduce false positives in complex cases + * Gil Barash - Initial implementation + * Elena laskavaia - Rewrote checker to reduce false positives in complex cases + * Sergey Prigogin (Google) *******************************************************************************/ package org.eclipse.cdt.codan.internal.checkers; @@ -50,8 +51,7 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke } /** - * This visitor looks for "switch" statements and invokes "SwitchVisitor" on - * them. + * This visitor looks for "switch" statements and invokes "SwitchVisitor" on them. */ class SwitchFindingVisitor extends ASTVisitor { SwitchFindingVisitor() { @@ -67,7 +67,7 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke * - "continue" * - "goto" (does not check that the goto actually exists the * switch) - * - "thorw" + * - "throw" * - "exit" */ protected boolean isBreakOrExitStatement(IASTStatement statement) { @@ -83,7 +83,7 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke IASTSwitchStatement switchStmt = (IASTSwitchStatement) statement; IASTStatement body = switchStmt.getBody(); if (body instanceof IASTCompoundStatement) { - // if not it is not really a switch + // If not it is not really a switch IASTStatement[] statements = ((IASTCompoundStatement) body).getStatements(); IASTStatement prevCase = null; for (int i = 0; i < statements.length; i++) { @@ -97,16 +97,16 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke if (isCaseStatement(curr)) { prevCase = curr; } - // next is case or end of switch - means this one is the last + // Next is case or end of switch - means this one is the last if (prevCase != null && (isCaseStatement(next) || next == null)) { - // check that current statement end with break or any other exit statement + // Check that current statement end with break or any other exit statement if (!_checkEmptyCase && isCaseStatement(curr) && next != null) { - continue; // empty case & we don't care + continue; // Empty case and we don't care } if (!_checkLastCase && next == null) { - continue; // last case and we don't care + continue; // Last case and we don't care } - if (isFallThroughStamement(curr)) { + if (!isProducedByMacroExpansion(prevCase) && isFallThroughStamement(curr)) { IASTComment comment = null; if (next != null) { comment = getLeadingComment(next); @@ -139,7 +139,7 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke } /** - * @param nextstatement + * @param body * @return */ public boolean isFallThroughStamement(IASTStatement body) { @@ -171,13 +171,11 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke IASTFileLocation astLocation = astNode.getFileLocation(); int line = astLocation.getEndingLineNumber(); IProblemLocationFactory locFactory = getRuntime().getProblemLocationFactory(); - return locFactory.createProblemLocation(getFile(), -1, - -1, line); + return locFactory.createProblemLocation(getFile(), -1, -1, line); } /** - * Checks if the given statement is a result of macro expansion with a - * possible + * Checks if the given statement is a result of macro expansion with a possible * exception for the trailing semicolon. * * @param statement the statement to check. diff --git a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/CaseBreakCheckerTest.java b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/CaseBreakCheckerTest.java index 083aff6960c..92799531245 100644 --- a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/CaseBreakCheckerTest.java +++ b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/CaseBreakCheckerTest.java @@ -6,7 +6,8 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Gil Barash - Initial implementation + * Gil Barash - Initial implementation + * Sergey Prigogin (Google) *******************************************************************************/ package org.eclipse.cdt.codan.core.internal.checkers; @@ -383,11 +384,11 @@ public class CaseBreakCheckerTest extends CheckerTestCase { } // void foo(void) { - // int a, b; - // switch( a ) { - // case 1: - // b = 2; - // } + // int a, b; + // switch( a ) { + // case 1: + // b = 2; + // } // } public void testLastCaseIgnore() { setLast(false); @@ -474,12 +475,12 @@ public class CaseBreakCheckerTest extends CheckerTestCase { } // void foo(void) { - // int a; - // switch( a ) { - // case 2: + // int a; + // switch( a ) { + // case 2: // break; - // case 1: - // } + // case 1: + // } // } public void testEmptyLastCaseError() { String code = getAboveComment(); @@ -493,31 +494,32 @@ public class CaseBreakCheckerTest extends CheckerTestCase { } // void foo(int a) { - // switch( a ) { - // case 2: + // switch( a ) { + // case 2: // if (a*2<10) - // return; + // return; // else - // break; - // case 1: - // break; - // } + // break; + // case 1: + // break; + // } // } public void testIf() { String code = getAboveComment(); loadCodeAndRun(code); checkNoErrors(); } + // void foo(int a) { - // switch( a ) { - // case 2: + // switch(a) { + // case 2: // if (a*2<10) - // return; + // return; // else - // a++; - // case 1: - // break; - // } + // a++; + // case 1: + // break; + // } // } public void testIfErr() { String code = getAboveComment(); @@ -525,53 +527,43 @@ public class CaseBreakCheckerTest extends CheckerTestCase { checkErrorLine(7); } -// #define DEFINE_BREAK {break;} -// void foo ( int a ) -// { -// switch ( a ) -// { -// case 1: -// DEFINE_BREAK // <-- Warning: No break at the end of this case -// } -// } + // #define DEFINE_BREAK {break;} + // void foo(int a) { + // switch (a) { + // case 1: + // DEFINE_BREAK // No warning here + // } + // } public void testBreakInBraces() { String code = getAboveComment(); loadCodeAndRun(code); checkNoErrors(); } - -// #define MY_MACRO(i) \ -// case i: \ -// { \ -// break; \ -// } -// -// void f() -// { -// int x; -// switch (x) -// { -// MY_MACRO(1) // WARNING HERE -// } -// } - + // #define MY_MACRO(i) \ + // case i: { \ + // } + // + // void f() { + // int x; + // switch (x) { + // MY_MACRO(1) // No warning here + // } + // } public void testInMacro() { String code = getAboveComment(); loadCodeAndRun(code); checkNoErrors(); } - //void foo() - //{ - //switch(0) - //default: - //{ - //} - //} - public void testEmptyCompoundStatement() { - String code = getAboveComment(); - loadCodeAndRun(code); - checkErrorLine(6); - } + // void foo() { + // switch (0) + // default: { + // } + // } + public void testEmptyCompoundStatement() { + String code = getAboveComment(); + loadCodeAndRun(code); + checkErrorLine(4); + } } From 17f96f9eb3a4f54696e76b19bfb4cbe9ed0fe8fb Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Sun, 28 Aug 2011 20:35:50 -0700 Subject: [PATCH 10/29] Bug 356040 - Invalid "Unused declaration of variable" warning. --- .../UnusedSymbolInFileScopeChecker.java | 31 +++++++++++-------- .../UnusedSymbolInFileScopeCheckerTest.java | 15 ++++++--- 2 files changed, 29 insertions(+), 17 deletions(-) diff --git a/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/UnusedSymbolInFileScopeChecker.java b/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/UnusedSymbolInFileScopeChecker.java index 8ef51bdcf2b..8341c1a9a9d 100644 --- a/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/UnusedSymbolInFileScopeChecker.java +++ b/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/UnusedSymbolInFileScopeChecker.java @@ -6,7 +6,8 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Andrew Gvozdev - initial API and implementation + * Andrew Gvozdev - initial API and implementation + * Sergey Prigogin (Google) *******************************************************************************/ package org.eclipse.cdt.codan.internal.checkers; @@ -90,11 +91,11 @@ public class UnusedSymbolInFileScopeChecker extends AbstractIndexAstChecker { } private boolean isAnyCandidate() { - return externFunctionDeclarations.size() > 0 || - staticFunctionDeclarations.size() > 0 || - staticFunctionDefinitions.size() > 0 || - externVariableDeclarations.size() > 0 || - staticVariableDeclarations.size() > 0; + return !externFunctionDeclarations.isEmpty() || + !staticFunctionDeclarations.isEmpty() || + !staticFunctionDefinitions.isEmpty() || + !externVariableDeclarations.isEmpty() || + !staticVariableDeclarations.isEmpty(); } public void processAst(IASTTranslationUnit ast) { @@ -138,16 +139,15 @@ public class UnusedSymbolInFileScopeChecker extends AbstractIndexAstChecker { } } else if (binding instanceof IVariable) { if (storageClass == IASTDeclSpecifier.sc_extern) { - IASTInitializer initializer = decl.getInitializer(); - // initializer makes "extern" declaration to become definition do not count these - if (initializer==null) { + // Initializer makes "extern" declaration to become definition do not count these + if (decl.getInitializer() == null) { externVariableDeclarations.put(binding, decl); } } else if (storageClass == IASTDeclSpecifier.sc_static) { IType type = ((IVariable) binding).getType(); - // account for class constructor and avoid possible false positive + // Account for class constructor and avoid possible false positive if (!(type instanceof ICPPClassType) && !(type instanceof IProblemType)) { - // check if initializer disqualifies it + // Check if initializer disqualifies it IASTInitializer initializer = decl.getInitializer(); IASTInitializerClause clause = null; if (initializer instanceof IASTEqualsInitializer) { @@ -156,7 +156,7 @@ public class UnusedSymbolInFileScopeChecker extends AbstractIndexAstChecker { } else if (initializer instanceof ICPPASTConstructorInitializer) { ICPPASTConstructorInitializer constructorInitializer = (ICPPASTConstructorInitializer) initializer; IASTInitializerClause[] args = constructorInitializer.getArguments(); - if (args.length==1) + if (args.length == 1) clause = args[0]; } if (clause instanceof IASTLiteralExpression) { @@ -232,7 +232,12 @@ public class UnusedSymbolInFileScopeChecker extends AbstractIndexAstChecker { staticFunctionDefinitions.remove(binding); } - if (!(parentNode instanceof IASTDeclarator)) { + if (parentNode instanceof IASTDeclarator) { + // Initializer makes "extern" declaration to become definition. + if (((IASTDeclarator) parentNode).getInitializer() != null) { + externVariableDeclarations.remove(binding); + } + } else { externVariableDeclarations.remove(binding); staticVariableDeclarations.remove(binding); } diff --git a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/UnusedSymbolInFileScopeCheckerTest.java b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/UnusedSymbolInFileScopeCheckerTest.java index 7206e8b7852..4cd1d7964fa 100644 --- a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/UnusedSymbolInFileScopeCheckerTest.java +++ b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/UnusedSymbolInFileScopeCheckerTest.java @@ -6,7 +6,8 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Andrew Gvozdev - initial API and implementation + * Andrew Gvozdev - initial API and implementation + * Sergey Prigogin (Google) *******************************************************************************/ package org.eclipse.cdt.codan.core.internal.checkers; @@ -17,7 +18,6 @@ import org.eclipse.cdt.codan.internal.checkers.UnusedSymbolInFileScopeChecker; /** * Test for {@see UnusedSymbolInFileScopeChecker} class - * */ public class UnusedSymbolInFileScopeCheckerTest extends CheckerTestCase { @Override @@ -222,8 +222,15 @@ public class UnusedSymbolInFileScopeCheckerTest extends CheckerTestCase { checkNoErrors(); } - // extern int test_var=0; // not quite legal but some compilers allow that - public void testExternVariable_Definition() throws IOException { + // extern const int test_var=0; // not quite legal but some compilers allow that + public void testExternVariable_Definition1() throws IOException { + loadCodeAndRun(getAboveComment()); + checkNoErrors(); + } + + // extern const int test_var; + // const int test_var = 0; + public void testExternVariable_Definition2() throws IOException { loadCodeAndRun(getAboveComment()); checkNoErrors(); } From d88c1111f7ce7264779d8d338a30dde430ddc277 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Sun, 28 Aug 2011 20:52:37 -0700 Subject: [PATCH 11/29] Cosmetics. --- .../dom/parser/c/CASTSimpleDeclaration.java | 64 +++++++++---------- 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTSimpleDeclaration.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTSimpleDeclaration.java index d2858934b81..8a28daf6a53 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTSimpleDeclaration.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTSimpleDeclaration.java @@ -6,9 +6,9 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * John Camelon (IBM Rational Software) - Initial API and implementation - * Markus Schorn (Wind River Systems) - * Yuan Zhang / Beth Tibbitts (IBM Research) + * John Camelon (IBM Rational Software) - Initial API and implementation + * Markus Schorn (Wind River Systems) + * Yuan Zhang / Beth Tibbitts (IBM Research) *******************************************************************************/ package org.eclipse.cdt.internal.core.dom.parser.c; @@ -25,7 +25,9 @@ import org.eclipse.cdt.internal.core.dom.parser.IASTAmbiguityParent; * Models a simple declaration. */ public class CASTSimpleDeclaration extends ASTNode implements IASTSimpleDeclaration, IASTAmbiguityParent { - + private IASTDeclarator[] declarators; + private int declaratorsPos = -1; + private IASTDeclSpecifier declSpecifier; public CASTSimpleDeclaration() { } @@ -42,7 +44,7 @@ public class CASTSimpleDeclaration extends ASTNode implements IASTSimpleDeclarat CASTSimpleDeclaration copy = new CASTSimpleDeclaration(); copy.setDeclSpecifier(declSpecifier == null ? null : declSpecifier.copy(style)); - for(IASTDeclarator declarator : getDeclarators()) + for (IASTDeclarator declarator : getDeclarators()) copy.addDeclarator(declarator == null ? null : declarator.copy(style)); copy.setOffsetAndLength(this); @@ -57,26 +59,21 @@ public class CASTSimpleDeclaration extends ASTNode implements IASTSimpleDeclarat } public IASTDeclarator[] getDeclarators() { - if( declarators == null ) return IASTDeclarator.EMPTY_DECLARATOR_ARRAY; - declarators = (IASTDeclarator[]) ArrayUtil.removeNullsAfter( IASTDeclarator.class, declarators, declaratorsPos ); + if (declarators == null) + return IASTDeclarator.EMPTY_DECLARATOR_ARRAY; + declarators = (IASTDeclarator[]) ArrayUtil.removeNullsAfter(IASTDeclarator.class, declarators, declaratorsPos); return declarators; } - public void addDeclarator( IASTDeclarator d ) { + public void addDeclarator(IASTDeclarator d) { assertNotFrozen(); if (d != null) { d.setParent(this); d.setPropertyInParent(DECLARATOR); - declarators = (IASTDeclarator[]) ArrayUtil.append( IASTDeclarator.class, declarators, ++declaratorsPos, d ); + declarators = (IASTDeclarator[]) ArrayUtil.append(IASTDeclarator.class, declarators, ++declaratorsPos, d); } } - - private IASTDeclarator [] declarators = null; - private int declaratorsPos=-1; - private IASTDeclSpecifier declSpecifier; - - public void setDeclSpecifier(IASTDeclSpecifier declSpecifier) { assertNotFrozen(); this.declSpecifier = declSpecifier; @@ -87,25 +84,28 @@ public class CASTSimpleDeclaration extends ASTNode implements IASTSimpleDeclarat } @Override - public boolean accept( ASTVisitor action ){ - if( action.shouldVisitDeclarations ){ - switch( action.visit( this ) ){ - case ASTVisitor.PROCESS_ABORT : return false; - case ASTVisitor.PROCESS_SKIP : return true; - default : break; + public boolean accept(ASTVisitor action) { + if (action.shouldVisitDeclarations) { + switch (action.visit(this)) { + case ASTVisitor.PROCESS_ABORT: return false; + case ASTVisitor.PROCESS_SKIP: return true; + default: break; } } - if( declSpecifier != null ) if( !declSpecifier.accept( action ) ) return false; - IASTDeclarator [] dtors = getDeclarators(); - for( int i = 0; i < dtors.length; i++ ) - if( !dtors[i].accept( action ) ) return false; + if (declSpecifier != null && !declSpecifier.accept(action)) + return false; + IASTDeclarator[] dtors = getDeclarators(); + for (int i = 0; i < dtors.length; i++) { + if (!dtors[i].accept(action)) + return false; + } - if( action.shouldVisitDeclarations ){ - switch( action.leave( this ) ){ - case ASTVisitor.PROCESS_ABORT : return false; - case ASTVisitor.PROCESS_SKIP : return true; - default : break; + if (action.shouldVisitDeclarations) { + switch (action.leave(this)) { + case ASTVisitor.PROCESS_ABORT: return false; + case ASTVisitor.PROCESS_SKIP: return true; + default: break; } } return true; @@ -118,8 +118,8 @@ public class CASTSimpleDeclaration extends ASTNode implements IASTSimpleDeclarat declSpecifier= (IASTDeclSpecifier) other; } else { IASTDeclarator[] declarators = getDeclarators(); - for(int i = 0; i < declarators.length; i++) { - if(declarators[i] == child) { + for (int i = 0; i < declarators.length; i++) { + if (declarators[i] == child) { declarators[i] = (IASTDeclarator)other; other.setParent(child.getParent()); other.setPropertyInParent(child.getPropertyInParent()); From a8522bf2a17e8ed808f938406f5ba6f8b11dd151 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Mon, 29 Aug 2011 17:03:55 -0700 Subject: [PATCH 12/29] Added ability to suppress unused variable and function warnings for code produced by macro expansion. --- .../checkers/CheckersMessages.properties | 10 +-- .../checkers/StatementHasNoEffectChecker.java | 4 +- .../UnusedSymbolInFileScopeChecker.java | 80 +++++++++++-------- .../cdt/codan/core/cxx/CxxAstUtils.java | 2 +- 4 files changed, 55 insertions(+), 41 deletions(-) diff --git a/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/CheckersMessages.properties b/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/CheckersMessages.properties index e7f79019b3f..bc5a2fe5ce8 100644 --- a/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/CheckersMessages.properties +++ b/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/CheckersMessages.properties @@ -9,8 +9,8 @@ # Alena Laskavaia - initial API and implementation ############################################################################### CaseBreakChecker_DefaultNoBreakCommentDescription=Comment text to suppress the problem: -CaseBreakChecker_EmptyCaseDescription=Check also empty case statement (except if last) -CaseBreakChecker_LastCaseDescription=Check also the last case statement +CaseBreakChecker_EmptyCaseDescription=Check also empty 'case' statement (except if last) +CaseBreakChecker_LastCaseDescription=Check also the last 'case' statement ClassMembersInitializationChecker_SkipConstructorsWithFCalls=Skip constructors with initialization function calls CatchByReference_ReportForUnknownType=Report a problem if type cannot be resolved NamingConventionFunctionChecker_LabelNamePattern=Name Pattern @@ -18,9 +18,9 @@ NamingConventionFunctionChecker_ParameterMethods=Also check C++ method names ReturnChecker_Param0=Also check functions with implicit return value GenericParameter_ParameterExceptions=Exceptions (value of the problem argument) GenericParameter_ParameterExceptionsItem=Value of the argument -StatementHasNoEffectChecker_ParameterMacro=Report problem in statements that comes from macro expansion -SuggestedParenthesisChecker_SuggestParanthesesAroundNot=Suggest parenthesis around not operator -SuspiciousSemicolonChecker_ParamAfterElse=Report an error if semicolon is right after else statement +StatementHasNoEffectChecker_ParameterMacro=Report problem in statements that come from macro expansion +SuggestedParenthesisChecker_SuggestParanthesesAroundNot=Suggest parenthesis around 'not' operator +SuspiciousSemicolonChecker_ParamAfterElse=Report an error if semicolon is right after 'else' statement SuspiciousSemicolonChecker_ParamElse=Do not report an error after 'if' when 'else' exists ProblemBindingChecker_Candidates=Candidates are: diff --git a/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/StatementHasNoEffectChecker.java b/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/StatementHasNoEffectChecker.java index ed023fb8870..f1d39829241 100644 --- a/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/StatementHasNoEffectChecker.java +++ b/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/StatementHasNoEffectChecker.java @@ -57,9 +57,7 @@ public class StatementHasNoEffectChecker extends AbstractIndexAstChecker { if (stmt instanceof IASTExpressionStatement) { IASTExpression expression = ((IASTExpressionStatement) stmt).getExpression(); if (hasNoEffect(expression)) { - boolean inMacro = CxxAstUtils.getInstance().isInMacro(expression); - boolean shouldReportInMacro = shouldReportInMacro(); - if (inMacro && !shouldReportInMacro) + if (!shouldReportInMacro() && CxxAstUtils.isInMacro(expression)) return PROCESS_SKIP; String arg = expression.getRawSignature(); if (!isFilteredArg(arg)) diff --git a/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/UnusedSymbolInFileScopeChecker.java b/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/UnusedSymbolInFileScopeChecker.java index 8341c1a9a9d..54390de9ece 100644 --- a/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/UnusedSymbolInFileScopeChecker.java +++ b/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/UnusedSymbolInFileScopeChecker.java @@ -19,6 +19,7 @@ import java.util.Map; import java.util.Map.Entry; import org.eclipse.cdt.codan.checkers.CodanCheckersActivator; +import org.eclipse.cdt.codan.core.cxx.CxxAstUtils; import org.eclipse.cdt.codan.core.cxx.model.AbstractIndexAstChecker; import org.eclipse.cdt.codan.core.model.IProblem; import org.eclipse.cdt.codan.core.model.IProblemWorkingCopy; @@ -55,6 +56,7 @@ public class UnusedSymbolInFileScopeChecker extends AbstractIndexAstChecker { public static final String ER_UNUSED_VARIABLE_DECLARATION_ID = "org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem"; //$NON-NLS-1$ public static final String ER_UNUSED_FUNCTION_DECLARATION_ID = "org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem"; //$NON-NLS-1$ public static final String ER_UNUSED_STATIC_FUNCTION_ID = "org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem"; //$NON-NLS-1$ + public static final String PARAM_MACRO_ID = "macro"; //$NON-NLS-1$ public static final String PARAM_EXCEPT_ARG_LIST = "exceptions"; //$NON-NLS-1$ private Map externFunctionDeclarations = new HashMap(); @@ -72,6 +74,7 @@ public class UnusedSymbolInFileScopeChecker extends AbstractIndexAstChecker { @Override public void initPreferences(IProblemWorkingCopy problem) { super.initPreferences(problem); + addPreference(problem, PARAM_MACRO_ID, CheckersMessages.StatementHasNoEffectChecker_ParameterMacro, Boolean.TRUE); if (problem.getId().equals(ER_UNUSED_VARIABLE_DECLARATION_ID)) { unusedVariableProblem = problem; ListProblemPreference pref = addListPreference(problem, PARAM_EXCEPT_ARG_LIST, @@ -132,41 +135,51 @@ public class UnusedSymbolInFileScopeChecker extends AbstractIndexAstChecker { int storageClass = simpleDeclaration.getDeclSpecifier().getStorageClass(); if (binding instanceof IFunction) { - if (storageClass == IASTDeclSpecifier.sc_extern || storageClass == IASTDeclSpecifier.sc_unspecified) { - externFunctionDeclarations.put(binding, decl); - } else if (storageClass == IASTDeclSpecifier.sc_static) { - staticFunctionDeclarations.put(binding, decl); - } - } else if (binding instanceof IVariable) { - if (storageClass == IASTDeclSpecifier.sc_extern) { - // Initializer makes "extern" declaration to become definition do not count these - if (decl.getInitializer() == null) { - externVariableDeclarations.put(binding, decl); + if (storageClass == IASTDeclSpecifier.sc_extern || + storageClass == IASTDeclSpecifier.sc_unspecified) { + if (shouldReportInMacro(ER_UNUSED_FUNCTION_DECLARATION_ID) || + !CxxAstUtils.isInMacro(astName)) { + externFunctionDeclarations.put(binding, decl); } } else if (storageClass == IASTDeclSpecifier.sc_static) { - IType type = ((IVariable) binding).getType(); - // Account for class constructor and avoid possible false positive - if (!(type instanceof ICPPClassType) && !(type instanceof IProblemType)) { - // Check if initializer disqualifies it - IASTInitializer initializer = decl.getInitializer(); - IASTInitializerClause clause = null; - if (initializer instanceof IASTEqualsInitializer) { - IASTEqualsInitializer equalsInitializer = (IASTEqualsInitializer) initializer; - clause = equalsInitializer.getInitializerClause(); - } else if (initializer instanceof ICPPASTConstructorInitializer) { - ICPPASTConstructorInitializer constructorInitializer = (ICPPASTConstructorInitializer) initializer; - IASTInitializerClause[] args = constructorInitializer.getArguments(); - if (args.length == 1) - clause = args[0]; + if (shouldReportInMacro(ER_UNUSED_STATIC_FUNCTION_ID) || + !CxxAstUtils.isInMacro(astName)) { + staticFunctionDeclarations.put(binding, decl); + } + } + } else if (binding instanceof IVariable) { + if (shouldReportInMacro(ER_UNUSED_VARIABLE_DECLARATION_ID) || + !CxxAstUtils.isInMacro(astName)) { + if (storageClass == IASTDeclSpecifier.sc_extern) { + // Initializer makes "extern" declaration to become definition do not count these + if (decl.getInitializer() == null) { + externVariableDeclarations.put(binding, decl); } - if (clause instanceof IASTLiteralExpression) { - IASTLiteralExpression literalExpression = (IASTLiteralExpression) clause; - String literal = literalExpression.toString(); - if (isFilteredOut(literal, unusedVariableProblem, PARAM_EXCEPT_ARG_LIST)) - continue; + } else if (storageClass == IASTDeclSpecifier.sc_static) { + IType type = ((IVariable) binding).getType(); + // Account for class constructor and avoid possible false positive + if (!(type instanceof ICPPClassType) && !(type instanceof IProblemType)) { + // Check if initializer disqualifies it + IASTInitializer initializer = decl.getInitializer(); + IASTInitializerClause clause = null; + if (initializer instanceof IASTEqualsInitializer) { + IASTEqualsInitializer equalsInitializer = (IASTEqualsInitializer) initializer; + clause = equalsInitializer.getInitializerClause(); + } else if (initializer instanceof ICPPASTConstructorInitializer) { + ICPPASTConstructorInitializer constructorInitializer = (ICPPASTConstructorInitializer) initializer; + IASTInitializerClause[] args = constructorInitializer.getArguments(); + if (args.length == 1) + clause = args[0]; + } + if (clause instanceof IASTLiteralExpression) { + IASTLiteralExpression literalExpression = (IASTLiteralExpression) clause; + String literal = literalExpression.toString(); + if (isFilteredOut(literal, unusedVariableProblem, PARAM_EXCEPT_ARG_LIST)) + continue; + } + + staticVariableDeclarations.put(binding, decl); } - - staticVariableDeclarations.put(binding, decl); } } } @@ -315,7 +328,7 @@ public class UnusedSymbolInFileScopeChecker extends AbstractIndexAstChecker { clearCandidates(); // release memory } - public boolean isFilteredOut(String arg, IProblem problem, String exceptionListParamId) { + private boolean isFilteredOut(String arg, IProblem problem, String exceptionListParamId) { Object[] arr = (Object[]) getPreference(problem, exceptionListParamId); for (int i = 0; i < arr.length; i++) { String str = (String) arr[i]; @@ -325,4 +338,7 @@ public class UnusedSymbolInFileScopeChecker extends AbstractIndexAstChecker { return false; } + private boolean shouldReportInMacro(String errorId) { + return (Boolean) getPreference(getProblemById(errorId, getFile()), PARAM_MACRO_ID); + } } diff --git a/codan/org.eclipse.cdt.codan.core.cxx/src/org/eclipse/cdt/codan/core/cxx/CxxAstUtils.java b/codan/org.eclipse.cdt.codan.core.cxx/src/org/eclipse/cdt/codan/core/cxx/CxxAstUtils.java index b297756c364..e7214b3016d 100644 --- a/codan/org.eclipse.cdt.codan.core.cxx/src/org/eclipse/cdt/codan/core/cxx/CxxAstUtils.java +++ b/codan/org.eclipse.cdt.codan.core.cxx/src/org/eclipse/cdt/codan/core/cxx/CxxAstUtils.java @@ -121,7 +121,7 @@ public final class CxxAstUtils { return (IType) typeName; } - public boolean isInMacro(IASTNode node) { + public static boolean isInMacro(IASTNode node) { IASTNodeSelector nodeSelector = node.getTranslationUnit().getNodeSelector(node.getTranslationUnit().getFilePath()); IASTFileLocation fileLocation = node.getFileLocation(); IASTPreprocessorMacroExpansion macro = nodeSelector.findEnclosingMacroExpansion(fileLocation.getNodeOffset(), From 97d0869a9a9c5f10a9e52dcdf7dfd5b2b115a023 Mon Sep 17 00:00:00 2001 From: Eugene Ostroukhov Date: Tue, 30 Aug 2011 15:20:25 -0400 Subject: [PATCH 13/29] Bug 352888: Add two new "done" methods to RequestMonitor and DataRequestMonitor --- .../cdt/tests/dsf/gdb/framework/SyncUtil.java | 5 ++-- dsf/org.eclipse.cdt.dsf/META-INF/MANIFEST.MF | 2 +- .../dsf/concurrent/DataRequestMonitor.java | 23 +++++++++++++++ .../cdt/dsf/concurrent/RequestMonitor.java | 29 ++++++++++++++++--- 4 files changed, 51 insertions(+), 8 deletions(-) diff --git a/dsf-gdb/org.eclipse.cdt.tests.dsf.gdb/src/org/eclipse/cdt/tests/dsf/gdb/framework/SyncUtil.java b/dsf-gdb/org.eclipse.cdt.tests.dsf.gdb/src/org/eclipse/cdt/tests/dsf/gdb/framework/SyncUtil.java index 2a7bfc09791..6cba61a4162 100644 --- a/dsf-gdb/org.eclipse.cdt.tests.dsf.gdb/src/org/eclipse/cdt/tests/dsf/gdb/framework/SyncUtil.java +++ b/dsf-gdb/org.eclipse.cdt.tests.dsf.gdb/src/org/eclipse/cdt/tests/dsf/gdb/framework/SyncUtil.java @@ -566,11 +566,10 @@ public class SyncUtil { Assert.assertEquals("unexpected number of processes", 1, contexts.length); IDMContext context = contexts[0]; Assert.assertNotNull("unexpected process context type ", context); - rm.setData((IContainerDMContext)context); + rm.done((IContainerDMContext)context); } else { - rm.setStatus(getStatus()); + rm.done(getStatus()); } - rm.done(); } }); } diff --git a/dsf/org.eclipse.cdt.dsf/META-INF/MANIFEST.MF b/dsf/org.eclipse.cdt.dsf/META-INF/MANIFEST.MF index c9121699acd..6710e232d69 100644 --- a/dsf/org.eclipse.cdt.dsf/META-INF/MANIFEST.MF +++ b/dsf/org.eclipse.cdt.dsf/META-INF/MANIFEST.MF @@ -3,7 +3,7 @@ Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-Vendor: %providerName Bundle-SymbolicName: org.eclipse.cdt.dsf;singleton:=true -Bundle-Version: 2.2.0.qualifier +Bundle-Version: 2.3.0.qualifier Bundle-Activator: org.eclipse.cdt.dsf.internal.DsfPlugin Bundle-Localization: plugin Require-Bundle: org.eclipse.core.runtime, diff --git a/dsf/org.eclipse.cdt.dsf/src/org/eclipse/cdt/dsf/concurrent/DataRequestMonitor.java b/dsf/org.eclipse.cdt.dsf/src/org/eclipse/cdt/dsf/concurrent/DataRequestMonitor.java index b185feddbc0..38f68389e6c 100644 --- a/dsf/org.eclipse.cdt.dsf/src/org/eclipse/cdt/dsf/concurrent/DataRequestMonitor.java +++ b/dsf/org.eclipse.cdt.dsf/src/org/eclipse/cdt/dsf/concurrent/DataRequestMonitor.java @@ -7,6 +7,7 @@ * * Contributors: * Wind River Systems - initial API and implementation + * Eugene Ostroukhov (NVIDIA) - new done(V) method *******************************************************************************/ package org.eclipse.cdt.dsf.concurrent; @@ -33,6 +34,8 @@ public class DataRequestMonitor extends RequestMonitor { * Sets the data object to specified value. To be called by the * asynchronous method implementor. * @param data Data value to set. + * + * @see #done(Object) */ public synchronized void setData(V data) { fData = data; } @@ -41,6 +44,26 @@ public class DataRequestMonitor extends RequestMonitor { */ public synchronized V getData() { return fData; } + /** + * Completes the monitor setting data object to specified value. To be + * called by asynchronous method implementor. + * + *

+ * Note: Only one done method should be called and only once, + * for every request issued. Even if the request was canceled. + *

+ * + * @param data Data value to set + * @see #setData(Object) + * @see #done() + * @see #done(org.eclipse.core.runtime.IStatus) + * @since 2.3 + */ + public synchronized void done(V data) { + setData(data); + done(); + } + @Override public String toString() { if (getData() != null) { diff --git a/dsf/org.eclipse.cdt.dsf/src/org/eclipse/cdt/dsf/concurrent/RequestMonitor.java b/dsf/org.eclipse.cdt.dsf/src/org/eclipse/cdt/dsf/concurrent/RequestMonitor.java index 09f876934bf..7bc6c32322b 100644 --- a/dsf/org.eclipse.cdt.dsf/src/org/eclipse/cdt/dsf/concurrent/RequestMonitor.java +++ b/dsf/org.eclipse.cdt.dsf/src/org/eclipse/cdt/dsf/concurrent/RequestMonitor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2010 Wind River Systems and others. + * Copyright (c) 2006, 2011 Wind River Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -7,6 +7,7 @@ * * Contributors: * Wind River Systems - initial API and implementation + * Eugene Ostroukhov (NVIDIA) - new done(IStatus) method *******************************************************************************/ package org.eclipse.cdt.dsf.concurrent; @@ -165,7 +166,9 @@ public class RequestMonitor extends DsfExecutable { /** * Sets the status of the result of the request. If status is OK, this - * method does not need to be called. + * method does not need to be called. + * + * @see #done(IStatus) */ public synchronized void setStatus(IStatus status) { assert isCanceled() || status.getSeverity() != IStatus.CANCEL; @@ -270,8 +273,8 @@ public class RequestMonitor extends DsfExecutable { * monitor submits a runnable to the DSF Executor to call the * handle... methods. *

- * Note: This method should be called once and only once, for every request - * issued. Even if the request was canceled. + * Note: Only one done method should be called and only once, + * for every request issued. Even if the request was canceled. *

*/ public synchronized void done() { @@ -306,6 +309,24 @@ public class RequestMonitor extends DsfExecutable { handleRejectedExecutionException(); } } + + /** + * Sets status and marks request monitor as completed. + * + *

+ * Note: Only one done method should be called and only once, + * for every request issued. Even if the request was canceled. + *

+ * + * @param status Request processing status + * @see #done() + * @see #setStatus(IStatus) + * @since 2.3 + */ + public synchronized void done(IStatus status) { + setStatus(status); + done(); + } @Override public String toString() { From fb7d64098f16af1f10c4699807783bd4784d7037 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Tue, 30 Aug 2011 14:44:22 -0700 Subject: [PATCH 14/29] Bug 356239 - ClassCastException in ClassTypeHelper.getOwnMethods. --- .../AbstractClassInstantiationChecker.java | 29 ++++++++++--------- .../core/dom/parser/cpp/ClassTypeHelper.java | 5 ++-- 2 files changed, 19 insertions(+), 15 deletions(-) diff --git a/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/AbstractClassInstantiationChecker.java b/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/AbstractClassInstantiationChecker.java index 41714eb89bc..8b5e66ceb3d 100644 --- a/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/AbstractClassInstantiationChecker.java +++ b/codan/org.eclipse.cdt.codan.checkers/src/org/eclipse/cdt/codan/internal/checkers/AbstractClassInstantiationChecker.java @@ -7,6 +7,7 @@ * * Contributors: * Anton Gorenkov - initial implementation + * Sergey Prigogin (Google) *******************************************************************************/ package org.eclipse.cdt.codan.internal.checkers; @@ -30,6 +31,7 @@ import org.eclipse.cdt.core.dom.ast.IASTParameterDeclaration; import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; import org.eclipse.cdt.core.dom.ast.IBinding; +import org.eclipse.cdt.core.dom.ast.IProblemBinding; import org.eclipse.cdt.core.dom.ast.IType; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTFunctionCallExpression; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNamedTypeSpecifier; @@ -179,22 +181,23 @@ public class AbstractClassInstantiationChecker extends AbstractIndexAstChecker { } /** - * Checks whether specified type (class or typedef to the class) is abstract class. - * If it is - reports violations on each pure virtual method + * Checks whether specified type (class or typedef to the class) is an abstract class. + * If it is, reports violations on each pure virtual method */ private void reportProblemsIfAbstract(IType typeToCheck, IASTNode problemNode ) { IType unwindedType = CxxAstUtils.getInstance().unwindTypedef(typeToCheck); - if (unwindedType instanceof ICPPClassType) { - ICPPClassType classType = (ICPPClassType) unwindedType; - ICPPMethod[] pureVirtualMethods = pureVirtualMethodsCache.get(classType); - if (pureVirtualMethods == null) { - pureVirtualMethods = ClassTypeHelper.getPureVirtualMethods(classType); - pureVirtualMethodsCache.put(classType, pureVirtualMethods); - } - - for (ICPPMethod method : pureVirtualMethods) { - reportProblem(ER_ID, problemNode, resolveName(classType), resolveName(method)); - } + if (!(unwindedType instanceof ICPPClassType) || unwindedType instanceof IProblemBinding) { + return; + } + ICPPClassType classType = (ICPPClassType) unwindedType; + ICPPMethod[] pureVirtualMethods = pureVirtualMethodsCache.get(classType); + if (pureVirtualMethods == null) { + pureVirtualMethods = ClassTypeHelper.getPureVirtualMethods(classType); + pureVirtualMethodsCache.put(classType, pureVirtualMethods); + } + + for (ICPPMethod method : pureVirtualMethods) { + reportProblem(ER_ID, problemNode, resolveName(classType), resolveName(method)); } } } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/ClassTypeHelper.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/ClassTypeHelper.java index 9525265030b..2d7f054aa5a 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/ClassTypeHelper.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/ClassTypeHelper.java @@ -310,12 +310,13 @@ public class ClassTypeHelper { /** * Returns methods either declared by the given class or generated by the compiler. Does not * include methods declared in base classes. - * @param classType - * @return */ private static ObjectSet getOwnMethods(ICPPClassType classType) { ObjectSet set= new ObjectSet(4); set.addAll(classType.getDeclaredMethods()); + if (classType instanceof IProblemBinding) { + return set; + } ICPPClassScope scope= (ICPPClassScope) classType.getCompositeScope(); set.addAll(scope.getImplicitMethods()); return set; From a87ea0e3ab32a7ca56886dab7a6ec84500c89795 Mon Sep 17 00:00:00 2001 From: Randy Rohrbach Date: Wed, 31 Aug 2011 13:35:55 -0400 Subject: [PATCH 15/29] Bug 356346 - Do not reload expressions if the debug context is the same as before. --- .../memorybrowser/GoToAddressBarWidget.java | 29 ++++++++++--------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/memory/org.eclipse.cdt.debug.ui.memory.memorybrowser/src/org/eclipse/cdt/debug/ui/memory/memorybrowser/GoToAddressBarWidget.java b/memory/org.eclipse.cdt.debug.ui.memory.memorybrowser/src/org/eclipse/cdt/debug/ui/memory/memorybrowser/GoToAddressBarWidget.java index fdc8c5ccfe6..5238a57dce2 100644 --- a/memory/org.eclipse.cdt.debug.ui.memory.memorybrowser/src/org/eclipse/cdt/debug/ui/memory/memorybrowser/GoToAddressBarWidget.java +++ b/memory/org.eclipse.cdt.debug.ui.memory.memorybrowser/src/org/eclipse/cdt/debug/ui/memory/memorybrowser/GoToAddressBarWidget.java @@ -62,6 +62,7 @@ public class GoToAddressBarWidget { private Button fOKButton; private Button fOKNewTabButton; private Composite fComposite; + private Object fCurrentDebugContext; protected static int ID_GO_NEW_TAB = 2000; @@ -267,20 +268,22 @@ public class GoToAddressBarWidget { */ public void loadSavedExpressions(Object context, String memorySpace) { - - try { - String[] expressions = getSavedExpressions(context, memorySpace); - String currentExpression = fExpression.getText(); - fExpression.removeAll(); - for (String expression : expressions) { - fExpression.add(expression); + if ( context != null && ! context.equals( fCurrentDebugContext ) ) { + try { + String[] expressions = getSavedExpressions(context, memorySpace); + String currentExpression = fExpression.getText(); + fExpression.removeAll(); + for (String expression : expressions) { + fExpression.add(expression); + } + if (currentExpression != null) { + fExpression.setText(currentExpression); + } + fCurrentDebugContext = context; + } catch (CoreException e) { + // Unexpected snag dealing with launch configuration + MemoryBrowserPlugin.log(e); } - if (currentExpression != null) { - fExpression.setText(currentExpression); - } - } catch (CoreException e) { - // Unexpected snag dealing with launch configuration - MemoryBrowserPlugin.log(e); } } From 98c81cf0fb7757780ea10161faa5b384792eea3e Mon Sep 17 00:00:00 2001 From: John Dallaway Date: Thu, 1 Sep 2011 08:09:13 -0400 Subject: [PATCH 16/29] Bug 349736: DSF-GDB breakpoint deleted when modifying thread filter --- jtag/org.eclipse.cdt.debug.gdbjtag.core/META-INF/MANIFEST.MF | 2 +- .../debug/gdbjtag/core/GDBJtagDSFFinalLaunchSequence.java | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/jtag/org.eclipse.cdt.debug.gdbjtag.core/META-INF/MANIFEST.MF b/jtag/org.eclipse.cdt.debug.gdbjtag.core/META-INF/MANIFEST.MF index 6f1e9c26e6f..4d8333e20e1 100644 --- a/jtag/org.eclipse.cdt.debug.gdbjtag.core/META-INF/MANIFEST.MF +++ b/jtag/org.eclipse.cdt.debug.gdbjtag.core/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-SymbolicName: org.eclipse.cdt.debug.gdbjtag.core;singleton:=true -Bundle-Version: 8.0.0.qualifier +Bundle-Version: 8.0.1.qualifier Bundle-Activator: org.eclipse.cdt.debug.gdbjtag.core.Activator Bundle-Localization: plugin Require-Bundle: org.eclipse.core.runtime, diff --git a/jtag/org.eclipse.cdt.debug.gdbjtag.core/src/org/eclipse/cdt/debug/gdbjtag/core/GDBJtagDSFFinalLaunchSequence.java b/jtag/org.eclipse.cdt.debug.gdbjtag.core/src/org/eclipse/cdt/debug/gdbjtag/core/GDBJtagDSFFinalLaunchSequence.java index 3cca427cf38..71ee49e2e83 100644 --- a/jtag/org.eclipse.cdt.debug.gdbjtag.core/src/org/eclipse/cdt/debug/gdbjtag/core/GDBJtagDSFFinalLaunchSequence.java +++ b/jtag/org.eclipse.cdt.debug.gdbjtag.core/src/org/eclipse/cdt/debug/gdbjtag/core/GDBJtagDSFFinalLaunchSequence.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007 - 2010 QNX Software Systems and others. + * Copyright (c) 2007 - 2011 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -11,6 +11,7 @@ * Sage Electronic Engineering, LLC - bug 305943 * - API generalization to become transport-independent (allow * connections via serial ports and pipes). + * John Dallaway - Wrong groupId during initialization (Bug 349736) *******************************************************************************/ package org.eclipse.cdt.debug.gdbjtag.core; @@ -615,7 +616,7 @@ public class GDBJtagDSFFinalLaunchSequence extends Sequence { public void execute(final RequestMonitor requestMonitor) { if (fSessionType != SessionType.CORE) { MIBreakpointsManager bpmService = fTracker.getService(MIBreakpointsManager.class); - IMIContainerDMContext containerDmc = fProcService.createContainerContextFromGroupId(fCommandControl.getContext(), null); + IMIContainerDMContext containerDmc = fProcService.createContainerContextFromGroupId(fCommandControl.getContext(), MIProcesses.UNIQUE_GROUP_ID); IBreakpointsTargetDMContext bpTargetDmc = DMContexts.getAncestorOfType(containerDmc, IBreakpointsTargetDMContext.class); bpmService.startTrackingBreakpoints(bpTargetDmc, requestMonitor); From 9cf02934609bb771a4d145ebee59bbac236f9be7 Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Thu, 1 Sep 2011 09:02:28 -0400 Subject: [PATCH 17/29] Bug 356463: Wrong label in thread filter for programs compiled without pthreads --- .../ui/breakpoints/GdbThreadFilterEditor.java | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/GdbThreadFilterEditor.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/GdbThreadFilterEditor.java index 3b4ae72dd26..22cbc9cbfe5 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/GdbThreadFilterEditor.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/GdbThreadFilterEditor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2009 QNX Software Systems and others. + * Copyright (c) 2004, 2011 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -7,6 +7,7 @@ * * Contributors: * QNX Software Systems - Initial API and implementation + * Marc Khouzam (Ericsson) - Check for a null threadId (Bug 356463) *******************************************************************************/ package org.eclipse.cdt.dsf.gdb.internal.ui.breakpoints; @@ -474,7 +475,15 @@ public class GdbThreadFilterEditor { new DataRequestMonitor(ImmediateExecutor.getInstance(), rm) { @Override public void handleSuccess() { - rm.setData(getData().getName()); + final StringBuilder builder = new StringBuilder(getData().getName()); + String containerId = getData().getId(); + if (containerId != null) { + builder.append(" ["); //$NON-NLS-1$ + builder.append(containerId); + builder.append("]"); //$NON-NLS-1$ + } + + rm.setData(builder.toString()); rm.done(); } }); @@ -524,8 +533,14 @@ public class GdbThreadFilterEditor { builder.append("["); //$NON-NLS-1$ builder.append(((IMIExecutionDMContext)thread).getThreadId()); builder.append("] "); //$NON-NLS-1$ - builder.append(getData().getId()); - builder.append(getData().getName()); + String threadId = getData().getId(); + if (threadId != null) { + builder.append(threadId); + } + String threadName = getData().getName(); + if (threadName != null) { + builder.append(threadName); + } rm.setData(builder.toString()); rm.done(); From e6d138a358e1eca344b5285c89f4ffbbca551b08 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Thu, 1 Sep 2011 12:31:04 -0700 Subject: [PATCH 18/29] Bug 356268 - Name resolution problem with 'using' declaration inside a class. Fix and test case. --- .../core/parser/tests/ast2/AST2CPPTests.java | 33 ++++++++-- .../parser/cpp/semantics/BaseClassLookup.java | 60 ++++++++----------- 2 files changed, 52 insertions(+), 41 deletions(-) diff --git a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2CPPTests.java b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2CPPTests.java index 013c8924b4a..9bc859802fc 100644 --- a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2CPPTests.java +++ b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2CPPTests.java @@ -9480,15 +9480,36 @@ public class AST2CPPTests extends AST2BaseTest { public void testAmbiguityResolution_Bug354599() throws Exception { parseAndCheckBindings(); } - + + // struct A { + // void method(A); + // }; + // + // struct B : A { + // void method(B); + // using A::method; + // }; + // + // struct C : B { + // }; + // + // void test() { + // B b; + // C c; + // c.method(b); + // } + public void testAmbiguityResolution_Bug356268() throws Exception { + parseAndCheckBindings(); + } + // void (g)(char); - // void (g )(int); - // void (g )(int); + // void (g)(int); //1 + // void (g)(int); //2 public void testFunctionRedeclarations() throws Exception { BindingAssertionHelper bh= getAssertionHelper(); - IFunction g1= bh.assertNonProblem("g)", 1); - IFunction g2= bh.assertNonProblem("g )", 1); - IFunction g3= bh.assertNonProblem("g )", 1); + IFunction g1= bh.assertNonProblem("g)(char)", 1); + IFunction g2= bh.assertNonProblem("g)(int); //1", 1); + IFunction g3= bh.assertNonProblem("g)(int); //2", 1); assertNotSame(g1, g2); assertSame(g2, g3); } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/BaseClassLookup.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/BaseClassLookup.java index 640c3594fb2..82ffa89a563 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/BaseClassLookup.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/BaseClassLookup.java @@ -22,7 +22,6 @@ import org.eclipse.cdt.core.dom.ast.DOMException; import org.eclipse.cdt.core.dom.ast.IBinding; import org.eclipse.cdt.core.dom.ast.IProblemBinding; import org.eclipse.cdt.core.dom.ast.IScope; -import org.eclipse.cdt.core.dom.ast.IType; import org.eclipse.cdt.core.dom.ast.cpp.ICPPBase; import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassScope; import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassType; @@ -56,8 +55,13 @@ class BaseClassLookup { rootInfo.collectResultForContentAssist(data); } else { hideVirtualBases(rootInfo, infoMap); - IBinding[] result= rootInfo.collectResult(data, true, null); - verifyResult(data, result); + IBinding[] result= rootInfo.collectResult(data, true, IBinding.EMPTY_BINDING_ARRAY); + if (data.problem == null) { + data.foundItems = ArrayUtil.addAll((Object[]) data.foundItems, result); + } else if (result.length > 0) { + data.problem.setCandidateBindings(result); + } +// verifyResult(data, result); } } @@ -323,7 +327,7 @@ class BaseClassLookup { } } - public IBinding[] collectResult(LookupData data, boolean asVirtualBase, IBinding[] result) { + private IBinding[] collectResult(LookupData data, boolean asVirtualBase, IBinding[] result) { if (asVirtualBase) { if (fHiddenAsVirtualBase) return result; @@ -337,41 +341,27 @@ class BaseClassLookup { if (fCollected) return result; fCollected= true; - - result= (IBinding[]) ArrayUtil.addAll(IBinding.class, result, fBindings); + + int numBindingsToAdd = 0; + for (int i = 0; i < fBindings.length; i++) { + IBinding binding = fBindings[i]; + if (binding == null) + break; + if (!ArrayUtil.contains(result, binding)) + fBindings[numBindingsToAdd++] = binding; + } + if (numBindingsToAdd < fBindings.length) + fBindings[numBindingsToAdd] = null; + if (result.length > 0 && numBindingsToAdd > 0 && data.problem == null) { + // Matches are found in more than one base class - this is an indication of ambiguity. + data.problem= new ProblemBinding(data.astName, + IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, result); + } + result= ArrayUtil.addAll(result, fBindings); for (int i= 0; i < fChildren.size(); i++) { BaseClassLookup child = fChildren.get(i); result= child.collectResult(data, fVirtual.get(i), result); } return result; } - - static void verifyResult(LookupData data, IBinding[] bindings) { - bindings= (IBinding[]) ArrayUtil.trim(IBinding.class, bindings); - if (bindings.length == 0) - return; - - if (data.problem != null) { - data.problem.setCandidateBindings(bindings); - } else { - ICPPClassType uniqueOwner= null; - for (IBinding b : bindings) { - if (!(b instanceof IType)) { - IBinding owner= b.getOwner(); - if (owner instanceof ICPPClassType) { - final ICPPClassType classOwner = (ICPPClassType) owner; - if (uniqueOwner == null) { - uniqueOwner= classOwner; - } else if (!uniqueOwner.isSameType(classOwner)) { - data.problem= new ProblemBinding(data.astName, - IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, bindings); - return; - } - } - } - } - } - - data.foundItems = ArrayUtil.addAll(Object.class, (Object[]) data.foundItems, bindings); - } } \ No newline at end of file From 77a94b7f641366f20d6e8d399270b64af05bf94a Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Thu, 1 Sep 2011 12:10:36 -0700 Subject: [PATCH 19/29] Clarified Javadoc. --- .../cdt/core/parser/util/ArrayUtil.java | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/parser/util/ArrayUtil.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/parser/util/ArrayUtil.java index 837954fd5eb..029c609b77e 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/parser/util/ArrayUtil.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/parser/util/ArrayUtil.java @@ -210,7 +210,14 @@ public abstract class ArrayUtil { } /** - * Assumes that both arrays contain nulls at the end, only. + * Takes contents of the two arrays up to the first null element and concatenates + * them. + * @param c The type of the element of the returned array if there was not enough free space + * in the destination array. + * @param dest The destination array. The elements of the source array are added to this array + * if there is enough free space in it. May be null. + * @param source The source array. May not be null. + * @return The concatenated array, which may be the same as the first parameter. */ public static Object[] addAll(Class c, Object[] dest, Object[] source) { if (source == null || source.length == 0) @@ -246,8 +253,12 @@ public abstract class ArrayUtil { } /** - * Concatenates two arrays skipping null elements. - * Assumes that both arrays contain nulls at the end, only. + * Takes contents of the two arrays up to the first null element and concatenates + * them. + * @param dest The destination array. The elements of the source array are added to this array + * if there is enough free space in it. May be null. + * @param source The source array. May not be null. + * @return The concatenated array, which may be the same as the first parameter. * @since 5.2 */ @SuppressWarnings("unchecked") @@ -264,7 +275,8 @@ public abstract class ArrayUtil { } if (dest == null || dest.length == 0) { - Class c = dest != null ? dest.getClass().getComponentType() : source.getClass().getComponentType(); + Class c = dest != null ? + dest.getClass().getComponentType() : source.getClass().getComponentType(); dest = (T[]) Array.newInstance(c, numToAdd); System.arraycopy(source, 0, dest, 0, numToAdd); return dest; From 6ba3a45797acb54b6c78c5a4237b31800e9e3160 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Thu, 1 Sep 2011 12:17:28 -0700 Subject: [PATCH 20/29] Cosmetics. --- .../core/parser/tests/ast2/AST2CPPTests.java | 710 +++++++++--------- 1 file changed, 355 insertions(+), 355 deletions(-) diff --git a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2CPPTests.java b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2CPPTests.java index 9bc859802fc..804b3f7fc24 100644 --- a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2CPPTests.java +++ b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2CPPTests.java @@ -157,13 +157,13 @@ public class AST2CPPTests extends AST2BaseTest { // class B { // public: - // B( int t ); + // B(int t); // }; // class A : public B { // public: - // A( int t ); + // A(int t); // }; - // A::A( int t ) : B( t - 1 ){} + // A::A(int t) : B(t - 1){} public void testBug78883() throws Exception { parseAndCheckBindings(getAboveComment()); } @@ -174,17 +174,17 @@ public class AST2CPPTests extends AST2BaseTest { // enum type2 {A, B}; // enum type2 d, e; public void testBug77967() throws Exception { - parseAndCheckBindings( getAboveComment() ); + parseAndCheckBindings(getAboveComment()); } public void testBug75189() throws Exception { - parseAndCheckBindings( "struct A{};typedef int (*F) (A*);" ); //$NON-NLS-1$ + parseAndCheckBindings("struct A{};typedef int (*F) (A*);"); //$NON-NLS-1$ } public void testBug75340() throws Exception { - IASTTranslationUnit tu = parseAndCheckBindings( "void f(int i = 0, int * p = 0);"); //$NON-NLS-1$ + IASTTranslationUnit tu = parseAndCheckBindings("void f(int i = 0, int * p = 0);"); //$NON-NLS-1$ IASTSimpleDeclaration sd = (IASTSimpleDeclaration) tu.getDeclarations()[0]; - isParameterSignatureEqual( sd.getDeclarators()[0], "(int=0, int*=0)" ); //$NON-NLS-1$ + isParameterSignatureEqual(sd.getDeclarators()[0], "(int=0, int*=0)"); //$NON-NLS-1$ } // #define REF_WRAP(e) class A { public: A (){ } A& foo2(e& v) { return *this; } } @@ -195,7 +195,7 @@ public class AST2CPPTests extends AST2BaseTest { // void foo(); // }; public void testBug79540() throws Exception { - parseAndCheckBindings( getAboveComment() ); + parseAndCheckBindings(getAboveComment()); } // template @@ -208,7 +208,7 @@ public class AST2CPPTests extends AST2BaseTest { // return 0; // } public void testBug103578() throws Exception { - parseAndCheckBindings( getAboveComment() ); + parseAndCheckBindings(getAboveComment()); } // int *p1; int *p2; @@ -222,7 +222,7 @@ public class AST2CPPTests extends AST2BaseTest { // MyStruct.b = 1; // } public void testBug78103() throws Exception { - parseAndCheckBindings( getAboveComment() ); + parseAndCheckBindings(getAboveComment()); } // signed int si(0); @@ -247,11 +247,11 @@ public class AST2CPPTests extends AST2BaseTest { // int f(int); // int x = f((a.*pm)(5)); public void testBug43242() throws Exception { - parseAndCheckBindings( getAboveComment() ); + parseAndCheckBindings(getAboveComment()); } public void testBug43241() throws Exception { - parseAndCheckBindings( "int m(int); int (*pm)(int) = &m; int f(){} int f(int); int x = f((*pm)(5));" ); //$NON-NLS-1$ + parseAndCheckBindings("int m(int); int (*pm)(int) = &m; int f(){} int f(int); int x = f((*pm)(5));"); //$NON-NLS-1$ } // int *zzz1 (char); @@ -259,18 +259,18 @@ public class AST2CPPTests extends AST2BaseTest { // int ((*zzz3)) (char); // int (*(zzz4)) (char); public void testBug40768() throws Exception { - IASTTranslationUnit tu = parse( getAboveComment(), ParserLanguage.CPP ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - assertNoProblemBindings( col ); + assertNoProblemBindings(col); } - protected IASTTranslationUnit parseAndCheckBindings( String code ) throws Exception + protected IASTTranslationUnit parseAndCheckBindings(String code) throws Exception { - IASTTranslationUnit tu = parse( code, ParserLanguage.CPP ); + IASTTranslationUnit tu = parse(code, ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - assertNoProblemBindings( col ); + assertNoProblemBindings(col); return tu; } @@ -286,38 +286,38 @@ public class AST2CPPTests extends AST2BaseTest { public void testBug40422() throws Exception { - IASTTranslationUnit tu = parse( "class A { int y; }; int A::* x = 0;", ParserLanguage.CPP ); //$NON-NLS-1$ + IASTTranslationUnit tu = parse("class A { int y; }; int A::* x = 0;", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - assertNoProblemBindings( col ); + assertNoProblemBindings(col); } public void testBug86282() throws Exception { - IASTTranslationUnit tu = parse( "void foo() { int (* f[])() = new (int (*[10])()); }", ParserLanguage.CPP ); //$NON-NLS-1$ + IASTTranslationUnit tu = parse("void foo() { int (* f[])() = new (int (*[10])()); }", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - assertNoProblemBindings( col ); + assertNoProblemBindings(col); } // bool f() { // int first, last; - // if(first < 1 || last > 99 ) + // if (first < 1 || last > 99) // return false; // } public void testBug75858() throws Exception { - IASTTranslationUnit tu = parse( getAboveComment(), ParserLanguage.CPP ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - assertNoProblemBindings( col ); + assertNoProblemBindings(col); } public void testBug95424() throws Exception { - IASTTranslationUnit tu = parse( "void f(){ traits_type::copy(__r->_M_refdata(), __buf, __i); }", ParserLanguage.CPP, true, true ); //$NON-NLS-1$ - tu = parse( "void f(){ traits_type::copy(__r->_M_refdata(), __buf, __i); }", ParserLanguage.CPP, false, true ); //$NON-NLS-1$ + IASTTranslationUnit tu = parse("void f(){ traits_type::copy(__r->_M_refdata(), __buf, __i); }", ParserLanguage.CPP, true, true); //$NON-NLS-1$ + tu = parse("void f(){ traits_type::copy(__r->_M_refdata(), __buf, __i); }", ParserLanguage.CPP, false, true); //$NON-NLS-1$ IASTFunctionDefinition f = (IASTFunctionDefinition) tu.getDeclarations()[0]; IASTCompoundStatement cs = (IASTCompoundStatement) f.getBody(); IASTExpressionStatement es = (IASTExpressionStatement) cs.getStatements()[0]; - assertTrue( es.getExpression() instanceof IASTFunctionCallExpression ); + assertTrue(es.getExpression() instanceof IASTFunctionCallExpression); } // class A { } a; @@ -350,14 +350,14 @@ public class AST2CPPTests extends AST2BaseTest { // for(A *y = start; y->x != 0; y = y->next) { // 42; // } - // for(int x = 0 ; x < 10; x++ ) { + // for(int x = 0 ; x < 10; x++) { // } // } public void testBug95411() throws Exception { - IASTTranslationUnit tu = parse( getAboveComment(), ParserLanguage.CPP ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector nameCol = new CPPNameCollector(); - tu.accept( nameCol ); - assertNoProblemBindings( nameCol ); + tu.accept(nameCol); + assertNoProblemBindings(nameCol); } // class A; class A {}; @@ -714,11 +714,11 @@ public class AST2CPPTests extends AST2BaseTest { assertInstances(collector, B2, 1); } - // void f( int i ); - // void f( char c ); + // void f(int i); + // void f(char c); // void main() { - // f( 1 ); //calls f( int ); - // f( 'b' ); + // f(1); //calls f(int); + // f('b'); // } public void testFunctionResolution() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -824,7 +824,7 @@ public class AST2CPPTests extends AST2BaseTest { } // struct x {}; - // void f( int x ) { + // void f(int x) { // struct x i; // } public void testStructureNamespace() throws Exception { @@ -837,8 +837,8 @@ public class AST2CPPTests extends AST2BaseTest { assertInstances(collector, x, 2); } - // void f( int a ); - // void f( int b ){ + // void f(int a); + // void f(int b){ // b; // } public void testFunctionDef() throws Exception { @@ -875,7 +875,7 @@ public class AST2CPPTests extends AST2BaseTest { } // void f() { - // for( int i = 0; i < 5; i++ ) { + // for(int i = 0; i < 5; i++) { // i; // } // } @@ -910,7 +910,7 @@ public class AST2CPPTests extends AST2BaseTest { // void f() { // col = blue; // cp = &col; - // if( *cp != red ) + // if (*cp != red) // return; // } public void testEnumerations() throws Exception { @@ -946,7 +946,7 @@ public class AST2CPPTests extends AST2BaseTest { assertTrue(pt.getType() instanceof IFunctionType); tu = parse( - "struct A; int (*pfi)( int, struct A * );", ParserLanguage.CPP); //$NON-NLS-1$ + "struct A; int (*pfi)(int, struct A *);", ParserLanguage.CPP); //$NON-NLS-1$ collector = new CPPNameCollector(); tu.accept(collector); ICPPClassType A = (ICPPClassType) collector.getName(0).resolveBinding(); @@ -962,9 +962,9 @@ public class AST2CPPTests extends AST2BaseTest { } // struct A; - // int * f( int i, char c ); - // void ( *g ) ( A * ); - // void (* (*h)(A**) ) ( int ); + // int * f(int i, char c); + // void (*g) (A *); + // void (* (*h)(A**)) (int); public void testFunctionTypes() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -1039,7 +1039,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testFnReturningPtrToFn() throws Exception { IASTTranslationUnit tu = parse( - "void ( * f( int ) )(){}", ParserLanguage.CPP); //$NON-NLS-1$ + "void (* f(int))(){}", ParserLanguage.CPP); //$NON-NLS-1$ IASTFunctionDefinition def = (IASTFunctionDefinition) tu .getDeclarations()[0]; @@ -1089,13 +1089,13 @@ public class AST2CPPTests extends AST2BaseTest { } // typedef int Int; - // void f( int i ); - // void f( const int ); - // void f( Int i ); - // void g( char * ); - // void g( char [] ); - // void h( int(a)() ); - // void h( int (*) () ); + // void f(int i); + // void f(const int); + // void f(Int i); + // void g(char *); + // void g(char []); + // void h(int(a)()); + // void h(int (*) ()); public void testFunctionDeclarations() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector collector = new CPPNameCollector(); @@ -1245,7 +1245,7 @@ public class AST2CPPTests extends AST2BaseTest { assertSame(qt.getType(), A); } - // class A { A(void); A( const A & ); }; + // class A { A(void); A(const A &); }; public void testConstructors() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -1515,7 +1515,7 @@ public class AST2CPPTests extends AST2BaseTest { // } // void f() { - // int ( *p ) [2]; + // int (*p) [2]; // (&p)[0] = 1; // } public void testBug84250() throws Exception { @@ -1534,7 +1534,7 @@ public class AST2CPPTests extends AST2BaseTest { } // void f() { - // int ( *p ) [2]; + // int (*p) [2]; // (&p)[0] = 1; // } public void testBug84250_2() throws Exception { @@ -1586,8 +1586,8 @@ public class AST2CPPTests extends AST2BaseTest { assertNotNull(s); } - // void f( int m, int c[m][m] ); - // void f( int m, int c[m][m] ){ + // void f(int m, int c[m][m]); + // void f(int m, int c[m][m]){ // int x; // { int x = x; } // } @@ -1724,12 +1724,12 @@ public class AST2CPPTests extends AST2BaseTest { // struct C { // void f(); - // const C& operator=( const C& ); + // const C& operator=(const C&); // }; - // const C& C::operator=( const C& other) { - // if( this != &other ) { + // const C& C::operator=(const C& other) { + // if (this != &other) { // this->~C(); - // new (this) C(other ); + // new (this) C(other); // f(); // } // return *this; @@ -1802,11 +1802,11 @@ public class AST2CPPTests extends AST2BaseTest { // namespace NS { // class T {}; - // void f( T ); + // void f(T); // } // NS::T parm; // int main() { - // f( parm ); + // f(parm); // } public void testArgumentDependantLookup() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -1825,16 +1825,16 @@ public class AST2CPPTests extends AST2BaseTest { } // namespace NS1{ - // void f( void * ); + // void f(void *); // } // namespace NS2{ // using namespace NS1; // class B {}; - // void f( void * ); + // void f(void *); // } // class A : public NS2::B {} *a; // int main() { - // f( a ); + // f(a); // } public void testArgumentDependantLookup_2() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -2042,10 +2042,10 @@ public class AST2CPPTests extends AST2BaseTest { // class A { public: int i; }; // class B : public A {}; - // void f( int B::* ); + // void f(int B::*); // void g() { // int A::* pm = &A::i; - // f( pm ); + // f(pm); // } public void testPMConversions() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -2067,11 +2067,11 @@ public class AST2CPPTests extends AST2BaseTest { // namespace N { // class A { public: int i; }; - // void f( int A::* ); + // void f(int A::*); // } // int N::A::* pm = &N::A::i; // void g() { - // f( pm ); + // f(pm); // } public void testPMKoenig() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -2089,7 +2089,7 @@ public class AST2CPPTests extends AST2BaseTest { // namespace M { // class B { }; - // void f( B* ); + // void f(B*); // } // namespace N { // class A { public: M::B * b; }; @@ -2097,7 +2097,7 @@ public class AST2CPPTests extends AST2BaseTest { // M::B* N::A::* pm = &N::A::b; // void g() { // N::A * a; - // f( a->*pm ); + // f(a->*pm); // } public void testPMKoenig_2() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -2228,8 +2228,8 @@ public class AST2CPPTests extends AST2BaseTest { assertSame(friends[0], helper); } - // void f( int ); - // void f( char ); + // void f(int); + // void f(char); // void (*pf) (int) = &f; // void foo() { // pf = &f; @@ -2248,13 +2248,13 @@ public class AST2CPPTests extends AST2BaseTest { assertInstances(col, f2, 1); } - // void f( char ); - // void f( int ); - // void g( void (*)( int ) ) {} - // void (*pg)( void(*)(int) ); + // void f(char); + // void f(int); + // void g(void (*)(int)) {} + // void (*pg)(void(*)(int)); // void foo() { - // g( &f ); - // (*pg)( &f ); + // g(&f); + // (*pg)(&f); // } public void testBug45763_2() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -2272,9 +2272,9 @@ public class AST2CPPTests extends AST2BaseTest { assertInstances(col, pg, 2); } - // void f( int ); - // void f( char ); - // void (* bar () ) ( int ) { + // void f(int); + // void f(char); + // void (* bar ()) (int) { // return &f; // } public void testBug45763_3() throws Exception { @@ -2291,10 +2291,10 @@ public class AST2CPPTests extends AST2BaseTest { assertInstances(col, f2, 1); } - // void f( int ); - // void f( char ); + // void f(int); + // void f(char); // void foo () { - // ( void (*)(int) ) &f; + // (void (*)(int)) &f; // } public void testBug45763_4() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -2404,12 +2404,12 @@ public class AST2CPPTests extends AST2BaseTest { // // return; // // } // public void testBug85310() throws Exception { - // IASTTranslationUnit tu = parse( getAboveComment(), ParserLanguage.CPP ); + // IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); // IASTFunctionDefinition f = (IASTFunctionDefinition) // tu.getDeclarations()[0]; // IASTCompoundStatement body = (IASTCompoundStatement) f.getBody(); // IASTCPPIfStatement if_stmt = (IASTCPPIfStatement) body.getStatements()[0]; - // assertNotNull( if_stmt.getCondition() ); + // assertNotNull(if_stmt.getCondition()); // } // struct B { void mutate(); }; @@ -2441,10 +2441,10 @@ public class AST2CPPTests extends AST2BaseTest { // struct C { // void f(); - // const C& operator =( const C& ); + // const C& operator =(const C&); // }; - // const C& C::operator = ( const C& other ) { - // if( this != &other ) { + // const C& C::operator = (const C& other) { + // if (this != &other) { // this->~C(); // new (this) C(other); // f(); @@ -2470,13 +2470,13 @@ public class AST2CPPTests extends AST2BaseTest { } // extern "C" { - // void printf( const char * ); - // void sprintf( const char * ); + // void printf(const char *); + // void sprintf(const char *); // } // void foo(){ // char *p; - // printf( p ); - // printf( "abc" ); + // printf(p); + // printf("abc"); // } public void testBug86279() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -2493,9 +2493,9 @@ public class AST2CPPTests extends AST2BaseTest { // struct S; // extern S a; - // void g( S ); + // void g(S); // void h() { - // g( a ); + // g(a); // } public void testBug86346() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -2510,7 +2510,7 @@ public class AST2CPPTests extends AST2BaseTest { } public void testBug86288() throws Exception { - String code = "int *foo( int *b ) { return (int *)(b); }"; //$NON-NLS-1$ + String code = "int *foo(int *b) { return (int *)(b); }"; //$NON-NLS-1$ IASTTranslationUnit tu = parse(code, ParserLanguage.CPP); IASTReturnStatement r = (IASTReturnStatement) ((IASTCompoundStatement) ((IASTFunctionDefinition) tu .getDeclarations()[0]).getBody()).getStatements()[0]; @@ -2538,10 +2538,10 @@ public class AST2CPPTests extends AST2BaseTest { } // struct T1 { - // T1 operator() ( int x ) { + // T1 operator() (int x) { // return T1(x); // } - // T1( int ) {} + // T1(int) {} // }; public void testBug86336() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -2594,7 +2594,7 @@ public class AST2CPPTests extends AST2BaseTest { // void foo() { // int i = 42; // int a[10]; - // for( int i = 0; i < 10; i++ ) + // for(int i = 0; i < 10; i++) // a[i] = 1; // int j = i; // } @@ -2692,7 +2692,7 @@ public class AST2CPPTests extends AST2BaseTest { // const D d2; // void foo() { // typeid(d1) == typeid(d2); - // typeid( D ) == typeid(d2); + // typeid(D) == typeid(d2); // } public void testBug86274() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -2709,11 +2709,11 @@ public class AST2CPPTests extends AST2BaseTest { assertInstances(col, d2, 3); } - // void point ( int = 3, int = 4 ); + // void point (int = 3, int = 4); // void foo() { - // point( 1, 2 ); - // point( 1 ); - // point( ); + // point(1, 2); + // point(1); + // point(); // } public void testBug86546() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -2775,13 +2775,13 @@ public class AST2CPPTests extends AST2BaseTest { } // struct B { - // void f ( char ); - // void g ( char ); + // void f (char); + // void g (char); // }; // struct D : B { // using B::f; - // void f( int ) { f('c'); } - // void g( int ) { g('c'); } + // void f(int) { f('c'); } + // void g(int) { g('c'); } // }; public void test86371() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -2852,8 +2852,8 @@ public class AST2CPPTests extends AST2BaseTest { } // namespace A { - // void f( char ); - // void f( int ); + // void f(char); + // void f(int); // } // using A::f; public void testBug86470_1() throws Exception { @@ -2883,18 +2883,18 @@ public class AST2CPPTests extends AST2BaseTest { } // namespace A { - // void f( int ); - // void f( double ); + // void f(int); + // void f(double); // } // namespace B { - // void f( int ); - // void f( double ); - // void f( char ); + // void f(int); + // void f(double); + // void f(char); // } // void g() { // using A::f; // using B::f; - // f( 'c' ); + // f('c'); // } public void testBug86470_2() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -2908,7 +2908,7 @@ public class AST2CPPTests extends AST2BaseTest { // namespace A { // struct g {}; - // void g ( char ); + // void g (char); // } // void f() { // using A::g; @@ -2983,13 +2983,13 @@ public class AST2CPPTests extends AST2BaseTest { } // namespace A { - // void f( int ); - // void f( double ); + // void f(int); + // void f(double); // } // void g() { - // void f( char ); + // void f(char); // using A::f; - // f( 3.5 ); + // f(3.5); // } public void testBug86470_5() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -2999,7 +2999,7 @@ public class AST2CPPTests extends AST2BaseTest { ICPPFunction f = (ICPPFunction) col.getName(3).resolveBinding(); ICPPFunction f_ref = (ICPPFunction) col.getName(11).resolveBinding(); - assertSame( f_ref, f); + assertSame(f_ref, f); String[] s = f_ref.getQualifiedName(); assertEquals(s[0], "A"); //$NON-NLS-1$ @@ -3015,10 +3015,10 @@ public class AST2CPPTests extends AST2BaseTest { // class B; // class A { // int i; - // friend void f( B * ); + // friend void f(B *); // }; // class B : public A {}; - // void f( B* p ) { + // void f(B* p) { // p->i = 1; // } public void testBug86678() throws Exception { @@ -3035,11 +3035,11 @@ public class AST2CPPTests extends AST2BaseTest { assertInstances(col, p, 3); } - // int printf( const char *, ... ); + // int printf(const char *, ...); // void foo(){ // int a, b; - // printf( "hello" ); - // printf("a=%d b=%d", a, b ); + // printf("hello"); + // printf("a=%d b=%d", a, b); // } public void testBug86543() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -3050,9 +3050,9 @@ public class AST2CPPTests extends AST2BaseTest { assertInstances(col, printf, 3); } - // int max( int a, int b, int c ) { - // int m = ( a > b ) ? a : b; - // return ( m > c ) ? m : c; + // int max(int a, int b, int c) { + // int m = (a > b) ? a : b; + // return (m > c) ? m : c; // } public void testBug86554() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -3165,7 +3165,7 @@ public class AST2CPPTests extends AST2BaseTest { assertSame(refs[0], col.getName(3)); } - // void f( int par ) { + // void f(int par) { // int v1; // { // int v2; @@ -3224,11 +3224,11 @@ public class AST2CPPTests extends AST2BaseTest { } // namespace A { - // void f( int ); - // void f( double ); + // void f(int); + // void f(double); // } // void g() { - // void f( char ); + // void f(char); // using A::f; // } public void testFind_3() throws Exception { @@ -3260,7 +3260,7 @@ public class AST2CPPTests extends AST2BaseTest { // void f(); // } // namespace B { - // void f( int ); + // void f(int); // } // namespace C { // using namespace B; @@ -3447,7 +3447,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testBug88501_1() throws Exception { IASTTranslationUnit tu = parse( - "void f(); void f( int ); struct f;", ParserLanguage.CPP); //$NON-NLS-1$ + "void f(); void f(int); struct f;", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); tu.accept(col); @@ -3457,14 +3457,14 @@ public class AST2CPPTests extends AST2BaseTest { } // public void testBug8342_1() throws Exception { - // IASTTranslationUnit tu = parse( "int a; int a;", ParserLanguage.CPP ); + // IASTTranslationUnit tu = parse("int a; int a;", ParserLanguage.CPP); // //$NON-NLS-1$ // CPPNameCollector col = new CPPNameCollector(); // tu.accept(col); // - // assertTrue( col.getName(0).resolveBinding() instanceof IVariable ); + // assertTrue(col.getName(0).resolveBinding() instanceof IVariable); // IProblemBinding p = (IProblemBinding) col.getName(1).resolveBinding(); - // assertEquals( p.getID(), IProblemBinding.SEMANTIC_INVALID_REDEFINITION ); + // assertEquals(p.getID(), IProblemBinding.SEMANTIC_INVALID_REDEFINITION); // } public void testBug8342_2() throws Exception { @@ -3549,7 +3549,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testBug89828() throws Exception { IASTTranslationUnit tu = parse( - "class B * b; void f(); void f( int );", ParserLanguage.CPP); //$NON-NLS-1$ + "class B * b; void f(); void f(int);", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); tu.accept(col); @@ -3567,11 +3567,11 @@ public class AST2CPPTests extends AST2BaseTest { // class A { // enum type { t1, t2 }; - // void f( type t ); + // void f(type t); // }; // class B : public A { // void g() { - // f( A::t1 ); + // f(A::t1); // } // }; public void testBug90039() throws Exception { @@ -3586,7 +3586,7 @@ public class AST2CPPTests extends AST2BaseTest { assertInstances(col, t1, 3); } - // void f( void ) { + // void f(void) { // enum { one }; // } public void testBug90039_2() throws Exception { @@ -3686,7 +3686,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testBug90498_1() throws Exception { IASTTranslationUnit tu = parse( - "typedef int INT;\ntypedef INT ( FOO ) (INT);", ParserLanguage.CPP); //$NON-NLS-1$ + "typedef int INT;\ntypedef INT (FOO) (INT);", ParserLanguage.CPP); //$NON-NLS-1$ IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu .getDeclarations()[1]; @@ -3769,9 +3769,9 @@ public class AST2CPPTests extends AST2BaseTest { assertTrue(((ITypedef) binding).getType() instanceof IFunctionType); } - // void f( int ); + // void f(int); // void foo(){ - // f( ( 1, 2 ) ); + // f((1, 2)); // } public void testBug90616() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -3824,7 +3824,7 @@ public class AST2CPPTests extends AST2BaseTest { // struct C { // void* operator new [ ] (unsigned int); // void* operator new (unsigned int); - // void operator delete [ ] ( void * ); + // void operator delete [ ] (void *); // void operator delete (void *); // const C& operator+=(const C&); // const C& operator -= (const C&); @@ -3851,7 +3851,7 @@ public class AST2CPPTests extends AST2BaseTest { // const C& operator->* // (const C&); // const C& operator -> (const C&); - // const C& operator /**/ ( /**/ ) /**/ (const C&); + // const C& operator /**/ (/**/) /**/ (const C&); // const C& operator /**/ [ /**/ ] /**/ (const C&); // const C& operator + (const C&); // const C& operator- (const C&); @@ -3956,7 +3956,7 @@ public class AST2CPPTests extends AST2BaseTest { } // typedef int I; - // void f11( I i ); + // void f11(I i); // void main(){ f a; } public void testBug90623_2() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -3968,13 +3968,13 @@ public class AST2CPPTests extends AST2BaseTest { } // class X { - // X( const X & ); + // X(const X &); // }; // class Y { // operator X (); // }; // Y y; - // X x = new X( y ); + // X x = new X(y); public void testBug90654_1() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); @@ -3990,8 +3990,8 @@ public class AST2CPPTests extends AST2BaseTest { // struct A { // operator short(); // } a; - // int f( int ); - // int f( float ); + // int f(int); + // int f(float); // int x = f(a); public void testBug90654_2() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -4005,7 +4005,7 @@ public class AST2CPPTests extends AST2BaseTest { // struct A {}; // struct B : public A { - // B& operator = (const B & ); + // B& operator = (const B &); // }; // B& B::operator = (const B & s){ // this->A::operator=(s); @@ -4028,9 +4028,9 @@ public class AST2CPPTests extends AST2BaseTest { assertSame(op, implicit); } - // void f( char * ); + // void f(char *); // void foo() { - // f( "test" ); + // f("test"); // } public void testBug86618() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -4041,10 +4041,10 @@ public class AST2CPPTests extends AST2BaseTest { assertInstances(col, f, 2); } - // void f( int (*pf) (char) ); - // int g( char ); + // void f(int (*pf) (char)); + // int g(char); // void foo () { - // f( g ) ; + // f(g) ; // } public void testBug45129() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -4186,7 +4186,7 @@ public class AST2CPPTests extends AST2BaseTest { } // class Dummy { int v(); int d; }; - // void Dummy::v( int ){ d++; } + // void Dummy::v(int){ d++; } public void testBug92882() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); @@ -4198,12 +4198,12 @@ public class AST2CPPTests extends AST2BaseTest { assertSame(d1, d2); } - // void f( int, int ); - // void f( int, int = 3); - // void f( int = 2, int ); + // void f(int, int); + // void f(int, int = 3); + // void f(int = 2, int); // void g() { - // f( 3 ); - // f( ); + // f(3); + // f(); // } public void testBug86547() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -4287,7 +4287,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testBug85786() throws Exception { IASTTranslationUnit tu = parse( - "void f( int ); void foo () { void * p = &f; ( (void (*) (int)) p ) ( 1 ); }", ParserLanguage.C); //$NON-NLS-1$ + "void f(int); void foo () { void * p = &f; ((void (*) (int)) p) (1); }", ParserLanguage.C); //$NON-NLS-1$ CPPNameCollector nameResolver = new CPPNameCollector(); tu.accept(nameResolver); assertNoProblemBindings(nameResolver); @@ -4312,8 +4312,8 @@ public class AST2CPPTests extends AST2BaseTest { // int a; // extern int b; // extern int c = 1; - // int f( ); - // int f( int p ){} + // int f(); + // int f(int p){} // struct S; // struct S { int d; }; // struct X { @@ -4321,8 +4321,8 @@ public class AST2CPPTests extends AST2BaseTest { // }; // namespace N {} // int X::y = 1; - // int ( *g(int) )(int); - // int ( *pf)(int); + // int (*g(int))(int); + // int (*pf)(int); public void testDeclDefn() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); @@ -4374,7 +4374,7 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals(2, ctors.length); // one user declared constructor, one copy constructor assertSame(ctor, ctors[1]); - tu = parse("class A { A( void ); };", ParserLanguage.CPP); //$NON-NLS-1$ + tu = parse("class A { A(void); };", ParserLanguage.CPP); //$NON-NLS-1$ col = new CPPNameCollector(); tu.accept(col); @@ -4386,10 +4386,10 @@ public class AST2CPPTests extends AST2BaseTest { assertSame(ctor, ctors[1]); } - // void f( char * ); + // void f(char *); // void g(){ // char x[100]; - // f( x ); + // f(x); // } public void testBug95461() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -4532,9 +4532,9 @@ public class AST2CPPTests extends AST2BaseTest { assertSame(bar, col.getName(6).resolveBinding()); } - // int strcmp( const char * ); - // void f( const char * const * argv ){ - // strcmp( *argv ); + // int strcmp(const char *); + // void f(const char * const * argv){ + // strcmp(*argv); // } public void testBug95419() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -4547,25 +4547,25 @@ public class AST2CPPTests extends AST2BaseTest { // class Other; // class Base { - // public: Base( Other * ); + // public: Base(Other *); // }; // class Sub : public Base { - // public: Sub( Other * ); + // public: Sub(Other *); // }; - // Sub::Sub( Other * b ) : Base(b) {} + // Sub::Sub(Other * b) : Base(b) {} public void testBug95673() throws Exception { BindingAssertionHelper ba= getAssertionHelper(); - ICPPConstructor ctor= ba.assertNonProblem("Base( Other", 4, ICPPConstructor.class); + ICPPConstructor ctor= ba.assertNonProblem("Base(Other", 4, ICPPConstructor.class); ICPPConstructor ctor2= ba.assertNonProblem("Base(b)", 4, ICPPConstructor.class); assertSame(ctor, ctor2); } - // void mem( void *, const void * ); + // void mem(void *, const void *); // void f() { // char *x; int offset; - // mem( x, "FUNC" ); - // mem( x + offset, "FUNC2" ); + // mem(x, "FUNC"); + // mem(x + offset, "FUNC2"); // } public void testBug95768() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -4577,12 +4577,12 @@ public class AST2CPPTests extends AST2BaseTest { assertSame(mem, col.getName(8).resolveBinding()); } - // void trace( const void * ); + // void trace(const void *); // class Foo { // public: int import(); // }; // int Foo::import(){ - // trace( this ); + // trace(this); // } public void testBug95741() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -4597,7 +4597,7 @@ public class AST2CPPTests extends AST2BaseTest { // char value; // public: operator char (void) const; // }; - // RTCharacter::operator char( void )const { + // RTCharacter::operator char(void)const { // return value; // } public void testBug95692() throws Exception { @@ -4609,10 +4609,10 @@ public class AST2CPPTests extends AST2BaseTest { assertSame(op, col.getName(6).resolveBinding()); } - // int str( const char * ); + // int str(const char *); // void f(){ - // str( 0 ); - // str( 00 ); str( 0x0 ); + // str(0); + // str(00); str(0x0); // } public void testBug95734() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -4625,11 +4625,11 @@ public class AST2CPPTests extends AST2BaseTest { assertSame(str, col.getName(5).resolveBinding()); } - // int str( bool ); + // int str(bool); // enum { ONE }; - // void f( char * p ){ - // str( 1.2 ); - // str( ONE ); str( p ); + // void f(char * p){ + // str(1.2); + // str(ONE); str(p); // } public void testBug95734_2() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -4668,8 +4668,8 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals(tu.getDeclarations().length, 1); } - // void f( int t ){ - // int s ( t ); + // void f(int t){ + // int s (t); // } public void testBug94779() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -4681,7 +4681,7 @@ public class AST2CPPTests extends AST2BaseTest { } // int t= 0; - // int s ( t ); + // int s (t); public void testBug211756() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); IASTSimpleDeclaration sd = (IASTSimpleDeclaration) (tu.getDeclarations()[1]); @@ -4692,7 +4692,7 @@ public class AST2CPPTests extends AST2BaseTest { // typedef struct xs { // int state; // } xs; - // void f( xs *ci ) { + // void f(xs *ci) { // ci->state; // (ci - 1)->state; // } @@ -4709,7 +4709,7 @@ public class AST2CPPTests extends AST2BaseTest { // float _Complex x; // double _Complex y; public void testBug95757() throws Exception { - IASTTranslationUnit tu = parse( getAboveComment(), ParserLanguage.CPP, true, true ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); IASTDeclaration[] decls = tu.getDeclarations(); assertTrue(((IASTSimpleDeclSpecifier)((IASTSimpleDeclaration)decls[0]).getDeclSpecifier()).isComplex()); @@ -4738,54 +4738,54 @@ public class AST2CPPTests extends AST2BaseTest { // return 5; // } // int main() { - // int a( 5 ); - // int b( f() ); + // int a(5); + // int b(f()); // return a+b; // } public void testBug86849() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - assertNoProblemBindings( col ); + assertNoProblemBindings(col); } - // void copy( void * ); + // void copy(void *); // typedef struct {} A; - // void f( A * a ) { - // copy( a ); + // void f(A * a) { + // copy(a); // } public void testBug96655() throws Exception { - IASTTranslationUnit tu = parse( getAboveComment(), ParserLanguage.CPP ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); ICPPFunction copy = (ICPPFunction) col.getName(0).resolveBinding(); - assertSame( copy, col.getName(7).resolveBinding() ); + assertSame(copy, col.getName(7).resolveBinding()); } public void testBug96678() throws Exception { - parse( "int x; // comment \r\n", ParserLanguage.CPP, false, true ); //$NON-NLS-1$ + parse("int x; // comment \r\n", ParserLanguage.CPP, false, true); //$NON-NLS-1$ } // struct A {}; - // void copy( A * ); - // void f( ) { - // copy( new A() ); + // void copy(A *); + // void f() { + // copy(new A()); // } public void testNewExpressionType() throws Exception { - IASTTranslationUnit tu = parse( getAboveComment(), ParserLanguage.CPP ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); ICPPFunction copy = (ICPPFunction) col.getName(1).resolveBinding(); - assertSame( copy, col.getName(5).resolveBinding() ); + assertSame(copy, col.getName(5).resolveBinding()); } // class A { - // A( int i = 0 ); + // A(int i = 0); // }; public void testDefaultConstructor() throws Exception { - IASTTranslationUnit tu = parse( getAboveComment(), ParserLanguage.CPP ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); @@ -4793,14 +4793,14 @@ public class AST2CPPTests extends AST2BaseTest { ICPPConstructor ctor = (ICPPConstructor) col.getName(1).resolveBinding(); ICPPConstructor [] cs = A.getConstructors(); - assertTrue( cs.length == 2 ); - assertSame( cs[1], ctor ); + assertTrue(cs.length == 2); + assertSame(cs[1], ctor); } // class C { public: int foo; }; // class B { // C* operator ->(); - // C& operator [] ( int ); + // C& operator [] (int); // }; // void f(){ // B b; @@ -4808,14 +4808,14 @@ public class AST2CPPTests extends AST2BaseTest { // b[0].foo; // } public void testBug91707() throws Exception { - IASTTranslationUnit tu = parse( getAboveComment(), ParserLanguage.CPP ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); ICPPField foo = (ICPPField) col.getName(1).resolveBinding(); - assertSame( foo, col.getName(12).resolveBinding() ); - assertSame( foo, col.getName(14).resolveBinding() ); + assertSame(foo, col.getName(12).resolveBinding()); + assertSame(foo, col.getName(14).resolveBinding()); } // class A; @@ -4825,7 +4825,7 @@ public class AST2CPPTests extends AST2BaseTest { // }; // class A::B{}; public void testBug92425() throws Exception { - IASTTranslationUnit tu = parse( getAboveComment(), ParserLanguage.CPP ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); @@ -4834,67 +4834,67 @@ public class AST2CPPTests extends AST2BaseTest { ICPPClassType C = (ICPPClassType) col.getName(3).resolveBinding(); ICPPClassType [] classes = A.getNestedClasses(); - assertEquals( classes.length, 2 ); - assertSame( classes[0], B ); - assertSame( classes[1], C ); + assertEquals(classes.length, 2); + assertSame(classes[0], B); + assertSame(classes[1], C); } // namespace A { // struct F {} f; - // void f( int a) {} + // void f(int a) {} // } public void testBug92425_2() throws Exception { - IASTTranslationUnit tu = parse( getAboveComment(), ParserLanguage.CPP ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); ICPPNamespace A = (ICPPNamespace) col.getName(0).resolveBinding(); IBinding [] bindings = A.getMemberBindings(); - assertEquals( bindings.length, 3 ); - assertSame( bindings[0], col.getName(1).resolveBinding() ); - assertSame( bindings[1], col.getName(2).resolveBinding() ); - assertSame( bindings[2], col.getName(3).resolveBinding() ); + assertEquals(bindings.length, 3); + assertSame(bindings[0], col.getName(1).resolveBinding()); + assertSame(bindings[1], col.getName(2).resolveBinding()); + assertSame(bindings[2], col.getName(3).resolveBinding()); } // A< B< C< D< E< F< G< H > > > > > > > a; // int A::B::* b; public void testBug98704() throws Exception { - parse( getAboveComment(), ParserLanguage.CPP ); + parse(getAboveComment(), ParserLanguage.CPP); } // void f(); - // void f( void ) {} + // void f(void) {} public void testBug_AIOOBE() throws Exception { - IASTTranslationUnit tu = parse( getAboveComment(), ParserLanguage.CPP ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); IFunction f = (IFunction) col.getName(0).resolveBinding(); - assertSame( f, col.getName(1).resolveBinding() ); + assertSame(f, col.getName(1).resolveBinding()); IParameter p = (IParameter) col.getName(2).resolveBinding(); - assertNotNull( p ); + assertNotNull(p); } - // void f( const int ); - // void f( int ); + // void f(const int); + // void f(int); // void g() { f(1); } public void testRankingQualificationConversions_a() throws Exception { - IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - assertSame( col.getName(2).resolveBinding(), col.getName(5).resolveBinding() ); + assertSame(col.getName(2).resolveBinding(), col.getName(5).resolveBinding()); } - // void f( const volatile int ); - // void f( const int ); + // void f(const volatile int); + // void f(const int); // void g() { f(1); } public void testRankingQualificationConversions_b() throws Exception { - IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - assertSame( col.getName(2).resolveBinding(), col.getName(5).resolveBinding() ); + assertSame(col.getName(2).resolveBinding(), col.getName(5).resolveBinding()); } // void f(const int&); @@ -4962,22 +4962,22 @@ public class AST2CPPTests extends AST2BaseTest { // } // } public void testBug98818() throws Exception { - IASTTranslationUnit tu = parse( getAboveComment(), ParserLanguage.CPP ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); ICPPNamespace n = (ICPPNamespace) col.getName(0).resolveBinding(); ICPPNamespace m = (ICPPNamespace) col.getName(1).resolveBinding(); - assertSame( n, col.getName(3).resolveBinding() ); - assertSame( n, col.getName(7).resolveBinding() ); - assertSame( m, col.getName(4).resolveBinding() ); - assertSame( m, col.getName(8).resolveBinding() ); + assertSame(n, col.getName(3).resolveBinding()); + assertSame(n, col.getName(7).resolveBinding()); + assertSame(m, col.getName(4).resolveBinding()); + assertSame(m, col.getName(8).resolveBinding()); ICPPClassType A = (ICPPClassType) col.getName(2).resolveBinding(); - assertSame( A, col.getName(5).resolveBinding() ); + assertSame(A, col.getName(5).resolveBinding()); ICPPMethod f = (ICPPMethod) col.getName(9).resolveBinding(); - assertSame( f, col.getName(11).resolveBinding() ); + assertSame(f, col.getName(11).resolveBinding()); } // struct A { @@ -4989,14 +4989,14 @@ public class AST2CPPTests extends AST2BaseTest { // a.B.i; a.C.j; // } public void testAnonymousStructures() throws Exception { - IASTTranslationUnit tu = parse( getAboveComment(), ParserLanguage.CPP ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); ICPPField i = (ICPPField) col.getName(12).resolveBinding(); ICPPField j = (ICPPField) col.getName(15).resolveBinding(); - assertSame( i, col.getName(2).resolveBinding() ); - assertSame( j, col.getName(5).resolveBinding() ); + assertSame(i, col.getName(2).resolveBinding()); + assertSame(j, col.getName(5).resolveBinding()); } public void testBug99262() throws Exception { @@ -5014,53 +5014,53 @@ public class AST2CPPTests extends AST2BaseTest { } public void testBug100408() throws Exception { - IASTTranslationUnit tu = parse( "int foo() { int x=1; (x)*3; }", ParserLanguage.CPP ); //$NON-NLS-1$ + IASTTranslationUnit tu = parse("int foo() { int x=1; (x)*3; }", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); - tu.accept( col ); - assertNoProblemBindings( col ); + tu.accept(col); + assertNoProblemBindings(col); } public void testBug84478_3() throws Exception { - IASTTranslationUnit tu = parse( "void foo() { switch( int x = 4 ) { case 4: x++; break; default: break;} }", ParserLanguage.CPP ); //$NON-NLS-1$ + IASTTranslationUnit tu = parse("void foo() { switch(int x = 4) { case 4: x++; break; default: break;} }", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); - tu.accept( col ); - assertNoProblemBindings( col ); - assertSame( col.getName(1).resolveBinding(), col.getName(2).resolveBinding() ); + tu.accept(col); + assertNoProblemBindings(col); + assertSame(col.getName(1).resolveBinding(), col.getName(2).resolveBinding()); } public void testBug84478_4() throws Exception { - IASTTranslationUnit tu = parse( "void foo() { for( int i = 0; int j = 0; ++i) {} }", ParserLanguage.CPP ); //$NON-NLS-1$ + IASTTranslationUnit tu = parse("void foo() { for(int i = 0; int j = 0; ++i) {} }", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); - tu.accept( col ); - assertNoProblemBindings( col ); + tu.accept(col); + assertNoProblemBindings(col); } // void f(){ - // if( int x = 1 ) x++; + // if (int x = 1) x++; // else x--; - // while( int y = 2 ) + // while(int y = 2) // y++; - // for( int a = 1; int b = 2; b++){ + // for(int a = 1; int b = 2; b++){ // a++; b++; // } // } public void testBug84478_2() throws Exception { - IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); CPPNameCollector col = new CPPNameCollector(); - tu.accept( col ); + tu.accept(col); - assertNoProblemBindings( col ); + assertNoProblemBindings(col); IVariable x = (IVariable) col.getName(1).resolveBinding(); - assertSame( x, col.getName(2).resolveBinding() ); - assertSame( x, col.getName(3).resolveBinding() ); + assertSame(x, col.getName(2).resolveBinding()); + assertSame(x, col.getName(3).resolveBinding()); IVariable y = (IVariable) col.getName(4).resolveBinding(); - assertSame( y, col.getName(5).resolveBinding() ); + assertSame(y, col.getName(5).resolveBinding()); IVariable a = (IVariable) col.getName(6).resolveBinding(); IVariable b = (IVariable) col.getName(7).resolveBinding(); - assertSame( b, col.getName(8).resolveBinding() ); - assertSame( a, col.getName(9).resolveBinding() ); - assertSame( b, col.getName(10).resolveBinding() ); + assertSame(b, col.getName(8).resolveBinding()); + assertSame(a, col.getName(9).resolveBinding()); + assertSame(b, col.getName(10).resolveBinding()); } // void free(void*); @@ -5088,14 +5088,14 @@ public class AST2CPPTests extends AST2BaseTest { // }; // } public void testBug86688() throws Exception { - IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); CPPNameCollector col = new CPPNameCollector(); - tu.accept( col ); + tu.accept(col); ICPPClassType X = (ICPPClassType) col.getName(0).resolveBinding(); - assertNotSame( X, col.getName(3).resolveBinding() ); - assertTrue( col.getName(3).resolveBinding() instanceof ICPPClassType ); - assertSame( X, col.getName(6).resolveBinding() ); + assertNotSame(X, col.getName(3).resolveBinding()); + assertTrue(col.getName(3).resolveBinding() instanceof ICPPClassType); + assertSame(X, col.getName(6).resolveBinding()); } // class m { @@ -5103,12 +5103,12 @@ public class AST2CPPTests extends AST2BaseTest { // }; // int m::f(){} public void testBug100403() throws Exception { - IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); CPPNameCollector col = new CPPNameCollector(); - tu.accept( col ); + tu.accept(col); ICPPMethod f = (ICPPMethod) col.getName(3).resolveBinding(); - assertSame( f, col.getName(6).resolveBinding() ); + assertSame(f, col.getName(6).resolveBinding()); } // struct A { @@ -5122,42 +5122,42 @@ public class AST2CPPTests extends AST2BaseTest { // friend void A::f2(BT); // }; public void testBug90609() throws Exception { - IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); CPPNameCollector col = new CPPNameCollector(); - tu.accept( col ); + tu.accept(col); ITypedef AT = (ITypedef) col.getName(1).resolveBinding(); ICPPMethod f1 = (ICPPMethod) col.getName(2).resolveBinding(); ICPPMethod f2 = (ICPPMethod) col.getName(5).resolveBinding(); ITypedef BT = (ITypedef) col.getName(8).resolveBinding(); - assertSame( f1, col.getName(11).resolveBinding() ); - assertSame( AT, col.getName(12).resolveBinding() ); - assertSame( f2, col.getName(16).resolveBinding() ); - assertSame( BT, col.getName(17).resolveBinding() ); + assertSame(f1, col.getName(11).resolveBinding()); + assertSame(AT, col.getName(12).resolveBinding()); + assertSame(f2, col.getName(16).resolveBinding()); + assertSame(BT, col.getName(17).resolveBinding()); } // struct Except { int blah; }; // void f() { // try { } - // catch ( Except * e ) { + // catch (Except * e) { // e->blah; // } // } public void testBug103281() throws Exception { - IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); CPPNameCollector col = new CPPNameCollector(); - tu.accept( col ); + tu.accept(col); IField blah = (IField) col.getName(1).resolveBinding(); IVariable e = (IVariable) col.getName(4).resolveBinding(); - assertSame( e, col.getName(5).resolveBinding() ); - assertSame( blah, col.getName(6).resolveBinding() ); + assertSame(e, col.getName(5).resolveBinding()); + assertSame(blah, col.getName(6).resolveBinding()); } public void testBug78800() throws Exception { - parseAndCheckBindings( "class Matrix { public: Matrix & operator *(Matrix &); }; Matrix rotate, translate; Matrix transform = rotate * translate;" ); //$NON-NLS-1$ + parseAndCheckBindings("class Matrix { public: Matrix & operator *(Matrix &); }; Matrix rotate, translate; Matrix transform = rotate * translate;"); //$NON-NLS-1$ } // struct U { static int i; }; @@ -5168,43 +5168,43 @@ public class AST2CPPTests extends AST2BaseTest { // i; // } public void test10_2s3b() throws Exception { - IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); CPPNameCollector col = new CPPNameCollector(); - tu.accept( col ); + tu.accept(col); ICPPField i = (ICPPField) col.getName(1).resolveBinding(); ICPPUsingDeclaration using = (ICPPUsingDeclaration) col.getName(6).resolveBinding(); IBinding[] delegates = using.getDelegates(); - assertEquals( delegates.length, 1 ); - assertSame( i, delegates[0]); + assertEquals(delegates.length, 1); + assertSame(i, delegates[0]); - assertSame( i, col.getName(16).resolveBinding() ); + assertSame(i, col.getName(16).resolveBinding()); } // int f() { - // int x = 4; while( x < 10 ) blah: ++x; + // int x = 4; while(x < 10) blah: ++x; // } public void test1043290() throws Exception { - IASTTranslationUnit tu = parseAndCheckBindings(getAboveComment() ); + IASTTranslationUnit tu = parseAndCheckBindings(getAboveComment()); IASTFunctionDefinition fd = (IASTFunctionDefinition) tu.getDeclarations()[0]; IASTStatement [] statements = ((IASTCompoundStatement)fd.getBody()).getStatements(); IASTWhileStatement whileStmt = (IASTWhileStatement) statements[1]; IASTLabelStatement labelStmt = (IASTLabelStatement) whileStmt.getBody(); - assertTrue( labelStmt.getNestedStatement() instanceof IASTExpressionStatement ); + assertTrue(labelStmt.getNestedStatement() instanceof IASTExpressionStatement); IASTExpressionStatement es = (IASTExpressionStatement) labelStmt.getNestedStatement(); - assertTrue( es.getExpression() instanceof IASTUnaryExpression ); + assertTrue(es.getExpression() instanceof IASTUnaryExpression); } // int f() { // int i; - // do { ++i; } while( i < 10 ); + // do { ++i; } while(i < 10); // return 0; // } public void testBug104800() throws Exception { - IASTTranslationUnit tu = parseAndCheckBindings( getAboveComment() ); + IASTTranslationUnit tu = parseAndCheckBindings(getAboveComment()); IASTFunctionDefinition f = (IASTFunctionDefinition) tu.getDeclarations()[0]; IASTCompoundStatement body = (IASTCompoundStatement) f.getBody(); - assertEquals( body.getStatements().length, 3 ); + assertEquals(body.getStatements().length, 3); } public void testBug107150() throws Exception { @@ -5218,7 +5218,7 @@ public class AST2CPPTests extends AST2BaseTest { buffer.append("return 0;\r\n"); //$NON-NLS-1$ buffer.append("}\r\n"); //$NON-NLS-1$ IASTTranslationUnit tu = parse(buffer.toString(), ParserLanguage.CPP); - assertFalse( tu.getDeclarations()[1] instanceof IASTProblemDeclaration ); + assertFalse(tu.getDeclarations()[1] instanceof IASTProblemDeclaration); buffer = new StringBuffer(); buffer.append("#define FUNC_PROTOTYPE_PARAMS(list) list\n"); //$NON-NLS-1$ @@ -5230,7 +5230,7 @@ public class AST2CPPTests extends AST2BaseTest { buffer.append("return 0;\n"); //$NON-NLS-1$ buffer.append("}\n"); //$NON-NLS-1$ tu = parse(buffer.toString(), ParserLanguage.CPP); - assertFalse( tu.getDeclarations()[1] instanceof IASTProblemDeclaration ); + assertFalse(tu.getDeclarations()[1] instanceof IASTProblemDeclaration); } // class __attribute__((visibility("default"))) FooClass @@ -5241,7 +5241,7 @@ public class AST2CPPTests extends AST2BaseTest { // return 0; // } public void testBug108202() throws Exception { - parse( getAboveComment(), ParserLanguage.CPP, true, true ); + parse(getAboveComment(), ParserLanguage.CPP, true, true); } @@ -5252,7 +5252,7 @@ public class AST2CPPTests extends AST2BaseTest { // }; // int MyClass::static_field; public void testBug174791() throws Exception { - IASTTranslationUnit tu = parse( getAboveComment(), ParserLanguage.CPP, true, true ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); // check class IASTSimpleDeclaration sd = (IASTSimpleDeclaration) tu.getDeclarations()[0]; @@ -5290,7 +5290,7 @@ public class AST2CPPTests extends AST2BaseTest { // void nsSplit::a() { // } public void testBug180979() throws Exception { - IASTTranslationUnit tu = parse( getAboveComment(), ParserLanguage.CPP, true, true ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); // check class IASTFunctionDefinition fd = (IASTFunctionDefinition) tu.getDeclarations()[2]; @@ -5306,7 +5306,7 @@ public class AST2CPPTests extends AST2BaseTest { // _GLIBCXX_BEGIN_NAMESPACE(std) // } // end the namespace public void testBug195701() throws Exception { - parse( getAboveComment(), ParserLanguage.CPP, true, true ); + parse(getAboveComment(), ParserLanguage.CPP, true, true); } // class A { @@ -5317,14 +5317,14 @@ public class AST2CPPTests extends AST2BaseTest { // using A::operator*; // }; public void testBug178059() throws Exception { - parse( getAboveComment(), ParserLanguage.CPP, true, true ); + parse(getAboveComment(), ParserLanguage.CPP, true, true); } // void foo (void *p) throw () ; - // void bar (void *p) __attribute__ (( __nonnull__(1) )); - // void zot (void *p) throw () __attribute__ (( __nonnull__(1) )); + // void bar (void *p) __attribute__ ((__nonnull__(1))); + // void zot (void *p) throw () __attribute__ ((__nonnull__(1))); public void testBug179712() throws Exception { - parse( getAboveComment(), ParserLanguage.CPP, true, true ); + parse(getAboveComment(), ParserLanguage.CPP, true, true); } // namespace outer { @@ -5412,7 +5412,7 @@ public class AST2CPPTests extends AST2BaseTest { // fs(1); // } public void testReferencesOfUsingDecls() throws Exception { - IASTTranslationUnit tu = parse( getAboveComment(), ParserLanguage.CPP, true, true ); + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); IASTDeclaration[] decls = tu.getDeclarations(); ICPPASTNamespaceDefinition nsdef= (ICPPASTNamespaceDefinition) decls[0]; @@ -5517,7 +5517,7 @@ public class AST2CPPTests extends AST2BaseTest { // int foo2() { // int relayIndex = -1; // int numRelays = 0; - // if( relayIndex < 0 || relayIndex > numRelays ) + // if (relayIndex < 0 || relayIndex > numRelays) // return 0; // } public void testTemplateIDAmbiguity_Bug104706() throws Exception { @@ -5525,7 +5525,7 @@ public class AST2CPPTests extends AST2BaseTest { bh.assertNonProblem("relayIndex <", 10); bh.assertNonProblem("relayIndex >", 10); - bh.assertNonProblem("numRelays )", 9); + bh.assertNonProblem("numRelays)", 9); } // template @@ -7148,7 +7148,7 @@ public class AST2CPPTests extends AST2BaseTest { parseAndCheckBindings(code, ParserLanguage.CPP); } - // void f(int volatile * const * ) {} + // void f(int volatile * const *) {} // void f(int const volatile * const *) {} // void test() { // int ** x; @@ -7563,7 +7563,7 @@ public class AST2CPPTests extends AST2BaseTest { // class ULONGLONG { // public : // ULONGLONG (unsigned long long val) {} - // friend ULONGLONG operator ~ ( const ULONGLONG & ) { return 0; } + // friend ULONGLONG operator ~ (const ULONGLONG &) { return 0; } // }; // // int main() { @@ -7668,8 +7668,8 @@ public class AST2CPPTests extends AST2BaseTest { // class ULONGLONG { // public : - // ULONGLONG ( unsigned long long val ) {} - // friend bool operator == ( const ULONGLONG & , const int ) { return true; } + // ULONGLONG (unsigned long long val) {} + // friend bool operator == (const ULONGLONG & , const int) { return true; } // }; // enum E {A, B, C}; // int main() { @@ -8201,7 +8201,7 @@ public class AST2CPPTests extends AST2BaseTest { // int a = {1}; // complex z{1,2}; // new vector{"a", "b", "c", "d"}; // 4 string elements - // f( {"a","b"} ); // pass list of two elements + // f({"a","b"}); // pass list of two elements // int* e {}; // initialization to zero / null pointer // a = double{1}; // explicitly construct a double // return { "a" }; // return list of one element @@ -8236,18 +8236,18 @@ public class AST2CPPTests extends AST2BaseTest { // void f(std::initializer_list); // void g(A); // void test() { - // f( {1,2,3} ); // OK: f(initializer_list) identity conversion - // f( {'a','b'} ); // OK: f(initializer_list) integral promotion - // f( {1.0} ); // error: narrowing + // f({1,2,3}); // OK: f(initializer_list) identity conversion + // f({'a','b'}); // OK: f(initializer_list) integral promotion + // f({1.0}); // error: narrowing // A a{ 1.0,2.0 }; // OK, uses #1 // g({ "foo", "bar" }); // OK, uses #3 // } public void testListInitialization_302412b() throws Exception { String code= getAboveComment(); BindingAssertionHelper bh= new BindingAssertionHelper(code, true); - bh.assertNonProblem("f( {1,2,3} )", 1); - bh.assertNonProblem("f( {'a','b'} )", 1); - bh.assertProblem("f( {1.0} )", 1); + bh.assertNonProblem("f({1,2,3})", 1); + bh.assertNonProblem("f({'a','b'})", 1); + bh.assertProblem("f({1.0})", 1); bh.assertNonProblem("g({ \"foo\", \"bar\" })", 1); } @@ -8283,24 +8283,24 @@ public class AST2CPPTests extends AST2BaseTest { // void x(const X); // // void test() { - // e( { 'a', 'b' }); // OK: f(A(std::initializer_list)) user-defined conversion - // g( { 'a', 'b' }); // OK: g(B(int,double)) user-defined conversion - // g( { 1.0, 1.0 }); // error: narrowing - // f( { 'a', 'b' }); // error: ambiguous f(A) or f(B) - // h( { "foo" }); // OK: h(C(std::string("foo"))) - // i( { { 1, 2 }, { "bar" } }); // OK: i(D(A(std::initializer_list{1,2}),C(std::string("bar")))) + // e({ 'a', 'b' }); // OK: f(A(std::initializer_list)) user-defined conversion + // g({ 'a', 'b' }); // OK: g(B(int,double)) user-defined conversion + // g({ 1.0, 1.0 }); // error: narrowing + // f({ 'a', 'b' }); // error: ambiguous f(A) or f(B) + // h({ "foo" }); // OK: h(C(std::string("foo"))) + // i({ { 1, 2 }, { "bar" } }); // OK: i(D(A(std::initializer_list{1,2}),C(std::string("bar")))) // X x1; // x({x1}); // no matching constructor // } public void testListInitialization_302412c() throws Exception { String code= getAboveComment(); BindingAssertionHelper bh= new BindingAssertionHelper(code, true); - bh.assertNonProblem("e( { 'a', 'b' })", 1); - bh.assertNonProblem("g( { 'a', 'b' })", 1); - bh.assertProblem("g( { 1.0, 1.0 })", 1); - bh.assertProblem("f( { 'a', 'b' })", 1); - bh.assertNonProblem("h( {", 1); - bh.assertNonProblem("i( { { 1, 2 }, {", 1); + bh.assertNonProblem("e({ 'a', 'b' })", 1); + bh.assertNonProblem("g({ 'a', 'b' })", 1); + bh.assertProblem("g({ 1.0, 1.0 })", 1); + bh.assertProblem("f({ 'a', 'b' })", 1); + bh.assertNonProblem("h({", 1); + bh.assertNonProblem("i({ { 1, 2 }, {", 1); bh.assertProblem("x({x1})", 1); } @@ -8313,15 +8313,15 @@ public class AST2CPPTests extends AST2BaseTest { // }; // void f(A); // void test() { - // f( {'a', 'b'} ); // OK: f(A(int,double)) user-defined conversion - // f( {1.0} ); // narrowing not detected by cdt. + // f({'a', 'b'}); // OK: f(A(int,double)) user-defined conversion + // f({1.0}); // narrowing not detected by cdt. // } public void testListInitialization_302412d() throws Exception { String code= getAboveComment(); BindingAssertionHelper bh= new BindingAssertionHelper(code, true); - bh.assertNonProblem("f( {'a', 'b'} )", 1); + bh.assertNonProblem("f({'a', 'b'})", 1); // not detected by CDT - // bh.assertProblem("f( {1.0} )", 1); + // bh.assertProblem("f({1.0})", 1); } // namespace std { @@ -8332,18 +8332,18 @@ public class AST2CPPTests extends AST2BaseTest { // void test() { // g({1}); // same conversion as int to double // - // h( {'a'} ); // OK: same conversion as char to int - // h( {1.0} ); // error: narrowing - // h( { } ); // OK: identity conversion + // h({'a'}); // OK: same conversion as char to int + // h({1.0}); // error: narrowing + // h({ }); // OK: identity conversion // } public void testListInitialization_302412e() throws Exception { String code= getAboveComment(); BindingAssertionHelper bh= new BindingAssertionHelper(code, true); // not detected by CDT // bh.assertProblem("g({1})", 1); - bh.assertNonProblem("h( {'a'} )", 1); - bh.assertProblem("h( {1.0} )", 1); - bh.assertNonProblem("h( { } )", 1); + bh.assertNonProblem("h({'a'})", 1); + bh.assertProblem("h({1.0})", 1); + bh.assertNonProblem("h({ })", 1); } // namespace std { From 5af07f83aab45877f9d6705a7f9bcf60ee50cc94 Mon Sep 17 00:00:00 2001 From: Eugene Ostroukhov Date: Fri, 2 Sep 2011 09:48:10 +0200 Subject: [PATCH 21/29] Bug 309908 - [vm] VMDelta does not override setIndex() --- dsf/org.eclipse.cdt.dsf.ui/META-INF/MANIFEST.MF | 2 +- dsf/org.eclipse.cdt.dsf.ui/pom.xml | 2 +- .../src/org/eclipse/cdt/dsf/ui/viewmodel/VMDelta.java | 4 ++++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/dsf/org.eclipse.cdt.dsf.ui/META-INF/MANIFEST.MF b/dsf/org.eclipse.cdt.dsf.ui/META-INF/MANIFEST.MF index 7f877def795..0f1a6dd9492 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/META-INF/MANIFEST.MF +++ b/dsf/org.eclipse.cdt.dsf.ui/META-INF/MANIFEST.MF @@ -3,7 +3,7 @@ Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-Vendor: %providerName Bundle-SymbolicName: org.eclipse.cdt.dsf.ui;singleton:=true -Bundle-Version: 2.2.0.qualifier +Bundle-Version: 2.2.1.qualifier Bundle-Activator: org.eclipse.cdt.dsf.internal.ui.DsfUIPlugin Bundle-Localization: plugin Require-Bundle: org.eclipse.ui;bundle-version="3.5.0", diff --git a/dsf/org.eclipse.cdt.dsf.ui/pom.xml b/dsf/org.eclipse.cdt.dsf.ui/pom.xml index 0ab33256cae..caa00004dbb 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/pom.xml +++ b/dsf/org.eclipse.cdt.dsf.ui/pom.xml @@ -11,7 +11,7 @@ ../../pom.xml - 2.2.0-SNAPSHOT + 2.2.1-SNAPSHOT org.eclipse.cdt.dsf.ui eclipse-plugin diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMDelta.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMDelta.java index 8f6434a3068..b071beab1e0 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMDelta.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/ui/viewmodel/VMDelta.java @@ -364,4 +364,8 @@ public class VMDelta extends ModelDelta { } } + @Override + public void setIndex(final int index) { + fIndex = index; + } } From 4a04387f57b097ed68c01a72a0f8f2ec3dad1b22 Mon Sep 17 00:00:00 2001 From: Anton Leherbauer Date: Fri, 2 Sep 2011 11:19:58 +0200 Subject: [PATCH 22/29] Bug 354793 - References in Project key binding missing --- core/org.eclipse.cdt.ui/plugin.properties | 16 +++-- core/org.eclipse.cdt.ui/plugin.xml | 20 ++++++ .../ui/editor/AbstractCModelOutlinePage.java | 9 ++- .../editor/ICEditorActionDefinitionIds.java | 66 ++++++++++++------ .../actions/DeclarationsSearchGroup.java | 62 ++++++++++------- .../search/actions/ReferencesSearchGroup.java | 67 +++++++++++-------- .../search/actions/SelectionSearchGroup.java | 40 ++++++----- 7 files changed, 185 insertions(+), 95 deletions(-) diff --git a/core/org.eclipse.cdt.ui/plugin.properties b/core/org.eclipse.cdt.ui/plugin.properties index 9897cc2cbe5..356cea095b7 100644 --- a/core/org.eclipse.cdt.ui/plugin.properties +++ b/core/org.eclipse.cdt.ui/plugin.properties @@ -94,11 +94,19 @@ ActionDefinition.opendecl.description= Open an editor on the selected element's ActionDefinition.opencview.name= Show in C/C++ Project view ActionDefinition.opencview.description= Show the selected resource in the C/C++ Project view -ActionDefinition.finddecl.name= Find Declaration -ActionDefinition.finddecl.description= Find Declaration +ActionDefinition.finddecl.name= Declaration +ActionDefinition.finddecl.description= Search for declarations of the selected element in the workspace +ActionDefinition.finddecl.project.name= Declaration in Project +ActionDefinition.finddecl.project.description= Search for declarations of the selected element in the enclosing project +ActionDefinition.finddecl.workingset.name= Declaration in Working Set +ActionDefinition.finddecl.workingset.description= Search for declarations of the selected element in a working set -ActionDefinition.findrefs.name= Find References -ActionDefinition.findrefs.description= Find References +ActionDefinition.findrefs.name= References +ActionDefinition.findrefs.description= Search for references to the selected element in the workspace +ActionDefinition.findrefs.project.name= References in Project +ActionDefinition.findrefs.project.description= Search for references to the selected element in the enclosing project +ActionDefinition.findrefs.workingset.name= References in Working Set +ActionDefinition.findrefs.workingset.description= Search for references to the selected element in a working set ActionDefinition.openCallHierarchy.name= Open Call Hierarchy ActionDefinition.openCallHierarchy.description= Open the call hierarchy for the selected element diff --git a/core/org.eclipse.cdt.ui/plugin.xml b/core/org.eclipse.cdt.ui/plugin.xml index 8bdb81c1c9c..b6fcfa05921 100644 --- a/core/org.eclipse.cdt.ui/plugin.xml +++ b/core/org.eclipse.cdt.ui/plugin.xml @@ -2378,11 +2378,31 @@ categoryId="org.eclipse.cdt.ui.category.source" name="%ActionDefinition.finddecl.name" id="org.eclipse.cdt.ui.search.finddecl"/> + + + + add block comment action * (value "org.eclipse.cdt.ui.edit.text.c.add.block.comment"). @@ -48,20 +48,20 @@ public interface ICEditorActionDefinitionIds extends ITextEditorActionDefinition * @since 3.0 */ public static final String REMOVE_BLOCK_COMMENT= "org.eclipse.cdt.ui.edit.text.c.remove.block.comment"; //$NON-NLS-1$ - + /** * Action definition ID of the source -> join lines action * (value "org.eclipse.cdt.ui.edit.text.c.join.lines"). * @since 3.0.2 */ public static final String JOIN_LINES= "org.eclipse.cdt.ui.edit.text.c.join.lines"; //$NON-NLS-1$ - + /** * Action definition ID of the source -> indent action * (value "org.eclipse.cdt.ui.edit.text.c.indent"). */ public static final String INDENT = "org.eclipse.cdt.ui.edit.text.c.indent"; //$NON-NLS-1$ - + /** * Action definition ID of the source -> format action * (value "org.eclipse.cdt.ui.edit.text.c.format"). @@ -72,20 +72,20 @@ public interface ICEditorActionDefinitionIds extends ITextEditorActionDefinition * Action definition ID of the source -> add include action * (value "org.eclipse.cdt.ui.edit.text.c.add.include"). */ - public static final String ADD_INCLUDE= "org.eclipse.cdt.ui.edit.text.c.add.include"; //$NON-NLS-1$ + public static final String ADD_INCLUDE= "org.eclipse.cdt.ui.edit.text.c.add.include"; //$NON-NLS-1$ /** * Action definition ID of the open declaration action * (value "org.eclipse.cdt.ui.edit.opendecl"). */ public static final String OPEN_DECL= "org.eclipse.cdt.ui.edit.opendecl"; //$NON-NLS-1$ - + /** * Action definition ID of the show in C/C++ Projects View action * (value "org.eclipse.cdt.ui.edit.opencview"). */ public static final String OPEN_CVIEW= "org.eclipse.cdt.ui.edit.opencview"; //$NON-NLS-1$ - + /** * Action definition ID of the refactor -> rename element action * (value "org.eclipse.cdt.ui.edit.text.rename.element"). @@ -103,7 +103,7 @@ public interface ICEditorActionDefinitionIds extends ITextEditorActionDefinition * (value "org.eclipse.cdt.ui.refactor.extract.local.variable"). */ public static final String EXTRACT_LOCAL_VARIABLE= "org.eclipse.cdt.ui.refactor.extract.local.variable"; //$NON-NLS-1$ - + /** * Action definition ID of the refactor -> extract function action (value * "org.eclipse.cdt.ui.refactor.extract.function"). @@ -121,7 +121,7 @@ public interface ICEditorActionDefinitionIds extends ITextEditorActionDefinition * (value "org.eclipse.cdt.ui.refactor.hide.method"). */ public static final String HIDE_METHOD= "org.eclipse.cdt.ui.refactor.hide.method"; //$NON-NLS-1$ - + /** * Action definition ID of the refactor -> implement method action * (value "org.eclipse.cdt.ui.refactor.implement.method"). @@ -139,24 +139,48 @@ public interface ICEditorActionDefinitionIds extends ITextEditorActionDefinition * (value "org.eclipse.cdt.ui.edit.text.undo.action"). */ public static final String UNDO_ACTION= "org.eclipse.cdt.ui.edit.text.undo.action"; //$NON-NLS-1$ - + /** * Action definition ID of the refactor -> redo action * (value "org.eclipse.cdt.ui.edit.text.redo.action"). */ - public static final String REDO_ACTION= "org.eclipse.cdt.ui.edit.text.redo.action"; //$NON-NLS-1$ + public static final String REDO_ACTION= "org.eclipse.cdt.ui.edit.text.redo.action"; //$NON-NLS-1$ /** * Action definition ID of the find references in workspace action * (value "org.eclipse.cdt.ui.search.findrefs"). */ - public static final String FIND_REFS= "org.eclipse.cdt.ui.search.findrefs"; //$NON-NLS-1$ - + public static final String FIND_REFS= "org.eclipse.cdt.ui.search.findrefs"; //$NON-NLS-1$ + + /** + * Action definition ID of the find references in project action + * (value "org.eclipse.cdt.ui.search.findrefs.project"). + */ + public static final String FIND_REFS_PROJECT= "org.eclipse.cdt.ui.search.findrefs.project"; //$NON-NLS-1$ + + /** + * Action definition ID of the find references in working set action + * (value "org.eclipse.cdt.ui.search.findrefs.workingset"). + */ + public static final String FIND_REFS_WORKING_SET= "org.eclipse.cdt.ui.search.findrefs.workingset"; //$NON-NLS-1$ + /** * Action definition ID of the find declarations in workspace action * (value "org.eclipse.cdt.ui.search.finddecl"). */ - public static final String FIND_DECL= "org.eclipse.cdt.ui.search.finddecl"; //$NON-NLS-1$ + public static final String FIND_DECL= "org.eclipse.cdt.ui.search.finddecl"; //$NON-NLS-1$ + + /** + * Action definition ID of the find declarations in project action + * (value "org.eclipse.cdt.ui.search.finddecl.project"). + */ + public static final String FIND_DECL_PROJECT= "org.eclipse.cdt.ui.search.finddecl.project"; //$NON-NLS-1$ + + /** + * Action definition ID of the find declarations in working set action + * (value "org.eclipse.cdt.ui.search.finddecl.workingset"). + */ + public static final String FIND_DECL_WORKING_SET= "org.eclipse.cdt.ui.search.finddecl.workingset"; //$NON-NLS-1$ /** * Action definition ID of the navigate -> open type hierarchy action @@ -218,18 +242,18 @@ public interface ICEditorActionDefinitionIds extends ITextEditorActionDefinition * Action definition ID for goto next bookmark action * (value "org.eclipse.cdt.ui.edit.text.c.goto.next.bookmark"). */ - public static final String GOTO_NEXT_BOOKMARK = "org.eclipse.cdt.ui.edit.text.c.goto.next.bookmark"; //$NON-NLS-1$ + public static final String GOTO_NEXT_BOOKMARK = "org.eclipse.cdt.ui.edit.text.c.goto.next.bookmark"; //$NON-NLS-1$ /** * Action definition ID for find word action * (value "org.eclipse.cdt.ui.edit.text.c.find.word"). */ - public static final String FIND_WORD = "org.eclipse.cdt.ui.edit.text.c.find.word"; //$NON-NLS-1$ + public static final String FIND_WORD = "org.eclipse.cdt.ui.edit.text.c.find.word"; //$NON-NLS-1$ /** * Action definition ID for toggle source/header action. * (value "org.eclipse.cdt.ui.edit.text.c.toggle.source.header") - * + * * @since 4.0 */ public static final String TOGGLE_SOURCE_HEADER = "org.eclipse.cdt.ui.edit.text.c.toggle.source.header"; //$NON-NLS-1$ @@ -260,19 +284,19 @@ public interface ICEditorActionDefinitionIds extends ITextEditorActionDefinition * (value "org.eclipse.cdt.ui.edit.text.c.select.enclosing"). */ public static final String SELECT_ENCLOSING = "org.eclipse.cdt.ui.edit.text.c.select.enclosing"; //$NON-NLS-1$ - + /** * Action definition ID of the edit -> select next action * (value "org.eclipse.cdt.ui.edit.text.c.select.next"). */ public static final String SELECT_NEXT = "org.eclipse.cdt.ui.edit.text.c.select.next"; //$NON-NLS-1$ - + /** * Action definition ID of the edit -> select previous action * (value "org.eclipse.cdt.ui.edit.text.c.select.previous"). */ public static final String SELECT_PREVIOUS = "org.eclipse.cdt.ui.edit.text.c.select.previous"; //$NON-NLS-1$ - + /** * Action definition ID of the edit -> select restore last action * (value "org.eclipse.cdt.ui.edit.text.c.select.last"). diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/DeclarationsSearchGroup.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/DeclarationsSearchGroup.java index b4bf6344960..6cfedede9f6 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/DeclarationsSearchGroup.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/DeclarationsSearchGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2008 IBM Corporation and others. + * Copyright (c) 2004, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -21,6 +21,7 @@ import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.search.ui.IContextMenuConstants; +import org.eclipse.ui.IActionBars; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.IWorkingSet; import org.eclipse.ui.actions.ActionGroup; @@ -35,18 +36,21 @@ import org.eclipse.cdt.internal.ui.search.CSearchUtil; public class DeclarationsSearchGroup extends ActionGroup { - + private CEditor fEditor; private IWorkbenchSite fSite; - + private FindDeclarationsAction fFindDeclarationsAction; private FindDeclarationsProjectAction fFindDeclarationsProjectAction; private FindDeclarationsInWorkingSetAction fFindDeclarationsInWorkingSetAction; - + public DeclarationsSearchGroup(IWorkbenchSite site) { fFindDeclarationsAction= new FindDeclarationsAction(site); + fFindDeclarationsAction.setActionDefinitionId(ICEditorActionDefinitionIds.FIND_DECL); fFindDeclarationsProjectAction = new FindDeclarationsProjectAction(site); + fFindDeclarationsProjectAction.setActionDefinitionId(ICEditorActionDefinitionIds.FIND_DECL_PROJECT); fFindDeclarationsInWorkingSetAction = new FindDeclarationsInWorkingSetAction(site,null); + fFindDeclarationsInWorkingSetAction.setActionDefinitionId(ICEditorActionDefinitionIds.FIND_DECL_WORKING_SET); fSite = site; } /** @@ -57,45 +61,53 @@ public class DeclarationsSearchGroup extends ActionGroup { fFindDeclarationsAction= new FindDeclarationsAction(editor); fFindDeclarationsAction.setActionDefinitionId(ICEditorActionDefinitionIds.FIND_DECL); - if (editor != null){ - editor.setAction(ICEditorActionDefinitionIds.FIND_DECL, fFindDeclarationsAction); - } - + editor.setAction(ICEditorActionDefinitionIds.FIND_DECL, fFindDeclarationsAction); + fFindDeclarationsProjectAction = new FindDeclarationsProjectAction(editor); - + fFindDeclarationsProjectAction.setActionDefinitionId(ICEditorActionDefinitionIds.FIND_DECL_PROJECT); + editor.setAction(ICEditorActionDefinitionIds.FIND_DECL_PROJECT, fFindDeclarationsProjectAction); fFindDeclarationsInWorkingSetAction = new FindDeclarationsInWorkingSetAction(editor,null); + fFindDeclarationsInWorkingSetAction.setActionDefinitionId(ICEditorActionDefinitionIds.FIND_DECL_WORKING_SET); + editor.setAction(ICEditorActionDefinitionIds.FIND_DECL_WORKING_SET, fFindDeclarationsInWorkingSetAction); } - /* + /* * Method declared on ActionGroup. */ @Override public void fillContextMenu(IMenuManager menu) { super.fillContextMenu(menu); - + IMenuManager incomingMenu = menu; - - IMenuManager declarationsMenu = new MenuManager(CSearchMessages.group_declarations, IContextMenuConstants.GROUP_SEARCH); - + + IMenuManager declarationsMenu = new MenuManager(CSearchMessages.group_declarations, IContextMenuConstants.GROUP_SEARCH); + if (fEditor != null){ - menu.appendToGroup(ITextEditorActionConstants.GROUP_FIND, declarationsMenu); + menu.appendToGroup(ITextEditorActionConstants.GROUP_FIND, declarationsMenu); } else { incomingMenu.appendToGroup(IContextMenuConstants.GROUP_SEARCH, declarationsMenu); } incomingMenu = declarationsMenu; - + FindAction[] actions = getWorkingSetActions(); incomingMenu.add(fFindDeclarationsAction); incomingMenu.add(fFindDeclarationsProjectAction); incomingMenu.add(fFindDeclarationsInWorkingSetAction); - + for (FindAction action : actions) { incomingMenu.add(action); } - } - + } + + @Override + public void fillActionBars(IActionBars actionBars) { + actionBars.setGlobalActionHandler(ICEditorActionDefinitionIds.FIND_DECL, fFindDeclarationsAction); + actionBars.setGlobalActionHandler(ICEditorActionDefinitionIds.FIND_DECL_PROJECT, fFindDeclarationsProjectAction); + actionBars.setGlobalActionHandler(ICEditorActionDefinitionIds.FIND_DECL_WORKING_SET, fFindDeclarationsInWorkingSetAction); + } + private FindAction[] getWorkingSetActions() { ArrayList actions= new ArrayList(CSearchUtil.LRU_WORKINGSET_LIST_SIZE); - + Iterator iter= CSearchUtil.getLRUWorkingSets().iterator(); while (iter.hasNext()) { IWorkingSet[] workingSets= iter.next(); @@ -104,10 +116,10 @@ public class DeclarationsSearchGroup extends ActionGroup { action= new WorkingSetFindAction(fEditor, new FindDeclarationsInWorkingSetAction(fEditor, workingSets), CSearchUtil.toString(workingSets)); else action= new WorkingSetFindAction(fSite, new FindDeclarationsInWorkingSetAction(fSite, workingSets), CSearchUtil.toString(workingSets)); - + actions.add(action); } - + return actions.toArray(new FindAction[actions.size()]); } public static boolean canActionBeAdded(ISelection selection) { @@ -116,7 +128,7 @@ public class DeclarationsSearchGroup extends ActionGroup { } return getElement(selection) != null; } - + private static ICElement getElement(ISelection sel) { if (!sel.isEmpty() && sel instanceof IStructuredSelection) { List list= ((IStructuredSelection)sel).toList(); @@ -129,8 +141,8 @@ public class DeclarationsSearchGroup extends ActionGroup { } return null; } - - /* + + /* * Overrides method declared in ActionGroup */ @Override diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/ReferencesSearchGroup.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/ReferencesSearchGroup.java index 1a1d1bb9780..df863fdca63 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/ReferencesSearchGroup.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/ReferencesSearchGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2008 IBM Corporation and others. + * Copyright (c) 2004, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -16,6 +16,7 @@ import java.util.Iterator; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.search.ui.IContextMenuConstants; +import org.eclipse.ui.IActionBars; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.IWorkingSet; import org.eclipse.ui.actions.ActionGroup; @@ -31,66 +32,78 @@ public class ReferencesSearchGroup extends ActionGroup { private FindRefsAction fFindRefsAction; private FindRefsProjectAction fFindRefsProjectAction; private FindRefsInWorkingSetAction fFindRefsInWorkingSetAction; - + private CEditor fEditor; private IWorkbenchSite fSite; - + public ReferencesSearchGroup(IWorkbenchSite site) { fFindRefsAction= new FindRefsAction(site); + fFindRefsAction.setActionDefinitionId(ICEditorActionDefinitionIds.FIND_REFS); fFindRefsProjectAction = new FindRefsProjectAction(site); + fFindRefsProjectAction.setActionDefinitionId(ICEditorActionDefinitionIds.FIND_REFS_PROJECT); fFindRefsInWorkingSetAction = new FindRefsInWorkingSetAction(site, null); + fFindRefsInWorkingSetAction.setActionDefinitionId(ICEditorActionDefinitionIds.FIND_REFS_WORKING_SET); fSite=site; } - + /** * @param editor */ public ReferencesSearchGroup(CEditor editor) { fEditor = editor; - + fFindRefsAction= new FindRefsAction(editor); fFindRefsAction.setActionDefinitionId(ICEditorActionDefinitionIds.FIND_REFS); - if (editor != null){ - editor.setAction(ICEditorActionDefinitionIds.FIND_REFS, fFindRefsAction); - } + editor.setAction(ICEditorActionDefinitionIds.FIND_REFS, fFindRefsAction); fFindRefsProjectAction = new FindRefsProjectAction(editor); + fFindRefsProjectAction.setActionDefinitionId(ICEditorActionDefinitionIds.FIND_REFS_PROJECT); + editor.setAction(ICEditorActionDefinitionIds.FIND_REFS_PROJECT, fFindRefsProjectAction); fFindRefsInWorkingSetAction = new FindRefsInWorkingSetAction(editor, null); + fFindRefsInWorkingSetAction.setActionDefinitionId(ICEditorActionDefinitionIds.FIND_REFS_WORKING_SET); + editor.setAction(ICEditorActionDefinitionIds.FIND_REFS_WORKING_SET, fFindRefsInWorkingSetAction); } - - /* + + /* * Method declared on ActionGroup. */ @Override public void fillContextMenu(IMenuManager menu) { - + super.fillContextMenu(menu); - + IMenuManager incomingMenu = menu; - - IMenuManager refsMenu = new MenuManager(CSearchMessages.group_references, IContextMenuConstants.GROUP_SEARCH); - + + IMenuManager refsMenu = new MenuManager(CSearchMessages.group_references, IContextMenuConstants.GROUP_SEARCH); + if (fEditor != null){ - menu.appendToGroup(ITextEditorActionConstants.GROUP_FIND, refsMenu); + menu.appendToGroup(ITextEditorActionConstants.GROUP_FIND, refsMenu); } else { incomingMenu.appendToGroup(IContextMenuConstants.GROUP_SEARCH, refsMenu); } - + incomingMenu = refsMenu; - + FindAction[] actions = getWorkingSetActions(); incomingMenu.add(fFindRefsAction); incomingMenu.add(fFindRefsProjectAction); incomingMenu.add(fFindRefsInWorkingSetAction); - + for (FindAction action : actions) { incomingMenu.add(action); } - - } - + + } + + @Override + public void fillActionBars(IActionBars actionBars) { + actionBars.setGlobalActionHandler(ICEditorActionDefinitionIds.FIND_REFS, fFindRefsAction); + actionBars.setGlobalActionHandler(ICEditorActionDefinitionIds.FIND_REFS_PROJECT, fFindRefsProjectAction); + actionBars.setGlobalActionHandler(ICEditorActionDefinitionIds.FIND_REFS, fFindRefsAction); + } + private FindAction[] getWorkingSetActions() { ArrayList actions= new ArrayList(CSearchUtil.LRU_WORKINGSET_LIST_SIZE); - + Iterator iter= CSearchUtil.getLRUWorkingSets().iterator(); while (iter.hasNext()) { IWorkingSet[] workingSets= iter.next(); @@ -99,14 +112,14 @@ public class ReferencesSearchGroup extends ActionGroup { action= new WorkingSetFindAction(fEditor, new FindRefsInWorkingSetAction(fEditor, workingSets), CSearchUtil.toString(workingSets)); else action= new WorkingSetFindAction(fSite, new FindRefsInWorkingSetAction(fSite, workingSets), CSearchUtil.toString(workingSets)); - + actions.add(action); } - + return actions.toArray(new FindAction[actions.size()]); } - - /* + + /* * Overrides method declared in ActionGroup */ @Override diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/SelectionSearchGroup.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/SelectionSearchGroup.java index 4b90bf40bf0..82a91226ff1 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/SelectionSearchGroup.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/SelectionSearchGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2008 IBM Corporation and others. + * Copyright (c) 2004, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -12,10 +12,12 @@ package org.eclipse.cdt.internal.ui.search.actions; import java.util.List; +import org.eclipse.core.runtime.Assert; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.ui.IActionBars; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.part.Page; @@ -25,16 +27,16 @@ import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.internal.ui.editor.CEditor; public class SelectionSearchGroup extends ActionGroup { - + private CEditor fEditor; - + private DeclarationsSearchGroup fDeclarationsSearchGroup; private ReferencesSearchGroup fRefSearchGroup; - + public SelectionSearchGroup(CEditor editor){ - //TODO: Assert editor not null + Assert.isNotNull(editor); fEditor= editor; - + fDeclarationsSearchGroup= new DeclarationsSearchGroup(fEditor); fRefSearchGroup = new ReferencesSearchGroup(fEditor); } @@ -51,24 +53,32 @@ public class SelectionSearchGroup extends ActionGroup { fDeclarationsSearchGroup= new DeclarationsSearchGroup(site); fRefSearchGroup = new ReferencesSearchGroup(site); } - /* + /* * Method declared on ActionGroup. */ @Override public void fillContextMenu(IMenuManager menu) { super.fillContextMenu(menu); - + fDeclarationsSearchGroup.fillContextMenu(menu); fRefSearchGroup.fillContextMenu(menu); - } - + } + + @Override + public void fillActionBars(IActionBars actionBars) { + if (fEditor == null) { + fDeclarationsSearchGroup.fillActionBars(actionBars); + fRefSearchGroup.fillActionBars(actionBars); + } + } + public static boolean canActionBeAdded(ISelection selection) { if(selection instanceof ITextSelection) { return (((ITextSelection)selection).getLength() > 0); } return getElement(selection) != null; } - + private static ICElement getElement(ISelection sel) { if (!sel.isEmpty() && sel instanceof IStructuredSelection) { List list= ((IStructuredSelection)sel).toList(); @@ -81,7 +91,7 @@ public class SelectionSearchGroup extends ActionGroup { } return null; } - + /* (non-Javadoc) * @see org.eclipse.ui.actions.ActionGroup#dispose() */ @@ -91,14 +101,14 @@ public class SelectionSearchGroup extends ActionGroup { fDeclarationsSearchGroup.dispose(); fDeclarationsSearchGroup= null; } - + if (fRefSearchGroup != null) { fRefSearchGroup.dispose(); fRefSearchGroup= null; } - + fEditor= null; - + super.dispose(); } } From 59d5eafbf610a5afab095923dcd02cbefffe1d02 Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Fri, 2 Sep 2011 14:26:08 -0400 Subject: [PATCH 23/29] Bug 355833: Thread filter effectively disables a breakpoint at the next session --- .../META-INF/MANIFEST.MF | 2 +- dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/pom.xml | 2 +- .../CBreakpointGdbThreadFilterPage.java | 10 +- .../ui/breakpoints/GdbThreadFilterEditor.java | 22 ++-- .../CBreakpointGdbThreadsFilterExtension.java | 4 +- .../dsf/mi/service/MIBreakpointsManager.java | 110 ++++++++++++------ dsf/org.eclipse.cdt.dsf/pom.xml | 2 +- .../service/IDsfBreakpointExtension.java | 61 +++++++++- 8 files changed, 146 insertions(+), 67 deletions(-) diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/META-INF/MANIFEST.MF b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/META-INF/MANIFEST.MF index 7094644dc3c..ec4f8c32b5d 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/META-INF/MANIFEST.MF +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/META-INF/MANIFEST.MF @@ -3,7 +3,7 @@ Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-Vendor: %providerName Bundle-SymbolicName: org.eclipse.cdt.dsf.gdb.ui;singleton:=true -Bundle-Version: 2.2.0.qualifier +Bundle-Version: 2.3.0.qualifier Bundle-Activator: org.eclipse.cdt.dsf.gdb.internal.ui.GdbUIPlugin Bundle-Localization: plugin Require-Bundle: org.eclipse.ui, diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/pom.xml b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/pom.xml index be8ecae0eb6..e21b2378937 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/pom.xml +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/pom.xml @@ -11,7 +11,7 @@ ../../pom.xml - 2.2.0-SNAPSHOT + 2.3.0-SNAPSHOT org.eclipse.cdt.dsf.gdb.ui eclipse-plugin diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/CBreakpointGdbThreadFilterPage.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/CBreakpointGdbThreadFilterPage.java index 9be5996014e..f519b8e2031 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/CBreakpointGdbThreadFilterPage.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/CBreakpointGdbThreadFilterPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2009 QNX Software Systems and others. + * Copyright (c) 2004, 2011 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -7,10 +7,12 @@ * * Contributors: * QNX Software Systems - Initial API and implementation + * Marc Khouzam (Ericsson) - Use IDsfBreakpointExtension directly (Bug 355833) *******************************************************************************/ package org.eclipse.cdt.dsf.gdb.internal.ui.breakpoints; import org.eclipse.cdt.debug.core.model.ICBreakpoint; +import org.eclipse.cdt.dsf.debug.service.IDsfBreakpointExtension; import org.eclipse.cdt.dsf.gdb.breakpoints.CBreakpointGdbThreadsFilterExtension; import org.eclipse.cdt.dsf.gdb.launching.GdbLaunchDelegate; import org.eclipse.core.runtime.CoreException; @@ -44,12 +46,12 @@ public class CBreakpointGdbThreadFilterPage extends PropertyPage { return (ICBreakpoint)getElement().getAdapter(ICBreakpoint.class); } - public CBreakpointGdbThreadsFilterExtension getFilterExtension() { + public IDsfBreakpointExtension getFilterExtension() { ICBreakpoint bp = getBreakpoint(); if (bp != null) { try { - CBreakpointGdbThreadsFilterExtension filter = - (CBreakpointGdbThreadsFilterExtension) bp.getExtension( + IDsfBreakpointExtension filter = + (IDsfBreakpointExtension) bp.getExtension( GdbLaunchDelegate.GDB_DEBUG_MODEL_ID, CBreakpointGdbThreadsFilterExtension.class); filter.initialize(bp); return filter; diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/GdbThreadFilterEditor.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/GdbThreadFilterEditor.java index 22cbc9cbfe5..120215ac8c7 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/GdbThreadFilterEditor.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/GdbThreadFilterEditor.java @@ -24,6 +24,7 @@ import org.eclipse.cdt.dsf.concurrent.ImmediateExecutor; import org.eclipse.cdt.dsf.concurrent.Query; import org.eclipse.cdt.dsf.datamodel.DMContexts; import org.eclipse.cdt.dsf.datamodel.IDMContext; +import org.eclipse.cdt.dsf.debug.service.IDsfBreakpointExtension; import org.eclipse.cdt.dsf.debug.service.IProcesses; import org.eclipse.cdt.dsf.debug.service.IProcesses.IProcessDMContext; import org.eclipse.cdt.dsf.debug.service.IProcesses.IThreadDMContext; @@ -32,7 +33,6 @@ import org.eclipse.cdt.dsf.debug.service.IRunControl; import org.eclipse.cdt.dsf.debug.service.IRunControl.IContainerDMContext; import org.eclipse.cdt.dsf.debug.service.IRunControl.IExecutionDMContext; import org.eclipse.cdt.dsf.debug.service.command.ICommandControlService; -import org.eclipse.cdt.dsf.gdb.breakpoints.CBreakpointGdbThreadsFilterExtension; import org.eclipse.cdt.dsf.gdb.internal.ui.GdbUIPlugin; import org.eclipse.cdt.dsf.gdb.launching.GdbLaunch; import org.eclipse.cdt.dsf.mi.service.IMIExecutionDMContext; @@ -302,27 +302,19 @@ public class GdbThreadFilterEditor { * a thread filter in a given thread, that thread should be checked. */ protected void setInitialCheckedState() { - CBreakpointGdbThreadsFilterExtension filterExtension = fPage.getFilterExtension(); + IDsfBreakpointExtension filterExtension = fPage.getFilterExtension(); try { IContainerDMContext[] targets = filterExtension.getTargetFilters(); - // TODO: Hack to properly initialize the target/thread list - // Should be done in filterExtension.initialize() but we don't know - // how to get the target list from an ICBreakpoint... - if (targets.length == 0) { - targets = getDebugTargets(); - for (IContainerDMContext target : targets) { - filterExtension.setTargetFilter(target); - } - } - // TODO: End of hack - for (int i = 0; i < targets.length; i++) { IExecutionDMContext[] filteredThreads = filterExtension.getThreadFilters(targets[i]); if (filteredThreads != null) { - for (int j = 0; j < filteredThreads.length; ++j) + for (int j = 0; j < filteredThreads.length; ++j) { + // Mark this thread as selected fCheckHandler.checkThread(filteredThreads[j], true); + } } else { + // Mark the entire process as selected fCheckHandler.checkTarget(targets[i], true); } } @@ -332,7 +324,7 @@ public class GdbThreadFilterEditor { } protected void doStore() { - CBreakpointGdbThreadsFilterExtension filterExtension = fPage.getFilterExtension(); + IDsfBreakpointExtension filterExtension = fPage.getFilterExtension(); IContainerDMContext[] targets = getDebugTargets(); for (int i = 0; i < targets.length; ++i) { try { diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/breakpoints/CBreakpointGdbThreadsFilterExtension.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/breakpoints/CBreakpointGdbThreadsFilterExtension.java index 3b61d811920..74d59bb728d 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/breakpoints/CBreakpointGdbThreadsFilterExtension.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/breakpoints/CBreakpointGdbThreadsFilterExtension.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2009 Wind River Systems and others. + * Copyright (c) 2007, 2011 Wind River Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -35,8 +35,6 @@ public class CBreakpointGdbThreadsFilterExtension implements IDsfBreakpointExten * @see org.eclipse.cdt.debug.core.model.ICBreakpointExtension#initialize(org.eclipse.cdt.debug.core.model.ICBreakpoint) */ public void initialize(ICBreakpoint breakpoint) { - // TODO: Initialize fFilteredThreadsByTarget with current IContainerDMContext[] - // TODO: IRunControl? } /* (non-Javadoc) diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/mi/service/MIBreakpointsManager.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/mi/service/MIBreakpointsManager.java index 8350f969927..40010e2f2ab 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/mi/service/MIBreakpointsManager.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/mi/service/MIBreakpointsManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2010 Wind River and others. + * Copyright (c) 2007, 2011 Wind River 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 @@ -11,6 +11,7 @@ * Ericsson - Added breakpoint filter support * Ericsson - Re-factored the service and put a few comments * Ericsson - Added Action support + * Marc Khouzam (Ericsson) - Fix support for thread filter (Bug 355833) *******************************************************************************/ package org.eclipse.cdt.dsf.mi.service; @@ -422,7 +423,24 @@ public class MIBreakpointsManager extends AbstractDsfService implements IBreakpo // Upon determining the debuggerPath, the breakpoint is installed determineDebuggerPath(dmc, attributes, new RequestMonitor(getExecutor(), countingRm) { @Override - protected void handleSuccess() { + protected void handleSuccess() { + // Before installing a breakpoint, set the target filter for that target. + // Even if the breakpoint is disabled when we start, the target filter + // can be accessed by the user through the breakpoint properties UI, so + // we must set it right now. + // This is the reason we don't do this in 'installBreakpoint', which is not + // called right away if the breakpoint is disabled. + try { + IContainerDMContext containerDmc = DMContexts.getAncestorOfType(dmc, IContainerDMContext.class); + IDsfBreakpointExtension filterExt = getFilterExtension(breakpoint); + if (filterExt.getThreadFilters(containerDmc) == null) { + // Do this only if there wasn't already an entry, or else we would + // erase the content of that previous entry. + filterExt.setTargetFilter(containerDmc); + } + } catch (CoreException e) { + } + // Install only if the breakpoint is enabled at startup (Bug261082) // Note that Tracepoints are not affected by "skip-all" boolean bpEnabled = attributes.get(ICBreakpoint.ENABLED).equals(true) && @@ -718,6 +736,14 @@ public class MIBreakpointsManager extends AbstractDsfService implements IBreakpo final Map> threadsIDs = fBreakpointThreads.get(dmc); assert threadsIDs != null; + // Remove any target filter (if any) + try { + IContainerDMContext containerDmc = DMContexts.getAncestorOfType(dmc, IContainerDMContext.class); + getFilterExtension(breakpoint).removeTargetFilter(containerDmc); + } + catch( CoreException e ) { + } + // Remove breakpoint problem marker (if any) removeBreakpointProblemMarker(breakpoint); @@ -1127,6 +1153,18 @@ public class MIBreakpointsManager extends AbstractDsfService implements IBreakpo new RequestMonitor(getExecutor(), countingRm) { @Override protected void handleSuccess() { + // For a new breakpoint, set the target filter. + try { + IContainerDMContext containerDmc = DMContexts.getAncestorOfType(dmc, IContainerDMContext.class); + IDsfBreakpointExtension filterExt = getFilterExtension((ICBreakpoint)breakpoint); + if (filterExt.getThreadFilters(containerDmc) == null) { + // Do this only if there wasn't already an entry, or else we would + // erase the content of that previous entry. + filterExt.setTargetFilter(containerDmc); + } + } catch (CoreException e) { + } + installBreakpoint(dmc, (ICBreakpoint) breakpoint, attrs, countingRm); } @@ -1372,15 +1410,28 @@ public class MIBreakpointsManager extends AbstractDsfService implements IBreakpo for (IBreakpointsTargetDMContext ctx : fPlatformBPs.keySet()) { Map> breakpoints = fPlatformBPs.get(ctx); clearBreakpointStatus(breakpoints.keySet().toArray(new ICBreakpoint[breakpoints.size()]), ctx); + + // Also clear any target filter since we will not be calling uninstallBreakpoint() which + // usually does that work. + IContainerDMContext dmc = DMContexts.getAncestorOfType(ctx, IContainerDMContext.class); + clearTargetFilter(dmc, breakpoints.keySet()); } // This will prevent Shutdown() from trying to remove bps from a // backend that has already shutdown fPlatformBPs.clear(); } - /////////////////////////////////////////////////////////////////////////// - // Breakpoint status handling functions - /////////////////////////////////////////////////////////////////////////// + private void clearTargetFilter(IContainerDMContext containerDmc, Set breakpoints) { + // Remove any target filter (if any) + try { + for (ICBreakpoint bp : breakpoints) { + getFilterExtension(bp).removeTargetFilter(containerDmc); + } + } + catch( CoreException e ) { + } + } + /** * @param bps @@ -1651,41 +1702,28 @@ public class MIBreakpointsManager extends AbstractDsfService implements IBreakpo * @return */ private Set extractThreads(IBreakpointsTargetDMContext context, ICBreakpoint breakpoint) { - Set results = new HashSet(); + Set results = new HashSet(); + + IExecutionDMContext[] threads = null; + try { + IContainerDMContext containerDmc = DMContexts.getAncestorOfType(context, IContainerDMContext.class); + threads = getFilterExtension(breakpoint).getThreadFilters(containerDmc); + } catch (CoreException e) { + } - // Find the ancestor - List threads = new ArrayList(1); - - try { - // Retrieve the targets - IDsfBreakpointExtension filterExtension = getFilterExtension(breakpoint); - IContainerDMContext[] targets = filterExtension.getTargetFilters(); - - // If no target is present, breakpoint applies to all. - if (targets.length == 0) { - results.add("0"); //$NON-NLS-1$ - return results; - } - - // Extract the thread IDs (if there is none, we are covered) - for (IContainerDMContext ctxt : targets) { - if (ctxt.equals(context) || DMContexts.isAncestorOf(ctxt, context)) { - threads.add(filterExtension.getThreadFilters(ctxt)); - } - } - } catch (CoreException e1) { + if (threads == null || threads.length == 0) { + results.add("0"); //$NON-NLS-1$ + return results; } - + if (supportsThreads(breakpoint)) { - for (IExecutionDMContext[] targetThreads : threads) { - if (targetThreads != null) { - for (IExecutionDMContext thread : targetThreads) { - if (thread instanceof IMIExecutionDMContext) { - IMIExecutionDMContext dmc = (IMIExecutionDMContext) thread; - results.add(((Integer) dmc.getThreadId()).toString()); - } - } + for (IExecutionDMContext thread : threads) { + if (thread instanceof IMIExecutionDMContext) { + results.add(Integer.toString(((IMIExecutionDMContext)thread).getThreadId())); } else { + // If any of the threads is not an IMIExecutionDMContext, + // we don't support thread filters at all. + results.clear(); results.add("0"); //$NON-NLS-1$ break; } diff --git a/dsf/org.eclipse.cdt.dsf/pom.xml b/dsf/org.eclipse.cdt.dsf/pom.xml index 6dd94f1dfb5..891b6e5943b 100644 --- a/dsf/org.eclipse.cdt.dsf/pom.xml +++ b/dsf/org.eclipse.cdt.dsf/pom.xml @@ -11,7 +11,7 @@ ../../pom.xml - 2.2.0-SNAPSHOT + 2.3.0-SNAPSHOT org.eclipse.cdt.dsf eclipse-plugin diff --git a/dsf/org.eclipse.cdt.dsf/src/org/eclipse/cdt/dsf/debug/service/IDsfBreakpointExtension.java b/dsf/org.eclipse.cdt.dsf/src/org/eclipse/cdt/dsf/debug/service/IDsfBreakpointExtension.java index ff0f92f9fab..c9f3e1a3c9e 100644 --- a/dsf/org.eclipse.cdt.dsf/src/org/eclipse/cdt/dsf/debug/service/IDsfBreakpointExtension.java +++ b/dsf/org.eclipse.cdt.dsf/src/org/eclipse/cdt/dsf/debug/service/IDsfBreakpointExtension.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2009 Wind River Systems and others. + * Copyright (c) 2007, 2011 Wind River Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -7,6 +7,7 @@ * * Contributors: * Wind River Systems - initial API and implementation + * Marc Khouzam (Ericsson) - Adding javadoc (Bug 355833) *******************************************************************************/ package org.eclipse.cdt.dsf.debug.service; @@ -35,12 +36,60 @@ import org.eclipse.core.runtime.CoreException; */ public interface IDsfBreakpointExtension extends ICBreakpointExtension { - public void setTargetFilter( IContainerDMContext target ) throws CoreException; - public void removeTargetFilter( IContainerDMContext target ) throws CoreException; + /** + * Add the given target to the list of this breakpoint's targets. + * Target filters are not persisted across workbench invocations. + * + * @param target the container to add to the list of this breakpoint's targets. + * @throws CoreException if unable to set the target filter + */ + public void setTargetFilter(IContainerDMContext target) throws CoreException; + + /** + * Removes the given target from the breakpoint's target list. + * The breakpoint has no effect in the given target. + * + * @param target the container filter to be removed + * @exception CoreException if unable to remove the target filter + */ + public void removeTargetFilter(IContainerDMContext target) throws CoreException; + + /** + * Returns all target filters set on this breakpoint. + * + * @return the targets that this breakpoint is restricted to + * @exception CoreException if unable to determine this breakpoint's target filters + */ public IContainerDMContext[] getTargetFilters() throws CoreException; - public void setThreadFilters( IExecutionDMContext[] threads ) throws CoreException; - public void removeThreadFilters( IExecutionDMContext[] threads ) throws CoreException; - public IExecutionDMContext[] getThreadFilters( IContainerDMContext target ) throws CoreException; + /** + * Restricts this breakpoint to suspend only in the given threads + * when encountered in the given threads' target. + * All threads must be from the same target. + * Thread filters are not persisted across workbench invocations. + * + * @param threads the thread filters to be set + * @exception CoreException if unable to set the thread filters + */ + public void setThreadFilters(IExecutionDMContext[] threads) throws CoreException; + /** + * Removes this breakpoint's thread filters in the given target, if any. + * Has no effect if this breakpoint does not have filters in the given target. + * All threads must be from the same target. + * + * @param threads the thread filters to be removed + * @exception CoreException if unable to remove the thread filter + */ + public void removeThreadFilters(IExecutionDMContext[] threads) throws CoreException; + + /** + * Returns the threads in the given target in which this breakpoint + * is enabled or null if this breakpoint is enabled in + * all threads in the given target. + * + * @return the threads in the given target that this breakpoint is enabled for + * @exception CoreException if unable to determine this breakpoint's thread filters + */ + public IExecutionDMContext[] getThreadFilters(IContainerDMContext target) throws CoreException; } From 28aea5e38548dc3bd9d4ef7483dbdba58ca6f0b5 Mon Sep 17 00:00:00 2001 From: Doug Schaefer Date: Tue, 30 Aug 2011 16:48:24 -0400 Subject: [PATCH 24/29] clean up last of the plug-in jars. --- core/org.eclipse.cdt.core.aix/build.properties | 4 ++-- core/org.eclipse.cdt.core.linux/build.properties | 4 ++-- core/org.eclipse.cdt.core.macosx/build.properties | 4 ++-- core/org.eclipse.cdt.core.solaris/build.properties | 4 ++-- core/org.eclipse.cdt.core.win32/build.properties | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/core/org.eclipse.cdt.core.aix/build.properties b/core/org.eclipse.cdt.core.aix/build.properties index 60ff641b21e..1c593888d45 100644 --- a/core/org.eclipse.cdt.core.aix/build.properties +++ b/core/org.eclipse.cdt.core.aix/build.properties @@ -8,9 +8,9 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### -source.cdtaix.jar = src/ +source.. = src/ bin.includes = fragment.xml,\ - cdtaix.jar,\ + .,\ about.html,\ META-INF/,\ os/ diff --git a/core/org.eclipse.cdt.core.linux/build.properties b/core/org.eclipse.cdt.core.linux/build.properties index 0fb31b9d170..6542e91cbdf 100644 --- a/core/org.eclipse.cdt.core.linux/build.properties +++ b/core/org.eclipse.cdt.core.linux/build.properties @@ -10,8 +10,8 @@ ############################################################################### bin.includes = fragment.xml,\ about.html,\ - cdt_linux.jar,\ + .,\ META-INF/ src.includes = about.html,\ library/ -source.cdt_linux.jar = src/ +source.. = src/ diff --git a/core/org.eclipse.cdt.core.macosx/build.properties b/core/org.eclipse.cdt.core.macosx/build.properties index dbce6b0a223..fc76b9bff0c 100644 --- a/core/org.eclipse.cdt.core.macosx/build.properties +++ b/core/org.eclipse.cdt.core.macosx/build.properties @@ -10,9 +10,9 @@ ############################################################################### bin.includes = fragment.xml,\ about.html,\ - cdt_macosx.jar,\ + .,\ os/,\ META-INF/ src.includes = about.html,\ library/ -source.cdt_macosx.jar = src/ +source.. = src/ diff --git a/core/org.eclipse.cdt.core.solaris/build.properties b/core/org.eclipse.cdt.core.solaris/build.properties index 2d1a77f10b3..682baefa984 100644 --- a/core/org.eclipse.cdt.core.solaris/build.properties +++ b/core/org.eclipse.cdt.core.solaris/build.properties @@ -11,8 +11,8 @@ bin.includes = fragment.xml,\ about.html,\ os/,\ - cdt_solaris.jar,\ + .,\ META-INF/ src.includes = about.html,\ library/ -source.cdt_solaris.jar = src/ +source.. = src/ diff --git a/core/org.eclipse.cdt.core.win32/build.properties b/core/org.eclipse.cdt.core.win32/build.properties index 7b3db958ad3..3805517ebdd 100644 --- a/core/org.eclipse.cdt.core.win32/build.properties +++ b/core/org.eclipse.cdt.core.win32/build.properties @@ -10,8 +10,8 @@ ############################################################################### bin.includes = fragment.xml,\ about.html,\ - cdt_win32.jar,\ + .,\ META-INF/ src.includes = about.html,\ library/ -source.cdt_win32.jar = src/ +source.. = src/ From d7f7e9cdac837654f4b36aad012a0be705115c2e Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Fri, 2 Sep 2011 14:47:01 -0400 Subject: [PATCH 25/29] Bug 356613: NPE when opening thread filter page with one running and one terminated launch --- .../dsf/gdb/internal/ui/breakpoints/GdbThreadFilterEditor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/GdbThreadFilterEditor.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/GdbThreadFilterEditor.java index 120215ac8c7..76fda1458b0 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/GdbThreadFilterEditor.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.ui/src/org/eclipse/cdt/dsf/gdb/internal/ui/breakpoints/GdbThreadFilterEditor.java @@ -402,7 +402,7 @@ public class GdbThreadFilterEditor { } catch (InterruptedException e) { } catch (ExecutionException e) { } - return null; + return new IContainerDMContext[0]; } private IExecutionDMContext[] syncGetThreads(final IContainerDMContext container) { From 68a58cd4e9cf3ab9d541db11fa4bf141fd5d6eb4 Mon Sep 17 00:00:00 2001 From: Randy Rohrbach Date: Wed, 31 Aug 2011 17:53:05 -0400 Subject: [PATCH 26/29] Bug 356352 : Added DnD capability to the expression text-box in the Memory Browser --- .../memory/memorybrowser/MemoryBrowser.java | 2540 +++++++++-------- 1 file changed, 1292 insertions(+), 1248 deletions(-) diff --git a/memory/org.eclipse.cdt.debug.ui.memory.memorybrowser/src/org/eclipse/cdt/debug/ui/memory/memorybrowser/MemoryBrowser.java b/memory/org.eclipse.cdt.debug.ui.memory.memorybrowser/src/org/eclipse/cdt/debug/ui/memory/memorybrowser/MemoryBrowser.java index 3d83d1d19b9..01224bd3b45 100644 --- a/memory/org.eclipse.cdt.debug.ui.memory.memorybrowser/src/org/eclipse/cdt/debug/ui/memory/memorybrowser/MemoryBrowser.java +++ b/memory/org.eclipse.cdt.debug.ui.memory.memorybrowser/src/org/eclipse/cdt/debug/ui/memory/memorybrowser/MemoryBrowser.java @@ -1,1248 +1,1292 @@ -/******************************************************************************* - * Copyright (c) 2009, 2010 Wind River Systems, Inc. and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Ted R Williams (Wind River Systems, Inc.) - initial implementation - * Ted R Williams (Mentor Graphics, Inc.) - address space enhancements - * Patrick Chuong (Texas Instruments) - Pin and Clone Supports (331781) - *******************************************************************************/ - -package org.eclipse.cdt.debug.ui.memory.memorybrowser; - -import java.lang.reflect.Type; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.eclipse.cdt.debug.core.model.provisional.IMemoryRenderingViewportProvider; -import org.eclipse.cdt.debug.core.model.provisional.IMemorySpaceAwareMemoryBlockRetrieval; -import org.eclipse.cdt.debug.internal.core.CRequest; -import org.eclipse.cdt.debug.ui.provisional.IRepositionableMemoryRendering2; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.SafeRunner; -import org.eclipse.core.runtime.Status; -import org.eclipse.debug.core.DebugEvent; -import org.eclipse.debug.core.DebugException; -import org.eclipse.debug.core.DebugPlugin; -import org.eclipse.debug.core.IDebugEventSetListener; -import org.eclipse.debug.core.ILaunch; -import org.eclipse.debug.core.model.IDebugElement; -import org.eclipse.debug.core.model.IDebugTarget; -import org.eclipse.debug.core.model.IMemoryBlock; -import org.eclipse.debug.core.model.IMemoryBlockExtension; -import org.eclipse.debug.core.model.IMemoryBlockRetrieval; -import org.eclipse.debug.core.model.IMemoryBlockRetrievalExtension; -import org.eclipse.debug.core.model.MemoryByte; -import org.eclipse.debug.internal.ui.memory.MemoryRenderingManager; -import org.eclipse.debug.ui.DebugUITools; -import org.eclipse.debug.ui.contexts.DebugContextEvent; -import org.eclipse.debug.ui.contexts.IDebugContextListener; -import org.eclipse.debug.ui.contexts.IDebugContextService; -import org.eclipse.debug.ui.memory.IMemoryRendering; -import org.eclipse.debug.ui.memory.IMemoryRenderingContainer; -import org.eclipse.debug.ui.memory.IMemoryRenderingSite; -import org.eclipse.debug.ui.memory.IMemoryRenderingSynchronizationService; -import org.eclipse.debug.ui.memory.IMemoryRenderingType; -import org.eclipse.debug.ui.memory.IRepositionableMemoryRendering; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.action.IMenuListener; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.IToolBarManager; -import org.eclipse.jface.action.MenuManager; -import org.eclipse.jface.action.Separator; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.resource.ColorRegistry; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.jface.util.SafeRunnable; -import org.eclipse.jface.viewers.IBasicPropertyConstants; -import org.eclipse.jface.viewers.ILabelDecorator; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.CTabFolder; -import org.eclipse.swt.custom.CTabFolder2Adapter; -import org.eclipse.swt.custom.CTabFolderEvent; -import org.eclipse.swt.custom.CTabItem; -import org.eclipse.swt.custom.StackLayout; -import org.eclipse.swt.events.DisposeEvent; -import org.eclipse.swt.events.DisposeListener; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.layout.FormAttachment; -import org.eclipse.swt.layout.FormData; -import org.eclipse.swt.layout.FormLayout; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Menu; -import org.eclipse.ui.IActionBars; -import org.eclipse.ui.IViewSite; -import org.eclipse.ui.IWorkbenchActionConstants; -import org.eclipse.ui.IWorkbenchPreferenceConstants; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.part.ViewPart; -import org.eclipse.ui.progress.UIJob; -import org.eclipse.ui.progress.WorkbenchJob; - -/** - * A lightweight rendering container. - * - * Debug model requirements: - * IMemoryBlockExtension (IMemoryBlock not supported) - * IMemoryBlockRetrievalExtension - *

- * Rendering requirements: - * IRepositionableMemoryRendering - * - */ - -@SuppressWarnings("restriction") -public class MemoryBrowser extends ViewPart implements IDebugContextListener, IMemoryRenderingSite, IDebugEventSetListener -{ - public static final String ID = "org.eclipse.cdt.debug.ui.memory.memorybrowser.MemoryBrowser"; //$NON-NLS-1$ - - protected StackLayout fStackLayout; - private Composite fRenderingsComposite; - private GoToAddressBarWidget fGotoAddressBar; - private Control fGotoAddressBarControl; - private Combo fGotoMemorySpaceControl; - private Label fUnsupportedLabel; - private Composite fMainComposite; - private String defaultRenderingTypeId = null; - private IMemoryRendering fActiveRendering; - - /** - * Every memory retrieval object is given its own tab folder. Typically all - * elements of a "process" (process, threads, frames) have the same - * retrieval object. - */ - private Map fContextFolders = new HashMap (); - - private List fCurrentContainers = new ArrayList(); - - private final static String KEY_CONTEXT = "CONTEXT"; //$NON-NLS-1$ - private final static String KEY_CONTAINER = "CONTAINER"; //$NON-NLS-1$ - private final static String KEY_RENDERING_TYPE = "RENDERING_TYPE"; //$NON-NLS-1$ - - /** - * Property we attach to a CTabItem to track the retrieval object we use to - * create memory blocks on the tab's behalf. Value is an - * {@link IMemoryBlockRetrieval} - */ - private final static String KEY_RETRIEVAL = "RETRIEVAL"; //$NON-NLS-1$ - - /** - * Property we attach to a CTabItem to track the memory space it's - * associated with. Value is a memory space ID (String), or null if n/a - */ - private final static String KEY_MEMORY_SPACE = "MEMORY_SPACE"; //$NON-NLS-1$ - - /** - * Property we attach to a CTabItem to track what renderings have been - * created on its behalf. There will be more than one rendering if the - * backend supports memory spaces, there is more than one such space, and - * the user has viewed memory in multiple memory spaces within that tab. - * The value is a map of memory-space-ID==>IMemoryRendering. - */ - private final static String KEY_RENDERINGS = "RENDERINGS"; //$NON-NLS-1$ - - /** - * Property we attach to a CTabItem to track the active rendering in the - * tab. The value is an IMemoryRendering. - */ - private final static String KEY_RENDERING = "RENDERING"; //$NON-NLS-1$ - - /** - * Property we attach to a CTabItem to track what memory blocks have been - * created on its behalf. There can be multiple when dealing with memory - * spaces, for the same reasons there can be multiple renderings. There is a - * 1:1:1 association between rendering, block and memory space. The value is - * a list of IMemoryBlockExtension - */ - private final static String KEY_MEMORY_BLOCKS = "MEMORY_BLOCKS"; //$NON-NLS-1$ - - /** - * Property we attach to a CTabItem to track the expression we used to - * create memory blocks on the tab's behalf. Value is an - * {@link String} - */ - private final static String KEY_EXPRESSION = "EXPRESSION"; //$NON-NLS-1$ - - public static final String PREF_DEFAULT_RENDERING = "org.eclipse.cdt.debug.ui.memory.memorybrowser.defaultRendering"; //$NON-NLS-1$ - - /** - * The text we use in the combobox to represent no memory space specification - */ - private static final String NA_MEMORY_SPACE_ID = " -----"; //$NON-NLS-1$ - - public MemoryBrowser() { - } - - public Control getControl() { - return fMainComposite; - } - - @Override - public void createPartControl(Composite parent) { - // set default rendering type. use the traditional rendering if available. fallback on first registered type. - // this should eventually be configurable via a preference page. - boolean isDefaultRenderingAvailable = false; - IPreferenceStore store = MemoryBrowserPlugin.getDefault().getPreferenceStore(); - String defaultRendering = store.getString(PREF_DEFAULT_RENDERING); - if(defaultRendering == null || defaultRendering.trim().length() == 0) - { - defaultRendering = "org.eclipse.cdt.debug.ui.memory.traditional.TraditionalRendering"; //$NON-NLS-1$ - } - - IMemoryRenderingType[] types = getRenderingTypes(); - for(final IMemoryRenderingType type : types) - { - if(type.getId().equals(defaultRendering)) - { - isDefaultRenderingAvailable = true; - break; - } - } - if(isDefaultRenderingAvailable) - defaultRenderingTypeId = defaultRendering; - else if(types.length > 0) - defaultRenderingTypeId = types[0].getId(); - - getSite().setSelectionProvider(new SelectionProviderAdapter()); - - fMainComposite = new Composite(parent, SWT.NONE); - - FormLayout layout = new FormLayout(); - layout.spacing = 0; - fMainComposite.setLayout(layout); - - fGotoMemorySpaceControl = new Combo(fMainComposite, SWT.DROP_DOWN | SWT.READ_ONLY); - fGotoAddressBar = new GoToAddressBarWidget(); - fGotoAddressBarControl = fGotoAddressBar.createControl(fMainComposite); - - fGotoAddressBar.getButton(IDialogConstants.OK_ID).addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - performGo(false); - } - }); - - fGotoAddressBar.getButton(GoToAddressBarWidget.ID_GO_NEW_TAB).addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - performGo(true); - } - }); - - fGotoAddressBar.getExpressionWidget().addSelectionListener(new SelectionAdapter() { - public void widgetDefaultSelected(SelectionEvent e) { - performGo(false); - } - public void widgetSelected(SelectionEvent e) { - performGo(false); - } - }); - - fGotoMemorySpaceControl.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - if(fGotoMemorySpaceControl.getItemCount() >= 2) { - final CTabFolder activeFolder = (CTabFolder) fStackLayout.topControl; - if (activeFolder != null) { - final Object context = activeFolder.getData(KEY_CONTEXT); - fGotoAddressBar.loadSavedExpressions(context, fGotoMemorySpaceControl.getText()); - } - } - } - }); - - - FormData data = new FormData(); - data.top = new FormAttachment(0); - data.left = new FormAttachment(fGotoMemorySpaceControl); - data.right = new FormAttachment(100); - fGotoAddressBarControl.setLayoutData(data); - - fRenderingsComposite = new Composite(fMainComposite, SWT.NONE); - data = new FormData(); - data.top = new FormAttachment(fGotoAddressBarControl); - data.left = new FormAttachment(0); - data.right = new FormAttachment(100); - data.bottom = new FormAttachment(100); - fRenderingsComposite.setLayoutData(data); - - fStackLayout = new StackLayout(); - - fRenderingsComposite.setLayout(fStackLayout); - - fUnsupportedLabel = new Label(fRenderingsComposite, SWT.NONE); - fUnsupportedLabel.setText(""); //$NON-NLS-1$ - - handleUnsupportedSelection(); - - PlatformUI.getWorkbench().getHelpSystem().setHelp(fMainComposite, MemoryBrowserPlugin.PLUGIN_ID); - makeActions(); - hookContextMenu(); - contributeToActionBars(); - - Object selection = null; - IDebugContextService contextService = - DebugUITools.getDebugContextManager().getContextService(getSite().getWorkbenchWindow()); - if (isBug145635Patched()) { - String presentationContextId = getPresentationContextId(); - contextService.addDebugContextListener(this, presentationContextId); - selection = contextService.getActiveContext(presentationContextId); - } else { - DebugUITools.addPartDebugContextListener(getSite(), this); - selection = contextService.getActiveContext(getSite().getId(), ((IViewSite)getSite()).getSecondaryId()); - } - - DebugPlugin.getDefault().addDebugEventListener(this); - - if(selection instanceof StructuredSelection) - handleDebugContextChanged(((StructuredSelection) selection).getFirstElement()); - } - - private boolean isBug145635Patched() { - Type[] managerTypes = DebugUITools.getDebugContextManager().getClass().getGenericInterfaces(); - for (int i = 0; i < managerTypes.length; i++) { - if (managerTypes[i] instanceof Class) { - Class clazz = (Class)managerTypes[i]; - if ("org.eclipse.debug.ui.contexts.IBug145635Marker".equals(clazz.getName()) ) { //$NON-NLS-1$ - return true; - } - } - } - return false; - } - - /** - * Clears the expression history for the active tab - */ - public void clearExpressionHistoryForActiveTab() { - final CTabFolder activeFolder = (CTabFolder) fStackLayout.topControl; - if (activeFolder != null) { - final Object context = activeFolder.getData(KEY_CONTEXT); - fGotoAddressBar.clearExpressionHistory(context); - } - } - - /** - * Returns the presentation context id for this view. Used to support the - * pin and clone feature patch from bug 145635. - * - * @return context id - */ - private String getPresentationContextId() { - IViewSite site = (IViewSite)getSite(); - return site.getId() + (site.getSecondaryId() != null ? (":" + site.getSecondaryId()) : ""); //$NON-NLS-1$ //$NON-NLS-2$ - } - - @Override - public void dispose() { - DebugPlugin.getDefault().removeDebugEventListener(this); - IDebugContextService contextService = - DebugUITools.getDebugContextManager().getContextService(getSite().getWorkbenchWindow()); - if (isBug145635Patched()) { - String presentationContextId = getPresentationContextId(); - contextService.removeDebugContextListener(this, presentationContextId); - } else { - DebugUITools.removePartDebugContextListener(getSite(), this); - } - super.dispose(); - } - - /* (non-Javadoc) - * @see org.eclipse.debug.core.IDebugEventSetListener#handleDebugEvents(org.eclipse.debug.core.DebugEvent[]) - */ - public void handleDebugEvents(DebugEvent[] events) { - for (DebugEvent event: events) { - Object source = event.getSource(); - if (event.getKind() == DebugEvent.TERMINATE && source instanceof IMemoryBlockRetrieval) { - releaseTabFolder((IMemoryBlockRetrieval)source); - } - } - } - - public IMemoryRenderingContainer getContainer(String id) { - return null; - } - - public IMemoryRenderingContainer[] getMemoryRenderingContainers() { - IMemoryRenderingContainer[] containerList = new IMemoryRenderingContainer[fCurrentContainers.size()]; - for ( int idx = 0 ; idx < fCurrentContainers.size() ; idx ++ ) { - containerList[ idx ] = fCurrentContainers.get( idx ); - } - return containerList; - } - - public IMemoryRenderingSynchronizationService getSynchronizationService() { - return null; - } - - private void handleUnsupportedSelection() { - fStackLayout.topControl = fUnsupportedLabel; - fGotoAddressBarControl.setVisible(false); - fGotoMemorySpaceControl.setVisible(false); - } - - private void performGo(boolean inNewTab) { - // Index zero is the 'auto' (n/a) memory space entry, unless the backend - // said we need to force a memory space selection - String memorySpace = null; - if (fGotoMemorySpaceControl.isVisible()) { - memorySpace = fGotoMemorySpaceControl.getText(); - if (memorySpace.equals(NA_MEMORY_SPACE_ID)) { - memorySpace = null; - } - assert (memorySpace == null) || (memorySpace.length() > 0); - } - - String expression = fGotoAddressBar.getExpressionText(); - if (expression.length() > 0) { - final CTabFolder activeFolder = (CTabFolder) fStackLayout.topControl; - Object context = null; - if (activeFolder != null) { - context = activeFolder.getData(KEY_CONTEXT); - } - fGotoAddressBar.addExpressionToHistory(context, expression, memorySpace); - performGo(inNewTab, expression, memorySpace); - } - } - - public void performGo(boolean inNewTab, final String expression, final String memorySpaceId) { - final CTabFolder activeFolder = (CTabFolder) fStackLayout.topControl; - if (activeFolder != null) { - final IMemoryBlockRetrieval retrieval = (IMemoryBlockRetrieval) activeFolder.getData(KEY_RETRIEVAL); - final Object context = activeFolder.getData(KEY_CONTEXT); - IMemoryRendering rendering = null; - - CTabItem item = activeFolder.getSelection(); - if (inNewTab || item == null) - { - try { - item = createTab(activeFolder, activeFolder.getSelectionIndex() + 1); - rendering = populateTabWithRendering(item, retrieval, context, memorySpaceId, expression); - fContextFolders.put(retrieval, activeFolder); - activeFolder.setSelection(item); - getSite().getSelectionProvider().setSelection(new StructuredSelection(item.getData(KEY_RENDERING))); - handleTabActivated(item); - } catch (DebugException e1) { - fGotoAddressBar.handleExpressionStatus(new Status(Status.ERROR, MemoryBrowserPlugin.PLUGIN_ID, - Messages.getString("MemoryBrowser.FailedToGoToAddressTitle"), e1)); //$NON-NLS-1$ - if (item != null) { - item.dispose(); - } - return; - } - } else { - // Tab is already in place. However, the user may have selected - // a different memory space. If so, that requires us to switch - // out the rendering in the tab with either a new one or an - // existing one already associated with that memory space. - String oldMemorySpaceId = (String)activeFolder.getSelection().getData(KEY_MEMORY_SPACE); - assert oldMemorySpaceId == null || !oldMemorySpaceId.equals(NA_MEMORY_SPACE_ID) : "should be null reference or an explicit, valid memory space ID (not including '----')"; //$NON-NLS-1$ - if ((oldMemorySpaceId != null && !oldMemorySpaceId.equals(memorySpaceId)) - || (oldMemorySpaceId == null && memorySpaceId != null)) { - try { - rendering = populateTabWithRendering(item, retrieval, context, memorySpaceId, expression); - activeFolder.setSelection(item); - getSite().getSelectionProvider().setSelection(new StructuredSelection(item.getData(KEY_RENDERING))); - handleTabActivated(item); - } catch (DebugException e) { - fGotoAddressBar.handleExpressionStatus(new Status(Status.ERROR, MemoryBrowserPlugin.PLUGIN_ID, - Messages.getString("MemoryBrowser.FailedToGoToAddressTitle"), e)); //$NON-NLS-1$ - return; - } - } - } - - if (rendering == null) { - rendering = (IRepositionableMemoryRendering) activeFolder.getSelection().getData(KEY_RENDERING); - } - - if (retrieval instanceof IMemoryBlockRetrievalExtension && - rendering instanceof IRepositionableMemoryRendering) { - final IRepositionableMemoryRendering renderingFinal = (IRepositionableMemoryRendering) rendering; - new Thread() { - @Override - public void run() { - try { - BigInteger newBase = getExpressionAddress(retrieval, expression, context, memorySpaceId); - IMemoryBlockExtension block = (IMemoryBlockExtension) renderingFinal.getMemoryBlock(); - if (block.supportBaseAddressModification()) { - block.setBaseAddress(newBase); - } - if(renderingFinal instanceof IRepositionableMemoryRendering2) { - ((IRepositionableMemoryRendering2)renderingFinal).goToAddress(newBase, expression); - } - else { - renderingFinal.goToAddress(newBase); - } - - runOnUIThread(new Runnable(){ - public void run() { - CTabItem selection = activeFolder.getSelection(); - selection.setData(KEY_EXPRESSION, expression); - fGotoAddressBar.handleExpressionStatus(Status.OK_STATUS); - updateLabel(selection, renderingFinal); - } - }); - } catch (final DebugException e1) { - // widgets update require Display - runOnUIThread(new Runnable(){ - public void run() { - fGotoAddressBar.handleExpressionStatus(new Status(Status.ERROR, MemoryBrowserPlugin.PLUGIN_ID, - Messages.getString("MemoryBrowser.FailedToGoToAddressTitle"), e1)); //$NON-NLS-1$ - } - }); - } - } - }.start(); - } - } - } - - private void updateLabel(CTabItem tab, IMemoryRendering rendering) { - // The default is to use the label provided by the base rendering - // interface. - String label = rendering.getLabel(); - - // If the rendering provides access to its viewport address (the first - // address shown in the rendering, subject to scrolling), display that - // in the tab rather than the expression that was used when the tab was - // first created. - if (rendering instanceof IMemoryRenderingViewportProvider) { - BigInteger viewportAddress = ((IMemoryRenderingViewportProvider)rendering).getViewportAddress(); - - // The base label generation puts the rendering type name in "<>" and - // appends it to the label. Fish that out - String renderingType = null; - int i = label.indexOf('<'); - if (i >= 0) { - renderingType = label.substring(i); - } - - label = null; - - // If a memory space is involved, we want to include its ID in the label - String memorySpaceID = (String)tab.getData(KEY_MEMORY_SPACE); - if (memorySpaceID != null) { - IMemoryBlockRetrieval retrieval = (IMemoryBlockRetrieval) tab.getParent().getData(KEY_RETRIEVAL); - if (retrieval instanceof IMemorySpaceAwareMemoryBlockRetrieval) { - label = ((IMemorySpaceAwareMemoryBlockRetrieval)retrieval).encodeAddress("0x" + viewportAddress.toString(16), memorySpaceID) + ' ' + renderingType; - } - } - if (label == null) { - label = "0x" + viewportAddress.toString(16) + ' ' + renderingType; - } - - // Allow the memory block to customize the label. The platform's - // Memory view support this (it was done in the call to - // rendering.getLabel() above) - IMemoryBlock block = rendering.getMemoryBlock(); - ILabelDecorator labelDec = (ILabelDecorator)block.getAdapter(ILabelDecorator.class); - if (labelDec != null) { - String newLabel = labelDec.decorateText(label, rendering); - if (newLabel != null) { - label = newLabel; - } - } - } - - tab.setText(label); - } - - private CTabFolder createTabFolder(Composite parent) - { - final CTabFolder folder = new CTabFolder(parent, SWT.NO_REDRAW_RESIZE | SWT.NO_TRIM | SWT.FLAT); - - ColorRegistry reg = JFaceResources.getColorRegistry(); - Color c1 = reg.get("org.eclipse.ui.workbench.ACTIVE_TAB_BG_START"), //$NON-NLS-1$ - c2 = reg.get("org.eclipse.ui.workbench.ACTIVE_TAB_BG_END"); //$NON-NLS-1$ - folder.setSelectionBackground(new Color[] {c1, c2}, new int[] {100}, true); - folder.setSelectionForeground(reg.get("org.eclipse.ui.workbench.ACTIVE_TAB_TEXT_COLOR")); //$NON-NLS-1$ - folder.setSimple(PlatformUI.getPreferenceStore().getBoolean(IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS)); - folder.setBorderVisible(true); - - // listener to dispose rendering resources for each closed tab - folder.addCTabFolder2Listener(new CTabFolder2Adapter() { - @Override - public void close(CTabFolderEvent event) { - event.doit = true; - CTabItem item = (CTabItem) event.item; - disposeTab(item); - } - }); - - // listener to dispose rendering resources for all tab items when view part is closed - folder.addDisposeListener(new DisposeListener() { - public void widgetDisposed(DisposeEvent e) { - for(CTabItem tab : folder.getItems()) { - disposeTab(tab); - } - folder.removeDisposeListener(this); - } - }); - return folder; - } - - // these utility methods allow us restrict the scope of the unavoidable @SuppressWarnings - - @SuppressWarnings("unchecked") - private static Map getRenderings(CTabItem tabItem) { - return (Map)tabItem.getData(KEY_RENDERINGS); - } - - @SuppressWarnings("unchecked") - private static List getMemoryBlocks(CTabItem tabItem) { - return (List)tabItem.getData(KEY_MEMORY_BLOCKS); - } - - - /** - * dispose rendering resources associated with the tab item - * @param item - */ - private void disposeTab(CTabItem item ) { - if (item.isDisposed()) - return; - - IMemoryRenderingContainer container = (IMemoryRenderingContainer) item.getData(KEY_CONTAINER); - fCurrentContainers.remove( container ); - Map map = getRenderings(item); - Collection renderings = map.values(); - for (IMemoryRendering rendering : renderings) { - // always deactivate rendering before disposing it. - rendering.deactivated(); - rendering.dispose(); - if (rendering == fActiveRendering) { - fActiveRendering = null; - getSite().getSelectionProvider().setSelection(new StructuredSelection()); - } - } - map.clear(); - - List blocks = getMemoryBlocks(item); - for (IMemoryBlockExtension block : blocks) { - try { - block.dispose(); - } catch (DebugException e) { - MemoryBrowserPlugin.getDefault().getLog().log(new Status(Status.ERROR, MemoryBrowserPlugin.PLUGIN_ID, "Could not dispose memory block", e)); //$NON-NLS-1$ - } - } - blocks.clear(); - } - - private CTabItem createTab(CTabFolder tabFolder, int index) { - int swtStyle = SWT.CLOSE; - CTabItem tab = new CTabItem(tabFolder, swtStyle, index); - tab.setData(KEY_RENDERINGS, new HashMap()); - tab.setData(KEY_MEMORY_BLOCKS, new ArrayList()); - return tab; - } - - private void hookContextMenu() { - MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$ - menuMgr.setRemoveAllWhenShown(true); - menuMgr.addMenuListener(new IMenuListener() { - public void menuAboutToShow(IMenuManager manager) { - MemoryBrowser.this.fillContextMenu(manager); - } - }); - Menu menu = menuMgr.createContextMenu(getControl()); - getControl().setMenu(menu); - } - - private void contributeToActionBars() { - IActionBars bars = getViewSite().getActionBars(); - fillLocalPullDown(bars.getMenuManager()); - fillLocalToolBar(bars.getToolBarManager()); - } - - private void fillLocalPullDown(IMenuManager manager) { - - - MenuManager sub = new MenuManager(Messages.getString("MemoryBrowser.DefaultRendering")); //$NON-NLS-1$ - - for(final IMemoryRenderingType type : getRenderingTypes()) - { - final Action action = new Action( - type.getLabel(), IAction.AS_RADIO_BUTTON) - { - @Override - public void run() - { - setDefaultRenderingTypeId(type.getId()); - } - }; - action.setChecked(type.getId().equals(getDefaultRenderingTypeId())); - sub.add(action); - } - - manager.add(sub); - manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); - } - - private void fillContextMenu(IMenuManager manager) { - manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); - } - - private void fillLocalToolBar(IToolBarManager manager) { - manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); - } - - private void makeActions() { - - } - - private IMemoryRenderingType[] getRenderingTypes() - { - return MemoryRenderingManager.getDefault().getRenderingTypes(new IMemoryBlockExtension(){ - public void connect(Object client) {} - public void disconnect(Object client) {} - public void dispose() throws DebugException {} - public int getAddressSize() throws DebugException { return 0; } - public int getAddressableSize() throws DebugException { return 0; } - public BigInteger getBigBaseAddress() throws DebugException { return null; } - public BigInteger getBigLength() throws DebugException { return null; } - public MemoryByte[] getBytesFromAddress(BigInteger address, long units) throws DebugException { return null; } - public MemoryByte[] getBytesFromOffset(BigInteger unitOffset, long addressableUnits) throws DebugException { return null; } - public Object[] getConnections() { return null; } - public String getExpression() { return null; } - public BigInteger getMemoryBlockEndAddress() throws DebugException { return null; } - public IMemoryBlockRetrieval getMemoryBlockRetrieval() { return null; } - public BigInteger getMemoryBlockStartAddress() throws DebugException { return null; } - public void setBaseAddress(BigInteger address) throws DebugException {} - public void setValue(BigInteger offset, byte[] bytes) throws DebugException {} - public boolean supportBaseAddressModification() throws DebugException { return false; } - public boolean supportsChangeManagement() { return false; } - public byte[] getBytes() throws DebugException { return null; } - public long getLength() { return 0; } - public long getStartAddress() { return 0; } - public void setValue(long offset, byte[] bytes) throws DebugException {} - public boolean supportsValueModification() { return false; } - public IDebugTarget getDebugTarget() { return null; } - public ILaunch getLaunch() { return null; } - public String getModelIdentifier() { return null; } - @SuppressWarnings("rawtypes") - public Object getAdapter(Class adapter) { return null; } - }); - } - - @Override - public void setFocus() { - getControl().setFocus(); - } - - public void debugContextChanged(DebugContextEvent event) { - handleDebugContextChanged(((StructuredSelection) event.getContext()).getFirstElement()); - } - - private final class MemoryBrowserRenderingContainer implements - IMemoryRenderingContainer { - private final List renderings = new ArrayList(); - - private MemoryBrowserRenderingContainer() { - } - - public void addMemoryRendering(IMemoryRendering rendering) { - // do not allow duplicated objects - if (!renderings.contains(rendering)) { - renderings.add(rendering); - } - } - - public IMemoryRendering getActiveRendering() { - return renderings.isEmpty() ? null : renderings.get(renderings.size() -1); - } - - public String getId() { - return "???"; //$NON-NLS-1$ - } - - public String getLabel() { - IMemoryRendering rendering = getActiveRendering(); - return rendering != null ? rendering.getLabel() : null; - } - - public IMemoryRenderingSite getMemoryRenderingSite() { - return MemoryBrowser.this; - } - - public IMemoryRendering[] getRenderings() { - return renderings.toArray(new IMemoryRendering[renderings.size()]); - } - - public void removeMemoryRendering(IMemoryRendering rendering) { - renderings.remove(rendering); - } - } - - private final class RenderingPropertyChangeListener implements - IPropertyChangeListener { - private final CTabItem tab; - private final IMemoryRendering newRendering; - - private RenderingPropertyChangeListener(CTabItem tab, - IMemoryRendering newRendering) { - this.tab = tab; - this.newRendering = newRendering; - } - - public void propertyChange(final PropertyChangeEvent event) { - WorkbenchJob job = new WorkbenchJob("MemoryBrowser PropertyChanged") { //$NON-NLS-1$ - @Override - public IStatus runInUIThread(IProgressMonitor monitor) { - if(tab.isDisposed()) - return Status.OK_STATUS; - - if (event.getProperty().equals(IBasicPropertyConstants.P_TEXT)) - updateLabel(tab, newRendering); - return Status.OK_STATUS; - } - }; - job.setSystem(true); - job.schedule(); - } - } - - private class GetMemorySpacesRequest extends CRequest implements IMemorySpaceAwareMemoryBlockRetrieval.GetMemorySpacesRequest { - String [] fMemorySpaces; - public String[] getMemorySpaces() { - return fMemorySpaces; - } - public void setMemorySpaces(String[] memorySpaceIds) { - fMemorySpaces = memorySpaceIds; - } - } - - public void handleDebugContextChanged(final Object context) { - if(defaultRenderingTypeId == null) - return; - - IAdaptable adaptable = null; - IMemoryBlockRetrieval retrieval = null; - ILaunch launch = null; - - if(context instanceof IAdaptable) - { - adaptable = (IAdaptable) context; - retrieval = ((IMemoryBlockRetrieval) adaptable.getAdapter(IMemoryBlockRetrieval.class)); - launch = ((ILaunch) adaptable.getAdapter(ILaunch.class)); - } - - if(retrieval != null && launch != null && !launch.isTerminated()) { - if (retrieval instanceof IMemorySpaceAwareMemoryBlockRetrieval) { - final IMemoryBlockRetrieval _retrieval = retrieval; - ((IMemorySpaceAwareMemoryBlockRetrieval)retrieval).getMemorySpaces(context, new GetMemorySpacesRequest(){ - @Override - public void done() { - updateTab(_retrieval, context, isSuccess() ? getMemorySpaces() : new String[0]); - } - }); - } - else { - updateTab(retrieval, context, new String[0]); - } - } - else { - handleUnsupportedSelection(); - } - - fGotoMemorySpaceControl.pack(true); - fStackLayout.topControl.getParent().layout(true); - } - - /** - * Called to update the tab once the asynchronous query for memory spaces - * has returned a result. - * - * @param retrieval - * the retrieval object associated with the newly active debug - * context - * @param context - * the newly active context - * @param memorySpaces - * the memory spaces, if applicable. Otherwise an empty array. - */ - private void updateTab(final IMemoryBlockRetrieval retrieval, final Object context, final String[] memorySpaces) { - // GUI activity must be on the main thread - runOnUIThread(new Runnable(){ - public void run() { - if (fGotoAddressBarControl.isDisposed()) { - return; - } - - fGotoAddressBarControl.setVisible(true); - - // If we've already created a tab folder for this retrieval - // object, bring it to the forefront. Otherwise create the - // folder. - CTabFolder tabFolder = fContextFolders.get(retrieval); - if(tabFolder != null) { - fStackLayout.topControl = tabFolder; - handleTabActivated(tabFolder.getSelection()); - } - else { - tabFolder = createTabFolder(fRenderingsComposite); - tabFolder.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) {} - public void widgetSelected(SelectionEvent e) { - CTabItem tabItem = (CTabItem)e.item; - updateExpression(tabItem); - updateMemorySpaceControlSelection(tabItem); - fGotoAddressBar.loadSavedExpressions(context, fGotoMemorySpaceControl.isVisible() ? fGotoMemorySpaceControl.getText() : null); - getSite().getSelectionProvider().setSelection(new StructuredSelection(tabItem.getData(KEY_RENDERING))); - handleTabActivated(tabItem); - } - }); - - tabFolder.setData(KEY_RETRIEVAL, retrieval); - fContextFolders.put(retrieval, tabFolder); - fStackLayout.topControl = tabFolder; - // set empty initial expression - fGotoAddressBar.setExpressionText(""); //$NON-NLS-1$ - fGotoAddressBar.loadSavedExpressions(context, fGotoMemorySpaceControl.isVisible() ? fGotoMemorySpaceControl.getText() : null); - } - // update debug context to the new selection - tabFolder.setData(KEY_CONTEXT, context); - - - final CTabFolder activeFolder = tabFolder; - if (!activeFolder.equals(tabFolder)) { - return; - } - - // Don't expose the memory spaces widget if there are none or - // only one memory space involved. - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=309032#c50 - if (memorySpaces.length >= 2) { - fGotoMemorySpaceControl.setItems(memorySpaces); - - // Add the '----' (N/A) entry unless the retrieval object - // says it requires a memory space ID in all cases - boolean addNA = true; - if (retrieval instanceof IMemorySpaceAwareMemoryBlockRetrieval) { - addNA = !((IMemorySpaceAwareMemoryBlockRetrieval)retrieval).creatingBlockRequiresMemorySpaceID(); - } - if (addNA) { - fGotoMemorySpaceControl.add(NA_MEMORY_SPACE_ID, 0); - } - setMemorySpaceControlVisible(true); - } - else { - fGotoMemorySpaceControl.setItems(new String[0]); - setMemorySpaceControlVisible(false); - } - - updateExpression(activeFolder.getSelection()); - updateMemorySpaceControlSelection(activeFolder.getSelection()); - fGotoAddressBar.loadSavedExpressions(context, fGotoMemorySpaceControl.isVisible() ? fGotoMemorySpaceControl.getText() : null); - - fStackLayout.topControl.getParent().layout(true); - } - }); - } - - /** - * Update the expression text in goto address widget to reflect the memory - * rendering expression - * - * @param item - * the active tab; may be null if in a "fresh" memory browser instance - */ - protected void updateExpression(CTabItem activeFolder) { - String expression = (activeFolder != null) ? (String) activeFolder.getData(KEY_EXPRESSION) : null; - if (expression != null) { - fGotoAddressBar.setExpressionText(expression); - } - } - - protected final void handleTabActivated(CTabItem item) { - if (item != null) { - updateActiveRendering((IMemoryRendering) item.getData(KEY_RENDERING)); - } - } - - private void updateActiveRendering(IMemoryRendering rendering) { - if (fActiveRendering == rendering) { - return; - } - if (fActiveRendering != null) { - fActiveRendering.deactivated(); - fActiveRendering.becomesHidden(); - } - if (rendering != null) { - rendering.activated(); - rendering.becomesVisible(); - } - fActiveRendering = rendering; - } - - private void setMemorySpaceControlVisible(boolean visible) { - FormData data = (FormData)fGotoAddressBarControl.getLayoutData(); - if (visible) { - data.left = new FormAttachment(fGotoMemorySpaceControl); - } - else { - data.left = new FormAttachment(0); - } - fGotoMemorySpaceControl.setVisible(visible); - - } - - /** - * Update the selection in the memory space combobox to reflect the memory - * space being shown in the given tab - * - * @param item - * the active tab; may be null if in a "fresh" memory browser instance - */ - private void updateMemorySpaceControlSelection(CTabItem item) { - String[] memorySpaces = fGotoMemorySpaceControl.getItems(); - if (memorySpaces.length > 0 ) { - // Don't assume that the memory space previously set in the tab - // is one of the ones now available. If it isn't, then select - // the first available one and update the tab data - boolean foundIt = false; - if (item != null) { - String currentMemorySpace = (String) item.getData(KEY_MEMORY_SPACE); - if (currentMemorySpace != null) { - assert currentMemorySpace.length() > 0; - for (String memorySpace : memorySpaces) { - if (memorySpace.equals(currentMemorySpace)) { - foundIt = true; - fGotoMemorySpaceControl.setText(currentMemorySpace); - break; - } - } - } - } - if (!foundIt) { - fGotoMemorySpaceControl.select(0); - if (item != null) { - item.setData(KEY_MEMORY_SPACE, null); - } - } - fGotoMemorySpaceControl.setVisible(true); - } - else { - fGotoMemorySpaceControl.setVisible(false); - } - fGotoMemorySpaceControl.getParent().layout(true); - - } - - private String getDefaultRenderingTypeId() - { - return defaultRenderingTypeId; - } - - public void setDefaultRenderingTypeId(String id) - { - defaultRenderingTypeId = id; - IPreferenceStore store = MemoryBrowserPlugin.getDefault().getPreferenceStore(); - store.setValue(PREF_DEFAULT_RENDERING, defaultRenderingTypeId); - } - - /** - * Populate given tab with a rendering positioned at specified expression and memory space. - * Will create a new rendering if one does not exist for the given memory space - * - * @param tab item to populate - * @param retrieval memory service to retrieve memory block from - * @param context memory block would be retrieved - * @param memorySpaceId of the expression or null if not supported - * @param expression from where to retrieve the memory block - * @return return the memory rendering or null if could not be created - * - * @throws DebugException if could not retrieve memory block (e.g. invalid expression) - */ - private IMemoryRendering populateTabWithRendering(final CTabItem tab, final IMemoryBlockRetrieval retrieval, Object context, String memorySpaceId, String expression) throws DebugException { - IMemoryRenderingType type = DebugUITools.getMemoryRenderingManager().getRenderingType(getDefaultRenderingTypeId()); - IMemoryRenderingContainer container = (IMemoryRenderingContainer)tab.getData(KEY_CONTAINER); - if (container == null) { - container = new MemoryBrowserRenderingContainer(); - fCurrentContainers.add(container); - } - - IMemoryRendering rendering = getRenderings(tab).get(memorySpaceId); - if (rendering == null) { - // No rendering yet. Create rendering and associated memory block. - // createMemoryBlock will throw if expression cannot be resolved - IMemoryBlockExtension block = createMemoryBlock(retrieval, expression, context, memorySpaceId); - try { - rendering = type.createRendering(); - } catch (CoreException e) { - MemoryBrowserPlugin.getDefault().getLog().log(new Status(Status.ERROR, MemoryBrowserPlugin.PLUGIN_ID, "", e)); //$NON-NLS-1$ - return null; - } - - rendering.init(container, block); - container.addMemoryRendering(rendering); - rendering.createControl(tab.getParent()); - getRenderings(tab).put(memorySpaceId, rendering); - getMemoryBlocks(tab).add(block); - rendering.addPropertyChangeListener(new RenderingPropertyChangeListener(tab, rendering)); - } - - tab.setControl(rendering.getControl()); - tab.getParent().setSelection(0); - tab.setData(KEY_RENDERING, rendering); - tab.setData(KEY_MEMORY_SPACE, memorySpaceId); - tab.setData(KEY_CONTAINER, container); - tab.setData(KEY_RENDERING_TYPE, type); - getSite().getSelectionProvider().setSelection(new StructuredSelection(tab.getData(KEY_RENDERING))); - updateLabel(tab, rendering); - - return rendering; - } - - - private void releaseTabFolder(final IMemoryBlockRetrieval retrieval) - { - final CTabFolder folder = fContextFolders.get(retrieval); - if(folder != null) - { - Runnable run = new Runnable() { - public void run() { - for(CTabItem tab : folder.getItems()) { - disposeTab(tab); - } - fContextFolders.remove(retrieval); - folder.dispose(); - - if (fStackLayout.topControl.equals(folder)) { - handleUnsupportedSelection(); - } - } - }; - runOnUIThread(run); - } - } - - class SelectionProviderAdapter implements ISelectionProvider { - - List listeners = new ArrayList(); - - ISelection theSelection = StructuredSelection.EMPTY; - - public void addSelectionChangedListener(ISelectionChangedListener listener) { - listeners.add(listener); - } - - public ISelection getSelection() { - return theSelection; - } - - public void removeSelectionChangedListener( - ISelectionChangedListener listener) { - listeners.remove(listener); - } - - public void setSelection(ISelection selection) { - theSelection = selection; - final SelectionChangedEvent e = new SelectionChangedEvent(this, selection); - Object[] listenersArray = listeners.toArray(); - - for (int i = 0; i < listenersArray.length; i++) { - final ISelectionChangedListener l = (ISelectionChangedListener) listenersArray[i]; - SafeRunner.run(new SafeRunnable() { - public void run() { - l.selectionChanged(e); - } - }); - } - } - } - - /** - * create a memory block - * @param retrieval memory block retrieval. - * @param expression expression to be evaluated to an addressL - * @param context context for evaluating the expression. This is typically - * a debug element. - * @param memorySpaceID a memory space identifier, or null if n/a - * @return a memory block based on the given expression and context - * @throws DebugException if unable to retrieve the specified memory - */ - private IMemoryBlockExtension createMemoryBlock(IMemoryBlockRetrieval retrieval, String expression, Object context, String memorySpaceID) throws DebugException { - IMemoryBlockExtension block = null; - IMemoryBlockRetrievalExtension retrievalExtension = null; - if (retrieval instanceof IMemoryBlockRetrievalExtension) { - retrievalExtension = (IMemoryBlockRetrievalExtension) retrieval; - } else if(retrieval instanceof IAdaptable) { - retrievalExtension = (IMemoryBlockRetrievalExtension)((IAdaptable) retrieval).getAdapter(IMemoryBlockRetrievalExtension.class); - } - if (retrievalExtension != null) { - if (retrievalExtension instanceof IMemorySpaceAwareMemoryBlockRetrieval) { - block = ((IMemorySpaceAwareMemoryBlockRetrieval)retrievalExtension).getMemoryBlock(expression, context, memorySpaceID); - } - else { - block = retrievalExtension.getExtendedMemoryBlock(expression, context); - } - } - if ( block == null ) { - throw new DebugException(new Status(Status.ERROR, MemoryBrowserPlugin.PLUGIN_ID, "Extended Memory Block could not be obtained")); //$NON-NLS-1$ - } - return block; - } - - /** - * Get a memory address for an expression in a given context. - * @param retrieval - * @param expression - * @param context - * @return BigInteger address of the expression - * @throws DebugException - */ - private BigInteger getExpressionAddress(IMemoryBlockRetrieval retrieval, String expression, Object context, String memorySpaceId) throws DebugException { - // Until 257842 issue is solved this is done via IMemoryBlockRetrievalExtension API. - IMemoryBlockExtension newBlock = createMemoryBlock(retrieval, expression, context, memorySpaceId); - BigInteger address = newBlock.getBigBaseAddress(); - newBlock.dispose(); - return address; - } - - /** - * Execute runnable on UI thread if the current thread is not an UI thread. - * Otherwise execute it directly. - * - * @param runnable - * the runnable to execute - */ - private void runOnUIThread(final Runnable runnable) { - if (Display.getCurrent() != null) { - runnable.run(); - } - else { - UIJob job = new UIJob("Memory Browser UI Job"){ //$NON-NLS-1$ - @Override - public IStatus runInUIThread(IProgressMonitor monitor) { - runnable.run(); - return Status.OK_STATUS; - }}; - job.setSystem(true); - job.schedule(); - } - } -} +/******************************************************************************* + * Copyright (c) 2009, 2010 Wind River Systems, Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Ted R Williams (Wind River Systems, Inc.) - initial implementation + * Ted R Williams (Mentor Graphics, Inc.) - address space enhancements + * Patrick Chuong (Texas Instruments) - Pin and Clone Supports (331781) + *******************************************************************************/ + +package org.eclipse.cdt.debug.ui.memory.memorybrowser; + +import java.lang.reflect.Type; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.cdt.debug.core.model.provisional.IMemoryRenderingViewportProvider; +import org.eclipse.cdt.debug.core.model.provisional.IMemorySpaceAwareMemoryBlockRetrieval; +import org.eclipse.cdt.debug.internal.core.CRequest; +import org.eclipse.cdt.debug.ui.provisional.IRepositionableMemoryRendering2; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.SafeRunner; +import org.eclipse.core.runtime.Status; +import org.eclipse.debug.core.DebugEvent; +import org.eclipse.debug.core.DebugException; +import org.eclipse.debug.core.DebugPlugin; +import org.eclipse.debug.core.IDebugEventSetListener; +import org.eclipse.debug.core.ILaunch; +import org.eclipse.debug.core.model.IDebugTarget; +import org.eclipse.debug.core.model.IMemoryBlock; +import org.eclipse.debug.core.model.IMemoryBlockExtension; +import org.eclipse.debug.core.model.IMemoryBlockRetrieval; +import org.eclipse.debug.core.model.IMemoryBlockRetrievalExtension; +import org.eclipse.debug.core.model.MemoryByte; +import org.eclipse.debug.internal.ui.memory.MemoryRenderingManager; +import org.eclipse.debug.ui.DebugUITools; +import org.eclipse.debug.ui.contexts.DebugContextEvent; +import org.eclipse.debug.ui.contexts.IDebugContextListener; +import org.eclipse.debug.ui.contexts.IDebugContextService; +import org.eclipse.debug.ui.memory.IMemoryRendering; +import org.eclipse.debug.ui.memory.IMemoryRenderingContainer; +import org.eclipse.debug.ui.memory.IMemoryRenderingSite; +import org.eclipse.debug.ui.memory.IMemoryRenderingSynchronizationService; +import org.eclipse.debug.ui.memory.IMemoryRenderingType; +import org.eclipse.debug.ui.memory.IRepositionableMemoryRendering; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.action.IMenuListener; +import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.action.IToolBarManager; +import org.eclipse.jface.action.MenuManager; +import org.eclipse.jface.action.Separator; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.resource.ColorRegistry; +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.jface.util.SafeRunnable; +import org.eclipse.jface.viewers.IBasicPropertyConstants; +import org.eclipse.jface.viewers.ILabelDecorator; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.CTabFolder; +import org.eclipse.swt.custom.CTabFolder2Adapter; +import org.eclipse.swt.custom.CTabFolderEvent; +import org.eclipse.swt.custom.CTabItem; +import org.eclipse.swt.custom.StackLayout; +import org.eclipse.swt.dnd.DND; +import org.eclipse.swt.dnd.DragSource; +import org.eclipse.swt.dnd.DropTarget; +import org.eclipse.swt.dnd.DropTargetAdapter; +import org.eclipse.swt.dnd.DropTargetEvent; +import org.eclipse.swt.dnd.FileTransfer; +import org.eclipse.swt.dnd.TextTransfer; +import org.eclipse.swt.dnd.Transfer; +import org.eclipse.swt.dnd.TransferData; +import org.eclipse.swt.events.DisposeEvent; +import org.eclipse.swt.events.DisposeListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.layout.FormAttachment; +import org.eclipse.swt.layout.FormData; +import org.eclipse.swt.layout.FormLayout; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.ui.IActionBars; +import org.eclipse.ui.IViewSite; +import org.eclipse.ui.IWorkbenchActionConstants; +import org.eclipse.ui.IWorkbenchPreferenceConstants; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.part.ViewPart; +import org.eclipse.ui.progress.UIJob; +import org.eclipse.ui.progress.WorkbenchJob; + +/** + * A lightweight rendering container. + * + * Debug model requirements: + * IMemoryBlockExtension (IMemoryBlock not supported) + * IMemoryBlockRetrievalExtension + *

+ * Rendering requirements: + * IRepositionableMemoryRendering + * + */ + +@SuppressWarnings("restriction") +public class MemoryBrowser extends ViewPart implements IDebugContextListener, IMemoryRenderingSite, IDebugEventSetListener +{ + public static final String ID = "org.eclipse.cdt.debug.ui.memory.memorybrowser.MemoryBrowser"; //$NON-NLS-1$ + + protected StackLayout fStackLayout; + private Composite fRenderingsComposite; + private GoToAddressBarWidget fGotoAddressBar; + private DropTarget fDropTarget; + private Control fGotoAddressBarControl; + private Combo fGotoMemorySpaceControl; + private Label fUnsupportedLabel; + private Composite fMainComposite; + private String defaultRenderingTypeId = null; + private IMemoryRendering fActiveRendering; + + /** + * Every memory retrieval object is given its own tab folder. Typically all + * elements of a "process" (process, threads, frames) have the same + * retrieval object. + */ + private Map fContextFolders = new HashMap (); + + private List fCurrentContainers = new ArrayList(); + + private final static String KEY_CONTEXT = "CONTEXT"; //$NON-NLS-1$ + private final static String KEY_CONTAINER = "CONTAINER"; //$NON-NLS-1$ + private final static String KEY_RENDERING_TYPE = "RENDERING_TYPE"; //$NON-NLS-1$ + + /** + * Property we attach to a CTabItem to track the retrieval object we use to + * create memory blocks on the tab's behalf. Value is an + * {@link IMemoryBlockRetrieval} + */ + private final static String KEY_RETRIEVAL = "RETRIEVAL"; //$NON-NLS-1$ + + /** + * Property we attach to a CTabItem to track the memory space it's + * associated with. Value is a memory space ID (String), or null if n/a + */ + private final static String KEY_MEMORY_SPACE = "MEMORY_SPACE"; //$NON-NLS-1$ + + /** + * Property we attach to a CTabItem to track what renderings have been + * created on its behalf. There will be more than one rendering if the + * backend supports memory spaces, there is more than one such space, and + * the user has viewed memory in multiple memory spaces within that tab. + * The value is a map of memory-space-ID==>IMemoryRendering. + */ + private final static String KEY_RENDERINGS = "RENDERINGS"; //$NON-NLS-1$ + + /** + * Property we attach to a CTabItem to track the active rendering in the + * tab. The value is an IMemoryRendering. + */ + private final static String KEY_RENDERING = "RENDERING"; //$NON-NLS-1$ + + /** + * Property we attach to a CTabItem to track what memory blocks have been + * created on its behalf. There can be multiple when dealing with memory + * spaces, for the same reasons there can be multiple renderings. There is a + * 1:1:1 association between rendering, block and memory space. The value is + * a list of IMemoryBlockExtension + */ + private final static String KEY_MEMORY_BLOCKS = "MEMORY_BLOCKS"; //$NON-NLS-1$ + + /** + * Property we attach to a CTabItem to track the expression we used to + * create memory blocks on the tab's behalf. Value is an + * {@link String} + */ + private final static String KEY_EXPRESSION = "EXPRESSION"; //$NON-NLS-1$ + + public static final String PREF_DEFAULT_RENDERING = "org.eclipse.cdt.debug.ui.memory.memorybrowser.defaultRendering"; //$NON-NLS-1$ + + /** + * The text we use in the combobox to represent no memory space specification + */ + private static final String NA_MEMORY_SPACE_ID = " -----"; //$NON-NLS-1$ + + public MemoryBrowser() { + } + + public Control getControl() { + return fMainComposite; + } + + /* + * Handles DnD from other views. + */ + private class MemoryDropAdapter extends DropTargetAdapter { + /* + * @see org.eclipse.swt.dnd.DropTargetListener#drop(org.eclipse.swt.dnd.DropTargetEvent) + */ + public void drop(final DropTargetEvent event) { + if (TextTransfer.getInstance().isSupportedType( event.currentDataType )) { + if ( event.data instanceof String ) { + fGotoAddressBar.setExpressionText( (String) event.data ); + performGo(false); + } + } + } + + /* + * @see org.eclipse.swt.dnd.DropTargetListener#dragEnter(org.eclipse.swt.dnd.DropTargetEvent) + */ + public void dragEnter(DropTargetEvent event) { + event.detail = DND.DROP_COPY; + event.feedback = DND.FEEDBACK_NONE; + } + } + + @Override + public void createPartControl(Composite parent) { + // set default rendering type. use the traditional rendering if available. fallback on first registered type. + // this should eventually be configurable via a preference page. + boolean isDefaultRenderingAvailable = false; + IPreferenceStore store = MemoryBrowserPlugin.getDefault().getPreferenceStore(); + String defaultRendering = store.getString(PREF_DEFAULT_RENDERING); + if(defaultRendering == null || defaultRendering.trim().length() == 0) + { + defaultRendering = "org.eclipse.cdt.debug.ui.memory.traditional.TraditionalRendering"; //$NON-NLS-1$ + } + + IMemoryRenderingType[] types = getRenderingTypes(); + for(final IMemoryRenderingType type : types) + { + if(type.getId().equals(defaultRendering)) + { + isDefaultRenderingAvailable = true; + break; + } + } + if(isDefaultRenderingAvailable) + defaultRenderingTypeId = defaultRendering; + else if(types.length > 0) + defaultRenderingTypeId = types[0].getId(); + + getSite().setSelectionProvider(new SelectionProviderAdapter()); + + fMainComposite = new Composite(parent, SWT.NONE); + + FormLayout layout = new FormLayout(); + layout.spacing = 0; + fMainComposite.setLayout(layout); + + fGotoMemorySpaceControl = new Combo(fMainComposite, SWT.DROP_DOWN | SWT.READ_ONLY); + fGotoAddressBar = new GoToAddressBarWidget(); + fGotoAddressBarControl = fGotoAddressBar.createControl(fMainComposite); + + if (fDropTarget == null) { + fDropTarget = new DropTarget(fGotoAddressBarControl, DND.DROP_COPY | DND.DROP_DEFAULT); + fDropTarget.setTransfer( new Transfer[] { TextTransfer.getInstance() }); + fDropTarget.addDropListener(new MemoryDropAdapter()); + } + + fGotoAddressBar.getButton(IDialogConstants.OK_ID).addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + performGo(false); + } + }); + + fGotoAddressBar.getButton(GoToAddressBarWidget.ID_GO_NEW_TAB).addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + performGo(true); + } + }); + + fGotoAddressBar.getExpressionWidget().addSelectionListener(new SelectionAdapter() { + public void widgetDefaultSelected(SelectionEvent e) { + performGo(false); + } + public void widgetSelected(SelectionEvent e) { + performGo(false); + } + }); + + fGotoMemorySpaceControl.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + if(fGotoMemorySpaceControl.getItemCount() >= 2) { + final CTabFolder activeFolder = (CTabFolder) fStackLayout.topControl; + if (activeFolder != null) { + final Object context = activeFolder.getData(KEY_CONTEXT); + fGotoAddressBar.loadSavedExpressions(context, fGotoMemorySpaceControl.getText()); + } + } + } + }); + + + FormData data = new FormData(); + data.top = new FormAttachment(0); + data.left = new FormAttachment(fGotoMemorySpaceControl); + data.right = new FormAttachment(100); + fGotoAddressBarControl.setLayoutData(data); + + fRenderingsComposite = new Composite(fMainComposite, SWT.NONE); + data = new FormData(); + data.top = new FormAttachment(fGotoAddressBarControl); + data.left = new FormAttachment(0); + data.right = new FormAttachment(100); + data.bottom = new FormAttachment(100); + fRenderingsComposite.setLayoutData(data); + + fStackLayout = new StackLayout(); + + fRenderingsComposite.setLayout(fStackLayout); + + fUnsupportedLabel = new Label(fRenderingsComposite, SWT.NONE); + fUnsupportedLabel.setText(""); //$NON-NLS-1$ + + handleUnsupportedSelection(); + + PlatformUI.getWorkbench().getHelpSystem().setHelp(fMainComposite, MemoryBrowserPlugin.PLUGIN_ID); + makeActions(); + hookContextMenu(); + contributeToActionBars(); + + Object selection = null; + IDebugContextService contextService = + DebugUITools.getDebugContextManager().getContextService(getSite().getWorkbenchWindow()); + if (isBug145635Patched()) { + String presentationContextId = getPresentationContextId(); + contextService.addDebugContextListener(this, presentationContextId); + selection = contextService.getActiveContext(presentationContextId); + } else { + DebugUITools.addPartDebugContextListener(getSite(), this); + selection = contextService.getActiveContext(getSite().getId(), ((IViewSite)getSite()).getSecondaryId()); + } + + DebugPlugin.getDefault().addDebugEventListener(this); + + if(selection instanceof StructuredSelection) + handleDebugContextChanged(((StructuredSelection) selection).getFirstElement()); + } + + private boolean isBug145635Patched() { + Type[] managerTypes = DebugUITools.getDebugContextManager().getClass().getGenericInterfaces(); + for (int i = 0; i < managerTypes.length; i++) { + if (managerTypes[i] instanceof Class) { + Class clazz = (Class)managerTypes[i]; + if ("org.eclipse.debug.ui.contexts.IBug145635Marker".equals(clazz.getName()) ) { //$NON-NLS-1$ + return true; + } + } + } + return false; + } + + /** + * Clears the expression history for the active tab + */ + public void clearExpressionHistoryForActiveTab() { + final CTabFolder activeFolder = (CTabFolder) fStackLayout.topControl; + if (activeFolder != null) { + final Object context = activeFolder.getData(KEY_CONTEXT); + fGotoAddressBar.clearExpressionHistory(context); + } + } + + /** + * Returns the presentation context id for this view. Used to support the + * pin and clone feature patch from bug 145635. + * + * @return context id + */ + private String getPresentationContextId() { + IViewSite site = (IViewSite)getSite(); + return site.getId() + (site.getSecondaryId() != null ? (":" + site.getSecondaryId()) : ""); //$NON-NLS-1$ //$NON-NLS-2$ + } + + @Override + public void dispose() { + if (fDropTarget != null) { + fDropTarget.dispose(); + fDropTarget = null; + } + DebugPlugin.getDefault().removeDebugEventListener(this); + IDebugContextService contextService = + DebugUITools.getDebugContextManager().getContextService(getSite().getWorkbenchWindow()); + if (isBug145635Patched()) { + String presentationContextId = getPresentationContextId(); + contextService.removeDebugContextListener(this, presentationContextId); + } else { + DebugUITools.removePartDebugContextListener(getSite(), this); + } + super.dispose(); + } + + /* (non-Javadoc) + * @see org.eclipse.debug.core.IDebugEventSetListener#handleDebugEvents(org.eclipse.debug.core.DebugEvent[]) + */ + public void handleDebugEvents(DebugEvent[] events) { + for (DebugEvent event: events) { + Object source = event.getSource(); + if (event.getKind() == DebugEvent.TERMINATE && source instanceof IMemoryBlockRetrieval) { + releaseTabFolder((IMemoryBlockRetrieval)source); + } + } + } + + public IMemoryRenderingContainer getContainer(String id) { + return null; + } + + public IMemoryRenderingContainer[] getMemoryRenderingContainers() { + IMemoryRenderingContainer[] containerList = new IMemoryRenderingContainer[fCurrentContainers.size()]; + for ( int idx = 0 ; idx < fCurrentContainers.size() ; idx ++ ) { + containerList[ idx ] = fCurrentContainers.get( idx ); + } + return containerList; + } + + public IMemoryRenderingSynchronizationService getSynchronizationService() { + return null; + } + + private void handleUnsupportedSelection() { + fStackLayout.topControl = fUnsupportedLabel; + fGotoAddressBarControl.setVisible(false); + fGotoMemorySpaceControl.setVisible(false); + } + + private void performGo(boolean inNewTab) { + // Index zero is the 'auto' (n/a) memory space entry, unless the backend + // said we need to force a memory space selection + String memorySpace = null; + if (fGotoMemorySpaceControl.isVisible()) { + memorySpace = fGotoMemorySpaceControl.getText(); + if (memorySpace.equals(NA_MEMORY_SPACE_ID)) { + memorySpace = null; + } + assert (memorySpace == null) || (memorySpace.length() > 0); + } + + String expression = fGotoAddressBar.getExpressionText(); + if (expression.length() > 0) { + final CTabFolder activeFolder = (CTabFolder) fStackLayout.topControl; + Object context = null; + if (activeFolder != null) { + context = activeFolder.getData(KEY_CONTEXT); + } + fGotoAddressBar.addExpressionToHistory(context, expression, memorySpace); + performGo(inNewTab, expression, memorySpace); + } + } + + public void performGo(boolean inNewTab, final String expression, final String memorySpaceId) { + final CTabFolder activeFolder = (CTabFolder) fStackLayout.topControl; + if (activeFolder != null) { + final IMemoryBlockRetrieval retrieval = (IMemoryBlockRetrieval) activeFolder.getData(KEY_RETRIEVAL); + final Object context = activeFolder.getData(KEY_CONTEXT); + IMemoryRendering rendering = null; + + CTabItem item = activeFolder.getSelection(); + if (inNewTab || item == null) + { + try { + item = createTab(activeFolder, activeFolder.getSelectionIndex() + 1); + rendering = populateTabWithRendering(item, retrieval, context, memorySpaceId, expression); + fContextFolders.put(retrieval, activeFolder); + activeFolder.setSelection(item); + getSite().getSelectionProvider().setSelection(new StructuredSelection(item.getData(KEY_RENDERING))); + handleTabActivated(item); + } catch (DebugException e1) { + fGotoAddressBar.handleExpressionStatus(new Status(Status.ERROR, MemoryBrowserPlugin.PLUGIN_ID, + Messages.getString("MemoryBrowser.FailedToGoToAddressTitle"), e1)); //$NON-NLS-1$ + if (item != null) { + item.dispose(); + } + return; + } + } else { + // Tab is already in place. However, the user may have selected + // a different memory space. If so, that requires us to switch + // out the rendering in the tab with either a new one or an + // existing one already associated with that memory space. + String oldMemorySpaceId = (String)activeFolder.getSelection().getData(KEY_MEMORY_SPACE); + assert oldMemorySpaceId == null || !oldMemorySpaceId.equals(NA_MEMORY_SPACE_ID) : "should be null reference or an explicit, valid memory space ID (not including '----')"; //$NON-NLS-1$ + if ((oldMemorySpaceId != null && !oldMemorySpaceId.equals(memorySpaceId)) + || (oldMemorySpaceId == null && memorySpaceId != null)) { + try { + rendering = populateTabWithRendering(item, retrieval, context, memorySpaceId, expression); + activeFolder.setSelection(item); + getSite().getSelectionProvider().setSelection(new StructuredSelection(item.getData(KEY_RENDERING))); + handleTabActivated(item); + } catch (DebugException e) { + fGotoAddressBar.handleExpressionStatus(new Status(Status.ERROR, MemoryBrowserPlugin.PLUGIN_ID, + Messages.getString("MemoryBrowser.FailedToGoToAddressTitle"), e)); //$NON-NLS-1$ + return; + } + } + } + + if (rendering == null) { + rendering = (IRepositionableMemoryRendering) activeFolder.getSelection().getData(KEY_RENDERING); + } + + if (retrieval instanceof IMemoryBlockRetrievalExtension && + rendering instanceof IRepositionableMemoryRendering) { + final IRepositionableMemoryRendering renderingFinal = (IRepositionableMemoryRendering) rendering; + new Thread() { + @Override + public void run() { + try { + BigInteger newBase = getExpressionAddress(retrieval, expression, context, memorySpaceId); + IMemoryBlockExtension block = (IMemoryBlockExtension) renderingFinal.getMemoryBlock(); + if (block.supportBaseAddressModification()) { + block.setBaseAddress(newBase); + } + if(renderingFinal instanceof IRepositionableMemoryRendering2) { + ((IRepositionableMemoryRendering2)renderingFinal).goToAddress(newBase, expression); + } + else { + renderingFinal.goToAddress(newBase); + } + + runOnUIThread(new Runnable(){ + public void run() { + CTabItem selection = activeFolder.getSelection(); + selection.setData(KEY_EXPRESSION, expression); + fGotoAddressBar.handleExpressionStatus(Status.OK_STATUS); + updateLabel(selection, renderingFinal); + } + }); + } catch (final DebugException e1) { + // widgets update require Display + runOnUIThread(new Runnable(){ + public void run() { + fGotoAddressBar.handleExpressionStatus(new Status(Status.ERROR, MemoryBrowserPlugin.PLUGIN_ID, + Messages.getString("MemoryBrowser.FailedToGoToAddressTitle"), e1)); //$NON-NLS-1$ + } + }); + } + } + }.start(); + } + } + } + + private void updateLabel(CTabItem tab, IMemoryRendering rendering) { + // The default is to use the label provided by the base rendering + // interface. + String label = rendering.getLabel(); + + // If the rendering provides access to its viewport address (the first + // address shown in the rendering, subject to scrolling), display that + // in the tab rather than the expression that was used when the tab was + // first created. + if (rendering instanceof IMemoryRenderingViewportProvider) { + BigInteger viewportAddress = ((IMemoryRenderingViewportProvider)rendering).getViewportAddress(); + + // The base label generation puts the rendering type name in "<>" and + // appends it to the label. Fish that out + String renderingType = null; + int i = label.indexOf('<'); + if (i >= 0) { + renderingType = label.substring(i); + } + + label = null; + + // If a memory space is involved, we want to include its ID in the label + String memorySpaceID = (String)tab.getData(KEY_MEMORY_SPACE); + if (memorySpaceID != null) { + IMemoryBlockRetrieval retrieval = (IMemoryBlockRetrieval) tab.getParent().getData(KEY_RETRIEVAL); + if (retrieval instanceof IMemorySpaceAwareMemoryBlockRetrieval) { + label = ((IMemorySpaceAwareMemoryBlockRetrieval)retrieval).encodeAddress("0x" + viewportAddress.toString(16), memorySpaceID) + ' ' + renderingType; + } + } + if (label == null) { + label = "0x" + viewportAddress.toString(16) + ' ' + renderingType; + } + + // Allow the memory block to customize the label. The platform's + // Memory view support this (it was done in the call to + // rendering.getLabel() above) + IMemoryBlock block = rendering.getMemoryBlock(); + ILabelDecorator labelDec = (ILabelDecorator)block.getAdapter(ILabelDecorator.class); + if (labelDec != null) { + String newLabel = labelDec.decorateText(label, rendering); + if (newLabel != null) { + label = newLabel; + } + } + } + + tab.setText(label); + } + + private CTabFolder createTabFolder(Composite parent) + { + final CTabFolder folder = new CTabFolder(parent, SWT.NO_REDRAW_RESIZE | SWT.NO_TRIM | SWT.FLAT); + + ColorRegistry reg = JFaceResources.getColorRegistry(); + Color c1 = reg.get("org.eclipse.ui.workbench.ACTIVE_TAB_BG_START"), //$NON-NLS-1$ + c2 = reg.get("org.eclipse.ui.workbench.ACTIVE_TAB_BG_END"); //$NON-NLS-1$ + folder.setSelectionBackground(new Color[] {c1, c2}, new int[] {100}, true); + folder.setSelectionForeground(reg.get("org.eclipse.ui.workbench.ACTIVE_TAB_TEXT_COLOR")); //$NON-NLS-1$ + folder.setSimple(PlatformUI.getPreferenceStore().getBoolean(IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS)); + folder.setBorderVisible(true); + + // listener to dispose rendering resources for each closed tab + folder.addCTabFolder2Listener(new CTabFolder2Adapter() { + @Override + public void close(CTabFolderEvent event) { + event.doit = true; + CTabItem item = (CTabItem) event.item; + disposeTab(item); + } + }); + + // listener to dispose rendering resources for all tab items when view part is closed + folder.addDisposeListener(new DisposeListener() { + public void widgetDisposed(DisposeEvent e) { + for(CTabItem tab : folder.getItems()) { + disposeTab(tab); + } + folder.removeDisposeListener(this); + } + }); + return folder; + } + + // these utility methods allow us restrict the scope of the unavoidable @SuppressWarnings + + @SuppressWarnings("unchecked") + private static Map getRenderings(CTabItem tabItem) { + return (Map)tabItem.getData(KEY_RENDERINGS); + } + + @SuppressWarnings("unchecked") + private static List getMemoryBlocks(CTabItem tabItem) { + return (List)tabItem.getData(KEY_MEMORY_BLOCKS); + } + + + /** + * dispose rendering resources associated with the tab item + * @param item + */ + private void disposeTab(CTabItem item ) { + if (item.isDisposed()) + return; + + IMemoryRenderingContainer container = (IMemoryRenderingContainer) item.getData(KEY_CONTAINER); + fCurrentContainers.remove( container ); + Map map = getRenderings(item); + Collection renderings = map.values(); + for (IMemoryRendering rendering : renderings) { + // always deactivate rendering before disposing it. + rendering.deactivated(); + rendering.dispose(); + if (rendering == fActiveRendering) { + fActiveRendering = null; + getSite().getSelectionProvider().setSelection(new StructuredSelection()); + } + } + map.clear(); + + List blocks = getMemoryBlocks(item); + for (IMemoryBlockExtension block : blocks) { + try { + block.dispose(); + } catch (DebugException e) { + MemoryBrowserPlugin.getDefault().getLog().log(new Status(Status.ERROR, MemoryBrowserPlugin.PLUGIN_ID, "Could not dispose memory block", e)); //$NON-NLS-1$ + } + } + blocks.clear(); + } + + private CTabItem createTab(CTabFolder tabFolder, int index) { + int swtStyle = SWT.CLOSE; + CTabItem tab = new CTabItem(tabFolder, swtStyle, index); + tab.setData(KEY_RENDERINGS, new HashMap()); + tab.setData(KEY_MEMORY_BLOCKS, new ArrayList()); + return tab; + } + + private void hookContextMenu() { + MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$ + menuMgr.setRemoveAllWhenShown(true); + menuMgr.addMenuListener(new IMenuListener() { + public void menuAboutToShow(IMenuManager manager) { + MemoryBrowser.this.fillContextMenu(manager); + } + }); + Menu menu = menuMgr.createContextMenu(getControl()); + getControl().setMenu(menu); + } + + private void contributeToActionBars() { + IActionBars bars = getViewSite().getActionBars(); + fillLocalPullDown(bars.getMenuManager()); + fillLocalToolBar(bars.getToolBarManager()); + } + + private void fillLocalPullDown(IMenuManager manager) { + + + MenuManager sub = new MenuManager(Messages.getString("MemoryBrowser.DefaultRendering")); //$NON-NLS-1$ + + for(final IMemoryRenderingType type : getRenderingTypes()) + { + final Action action = new Action( + type.getLabel(), IAction.AS_RADIO_BUTTON) + { + @Override + public void run() + { + setDefaultRenderingTypeId(type.getId()); + } + }; + action.setChecked(type.getId().equals(getDefaultRenderingTypeId())); + sub.add(action); + } + + manager.add(sub); + manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); + } + + private void fillContextMenu(IMenuManager manager) { + manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); + } + + private void fillLocalToolBar(IToolBarManager manager) { + manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); + } + + private void makeActions() { + + } + + private IMemoryRenderingType[] getRenderingTypes() + { + return MemoryRenderingManager.getDefault().getRenderingTypes(new IMemoryBlockExtension(){ + public void connect(Object client) {} + public void disconnect(Object client) {} + public void dispose() throws DebugException {} + public int getAddressSize() throws DebugException { return 0; } + public int getAddressableSize() throws DebugException { return 0; } + public BigInteger getBigBaseAddress() throws DebugException { return null; } + public BigInteger getBigLength() throws DebugException { return null; } + public MemoryByte[] getBytesFromAddress(BigInteger address, long units) throws DebugException { return null; } + public MemoryByte[] getBytesFromOffset(BigInteger unitOffset, long addressableUnits) throws DebugException { return null; } + public Object[] getConnections() { return null; } + public String getExpression() { return null; } + public BigInteger getMemoryBlockEndAddress() throws DebugException { return null; } + public IMemoryBlockRetrieval getMemoryBlockRetrieval() { return null; } + public BigInteger getMemoryBlockStartAddress() throws DebugException { return null; } + public void setBaseAddress(BigInteger address) throws DebugException {} + public void setValue(BigInteger offset, byte[] bytes) throws DebugException {} + public boolean supportBaseAddressModification() throws DebugException { return false; } + public boolean supportsChangeManagement() { return false; } + public byte[] getBytes() throws DebugException { return null; } + public long getLength() { return 0; } + public long getStartAddress() { return 0; } + public void setValue(long offset, byte[] bytes) throws DebugException {} + public boolean supportsValueModification() { return false; } + public IDebugTarget getDebugTarget() { return null; } + public ILaunch getLaunch() { return null; } + public String getModelIdentifier() { return null; } + @SuppressWarnings("rawtypes") + public Object getAdapter(Class adapter) { return null; } + }); + } + + @Override + public void setFocus() { + getControl().setFocus(); + } + + public void debugContextChanged(DebugContextEvent event) { + handleDebugContextChanged(((StructuredSelection) event.getContext()).getFirstElement()); + } + + private final class MemoryBrowserRenderingContainer implements + IMemoryRenderingContainer { + private final List renderings = new ArrayList(); + + private MemoryBrowserRenderingContainer() { + } + + public void addMemoryRendering(IMemoryRendering rendering) { + // do not allow duplicated objects + if (!renderings.contains(rendering)) { + renderings.add(rendering); + } + } + + public IMemoryRendering getActiveRendering() { + return renderings.isEmpty() ? null : renderings.get(renderings.size() -1); + } + + public String getId() { + return "???"; //$NON-NLS-1$ + } + + public String getLabel() { + IMemoryRendering rendering = getActiveRendering(); + return rendering != null ? rendering.getLabel() : null; + } + + public IMemoryRenderingSite getMemoryRenderingSite() { + return MemoryBrowser.this; + } + + public IMemoryRendering[] getRenderings() { + return renderings.toArray(new IMemoryRendering[renderings.size()]); + } + + public void removeMemoryRendering(IMemoryRendering rendering) { + renderings.remove(rendering); + } + } + + private final class RenderingPropertyChangeListener implements + IPropertyChangeListener { + private final CTabItem tab; + private final IMemoryRendering newRendering; + + private RenderingPropertyChangeListener(CTabItem tab, + IMemoryRendering newRendering) { + this.tab = tab; + this.newRendering = newRendering; + } + + public void propertyChange(final PropertyChangeEvent event) { + WorkbenchJob job = new WorkbenchJob("MemoryBrowser PropertyChanged") { //$NON-NLS-1$ + @Override + public IStatus runInUIThread(IProgressMonitor monitor) { + if(tab.isDisposed()) + return Status.OK_STATUS; + + if (event.getProperty().equals(IBasicPropertyConstants.P_TEXT)) + updateLabel(tab, newRendering); + return Status.OK_STATUS; + } + }; + job.setSystem(true); + job.schedule(); + } + } + + private class GetMemorySpacesRequest extends CRequest implements IMemorySpaceAwareMemoryBlockRetrieval.GetMemorySpacesRequest { + String [] fMemorySpaces; + public String[] getMemorySpaces() { + return fMemorySpaces; + } + public void setMemorySpaces(String[] memorySpaceIds) { + fMemorySpaces = memorySpaceIds; + } + } + + public void handleDebugContextChanged(final Object context) { + if(defaultRenderingTypeId == null) + return; + + IAdaptable adaptable = null; + IMemoryBlockRetrieval retrieval = null; + ILaunch launch = null; + + if(context instanceof IAdaptable) + { + adaptable = (IAdaptable) context; + retrieval = ((IMemoryBlockRetrieval) adaptable.getAdapter(IMemoryBlockRetrieval.class)); + launch = ((ILaunch) adaptable.getAdapter(ILaunch.class)); + } + + if(retrieval != null && launch != null && !launch.isTerminated()) { + if (retrieval instanceof IMemorySpaceAwareMemoryBlockRetrieval) { + final IMemoryBlockRetrieval _retrieval = retrieval; + ((IMemorySpaceAwareMemoryBlockRetrieval)retrieval).getMemorySpaces(context, new GetMemorySpacesRequest(){ + @Override + public void done() { + updateTab(_retrieval, context, isSuccess() ? getMemorySpaces() : new String[0]); + } + }); + } + else { + updateTab(retrieval, context, new String[0]); + } + } + else { + handleUnsupportedSelection(); + } + + fGotoMemorySpaceControl.pack(true); + fStackLayout.topControl.getParent().layout(true); + } + + /** + * Called to update the tab once the asynchronous query for memory spaces + * has returned a result. + * + * @param retrieval + * the retrieval object associated with the newly active debug + * context + * @param context + * the newly active context + * @param memorySpaces + * the memory spaces, if applicable. Otherwise an empty array. + */ + private void updateTab(final IMemoryBlockRetrieval retrieval, final Object context, final String[] memorySpaces) { + // GUI activity must be on the main thread + runOnUIThread(new Runnable(){ + public void run() { + if (fGotoAddressBarControl.isDisposed()) { + return; + } + + fGotoAddressBarControl.setVisible(true); + + // If we've already created a tab folder for this retrieval + // object, bring it to the forefront. Otherwise create the + // folder. + CTabFolder tabFolder = fContextFolders.get(retrieval); + if(tabFolder != null) { + fStackLayout.topControl = tabFolder; + handleTabActivated(tabFolder.getSelection()); + } + else { + tabFolder = createTabFolder(fRenderingsComposite); + tabFolder.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) {} + public void widgetSelected(SelectionEvent e) { + CTabItem tabItem = (CTabItem)e.item; + updateExpression(tabItem); + updateMemorySpaceControlSelection(tabItem); + fGotoAddressBar.loadSavedExpressions(context, fGotoMemorySpaceControl.isVisible() ? fGotoMemorySpaceControl.getText() : null); + getSite().getSelectionProvider().setSelection(new StructuredSelection(tabItem.getData(KEY_RENDERING))); + handleTabActivated(tabItem); + } + }); + + tabFolder.setData(KEY_RETRIEVAL, retrieval); + fContextFolders.put(retrieval, tabFolder); + fStackLayout.topControl = tabFolder; + // set empty initial expression + fGotoAddressBar.setExpressionText(""); //$NON-NLS-1$ + fGotoAddressBar.loadSavedExpressions(context, fGotoMemorySpaceControl.isVisible() ? fGotoMemorySpaceControl.getText() : null); + } + // update debug context to the new selection + tabFolder.setData(KEY_CONTEXT, context); + + + final CTabFolder activeFolder = tabFolder; + if (!activeFolder.equals(tabFolder)) { + return; + } + + // Don't expose the memory spaces widget if there are none or + // only one memory space involved. + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=309032#c50 + if (memorySpaces.length >= 2) { + fGotoMemorySpaceControl.setItems(memorySpaces); + + // Add the '----' (N/A) entry unless the retrieval object + // says it requires a memory space ID in all cases + boolean addNA = true; + if (retrieval instanceof IMemorySpaceAwareMemoryBlockRetrieval) { + addNA = !((IMemorySpaceAwareMemoryBlockRetrieval)retrieval).creatingBlockRequiresMemorySpaceID(); + } + if (addNA) { + fGotoMemorySpaceControl.add(NA_MEMORY_SPACE_ID, 0); + } + setMemorySpaceControlVisible(true); + } + else { + fGotoMemorySpaceControl.setItems(new String[0]); + setMemorySpaceControlVisible(false); + } + + updateExpression(activeFolder.getSelection()); + updateMemorySpaceControlSelection(activeFolder.getSelection()); + fGotoAddressBar.loadSavedExpressions(context, fGotoMemorySpaceControl.isVisible() ? fGotoMemorySpaceControl.getText() : null); + + fStackLayout.topControl.getParent().layout(true); + } + }); + } + + /** + * Update the expression text in goto address widget to reflect the memory + * rendering expression + * + * @param item + * the active tab; may be null if in a "fresh" memory browser instance + */ + protected void updateExpression(CTabItem activeFolder) { + String expression = (activeFolder != null) ? (String) activeFolder.getData(KEY_EXPRESSION) : null; + if (expression != null) { + fGotoAddressBar.setExpressionText(expression); + } + } + + protected final void handleTabActivated(CTabItem item) { + if (item != null) { + updateActiveRendering((IMemoryRendering) item.getData(KEY_RENDERING)); + } + } + + private void updateActiveRendering(IMemoryRendering rendering) { + if (fActiveRendering == rendering) { + return; + } + if (fActiveRendering != null) { + fActiveRendering.deactivated(); + fActiveRendering.becomesHidden(); + } + if (rendering != null) { + rendering.activated(); + rendering.becomesVisible(); + } + fActiveRendering = rendering; + } + + private void setMemorySpaceControlVisible(boolean visible) { + FormData data = (FormData)fGotoAddressBarControl.getLayoutData(); + if (visible) { + data.left = new FormAttachment(fGotoMemorySpaceControl); + } + else { + data.left = new FormAttachment(0); + } + fGotoMemorySpaceControl.setVisible(visible); + + } + + /** + * Update the selection in the memory space combobox to reflect the memory + * space being shown in the given tab + * + * @param item + * the active tab; may be null if in a "fresh" memory browser instance + */ + private void updateMemorySpaceControlSelection(CTabItem item) { + String[] memorySpaces = fGotoMemorySpaceControl.getItems(); + if (memorySpaces.length > 0 ) { + // Don't assume that the memory space previously set in the tab + // is one of the ones now available. If it isn't, then select + // the first available one and update the tab data + boolean foundIt = false; + if (item != null) { + String currentMemorySpace = (String) item.getData(KEY_MEMORY_SPACE); + if (currentMemorySpace != null) { + assert currentMemorySpace.length() > 0; + for (String memorySpace : memorySpaces) { + if (memorySpace.equals(currentMemorySpace)) { + foundIt = true; + fGotoMemorySpaceControl.setText(currentMemorySpace); + break; + } + } + } + } + if (!foundIt) { + fGotoMemorySpaceControl.select(0); + if (item != null) { + item.setData(KEY_MEMORY_SPACE, null); + } + } + fGotoMemorySpaceControl.setVisible(true); + } + else { + fGotoMemorySpaceControl.setVisible(false); + } + fGotoMemorySpaceControl.getParent().layout(true); + + } + + private String getDefaultRenderingTypeId() + { + return defaultRenderingTypeId; + } + + public void setDefaultRenderingTypeId(String id) + { + defaultRenderingTypeId = id; + IPreferenceStore store = MemoryBrowserPlugin.getDefault().getPreferenceStore(); + store.setValue(PREF_DEFAULT_RENDERING, defaultRenderingTypeId); + } + + /** + * Populate given tab with a rendering positioned at specified expression and memory space. + * Will create a new rendering if one does not exist for the given memory space + * + * @param tab item to populate + * @param retrieval memory service to retrieve memory block from + * @param context memory block would be retrieved + * @param memorySpaceId of the expression or null if not supported + * @param expression from where to retrieve the memory block + * @return return the memory rendering or null if could not be created + * + * @throws DebugException if could not retrieve memory block (e.g. invalid expression) + */ + private IMemoryRendering populateTabWithRendering(final CTabItem tab, final IMemoryBlockRetrieval retrieval, Object context, String memorySpaceId, String expression) throws DebugException { + IMemoryRenderingType type = DebugUITools.getMemoryRenderingManager().getRenderingType(getDefaultRenderingTypeId()); + IMemoryRenderingContainer container = (IMemoryRenderingContainer)tab.getData(KEY_CONTAINER); + if (container == null) { + container = new MemoryBrowserRenderingContainer(); + fCurrentContainers.add(container); + } + + IMemoryRendering rendering = getRenderings(tab).get(memorySpaceId); + if (rendering == null) { + // No rendering yet. Create rendering and associated memory block. + // createMemoryBlock will throw if expression cannot be resolved + IMemoryBlockExtension block = createMemoryBlock(retrieval, expression, context, memorySpaceId); + try { + rendering = type.createRendering(); + } catch (CoreException e) { + MemoryBrowserPlugin.getDefault().getLog().log(new Status(Status.ERROR, MemoryBrowserPlugin.PLUGIN_ID, "", e)); //$NON-NLS-1$ + return null; + } + + rendering.init(container, block); + container.addMemoryRendering(rendering); + rendering.createControl(tab.getParent()); + getRenderings(tab).put(memorySpaceId, rendering); + getMemoryBlocks(tab).add(block); + rendering.addPropertyChangeListener(new RenderingPropertyChangeListener(tab, rendering)); + } + + tab.setControl(rendering.getControl()); + tab.getParent().setSelection(0); + tab.setData(KEY_RENDERING, rendering); + tab.setData(KEY_MEMORY_SPACE, memorySpaceId); + tab.setData(KEY_CONTAINER, container); + tab.setData(KEY_RENDERING_TYPE, type); + getSite().getSelectionProvider().setSelection(new StructuredSelection(tab.getData(KEY_RENDERING))); + updateLabel(tab, rendering); + + return rendering; + } + + + private void releaseTabFolder(final IMemoryBlockRetrieval retrieval) + { + final CTabFolder folder = fContextFolders.get(retrieval); + if(folder != null) + { + Runnable run = new Runnable() { + public void run() { + for(CTabItem tab : folder.getItems()) { + disposeTab(tab); + } + fContextFolders.remove(retrieval); + folder.dispose(); + + if (fStackLayout.topControl.equals(folder)) { + handleUnsupportedSelection(); + } + } + }; + runOnUIThread(run); + } + } + + class SelectionProviderAdapter implements ISelectionProvider { + + List listeners = new ArrayList(); + + ISelection theSelection = StructuredSelection.EMPTY; + + public void addSelectionChangedListener(ISelectionChangedListener listener) { + listeners.add(listener); + } + + public ISelection getSelection() { + return theSelection; + } + + public void removeSelectionChangedListener( + ISelectionChangedListener listener) { + listeners.remove(listener); + } + + public void setSelection(ISelection selection) { + theSelection = selection; + final SelectionChangedEvent e = new SelectionChangedEvent(this, selection); + Object[] listenersArray = listeners.toArray(); + + for (int i = 0; i < listenersArray.length; i++) { + final ISelectionChangedListener l = (ISelectionChangedListener) listenersArray[i]; + SafeRunner.run(new SafeRunnable() { + public void run() { + l.selectionChanged(e); + } + }); + } + } + } + + /** + * create a memory block + * @param retrieval memory block retrieval. + * @param expression expression to be evaluated to an addressL + * @param context context for evaluating the expression. This is typically + * a debug element. + * @param memorySpaceID a memory space identifier, or null if n/a + * @return a memory block based on the given expression and context + * @throws DebugException if unable to retrieve the specified memory + */ + private IMemoryBlockExtension createMemoryBlock(IMemoryBlockRetrieval retrieval, String expression, Object context, String memorySpaceID) throws DebugException { + IMemoryBlockExtension block = null; + IMemoryBlockRetrievalExtension retrievalExtension = null; + if (retrieval instanceof IMemoryBlockRetrievalExtension) { + retrievalExtension = (IMemoryBlockRetrievalExtension) retrieval; + } else if(retrieval instanceof IAdaptable) { + retrievalExtension = (IMemoryBlockRetrievalExtension)((IAdaptable) retrieval).getAdapter(IMemoryBlockRetrievalExtension.class); + } + if (retrievalExtension != null) { + if (retrievalExtension instanceof IMemorySpaceAwareMemoryBlockRetrieval) { + block = ((IMemorySpaceAwareMemoryBlockRetrieval)retrievalExtension).getMemoryBlock(expression, context, memorySpaceID); + } + else { + block = retrievalExtension.getExtendedMemoryBlock(expression, context); + } + } + if ( block == null ) { + throw new DebugException(new Status(Status.ERROR, MemoryBrowserPlugin.PLUGIN_ID, "Extended Memory Block could not be obtained")); //$NON-NLS-1$ + } + return block; + } + + /** + * Get a memory address for an expression in a given context. + * @param retrieval + * @param expression + * @param context + * @return BigInteger address of the expression + * @throws DebugException + */ + private BigInteger getExpressionAddress(IMemoryBlockRetrieval retrieval, String expression, Object context, String memorySpaceId) throws DebugException { + // Until 257842 issue is solved this is done via IMemoryBlockRetrievalExtension API. + IMemoryBlockExtension newBlock = createMemoryBlock(retrieval, expression, context, memorySpaceId); + BigInteger address = newBlock.getBigBaseAddress(); + newBlock.dispose(); + return address; + } + + /** + * Execute runnable on UI thread if the current thread is not an UI thread. + * Otherwise execute it directly. + * + * @param runnable + * the runnable to execute + */ + private void runOnUIThread(final Runnable runnable) { + if (Display.getCurrent() != null) { + runnable.run(); + } + else { + UIJob job = new UIJob("Memory Browser UI Job"){ //$NON-NLS-1$ + @Override + public IStatus runInUIThread(IProgressMonitor monitor) { + runnable.run(); + return Status.OK_STATUS; + }}; + job.setSystem(true); + job.schedule(); + } + } +} From bca8fe06a1b09baf4dc7cde31a17dc2fcca42f79 Mon Sep 17 00:00:00 2001 From: Doug Schaefer Date: Fri, 2 Sep 2011 20:48:39 -0400 Subject: [PATCH 27/29] Fix poms for tycho 0.13. --- build/org.eclipse.cdt.gnu.build-feature/pom.xml | 3 ++- build/org.eclipse.cdt.gnu.build.source-feature/pom.xml | 3 ++- cross/org.eclipse.cdt.build.crossgcc-feature/pom.xml | 3 ++- debug/org.eclipse.cdt.gdb-feature/pom.xml | 3 ++- debug/org.eclipse.cdt.gdb.source-feature/pom.xml | 3 ++- debug/org.eclipse.cdt.gnu.debug-feature/pom.xml | 3 ++- debug/org.eclipse.cdt.gnu.debug.source-feature/pom.xml | 3 ++- dsf-gdb/org.eclipse.cdt.gnu.dsf-feature/pom.xml | 3 ++- dsf-gdb/org.eclipse.cdt.gnu.dsf.source-feature/pom.xml | 3 ++- dsf/org.eclipse.cdt.examples.dsf-feature/pom.xml | 3 ++- jtag/org.eclipse.cdt.debug.gdbjtag-feature/pom.xml | 3 ++- jtag/org.eclipse.cdt.debug.gdbjtag.core/pom.xml | 2 +- lrparser/org.eclipse.cdt.core.lrparser.sdk.feature/pom.xml | 3 ++- lrparser/org.eclipse.cdt.core.lrparser.source.feature/pom.xml | 3 ++- memory/org.eclipse.cdt.debug.ui.memory-feature/pom.xml | 3 ++- p2/org.eclipse.cdt.p2-feature/pom.xml | 3 ++- releng/org.eclipse.cdt-feature/pom.xml | 3 ++- releng/org.eclipse.cdt.platform-feature/pom.xml | 3 ++- releng/org.eclipse.cdt.platform.source-feature/pom.xml | 3 ++- releng/org.eclipse.cdt.sdk-feature/pom.xml | 3 ++- upc/org.eclipse.cdt.bupc-feature/pom.xml | 3 ++- upc/org.eclipse.cdt.core.parser.upc.sdk.feature/pom.xml | 3 ++- upc/org.eclipse.cdt.core.parser.upc.source.feature/pom.xml | 3 ++- util/org.eclipse.cdt.util-feature/pom.xml | 3 ++- windows/org.eclipse.cdt.msw-feature/pom.xml | 3 ++- xlc/org.eclipse.cdt.xlc.sdk-feature/pom.xml | 3 ++- xlc/org.eclipse.cdt.xlc.source.feature/pom.xml | 3 ++- 27 files changed, 53 insertions(+), 27 deletions(-) diff --git a/build/org.eclipse.cdt.gnu.build-feature/pom.xml b/build/org.eclipse.cdt.gnu.build-feature/pom.xml index 3f346e92611..d7cb7798566 100644 --- a/build/org.eclipse.cdt.gnu.build-feature/pom.xml +++ b/build/org.eclipse.cdt.gnu.build-feature/pom.xml @@ -11,6 +11,7 @@ ../../pom.xml - org.eclipse.cdt.gnu.build-feature + org.eclipse.cdt.features + org.eclipse.cdt.gnu.build eclipse-feature diff --git a/build/org.eclipse.cdt.gnu.build.source-feature/pom.xml b/build/org.eclipse.cdt.gnu.build.source-feature/pom.xml index c6e6e2d2705..38de6b463b4 100644 --- a/build/org.eclipse.cdt.gnu.build.source-feature/pom.xml +++ b/build/org.eclipse.cdt.gnu.build.source-feature/pom.xml @@ -11,6 +11,7 @@ ../../pom.xml - org.eclipse.cdt.gnu.build.source-feature + org.eclipse.cdt.features + org.eclipse.cdt.gnu.build.source eclipse-feature diff --git a/cross/org.eclipse.cdt.build.crossgcc-feature/pom.xml b/cross/org.eclipse.cdt.build.crossgcc-feature/pom.xml index 5e69295e395..0dbd208747f 100644 --- a/cross/org.eclipse.cdt.build.crossgcc-feature/pom.xml +++ b/cross/org.eclipse.cdt.build.crossgcc-feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml + org.eclipse.cdt.features 1.0.0-SNAPSHOT - org.eclipse.cdt.build.crossgcc-feature + org.eclipse.cdt.build.crossgcc eclipse-feature diff --git a/debug/org.eclipse.cdt.gdb-feature/pom.xml b/debug/org.eclipse.cdt.gdb-feature/pom.xml index 9557483fafa..37e0cb11ad3 100644 --- a/debug/org.eclipse.cdt.gdb-feature/pom.xml +++ b/debug/org.eclipse.cdt.gdb-feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml - org.eclipse.cdt.gdb-feature + org.eclipse.cdt.features + org.eclipse.cdt.gdb eclipse-feature 7.0.0-SNAPSHOT diff --git a/debug/org.eclipse.cdt.gdb.source-feature/pom.xml b/debug/org.eclipse.cdt.gdb.source-feature/pom.xml index 640772e3b98..20ba4cadd25 100644 --- a/debug/org.eclipse.cdt.gdb.source-feature/pom.xml +++ b/debug/org.eclipse.cdt.gdb.source-feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml - org.eclipse.cdt.gdb.source-feature + org.eclipse.cdt.features + org.eclipse.cdt.gdb.source eclipse-feature 7.0.0-SNAPSHOT diff --git a/debug/org.eclipse.cdt.gnu.debug-feature/pom.xml b/debug/org.eclipse.cdt.gnu.debug-feature/pom.xml index 5398f7632aa..75d1005c392 100644 --- a/debug/org.eclipse.cdt.gnu.debug-feature/pom.xml +++ b/debug/org.eclipse.cdt.gnu.debug-feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml - org.eclipse.cdt.gnu.debug-feature + org.eclipse.cdt.feature + org.eclipse.cdt.gnu.debug eclipse-feature 7.1.0-SNAPSHOT diff --git a/debug/org.eclipse.cdt.gnu.debug.source-feature/pom.xml b/debug/org.eclipse.cdt.gnu.debug.source-feature/pom.xml index d3dad153249..43f7cc7e261 100644 --- a/debug/org.eclipse.cdt.gnu.debug.source-feature/pom.xml +++ b/debug/org.eclipse.cdt.gnu.debug.source-feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml - org.eclipse.cdt.gnu.debug.source-feature + org.eclipse.cdt.features + org.eclipse.cdt.gnu.debug.source eclipse-feature 7.1.0-SNAPSHOT diff --git a/dsf-gdb/org.eclipse.cdt.gnu.dsf-feature/pom.xml b/dsf-gdb/org.eclipse.cdt.gnu.dsf-feature/pom.xml index 9dfaab0d04a..15429734414 100644 --- a/dsf-gdb/org.eclipse.cdt.gnu.dsf-feature/pom.xml +++ b/dsf-gdb/org.eclipse.cdt.gnu.dsf-feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml + org.eclipse.cdt.feature 4.0.0-SNAPSHOT - org.eclipse.cdt.gdb.dsf-feature + org.eclipse.cdt.gnu.dsf eclipse-feature diff --git a/dsf-gdb/org.eclipse.cdt.gnu.dsf.source-feature/pom.xml b/dsf-gdb/org.eclipse.cdt.gnu.dsf.source-feature/pom.xml index ec4f9e758ec..e2800dc1574 100644 --- a/dsf-gdb/org.eclipse.cdt.gnu.dsf.source-feature/pom.xml +++ b/dsf-gdb/org.eclipse.cdt.gnu.dsf.source-feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml + org.eclipse.cdt.features 4.0.0-SNAPSHOT - org.eclipse.cdt.gdb.dsf.source-feature + org.eclipse.cdt.gnu.dsf.source eclipse-feature diff --git a/dsf/org.eclipse.cdt.examples.dsf-feature/pom.xml b/dsf/org.eclipse.cdt.examples.dsf-feature/pom.xml index 4441f062917..dd728c9dbb3 100644 --- a/dsf/org.eclipse.cdt.examples.dsf-feature/pom.xml +++ b/dsf/org.eclipse.cdt.examples.dsf-feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml + org.eclipse.cdt.features 2.1.0-SNAPSHOT - org.eclipse.cdt.examples.dsf-feature + org.eclipse.cdt.examples.dsf eclipse-feature diff --git a/jtag/org.eclipse.cdt.debug.gdbjtag-feature/pom.xml b/jtag/org.eclipse.cdt.debug.gdbjtag-feature/pom.xml index c944e575329..a4455f31a81 100644 --- a/jtag/org.eclipse.cdt.debug.gdbjtag-feature/pom.xml +++ b/jtag/org.eclipse.cdt.debug.gdbjtag-feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml + org.eclipse.cdt.features 7.0.0-SNAPSHOT - org.eclipse.cdtdebug.gdbjtag-feature + org.eclipse.cdt.debug.gdbjtag eclipse-feature diff --git a/jtag/org.eclipse.cdt.debug.gdbjtag.core/pom.xml b/jtag/org.eclipse.cdt.debug.gdbjtag.core/pom.xml index cf9e28368c9..b3da39ced44 100644 --- a/jtag/org.eclipse.cdt.debug.gdbjtag.core/pom.xml +++ b/jtag/org.eclipse.cdt.debug.gdbjtag.core/pom.xml @@ -11,7 +11,7 @@ ../../pom.xml - 8.0.0-SNAPSHOT + 8.0.1-SNAPSHOT org.eclipse.cdt.debug.gdbjtag.core eclipse-plugin diff --git a/lrparser/org.eclipse.cdt.core.lrparser.sdk.feature/pom.xml b/lrparser/org.eclipse.cdt.core.lrparser.sdk.feature/pom.xml index ff465dede44..43fe2313723 100644 --- a/lrparser/org.eclipse.cdt.core.lrparser.sdk.feature/pom.xml +++ b/lrparser/org.eclipse.cdt.core.lrparser.sdk.feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml + org.eclipse.cdt.features 5.2.0-SNAPSHOT - org.eclipse.cdt.core.lrparser.sdk.feature + org.eclipse.cdt.core.lrparser.sdk eclipse-feature diff --git a/lrparser/org.eclipse.cdt.core.lrparser.source.feature/pom.xml b/lrparser/org.eclipse.cdt.core.lrparser.source.feature/pom.xml index 4b49629a7ef..e70437ff8d7 100644 --- a/lrparser/org.eclipse.cdt.core.lrparser.source.feature/pom.xml +++ b/lrparser/org.eclipse.cdt.core.lrparser.source.feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml + org.eclipse.cdt.features 5.2.0-SNAPSHOT - org.eclipse.cdt.core.lrparser.source.feature + org.eclipse.cdt.core.lrparser.source eclipse-feature diff --git a/memory/org.eclipse.cdt.debug.ui.memory-feature/pom.xml b/memory/org.eclipse.cdt.debug.ui.memory-feature/pom.xml index 2fca78c685c..a762d34f0dc 100644 --- a/memory/org.eclipse.cdt.debug.ui.memory-feature/pom.xml +++ b/memory/org.eclipse.cdt.debug.ui.memory-feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml + org.eclipse.cdt.features 2.1.100-SNAPSHOT - org.eclipse.cdt.debug.ui.memory-feature + org.eclipse.cdt.debug.ui.memory eclipse-feature diff --git a/p2/org.eclipse.cdt.p2-feature/pom.xml b/p2/org.eclipse.cdt.p2-feature/pom.xml index 3016643ba12..2cbde6f9d5e 100644 --- a/p2/org.eclipse.cdt.p2-feature/pom.xml +++ b/p2/org.eclipse.cdt.p2-feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml + org.eclipse.cdt.features 1.0.0-SNAPSHOT - org.eclipse.cdt.p2-feature + org.eclipse.cdt.p2 eclipse-feature diff --git a/releng/org.eclipse.cdt-feature/pom.xml b/releng/org.eclipse.cdt-feature/pom.xml index 6d0c62769e1..028f479703a 100644 --- a/releng/org.eclipse.cdt-feature/pom.xml +++ b/releng/org.eclipse.cdt-feature/pom.xml @@ -11,6 +11,7 @@ ../../pom.xml - org.eclipse.cdt-feature + org.eclipse.cdt.features + org.eclipse.cdt eclipse-feature diff --git a/releng/org.eclipse.cdt.platform-feature/pom.xml b/releng/org.eclipse.cdt.platform-feature/pom.xml index ed7f836a907..f42595737f0 100644 --- a/releng/org.eclipse.cdt.platform-feature/pom.xml +++ b/releng/org.eclipse.cdt.platform-feature/pom.xml @@ -11,6 +11,7 @@ ../../pom.xml - org.eclipse.cdt.platform-feature + org.eclipse.cdt.features + org.eclipse.cdt.platform eclipse-feature diff --git a/releng/org.eclipse.cdt.platform.source-feature/pom.xml b/releng/org.eclipse.cdt.platform.source-feature/pom.xml index 54a16327fea..67d6df2f593 100644 --- a/releng/org.eclipse.cdt.platform.source-feature/pom.xml +++ b/releng/org.eclipse.cdt.platform.source-feature/pom.xml @@ -11,6 +11,7 @@ ../../pom.xml - org.eclipse.cdt.platform.source-feature + org.eclipse.cdt.features + org.eclipse.cdt.platform.source eclipse-feature diff --git a/releng/org.eclipse.cdt.sdk-feature/pom.xml b/releng/org.eclipse.cdt.sdk-feature/pom.xml index 8d8fb0696a3..ac901feebff 100644 --- a/releng/org.eclipse.cdt.sdk-feature/pom.xml +++ b/releng/org.eclipse.cdt.sdk-feature/pom.xml @@ -11,6 +11,7 @@ ../../pom.xml - org.eclipse.cdt.sdk-feature + org.eclipse.cdt.features + org.eclipse.cdt.sdk eclipse-feature diff --git a/upc/org.eclipse.cdt.bupc-feature/pom.xml b/upc/org.eclipse.cdt.bupc-feature/pom.xml index 8a069b6827d..7dbcecf3fd7 100644 --- a/upc/org.eclipse.cdt.bupc-feature/pom.xml +++ b/upc/org.eclipse.cdt.bupc-feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml + org.eclipse.cdt.features 1.0.3-SNAPSHOT - org.eclipse.cdt.bupc-feature + org.eclipse.cdt.bupc eclipse-feature diff --git a/upc/org.eclipse.cdt.core.parser.upc.sdk.feature/pom.xml b/upc/org.eclipse.cdt.core.parser.upc.sdk.feature/pom.xml index a5db8467e60..fcd12aef9dc 100644 --- a/upc/org.eclipse.cdt.core.parser.upc.sdk.feature/pom.xml +++ b/upc/org.eclipse.cdt.core.parser.upc.sdk.feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml + org.eclipse.cdt.features 5.1.0-SNAPSHOT - org.eclipse.cdt.core.parser.upc.sdk.feature + org.eclipse.cdt.core.parser.upc.sdk eclipse-feature diff --git a/upc/org.eclipse.cdt.core.parser.upc.source.feature/pom.xml b/upc/org.eclipse.cdt.core.parser.upc.source.feature/pom.xml index 424facea986..589c5e15a0c 100644 --- a/upc/org.eclipse.cdt.core.parser.upc.source.feature/pom.xml +++ b/upc/org.eclipse.cdt.core.parser.upc.source.feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml + org.eclipse.cdt.features 5.1.0-SNAPSHOT - org.eclipse.cdt.core.parser.upc.source.feature + org.eclipse.cdt.core.parser.upc.source eclipse-feature diff --git a/util/org.eclipse.cdt.util-feature/pom.xml b/util/org.eclipse.cdt.util-feature/pom.xml index ee2668cccd5..12d34011929 100644 --- a/util/org.eclipse.cdt.util-feature/pom.xml +++ b/util/org.eclipse.cdt.util-feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml + org.eclipse.cdt.features 5.1.0-SNAPSHOT - org.eclipse.cdt.util-feature + org.eclipse.cdt.util eclipse-feature diff --git a/windows/org.eclipse.cdt.msw-feature/pom.xml b/windows/org.eclipse.cdt.msw-feature/pom.xml index c9dc94c493e..413e52398ec 100644 --- a/windows/org.eclipse.cdt.msw-feature/pom.xml +++ b/windows/org.eclipse.cdt.msw-feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml + org.eclipse.cdt.features 1.0.0-SNAPSHOT - org.eclipse.cdt.msw-feature + org.eclipse.cdt.msw eclipse-feature diff --git a/xlc/org.eclipse.cdt.xlc.sdk-feature/pom.xml b/xlc/org.eclipse.cdt.xlc.sdk-feature/pom.xml index 89d8d8b564f..e13665a81ed 100644 --- a/xlc/org.eclipse.cdt.xlc.sdk-feature/pom.xml +++ b/xlc/org.eclipse.cdt.xlc.sdk-feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml + org.eclipse.cdt.features 6.1.0-SNAPSHOT - org.eclipse.cdt.xlc.sdk-feature + org.eclipse.cdt.xlc.sdk eclipse-feature diff --git a/xlc/org.eclipse.cdt.xlc.source.feature/pom.xml b/xlc/org.eclipse.cdt.xlc.source.feature/pom.xml index 3fca6e7739b..496cfdee59b 100644 --- a/xlc/org.eclipse.cdt.xlc.source.feature/pom.xml +++ b/xlc/org.eclipse.cdt.xlc.source.feature/pom.xml @@ -11,7 +11,8 @@ ../../pom.xml + org.eclipse.cdt.features 6.1.0-SNAPSHOT - org.eclipse.cdt.xlc.source.feature + org.eclipse.cdt.xlc.source eclipse-feature From 5eb921be84ad66f1c3558dd906ef62590b3313fc Mon Sep 17 00:00:00 2001 From: Marc-Andre Laperle Date: Fri, 2 Sep 2011 22:58:26 -0400 Subject: [PATCH 28/29] Fix codan.test pom --- codan/org.eclipse.cdt.codan.core.test/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codan/org.eclipse.cdt.codan.core.test/pom.xml b/codan/org.eclipse.cdt.codan.core.test/pom.xml index 7e3644fc28a..8162828c0ef 100644 --- a/codan/org.eclipse.cdt.codan.core.test/pom.xml +++ b/codan/org.eclipse.cdt.codan.core.test/pom.xml @@ -12,7 +12,7 @@ 1.0.0-SNAPSHOT - org.eclipse.cdt.codan.core.tests + org.eclipse.cdt.codan.core.test eclipse-test-plugin From 0e70cab1786e1e7902164e6f25e3735a3109b092 Mon Sep 17 00:00:00 2001 From: Markus Schorn Date: Tue, 6 Sep 2011 15:52:37 +0200 Subject: [PATCH 29/29] Bug 355052: Type of sizeof expression. --- .../cdt/core/parser/tests/ast2/AST2Tests.java | 23 +++++ .../dom/parser/c/CASTTypeIdExpression.java | 2 +- .../dom/parser/c/CASTUnaryExpression.java | 5 +- .../internal/core/dom/parser/c/CVisitor.java | 27 +++--- .../dom/parser/cpp/semantics/CPPVisitor.java | 83 ++++++++----------- 5 files changed, 81 insertions(+), 59 deletions(-) diff --git a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2Tests.java b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2Tests.java index 9966c5c8390..c6392ba67ef 100644 --- a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2Tests.java +++ b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2Tests.java @@ -7337,4 +7337,27 @@ public class AST2Tests extends AST2BaseTest { assertFalse(((IASTPreprocessorIfdefStatement) stmts[0]).taken()); assertFalse(((IASTPreprocessorIfdefStatement) stmts[1]).taken()); } + + + // void a() { + // typedef float size_t; + // sizeof(10); // wrong - getExpressionType returns float + // sizeof(int); // wrong - getExpressionType returns float + // } + public void testTypeOfSizeof_Bug355052() throws Exception { + final String code = getAboveComment(); + IASTTranslationUnit tu= parseAndCheckBindings(code, ParserLanguage.CPP); + IASTFunctionDefinition a= getDeclaration(tu, 0); + IASTExpressionStatement es= getStatement(a, 1); + assertEquals("unsigned long int", ASTTypeUtil.getType(es.getExpression().getExpressionType())); + es= getStatement(a, 2); + assertEquals("unsigned long int", ASTTypeUtil.getType(es.getExpression().getExpressionType())); + + tu= parseAndCheckBindings(code, ParserLanguage.C); + a= getDeclaration(tu, 0); + es= getStatement(a, 1); + assertEquals("unsigned long int", ASTTypeUtil.getType(es.getExpression().getExpressionType())); + es= getStatement(a, 2); + assertEquals("unsigned long int", ASTTypeUtil.getType(es.getExpression().getExpressionType())); + } } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTTypeIdExpression.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTTypeIdExpression.java index f732e93a0e1..c816c14fd93 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTTypeIdExpression.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTTypeIdExpression.java @@ -94,7 +94,7 @@ public class CASTTypeIdExpression extends ASTNode implements IASTTypeIdExpressio public IType getExpressionType() { if (getOperator() == op_sizeof) { - return CVisitor.getSize_T(this); + return CVisitor.get_SIZE_T(this); } return CVisitor.createType(typeId.getAbstractDeclarator()); } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTUnaryExpression.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTUnaryExpression.java index 7ddb5d5447d..ab1fe112d4a 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTUnaryExpression.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTUnaryExpression.java @@ -107,9 +107,12 @@ public class CASTUnaryExpression extends ASTNode implements IASTUnaryExpression, } public IType getExpressionType() { + int op = getOperator(); + if (op == op_sizeof) { + return CVisitor.get_SIZE_T(this); + } final IType exprType = getOperand().getExpressionType(); IType type = CVisitor.unwrapTypedefs(exprType); - int op = getOperator(); switch(op) { case op_star: if (type instanceof IPointerType || type instanceof IArrayType) { diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CVisitor.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CVisitor.java index b2ee9350d7f..56598d75ef4 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CVisitor.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CVisitor.java @@ -104,6 +104,11 @@ import org.eclipse.cdt.internal.core.parser.util.ContentAssistMatcherFactory; * Collection of methods to find information in an AST. */ public class CVisitor extends ASTQueries { + /** + * + */ + private static final CBasicType UNSIGNED_LONG_INT = new CBasicType(Kind.eInt, IBasicType.IS_LONG | IBasicType.IS_UNSIGNED); + public static class CollectProblemsAction extends ASTVisitor { { shouldVisitDeclarations = true; @@ -646,19 +651,21 @@ public class CVisitor extends ASTQueries { return new CBasicType(Kind.eInt, 0, expr); } - - static IType getSize_T(IASTExpression expr) { - IScope scope = getContainingScope(expr); - IBinding[] bs = scope.find(SIZE_T); - for (IBinding b : bs) { - if (b instanceof IType) { - if (!(b instanceof ICInternalBinding) || - CVisitor.declaredBefore(((ICInternalBinding) b).getPhysicalNode(), expr)) { - return (IType) b; + + static IType get_SIZE_T(IASTExpression expr) { + IASTTranslationUnit tu= expr.getTranslationUnit(); + if (tu != null) { + IBinding[] bs = tu.getScope().find(SIZE_T); + for (IBinding b : bs) { + if (b instanceof IType) { + if (!(b instanceof ICInternalBinding) || + CVisitor.declaredBefore(((ICInternalBinding) b).getPhysicalNode(), expr)) { + return (IType) b; + } } } } - return new CBasicType(Kind.eInt, IBasicType.IS_LONG | IBasicType.IS_UNSIGNED); + return UNSIGNED_LONG_INT; } static IType unwrapTypedefs(IType type) { diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVisitor.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVisitor.java index ebf43313861..e720e48d894 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVisitor.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVisitor.java @@ -137,6 +137,7 @@ import org.eclipse.cdt.core.dom.ast.cpp.ICPPFunctionTemplate; import org.eclipse.cdt.core.dom.ast.cpp.ICPPFunctionType; import org.eclipse.cdt.core.dom.ast.cpp.ICPPMethod; import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespace; +import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespaceScope; import org.eclipse.cdt.core.dom.ast.cpp.ICPPReferenceType; import org.eclipse.cdt.core.dom.ast.cpp.ICPPScope; import org.eclipse.cdt.core.dom.ast.cpp.ICPPSpecialization; @@ -195,12 +196,15 @@ import org.eclipse.cdt.internal.core.index.IIndexScope; * Collection of methods to extract information from a C++ translation unit. */ public class CPPVisitor extends ASTQueries { - public static final char[] SIZE_T = "size_t".toCharArray(); //$NON-NLS-1$ - public static final char[] PTRDIFF_T = "ptrdiff_t".toCharArray(); //$NON-NLS-1$ + private static final CPPBasicType UNSIGNED_LONG = new CPPBasicType(Kind.eInt, IBasicType.IS_LONG | IBasicType.IS_UNSIGNED); + private static final CPPBasicType INT_TYPE = new CPPBasicType(Kind.eInt, 0); + static final char[] BEGIN = "begin".toCharArray(); //$NON-NLS-1$ - public static final String STD = "std"; //$NON-NLS-1$ - public static final String TYPE_INFO= "type_info"; //$NON-NLS-1$ - private static final String INITIALIZER_LIST = "initializer_list"; //$NON-NLS-1$ + static final String STD = "std"; //$NON-NLS-1$ + private static final char[] SIZE_T = "size_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[] INITIALIZER_LIST = "initializer_list".toCharArray(); //$NON-NLS-1$ // Thread-local set of DeclSpecifiers for which auto types are being created. // Used to prevent infinite recursion while processing invalid self-referencing @@ -2091,53 +2095,21 @@ public class CPPVisitor extends ASTQueries { } public static IType getPointerDiffType(final IASTBinaryExpression binary) { - CPPBasicType basicType; - IScope scope = getContainingScope(binary); - IBinding[] bs= CPPSemantics.findBindings(scope, PTRDIFF_T, false, binary); - if (bs.length > 0) { - for (IBinding b : bs) { - if (b instanceof IType && CPPSemantics.declaredBefore(b, binary, false)) { - return (IType) b; - } - } - } - basicType= new CPPBasicType(Kind.eInt, 0); - basicType.setFromExpression(binary); - return basicType; + IType t= getStdType(binary, PTRDIFF_T); + return t != null ? t : INT_TYPE; } - public static IType get_type_info(IASTExpression expression) { - IBinding[] std= expression.getTranslationUnit().getScope().find(STD); - for (IBinding binding : std) { - if (binding instanceof ICPPNamespace) { - IBinding[] typeInfo= ((ICPPNamespace) binding).getNamespaceScope().find(TYPE_INFO); - for (IBinding t : typeInfo) { - if (t instanceof ICPPClassType) { - return (ICPPClassType) t; - } - } - } - } - return new CPPBasicType(Kind.eInt, 0); - } - - public static IType get_SIZE_T(IASTNode sizeofExpr) { - IScope scope = getContainingScope(sizeofExpr); - IBinding[] bs = CPPSemantics.findBindings(scope, SIZE_T, false, sizeofExpr); - if (bs.length > 0 && bs[0] instanceof IType) { - return (IType) bs[0]; - } - return new CPPBasicType(Kind.eInt, IBasicType.IS_LONG | IBasicType.IS_UNSIGNED); - } - - public static ICPPClassTemplate get_initializer_list(IASTNode node) { + private static IType getStdType(final IASTNode node, char[] name) { IBinding[] std= node.getTranslationUnit().getScope().find(STD); for (IBinding binding : std) { if (binding instanceof ICPPNamespace) { - IBinding[] initializer_list= ((ICPPNamespace) binding).getNamespaceScope().find(INITIALIZER_LIST); - for (IBinding t : initializer_list) { - if (t instanceof ICPPClassTemplate) { - return (ICPPClassTemplate) t; + final ICPPNamespaceScope scope = ((ICPPNamespace) binding).getNamespaceScope(); + IBinding[] bs= CPPSemantics.findBindings(scope, name, false, node); + if (bs.length > 0) { + for (IBinding b : bs) { + if (b instanceof IType && CPPSemantics.declaredBefore(b, node, false)) { + return (IType) b; + } } } } @@ -2145,6 +2117,23 @@ public class CPPVisitor extends ASTQueries { return null; } + public static IType get_type_info(IASTExpression expression) { + IType t= getStdType(expression, TYPE_INFO); + return t != null ? t : INT_TYPE; + } + + public static IType get_SIZE_T(IASTNode sizeofExpr) { + IType t= getStdType(sizeofExpr, SIZE_T); + return t != null ? t : UNSIGNED_LONG; + } + + public static ICPPClassTemplate get_initializer_list(IASTNode node) { + IType t= getStdType(node, INITIALIZER_LIST); + if (t instanceof ICPPClassTemplate) + return (ICPPClassTemplate) t; + return null; + } + public static IASTProblem[] getProblems(IASTTranslationUnit tu) { CollectProblemsAction action = new CollectProblemsAction(); tu.accept(action);