From 2e5c77c1ab91a033296cfab467d53c1c9a260e54 Mon Sep 17 00:00:00 2001 From: Patrick Chuong Date: Mon, 6 Feb 2012 12:58:53 -0500 Subject: [PATCH 01/43] Bug 369998 - IBreakpointLocationProvider methods need a target or viewsite parameter --- .../ui/disassembly/DisassemblyPart.java | 22 ++++++++------- .../model/BreakpointsAnnotationModel.java | 21 +++++++++----- .../IBreakpointLocationProvider.java | 28 ++++++++++--------- 3 files changed, 41 insertions(+), 30 deletions(-) diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyPart.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyPart.java index 086a186bff3..308999dadbc 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyPart.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/DisassemblyPart.java @@ -9,9 +9,10 @@ * Wind River Systems - initial API and implementation * Patrick Chuong (Texas Instruments) - Bug 326670 * Patrick Chuong (Texas Instruments) - Bug 329682 - * Patrick Chuong (Texas Instruments) - bug 330259 + * Patrick Chuong (Texas Instruments) - Bug 330259 * Patrick Chuong (Texas Instruments) - Pin and Clone Supports (331781) * Patrick Chuong (Texas Instruments) - Bug 364405 + * Patrick Chuong (Texas Instruments) - Bug 369998 *******************************************************************************/ package org.eclipse.cdt.dsf.debug.internal.ui.disassembly; @@ -303,7 +304,8 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem protected boolean fTrackExpression = false; private String fPCLastLocationTxt = DisassemblyMessages.Disassembly_GotoLocation_initial_text; private BigInteger fPCLastAddress = PC_UNKNOWN; - + private IAdaptable fDebugContext; + private String fPCAnnotationColorKey; private ArrayList fRunnableQueue = new ArrayList(); @@ -1851,22 +1853,22 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } protected void updateDebugContext() { - IAdaptable context = DebugUITools.getPartDebugContext(getSite()); + fDebugContext = DebugUITools.getPartDebugContext(getSite()); IDisassemblyBackend prevBackend = fBackend; IDisassemblyBackend newBackend = null; fDebugSessionId = null; boolean needUpdate = false; - if (context != null) { - IDisassemblyBackend contextBackend = (IDisassemblyBackend)context.getAdapter(IDisassemblyBackend.class); + if (fDebugContext != null) { + IDisassemblyBackend contextBackend = (IDisassemblyBackend)fDebugContext.getAdapter(IDisassemblyBackend.class); // Need to compare the backend classes to prevent reusing the same backend object. // sub class can overwrite the standard disassembly backend to provide its own customization. - if ((prevBackend != null) && (contextBackend != null) && prevBackend.getClass().equals(contextBackend.getClass()) && prevBackend.supportsDebugContext(context)) { + if ((prevBackend != null) && (contextBackend != null) && prevBackend.getClass().equals(contextBackend.getClass()) && prevBackend.supportsDebugContext(fDebugContext)) { newBackend = prevBackend; } else { needUpdate = true; - newBackend = (IDisassemblyBackend)context.getAdapter(IDisassemblyBackend.class); + newBackend = (IDisassemblyBackend)fDebugContext.getAdapter(IDisassemblyBackend.class); if (newBackend != null) { - if (newBackend.supportsDebugContext(context)) { + if (newBackend.supportsDebugContext(fDebugContext)) { newBackend.init(this); } else { newBackend = null; @@ -1876,7 +1878,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem } fBackend = newBackend; if (newBackend != null) { - IDisassemblyBackend.SetDebugContextResult result = newBackend.setDebugContext(context); + IDisassemblyBackend.SetDebugContextResult result = newBackend.setDebugContext(fDebugContext); if (result != null) { fDebugSessionId = result.sessionId; if (result.contextChanged) { @@ -1981,7 +1983,7 @@ public abstract class DisassemblyPart extends WorkbenchPart implements IDisassem IAnnotationModel annotationModel = fViewer.getAnnotationModel(); if (annotationModel instanceof IAnnotationModelExtension) { IAnnotationModelExtension ame= (IAnnotationModelExtension) annotationModel; - ame.addAnnotationModel(BREAKPOINT_ANNOTATIONS, new BreakpointsAnnotationModel()); + ame.addAnnotationModel(BREAKPOINT_ANNOTATIONS, new BreakpointsAnnotationModel(fDebugContext)); } } diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/BreakpointsAnnotationModel.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/BreakpointsAnnotationModel.java index 0a33a546846..730db8b7991 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/BreakpointsAnnotationModel.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/model/BreakpointsAnnotationModel.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2011 Wind River Systems, Inc. and others. + * Copyright (c) 2008, 2012 Wind River Systems, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -7,7 +7,8 @@ * * Contributors: * Anton Leherbauer (Wind River Systems) - initial API and implementation - * Patrick Chuong (Texas Instruments) - bug 300053 + * Patrick Chuong (Texas Instruments) - Bug 300053 + * Patrick Chuong (Texas Instruments) - Bug 369998 *******************************************************************************/ package org.eclipse.cdt.dsf.debug.internal.ui.disassembly.model; @@ -25,6 +26,7 @@ import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IMarkerDelta; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IAdaptable; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IBreakpointListener; import org.eclipse.debug.core.IBreakpointManager; @@ -47,7 +49,12 @@ import org.eclipse.ui.texteditor.SimpleMarkerAnnotation; public class BreakpointsAnnotationModel extends DisassemblyAnnotationModel implements IBreakpointListener, IDocumentListener { private Runnable fCatchup; - + private IAdaptable fDebugContext; + + public BreakpointsAnnotationModel(IAdaptable debugContext) { + fDebugContext = debugContext; + } + @Override public void connect(IDocument document) { super.connect(document); @@ -159,14 +166,14 @@ public class BreakpointsAnnotationModel extends DisassemblyAnnotationModel imple if (locationProvider != null) { /* if there is source info, than create a source line position */ - String sourceFile = locationProvider.getSourceFile(breakpoint); + String sourceFile = locationProvider.getSourceFile(breakpoint, fDebugContext); if (sourceFile != null) { - int lineNumber = locationProvider.getLineNumber(breakpoint) - 1; + int lineNumber = locationProvider.getLineNumber(breakpoint, fDebugContext) - 1; return createPositionFromSourceLine(sourceFile, lineNumber); } else { /* if there is label info, than create a label position */ - IAddress labelAddress = locationProvider.getLabelAddress(breakpoint); + IAddress labelAddress = locationProvider.getLabelAddress(breakpoint, fDebugContext); if (labelAddress != null) { return createPositionFromLabel(labelAddress.getValue()); @@ -178,7 +185,7 @@ public class BreakpointsAnnotationModel extends DisassemblyAnnotationModel imple // // So for now, we only create an annotation for the first valid address. We can add // support for multiple annotations per breakpoint when it's needed. - IAddress[] addresses = locationProvider.getAddresses(breakpoint); + IAddress[] addresses = locationProvider.getAddresses(breakpoint, fDebugContext); for (int i = 0; addresses != null && i < addresses.length; ++i) { BigInteger address = addresses[i].getValue(); Position position = createPositionFromAddress(address); diff --git a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/IBreakpointLocationProvider.java b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/IBreakpointLocationProvider.java index 221b3b4fb36..37551e26f4d 100644 --- a/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/IBreakpointLocationProvider.java +++ b/dsf/org.eclipse.cdt.dsf.ui/src/org/eclipse/cdt/dsf/debug/internal/ui/disassembly/provisional/IBreakpointLocationProvider.java @@ -1,5 +1,5 @@ /***************************************************************** - * Copyright (c) 2010 Texas Instruments and others + * Copyright (c) 2010, 2012 Texas Instruments 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,11 +7,13 @@ * * Contributors: * Patrick Chuong (Texas Instruments) - Initial API and implementation (Bug 300053) + * Patrick Chuong (Texas Instruments) - Bug 369998 *****************************************************************/ package org.eclipse.cdt.dsf.debug.internal.ui.disassembly.provisional; import org.eclipse.cdt.core.IAddress; import org.eclipse.cdt.debug.core.model.ICAddressBreakpoint; +import org.eclipse.core.runtime.IAdaptable; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.debug.core.model.ILineBreakpoint; @@ -46,31 +48,31 @@ public interface IBreakpointLocationProvider { * Returns the line number of the breakpoint or -1 if no line number is * available. * - * @param breakpoint - * the breakpoint + * @param breakpoint the breakpoint + * @param debugContext the debug context of the view * @return the line number or -1 */ - int getLineNumber(IBreakpoint breakpoint); + int getLineNumber(IBreakpoint breakpoint, IAdaptable debugContext); /** * Returns the source file path of the breakpoint or null if no * source file is associated with this breakpoint. * - * @param breakpoint - * the breakpoint + * @param breakpoint the breakpoint + * @param debugContext the debug context of the view * @return the file path, can be null */ - String getSourceFile(IBreakpoint breakpoint); + String getSourceFile(IBreakpoint breakpoint, IAdaptable debugContext); /** * Returns the label address of the breakpoint or null if no * label is associated with this breakpoint. * - * @param breakpoint - * the breakpoint + * @param breakpoint the breakpoint + * @param debugContext the debug context of the view * @return the label address, can be null */ - IAddress getLabelAddress(IBreakpoint breakpoint); + IAddress getLabelAddress(IBreakpoint breakpoint, IAdaptable debugContext); /** * Returns the addresses of the breakpoint. @@ -81,9 +83,9 @@ public interface IBreakpointLocationProvider { * multiple annotations per breakpoint is up for future enhancements. *

* - * @param breakpoint - * the breakpoint + * @param breakpoint the breakpoint + * @param debugContext the debug context of the view * @return the addresses, can be null */ - IAddress[] getAddresses(IBreakpoint breakpoint); + IAddress[] getAddresses(IBreakpoint breakpoint, IAdaptable debugContext); } From 8a73a23e9d27e3b2065394ef76c0e722226cf700 Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Mon, 6 Feb 2012 15:16:20 -0500 Subject: [PATCH 02/43] Bug 369594: GDB 7.4 now reports solib events in MI, but no longer in CLI --- .../org/eclipse/cdt/debug/mi/core/RxThread.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/debug/org.eclipse.cdt.debug.mi.core/mi/org/eclipse/cdt/debug/mi/core/RxThread.java b/debug/org.eclipse.cdt.debug.mi.core/mi/org/eclipse/cdt/debug/mi/core/RxThread.java index 3eb0cc86c4b..d83a41a27e7 100644 --- a/debug/org.eclipse.cdt.debug.mi.core/mi/org/eclipse/cdt/debug/mi/core/RxThread.java +++ b/debug/org.eclipse.cdt.debug.mi.core/mi/org/eclipse/cdt/debug/mi/core/RxThread.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 QNX Software Systems and others. + * Copyright (c) 2000, 2012 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -9,6 +9,7 @@ * QNX Software Systems - Initial API and implementation * Norbert Ploett, Siemens AG - fix for bug 119370 * Hewlett-Packard Development Company - fix for bug 109733 (null check in setPrompt) + * Marc Khouzam (Ericsson) - Bug 369594: GDB 7.4 now reports solib events in MI, but no longer in CLI *******************************************************************************/ package org.eclipse.cdt.debug.mi.core; @@ -306,7 +307,7 @@ public class RxThread extends Thread { } // GDB does not provide reason when stopping on a shared library - // event or because of a catchpoint (in gdb < 7.0). + // event (gdb < 7.4) or because of a catchpoint (in gdb < 7.0). // Hopefully this will be fixed in a future version. Meanwhile, // we will use a hack to cope. On most platform we can detect by // looking at the console stream for phrase. Although it is a @@ -427,13 +428,13 @@ public class RxThread extends Thread { } } } - // GDB does not have reason when stopping on shared, hopefully - // this will be fix in newer version meanwhile, we will use a hack + // GDB does not have reason when stopping on shared (gdb < 7.4) + // we will use a hack // to cope. On most platform we can detect this state by looking at the // console stream for the phrase: // ~"Stopped due to shared library event\n" // - // Althought it is a _real_ bad idea to do this, we do not have + // Although it is a _real_ bad idea to do this, we do not have // any other alternatives. if (list.isEmpty()) { String[] logs = getStreamRecords(); @@ -533,7 +534,10 @@ public class RxThread extends Thread { event = new MIInferiorSignalExitEvent(session, rr); } session.getMIInferior().setTerminated(0,false); - } else if ("shlib-event".equals(reason)) { //$NON-NLS-1$ + } else if ("shlib-event".equals(reason) || //$NON-NLS-1$ + // GDB 7.4 reports this event as "solib-event" + // Bug 369594 + "solib-event".equals(reason)) {//$NON-NLS-1$ if (exec != null) { event = new MISharedLibEvent(session, exec); } else if (rr != null) { From 38803901ecdacb12861b9b54e0d82def128d2a2a Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Mon, 6 Feb 2012 20:36:09 -0800 Subject: [PATCH 03/43] Cosmetics. --- .../core/dom/ast/IASTBinaryExpression.java | 9 ++--- .../dom/ast/IASTBinaryTypeIdExpression.java | 11 +++--- .../cdt/core/dom/ast/IASTExpression.java | 6 +-- .../cdt/core/dom/ast/IASTUnaryExpression.java | 3 +- .../dom/ast/cpp/ICPPASTBinaryExpression.java | 7 ++-- .../cdt/core/dom/rewrite/ASTRewrite.java | 5 ++- .../dom/rewrite/ITrackedNodePosition.java | 1 - .../cdt/internal/core/dom/parser/ASTNode.java | 23 ++++++----- .../parser/cpp/CPPASTLiteralExpression.java | 4 +- .../parser/scanner/ASTPreprocessorNode.java | 15 +++----- .../scanner/LocationCtxMacroExpansion.java | 2 +- .../extractfunction/ExtractExpression.java | 14 +++---- .../extractfunction/ExtractStatement.java | 8 ++-- ...eFromInHeaderToImplementationStrategy.java | 26 ++++++------- .../ui/viewsupport/ProjectTemplateStore.java | 38 +++++++++---------- 15 files changed, 80 insertions(+), 92 deletions(-) diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTBinaryExpression.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTBinaryExpression.java index 969f7275f22..d9cd509e200 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTBinaryExpression.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTBinaryExpression.java @@ -11,7 +11,6 @@ *******************************************************************************/ package org.eclipse.cdt.core.dom.ast; - /** * This interface represents a binary expression. * @@ -36,15 +35,14 @@ public interface IASTBinaryExpression extends IASTExpression { "IASTBinaryExpression.OPERAND_TWO - IASTExpression for RHS"); //$NON-NLS-1$ /** - * Set the operator. + * Sets the operator. * - * @param op - * Value to set. + * @param op value to set. */ public void setOperator(int op); /** - * Get the operator. + * Returns the operator. * * @return int value as operator */ @@ -244,7 +242,6 @@ public interface IASTBinaryExpression extends IASTExpression { * @param expression * IASTExpression value. */ - public void setOperand1(IASTExpression expression); /** diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTBinaryTypeIdExpression.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTBinaryTypeIdExpression.java index e43f0b4756c..3d5cf6532b2 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTBinaryTypeIdExpression.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTBinaryTypeIdExpression.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Markus Schorn (Wind River Systems) - Initial API and implementation + * Markus Schorn (Wind River Systems) - Initial API and implementation *******************************************************************************/ package org.eclipse.cdt.core.dom.ast; @@ -25,7 +25,7 @@ public interface IASTBinaryTypeIdExpression extends IASTExpression { public static enum Operator {__is_base_of} /** - * Get the operator for the expression. + * Returns the operator for the expression. */ public Operator getOperator(); @@ -40,22 +40,23 @@ public interface IASTBinaryTypeIdExpression extends IASTExpression { public IASTTypeId getOperand2(); /** - * Set the operator for the expression. + * Sets the operator for the expression. */ public void setOperator(Operator value); /** - * Set the first operand. + * Sets the first operand. */ public void setOperand1(IASTTypeId typeId); /** - * Set the second operand. + * Sets the second operand. */ public void setOperand2(IASTTypeId typeId); @Override public IASTBinaryTypeIdExpression copy(); + @Override public IASTBinaryTypeIdExpression copy(CopyStyle style); } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTExpression.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTExpression.java index c5b548b3238..ab5cb7f26fc 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTExpression.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTExpression.java @@ -11,7 +11,6 @@ *******************************************************************************/ package org.eclipse.cdt.core.dom.ast; - /** * This is the root class of expressions. * @@ -28,7 +27,7 @@ public interface IASTExpression extends IASTInitializerClause { */ LVALUE, /** - * Expiring value as introduced by c++ 0x. + * Expiring value as introduced by c++11. */ XVALUE, /** @@ -42,6 +41,7 @@ public interface IASTExpression extends IASTInitializerClause { public boolean isRValue() { return this != LVALUE; } + /** * A generalized lvalue is either an lvalue or an xvalue. */ @@ -53,7 +53,7 @@ public interface IASTExpression extends IASTInitializerClause { /** * Empty expression array. */ - public static final IASTExpression[] EMPTY_EXPRESSION_ARRAY = new IASTExpression[0]; + public static final IASTExpression[] EMPTY_EXPRESSION_ARRAY = {}; public IType getExpressionType(); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTUnaryExpression.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTUnaryExpression.java index 7af56b5f991..2a4cf858a75 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTUnaryExpression.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTUnaryExpression.java @@ -17,7 +17,6 @@ package org.eclipse.cdt.core.dom.ast; * @noimplement This interface is not intended to be implemented by clients. */ public interface IASTUnaryExpression extends IASTExpression { - /** * Prefix increment. * op_prefixIncr ++exp @@ -32,7 +31,7 @@ public interface IASTUnaryExpression extends IASTExpression { /** * Operator plus. - * op_plus ==> + exp + * op_plus ==> +exp */ public static final int op_plus = 2; diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/cpp/ICPPASTBinaryExpression.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/cpp/ICPPASTBinaryExpression.java index 6f7e75df787..a447daa91a0 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/cpp/ICPPASTBinaryExpression.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/cpp/ICPPASTBinaryExpression.java @@ -6,9 +6,9 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * John Camelon (IBM) - Initial API and implementation - * Mike Kucera (IBM) - * Sergey Prigogin (Google) + * John Camelon (IBM) - Initial API and implementation + * Mike Kucera (IBM) + * Sergey Prigogin (Google) *******************************************************************************/ package org.eclipse.cdt.core.dom.ast.cpp; @@ -22,7 +22,6 @@ import org.eclipse.cdt.core.dom.ast.IASTImplicitNameOwner; * @noimplement This interface is not intended to be implemented by clients. */ public interface ICPPASTBinaryExpression extends IASTBinaryExpression, IASTImplicitNameOwner { - /** * op_pmdot pointer-to-member field dereference. */ diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/rewrite/ASTRewrite.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/rewrite/ASTRewrite.java index ee2b2e90f12..a83b0a2e559 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/rewrite/ASTRewrite.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/rewrite/ASTRewrite.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2011 Wind River Systems, Inc. and others. + * Copyright (c) 2007, 2012 Wind River Systems, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -260,9 +260,10 @@ public final class ASTRewrite { } /** + * Returns comments for the given node. * * @param node the node - * @param pos the position + * @param pos the position of the comments * @return All comments assigned to the node at this position * @since 5.3 */ diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/rewrite/ITrackedNodePosition.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/rewrite/ITrackedNodePosition.java index d9d2a9ff374..197568f9125 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/rewrite/ITrackedNodePosition.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/rewrite/ITrackedNodePosition.java @@ -20,7 +20,6 @@ package org.eclipse.cdt.core.dom.rewrite; * @noextend This interface is not intended to be extended by clients. */ public interface ITrackedNodePosition { - /** * Returns the original or modified start position of the tracked node depending if called before * or after the rewrite is applied. -1 is returned for removed nodes. diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTNode.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTNode.java index 4d45e26519a..89d0b9123db 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTNode.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTNode.java @@ -259,7 +259,7 @@ public abstract class ASTNode implements IASTNode { ASTNode astNode= (ASTNode) node; final int offset = getOffset(); final int nodeOffset= astNode.getOffset(); - return offset <= nodeOffset && nodeOffset+astNode.length <= offset+length; + return offset <= nodeOffset && nodeOffset + astNode.length <= offset + length; } return false; } @@ -267,7 +267,7 @@ public abstract class ASTNode implements IASTNode { @Override public IToken getSyntax() throws ExpansionOverlapsBoundaryException { final int offset = getOffset(); - return getSyntax(offset, offset+length, 0); + return getSyntax(offset, offset + length, 0); } @Override @@ -279,7 +279,7 @@ public abstract class ASTNode implements IASTNode { @Override public IToken getTrailingSyntax() throws ExpansionOverlapsBoundaryException { int right= getBoundary(1); - return getSyntax(getOffset()+length, right, 1); + return getSyntax(getOffset() + length, right, 1); } /** @@ -296,15 +296,14 @@ public abstract class ASTNode implements IASTNode { ASTNode astNode= (ASTNode) sib; int offset= astNode.getOffset(); if (direction < 0) { - offset+= astNode.getLength(); + offset += astNode.getLength(); } return offset; } - // no parent + // No parent. throw new UnsupportedOperationException(); } - private IToken getSyntax(int fromSequenceNumber, int nextSequenceNumber, int direction) throws ExpansionOverlapsBoundaryException { final IASTTranslationUnit tu= getTranslationUnit(); if (!(tu instanceof ASTNode)) @@ -315,7 +314,7 @@ public abstract class ASTNode implements IASTNode { throw new UnsupportedOperationException(); int endSequenceNumber= lr.convertToSequenceEndNumber(nextSequenceNumber); - IASTFileLocation total= lr.getMappedFileLocation(fromSequenceNumber, endSequenceNumber-fromSequenceNumber); + IASTFileLocation total= lr.getMappedFileLocation(fromSequenceNumber, endSequenceNumber - fromSequenceNumber); IASTFileLocation myfloc= getFileLocation(); if (total == null || myfloc == null) throw new UnsupportedOperationException(); @@ -324,13 +323,13 @@ public abstract class ASTNode implements IASTNode { throw new ExpansionOverlapsBoundaryException(); if (fromSequenceNumber > 0) { - IASTFileLocation fl= lr.getMappedFileLocation(fromSequenceNumber-1, endSequenceNumber-fromSequenceNumber+1); + IASTFileLocation fl= lr.getMappedFileLocation(fromSequenceNumber-1, endSequenceNumber - fromSequenceNumber + 1); if (fl.getFileName().equals(total.getFileName()) && fl.getNodeOffset() == total.getNodeOffset()) throw new ExpansionOverlapsBoundaryException(); } if (endSequenceNumber < ((ASTNode) tu).getOffset() + ((ASTNode) tu).getLength()) { - IASTFileLocation fl= lr.getMappedFileLocation(fromSequenceNumber, nextSequenceNumber-fromSequenceNumber+1); + IASTFileLocation fl= lr.getMappedFileLocation(fromSequenceNumber, nextSequenceNumber - fromSequenceNumber + 1); if (fl.getFileName().equals(total.getFileName()) && fl.getNodeLength() == total.getNodeLength()) throw new ExpansionOverlapsBoundaryException(); } @@ -345,7 +344,7 @@ public abstract class ASTNode implements IASTNode { try { Token result= null; Token last= null; - for (;;) { + while (true) { Token t= lex.nextToken(); switch (t.getType()) { case IToken.tEND_OF_INPUT: @@ -366,12 +365,12 @@ public abstract class ASTNode implements IASTNode { } } } catch (OffsetLimitReachedException e) { - // does not happen without using content assist limit + // Does not happen without using content assist limit. } return null; } protected void setCopyLocation(IASTNode originalNode) { - locations = new IASTNodeLocation[] {new ASTCopyLocation(originalNode)}; + locations = new IASTNodeLocation[] { new ASTCopyLocation(originalNode) }; } } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTLiteralExpression.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTLiteralExpression.java index 4742eb26e0a..a439bfa8f03 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTLiteralExpression.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTLiteralExpression.java @@ -51,8 +51,8 @@ public class CPPASTLiteralExpression extends ASTNode implements ICPPASTLiteralEx @Override public CPPASTLiteralExpression copy(CopyStyle style) { - CPPASTLiteralExpression copy = new CPPASTLiteralExpression(kind, value == null ? null - : value.clone()); + CPPASTLiteralExpression copy = new CPPASTLiteralExpression(kind, + value == null ? null : value.clone()); copy.setOffsetAndLength(this); if (style == CopyStyle.withLocations) { copy.setCopyLocation(this); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/ASTPreprocessorNode.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/ASTPreprocessorNode.java index d438bd47cac..8334909db5f 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/ASTPreprocessorNode.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/ASTPreprocessorNode.java @@ -59,7 +59,7 @@ abstract class ASTPreprocessorNode extends ASTNode { setParent(parent); setPropertyInParent(property); setOffset(startNumber); - setLength(endNumber-startNumber); + setLength(endNumber - startNumber); } protected char[] getSource(int offset, int length) { @@ -597,9 +597,9 @@ class ASTFunctionStyleMacroDefinition extends ASTMacroDefinition implements IAST } } - class ASTUndef extends ASTPreprocessorNode implements IASTPreprocessorUndefStatement { private final ASTPreprocessorName fName; + public ASTUndef(IASTTranslationUnit parent, char[] name, int startNumber, int nameNumber, int nameEndNumber, IBinding binding, boolean isActive) { super(parent, IASTTranslationUnit.PREPROCESSOR_STATEMENT, startNumber, nameEndNumber); fName= new ASTPreprocessorName(this, IASTPreprocessorStatement.MACRO_NAME, nameNumber, nameEndNumber, name, binding); @@ -686,7 +686,7 @@ class ASTFileLocation implements IASTFileLocation { @Override public int getEndingLineNumber() { - int end= fLength > 0 ? fOffset+fLength-1 : fOffset; + int end= fLength > 0 ? fOffset + fLength - 1 : fOffset; return fLocationCtx.getLineNumber(end); } @@ -701,7 +701,7 @@ class ASTFileLocation implements IASTFileLocation { @Override public String toString() { - return getFileName() + "[" + fOffset + "," + (fOffset+fLength) + ")"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + return getFileName() + "[" + fOffset + "," + (fOffset + fLength) + "]"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ } public int getSequenceNumber() { @@ -709,7 +709,7 @@ class ASTFileLocation implements IASTFileLocation { } public int getSequenceEndNumber() { - return fLocationCtx.getSequenceNumberForOffset(fOffset+fLength, true); + return fLocationCtx.getSequenceNumberForOffset(fOffset + fLength, true); } public LocationCtxFile getLocationContext() { @@ -723,7 +723,6 @@ class ASTFileLocation implements IASTFileLocation { } class ASTMacroExpansion extends ASTPreprocessorNode implements IASTPreprocessorMacroExpansion { - private LocationCtxMacroExpansion fContext; public ASTMacroExpansion(IASTNode parent, int startNumber, int endNumber) { @@ -765,7 +764,6 @@ class ASTMacroExpansion extends ASTPreprocessorNode implements IASTPreprocessorM @SuppressWarnings("deprecation") class ASTMacroExpansionLocation implements IASTMacroExpansionLocation, org.eclipse.cdt.core.dom.ast.IASTMacroExpansion { - private LocationCtxMacroExpansion fContext; private int fOffset; private int fLength; @@ -817,7 +815,7 @@ class ASTMacroExpansionLocation implements IASTMacroExpansionLocation, org.eclip @Override public String toString() { - return fContext.getMacroDefinition().getName().toString() + "[" + fOffset + "," + (fOffset+fLength) + ")"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + return fContext.getMacroDefinition().getName().toString() + "[" + fOffset + "," + (fOffset+fLength) + "]"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ } public IASTImageLocation getImageLocation() { @@ -872,7 +870,6 @@ class ASTFileLocationForBuiltins implements IASTFileLocation { } } - class ASTImageLocation extends ASTFileLocationForBuiltins implements IASTImageLocation { private final int fKind; diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/LocationCtxMacroExpansion.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/LocationCtxMacroExpansion.java index 9e37e56a97f..ad3fe391019 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/LocationCtxMacroExpansion.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/LocationCtxMacroExpansion.java @@ -34,7 +34,7 @@ class LocationCtxMacroExpansion extends LocationCtx { fLength= length; fLocationInfos= imageLocations; fExpansionName= expansionName; - if (expansionName.getParent() instanceof ASTMacroExpansion == false) { + if (!(expansionName.getParent() instanceof ASTMacroExpansion)) { throw new IllegalArgumentException(expansionName.toString() + " is not a macro expansion name"); //$NON-NLS-1$ } } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractExpression.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractExpression.java index 0135b5211bb..d7be786dfcf 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractExpression.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractExpression.java @@ -58,7 +58,7 @@ import org.eclipse.cdt.internal.ui.refactoring.NameInformation; * @author Mirko Stocker */ public class ExtractExpression extends ExtractedFunctionConstructionHelper { - final static char[] ZERO= { '0' }; + private final static char[] ZERO= { '0' }; @Override public void constructMethodBody(IASTCompoundStatement compound, List list, @@ -74,12 +74,12 @@ public class ExtractExpression extends ExtractedFunctionConstructionHelper { private IASTExpression getExpression(List list) { if (list.size() > 1) { - CPPASTBinaryExpression bExp = new CPPASTBinaryExpression(); - bExp.setParent(list.get(0).getParent()); - bExp.setOperand1((IASTExpression) list.get(0).copy(CopyStyle.withLocations)); - bExp.setOperator(((IASTBinaryExpression) list.get(1).getParent()).getOperator()); - bExp.setOperand2(getExpression(list.subList(1, list.size()))); - return bExp; + CPPASTBinaryExpression expression = new CPPASTBinaryExpression(); + expression.setParent(list.get(0).getParent()); + expression.setOperand1((IASTExpression) list.get(0).copy(CopyStyle.withLocations)); + expression.setOperator(((IASTBinaryExpression) list.get(1).getParent()).getOperator()); + expression.setOperand2(getExpression(list.subList(1, list.size()))); + return expression; } else { return (IASTExpression) list.get(0).copy(CopyStyle.withLocations); } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractStatement.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractStatement.java index 4839c7379b5..5e3c0fa0cf3 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractStatement.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractStatement.java @@ -34,9 +34,9 @@ import org.eclipse.cdt.internal.ui.refactoring.utils.ASTHelper; */ public class ExtractStatement extends ExtractedFunctionConstructionHelper { @Override - public void constructMethodBody(IASTCompoundStatement compound, List list, + public void constructMethodBody(IASTCompoundStatement compound, List nodes, ASTRewrite rewrite, TextEditGroup group) { - for (IASTNode node : list) { + for (IASTNode node : nodes) { rewrite.insertBefore(compound, null, node, group); } } @@ -48,8 +48,8 @@ public class ExtractStatement extends ExtractedFunctionConstructionHelper { IASTNode decl = ASTHelper.getDeclarationForNode(returnVariable.getDeclarationName()); return ASTHelper.getDeclarationSpecifier(decl).copy(CopyStyle.withLocations); } - IASTDeclSpecifier declSpec = new CPPASTSimpleDeclSpecifier(); - ((IASTSimpleDeclSpecifier) declSpec).setType(IASTSimpleDeclSpecifier.t_void); + IASTSimpleDeclSpecifier declSpec = new CPPASTSimpleDeclSpecifier(); + declSpec.setType(IASTSimpleDeclSpecifier.t_void); return declSpec.copy(CopyStyle.withLocations); } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/togglefunction/ToggleFromInHeaderToImplementationStrategy.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/togglefunction/ToggleFromInHeaderToImplementationStrategy.java index 701396beaaa..ff13a676cd2 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/togglefunction/ToggleFromInHeaderToImplementationStrategy.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/togglefunction/ToggleFromInHeaderToImplementationStrategy.java @@ -57,10 +57,10 @@ import org.eclipse.cdt.internal.ui.refactoring.Container; import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector; public class ToggleFromInHeaderToImplementationStrategy implements IToggleRefactoringStrategy { - private IASTTranslationUnit impl_unit; + private IASTTranslationUnit implUnit; private ToggleRefactoringContext context; private TextEditGroup infoText; - private ASTLiteralNode includenode; + private ASTLiteralNode includeNode; public ToggleFromInHeaderToImplementationStrategy(final ToggleRefactoringContext context) { this.infoText = new TextEditGroup(Messages.EditGroupName); @@ -80,9 +80,9 @@ public class ToggleFromInHeaderToImplementationStrategy implements IToggleRefact replaceDefinitionWithDeclaration(collector); } - ASTRewrite implRewrite = collector.rewriterForTranslationUnit(impl_unit); - if (includenode != null) { - implRewrite.insertBefore(impl_unit, null, includenode, infoText); + ASTRewrite implRewrite = collector.rewriterForTranslationUnit(implUnit); + if (includeNode != null) { + implRewrite.insertBefore(implUnit, null, includeNode, infoText); } IASTNode insertionParent = null; @@ -93,11 +93,11 @@ public class ToggleFromInHeaderToImplementationStrategy implements IToggleRefact insertionParent = searchNamespaceInImplementation(parent.getName()); if (insertionParent == null) { insertionParent = createNamespace(parent); - implRewrite = implRewrite.insertBefore(impl_unit.getTranslationUnit(), + implRewrite = implRewrite.insertBefore(implUnit.getTranslationUnit(), null, insertionParent, infoText); } } else { - insertionParent = impl_unit.getTranslationUnit(); + insertionParent = implUnit.getTranslationUnit(); } newDefinition.setParent(insertionParent); @@ -241,13 +241,13 @@ public class ToggleFromInHeaderToImplementationStrategy implements IToggleRefact } private boolean newFileCheck() { - impl_unit = context.getTUForSiblingFile(); - if (impl_unit == null) { + implUnit = context.getTUForSiblingFile(); + if (implUnit == null) { ToggleFileCreator filecreator = new ToggleFileCreator(context, ".cpp"); //$NON-NLS-1$ if (filecreator.askUserForFileCreation(context)) { filecreator.createNewFile(); - impl_unit = filecreator.loadTranslationUnit(); - includenode = new ASTLiteralNode(filecreator.getIncludeStatement()); + implUnit = filecreator.loadTranslationUnit(); + includeNode = new ASTLiteralNode(filecreator.getIncludeStatement()); return true; } else { return false; @@ -342,7 +342,7 @@ public class ToggleFromInHeaderToImplementationStrategy implements IToggleRefact private CPPASTNamespaceDefinition createNamespace(ICPPASTNamespaceDefinition parent_namespace) { CPPASTNamespaceDefinition insertionParent = new CPPASTNamespaceDefinition( parent_namespace.getName().copy(CopyStyle.withLocations)); - insertionParent.setParent(impl_unit); + insertionParent.setParent(implUnit); return insertionParent; } @@ -354,7 +354,7 @@ public class ToggleFromInHeaderToImplementationStrategy implements IToggleRefact private IASTNode searchNamespaceInImplementation(final IASTName name) { final Container result = new Container(); - this.impl_unit.accept(new ASTVisitor() { + this.implUnit.accept(new ASTVisitor() { { shouldVisitNamespaces = true; } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/viewsupport/ProjectTemplateStore.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/viewsupport/ProjectTemplateStore.java index 393fd8c3600..27b8dac4ee7 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/viewsupport/ProjectTemplateStore.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/viewsupport/ProjectTemplateStore.java @@ -32,12 +32,11 @@ import org.eclipse.cdt.ui.CUIPlugin; * @since 5.0 */ public final class ProjectTemplateStore { - private static final String KEY= "org.eclipse.cdt.ui.text.custom_code_templates"; //$NON-NLS-1$ private final TemplateStore fInstanceStore; private final TemplateStore fProjectStore; - + public ProjectTemplateStore(IProject project) { fInstanceStore= CUIPlugin.getDefault().getCodeTemplateStore(); if (project == null) { @@ -57,21 +56,20 @@ public final class ProjectTemplateStore { internalAdd(data); } } - + @Override public void save() throws IOException { - StringWriter output= new StringWriter(); TemplateReaderWriter writer= new TemplateReaderWriter(); writer.save(getTemplateData(false), output); - + projectSettings.setValue(KEY, output.toString()); projectSettings.save(); } }; } } - + public static boolean hasProjectSpecificTempates(IProject project) { String pref= new ProjectScope(project).getNode(CUIPlugin.PLUGIN_ID).get(KEY, null); if (pref != null && pref.trim().length() > 0) { @@ -87,29 +85,28 @@ public final class ProjectTemplateStore { } return false; } - - + public TemplatePersistenceData[] getTemplateData() { if (fProjectStore != null) { return fProjectStore.getTemplateData(true); } return fInstanceStore.getTemplateData(true); } - + public Template findTemplateById(String id) { Template template= null; if (fProjectStore != null) template= fProjectStore.findTemplateById(id); if (template == null) template= fInstanceStore.findTemplateById(id); - + return template; } - + public void load() throws IOException { if (fProjectStore != null) { fProjectStore.load(); - + Set datas= new HashSet(); TemplatePersistenceData[] data= fProjectStore.getTemplateData(false); for (TemplatePersistenceData element : data) { @@ -119,7 +116,7 @@ public final class ProjectTemplateStore { } datas.add(id); } - + data= fInstanceStore.getTemplateData(false); for (TemplatePersistenceData orig : data) { String origId= orig.getId(); @@ -134,22 +131,21 @@ public final class ProjectTemplateStore { } } } - + public boolean isProjectSpecific(String id) { if (id == null) { return false; } - + if (fProjectStore == null) return false; - + return fProjectStore.findTemplateById(id) != null; } - - + public void setProjectSpecific(String id, boolean projectSpecific) { Assert.isNotNull(fProjectStore); - + TemplatePersistenceData data= fProjectStore.getTemplateData(id); if (data == null) { return; // does not exist @@ -164,7 +160,7 @@ public final class ProjectTemplateStore { fProjectStore.restoreDefaults(); } } - + public void save() throws IOException { if (fProjectStore == null) { fInstanceStore.save(); @@ -172,7 +168,7 @@ public final class ProjectTemplateStore { fProjectStore.save(); } } - + public void revertChanges() throws IOException { if (fProjectStore != null) { // nothing to do From 8dc598a145c58533105f9a1e353066e7f300fa8a Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Tue, 7 Feb 2012 14:36:47 -0800 Subject: [PATCH 04/43] Fixed passing parameters by pointer and renaming of parameters in Extract Function refactoring. --- .../cdt/core/parser/tests/ASTComparer.java | 40 +-- .../eclipse/cdt/core/dom/ast/IASTComment.java | 5 +- .../cdt/core/dom/ast/IASTIdExpression.java | 3 +- .../dom/ast/cpp/ICPPASTFieldReference.java | 5 +- .../cdt/internal/core/dom/parser/ASTNode.java | 16 + .../core/dom/parser/c/CASTFieldReference.java | 52 ++- .../dom/parser/cpp/CPPASTFieldReference.java | 21 +- .../ExtractFunctionRefactoringTest.java | 332 +++++++++++++----- .../ui/refactoring/NameInformation.java | 109 ++++-- .../ui/refactoring/NodeContainer.java | 60 ++-- .../extractfunction/ExtractExpression.java | 37 +- .../ExtractFunctionRefactoring.java | 85 ++--- .../extractfunction/ExtractStatement.java | 13 +- .../ExtractedFunctionConstructionHelper.java | 95 ++++- 14 files changed, 580 insertions(+), 293 deletions(-) diff --git a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ASTComparer.java b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ASTComparer.java index fca045aba8a..345f9413f2f 100644 --- a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ASTComparer.java +++ b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ASTComparer.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Mike Kucera (IBM) - Initial API and implementation + * Mike Kucera (IBM) - Initial API and implementation *******************************************************************************/ package org.eclipse.cdt.core.parser.tests; @@ -28,7 +28,7 @@ public class ASTComparer extends Assert { private static Set methodsToIgnore = new HashSet(Arrays.asList( // Prevent infinite recursion - "getParent", + "getParent", "getTranslationUnit", "getLastName", @@ -39,6 +39,7 @@ public class ASTComparer extends Assert { // Can be different in copy "isFrozen", "getContainingFilename", + "getOriginalNode", // These methods are problematic "getProblem", @@ -62,18 +63,16 @@ public class ASTComparer extends Assert { "isLValue" )); - public static void assertCopy(IASTNode node1, IASTNode node2) { try { assertCopy(node1, node2, 0); - } catch(Exception e) { + } catch (Exception e) { throw new RuntimeException(e); } } - private static void assertCopy(IASTNode node1, IASTNode node2, int n) throws Exception { - if(node1 == null && node2 == null) + if (node1 == null && node2 == null) return; assertNotNull(node1); assertNotNull(node2); @@ -86,11 +85,11 @@ public class ASTComparer extends Assert { BeanInfo beanInfo = Introspector.getBeanInfo(klass1); - for(PropertyDescriptor property : beanInfo.getPropertyDescriptors()) { + for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) { Method getter = property.getReadMethod(); - if(getter == null) + if (getter == null) continue; - if(methodsToIgnore.contains(getter.getName())) + if (methodsToIgnore.contains(getter.getName())) continue; if (getter.getAnnotation(Deprecated.class) != null) @@ -99,48 +98,43 @@ public class ASTComparer extends Assert { try { Class returnType = getter.getReturnType(); - if(IASTNode.class.isAssignableFrom(returnType)) { + if (IASTNode.class.isAssignableFrom(returnType)) { //System.out.println(spaces(n) + "Testing1: " + getter.getName()); IASTNode result1 = (IASTNode) getter.invoke(node1); IASTNode result2 = (IASTNode) getter.invoke(node2); - assertCopy(result1, result2, n+1); // members must be same - } - else if(returnType.isArray() && IASTNode.class.isAssignableFrom(returnType.getComponentType())) { + assertCopy(result1, result2, n + 1); // members must be same + } else if (returnType.isArray() && IASTNode.class.isAssignableFrom(returnType.getComponentType())) { //System.out.println(spaces(n) + "Testing2: " + getter.getName()); IASTNode[] result1 = (IASTNode[]) getter.invoke(node1); IASTNode[] result2 = (IASTNode[]) getter.invoke(node2); - if(result1 == null && result2 == null) + if (result1 == null && result2 == null) continue; assertNotNull(result1); assertNotNull(result2); assertEquals(result1.length, result2.length); for(int i = 0; i < result1.length; i++) - assertCopy(result1[i], result2[i], n+1); - } - else if((returnType.isPrimitive() || returnType.equals(String.class)) && !returnType.equals(Void.class)) { + assertCopy(result1[i], result2[i], n + 1); + } else if ((returnType.isPrimitive() || returnType.equals(String.class)) && !returnType.equals(Void.class)) { //System.out.println(spaces(n) + "Testing3: " + getter.getName()); Object result1 = getter.invoke(node1); Object result2 = getter.invoke(node2); assertEquals(result1, result2); } - - } catch(AssertionFailedError e) { + } catch (AssertionFailedError e) { System.out.printf("Failure when calling %s.%s() @(%d,%d)\n", node1.getClass().getSimpleName(), getter.getName(), - ((ASTNode)node1).getOffset(), - ((ASTNode)node1).getLength()); + ((ASTNode) node1).getOffset(), + ((ASTNode) node1).getLength()); throw e; } } } - // private static String spaces(int n) { // char[] spaces = new char[n*2]; // Arrays.fill(spaces, ' '); // return new String(spaces); // } - } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTComment.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTComment.java index 0a0a9017145..48f1047adbf 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTComment.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTComment.java @@ -18,6 +18,10 @@ package org.eclipse.cdt.core.dom.ast; * @noimplement This interface is not intended to be implemented by clients. */ public interface IASTComment extends IASTNode { + /** + * @since 5.4 + */ + public final IASTComment[] EMPTY_COMMENT_ARRAY = {}; /** * Set the comment. @@ -39,5 +43,4 @@ public interface IASTComment extends IASTNode { * @return true if this is a blockcomment */ public boolean isBlockComment(); - } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTIdExpression.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTIdExpression.java index 838b56f3a98..9d7934fc4aa 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTIdExpression.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTIdExpression.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Doug Schaefer (IBM) - Initial API and implementation + * Doug Schaefer (IBM) - Initial API and implementation *******************************************************************************/ package org.eclipse.cdt.core.dom.ast; @@ -17,7 +17,6 @@ package org.eclipse.cdt.core.dom.ast; * @noimplement This interface is not intended to be implemented by clients. */ public interface IASTIdExpression extends IASTExpression, IASTNameOwner { - /** * ID_NAME represents the relationship between an * IASTIdExpression and a IASTName. diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/cpp/ICPPASTFieldReference.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/cpp/ICPPASTFieldReference.java index 9e1a55b47ea..3036f284c0b 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/cpp/ICPPASTFieldReference.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/cpp/ICPPASTFieldReference.java @@ -6,8 +6,8 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * John Camelon (IBM) - Initial API and implementation - * Mike Kucera (IBM) + * John Camelon (IBM) - Initial API and implementation + * Mike Kucera (IBM) *******************************************************************************/ package org.eclipse.cdt.core.dom.ast.cpp; @@ -23,7 +23,6 @@ import org.eclipse.cdt.core.dom.ast.IType; * @noimplement This interface is not intended to be implemented by clients. */ public interface ICPPASTFieldReference extends IASTFieldReference, IASTImplicitNameOwner { - /** * Was template keyword used? * diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTNode.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTNode.java index 89d0b9123db..0cf76a44f6c 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTNode.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTNode.java @@ -14,6 +14,7 @@ package org.eclipse.cdt.internal.core.dom.parser; import org.eclipse.cdt.core.dom.ast.ASTNodeProperty; import org.eclipse.cdt.core.dom.ast.ASTVisitor; import org.eclipse.cdt.core.dom.ast.ExpansionOverlapsBoundaryException; +import org.eclipse.cdt.core.dom.ast.IASTCopyLocation; import org.eclipse.cdt.core.dom.ast.IASTFileLocation; import org.eclipse.cdt.core.dom.ast.IASTImageLocation; import org.eclipse.cdt.core.dom.ast.IASTNode; @@ -373,4 +374,19 @@ public abstract class ASTNode implements IASTNode { protected void setCopyLocation(IASTNode originalNode) { locations = new IASTNodeLocation[] { new ASTCopyLocation(originalNode) }; } + + /** + * If the node is a copy of some other node, returns the original node. + * Otherwise returns the node itself. + */ + public IASTNode getOriginalNode() { + IASTNode node = this; + while (true) { + IASTNodeLocation[] locations = node.getNodeLocations(); + if (locations.length == 0 || !(locations[0] instanceof IASTCopyLocation)) + break; + node = ((IASTCopyLocation) locations[0]).getOriginalNode(); + } + return node; + } } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTFieldReference.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTFieldReference.java index 094e90b0f39..0b247b0f768 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTFieldReference.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTFieldReference.java @@ -6,10 +6,10 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * John Camelon (IBM Rational Software) - Initial API and implementation - * Yuan Zhang / Beth Tibbitts (IBM Research) - * Bryan Wilkinson (QNX) - * Markus Schorn (Wind River Systems) + * John Camelon (IBM Rational Software) - Initial API and implementation + * Yuan Zhang / Beth Tibbitts (IBM Research) + * Bryan Wilkinson (QNX) + * Markus Schorn (Wind River Systems) *******************************************************************************/ package org.eclipse.cdt.internal.core.dom.parser.c; @@ -30,21 +30,19 @@ import org.eclipse.cdt.internal.core.dom.parser.ProblemType; /** * Field reference in C. */ -public class CASTFieldReference extends ASTNode implements IASTFieldReference, IASTAmbiguityParent, IASTCompletionContext { - +public class CASTFieldReference extends ASTNode + implements IASTFieldReference, IASTAmbiguityParent, IASTCompletionContext { private IASTExpression owner; private IASTName name; private boolean ptr; public CASTFieldReference() { } - public CASTFieldReference(IASTName name, IASTExpression owner) { this(name, owner, false); } - public CASTFieldReference(IASTName name, IASTExpression owner, boolean ptr) { setFieldOwner(owner); setFieldName(name); @@ -111,41 +109,40 @@ public class CASTFieldReference extends ASTNode implements IASTFieldReference, I } @Override - public boolean accept( ASTVisitor action ){ - if( action.shouldVisitExpressions ){ - switch( action.visit( this ) ){ - case ASTVisitor.PROCESS_ABORT : return false; - case ASTVisitor.PROCESS_SKIP : return true; - default : break; + public boolean accept(ASTVisitor action) { + if (action.shouldVisitExpressions) { + switch (action.visit(this)) { + case ASTVisitor.PROCESS_ABORT: return false; + case ASTVisitor.PROCESS_SKIP: return true; + default: break; } } - if( owner != null ) if( !owner.accept( action ) ) return false; - if( name != null ) if( !name.accept( action ) ) return false; + if (owner != null && !owner.accept(action)) return false; + if (name != null && !name.accept(action)) return false; - if( action.shouldVisitExpressions ){ - switch( action.leave( this ) ){ - case ASTVisitor.PROCESS_ABORT : return false; - case ASTVisitor.PROCESS_SKIP : return true; - default : break; + if (action.shouldVisitExpressions) { + switch (action.leave(this)) { + case ASTVisitor.PROCESS_ABORT: return false; + case ASTVisitor.PROCESS_SKIP: return true; + default: break; } } return true; } @Override - public int getRoleForName(IASTName n ) { - if( n == this.name ) + public int getRoleForName(IASTName n) { + if (n == this.name) return r_reference; return r_unclear; } @Override public void replace(IASTNode child, IASTNode other) { - if( child == owner) - { - other.setPropertyInParent( child.getPropertyInParent() ); - other.setParent( child.getParent() ); + if (child == owner) { + other.setPropertyInParent(child.getPropertyInParent()); + other.setParent(child.getParent()); owner = (IASTExpression) other; } } @@ -159,7 +156,6 @@ public class CASTFieldReference extends ASTNode implements IASTFieldReference, I return new ProblemType(ISemanticProblem.TYPE_UNKNOWN_FOR_EXPRESSION); } - @Override public boolean isLValue() { if (isPointerDereference()) diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTFieldReference.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTFieldReference.java index c55a50dd697..42df2fd5c8d 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTFieldReference.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTFieldReference.java @@ -18,7 +18,11 @@ import static org.eclipse.cdt.core.dom.ast.IASTExpression.ValueCategory.PRVALUE; import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.glvalueType; import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.prvalueType; import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.typeFromFunctionCall; -import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.*; +import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.ALLCVQ; +import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.CVTYPE; +import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.REF; +import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.TDEF; +import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.getUltimateTypeUptoPointers; import java.util.ArrayList; import java.util.Collection; @@ -53,15 +57,13 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPSemantics; import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CVQualifier; import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil; -public class CPPASTFieldReference extends ASTNode implements ICPPASTFieldReference, IASTAmbiguityParent, - ICPPASTCompletionContext { - +public class CPPASTFieldReference extends ASTNode + implements ICPPASTFieldReference, IASTAmbiguityParent, ICPPASTCompletionContext { private boolean isTemplate; private IASTExpression owner; private IASTName name; private boolean isDeref; - - private IASTImplicitName[] implicitNames = null; + private IASTImplicitName[] implicitNames; public CPPASTFieldReference() { } @@ -148,15 +150,15 @@ public class CPPASTFieldReference extends ASTNode implements ICPPASTFieldReferen if (!isDeref) return implicitNames = IASTImplicitName.EMPTY_NAME_ARRAY; - // collect the function bindings + // Collect the function bindings List functionBindings = new ArrayList(); getFieldOwnerType(functionBindings); if (functionBindings.isEmpty()) return implicitNames = IASTImplicitName.EMPTY_NAME_ARRAY; - // create a name to wrap each binding + // Create a name to wrap each binding implicitNames = new IASTImplicitName[functionBindings.size()]; - int i=-1; + int i= -1; for (ICPPFunction op : functionBindings) { if (op != null && !(op instanceof CPPImplicitFunction)) { CPPASTImplicitName operatorName = new CPPASTImplicitName(OverloadableOperator.ARROW, this); @@ -280,7 +282,6 @@ public class CPPASTFieldReference extends ASTNode implements ICPPASTFieldReferen } return fieldType; } - @Override public ValueCategory getValueCategory() { diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java index d755f2ac8a5..2d03fbd4db7 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java @@ -12,10 +12,17 @@ *******************************************************************************/ package org.eclipse.cdt.ui.tests.refactoring.extractfunction; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import junit.framework.Test; +import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.cdt.ui.CUIPlugin; +import org.eclipse.cdt.ui.PreferenceConstants; import org.eclipse.cdt.ui.tests.refactoring.RefactoringTestBase; import org.eclipse.cdt.internal.ui.refactoring.NameInformation; @@ -31,6 +38,10 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase { private ExtractFunctionInformation refactoringInfo; private String extractedFunctionName = "extracted"; private String returnValue; + // Map from old names to new ones. + private Map parameterRename = new HashMap(); + // New positions of parameters, or null. + private int[] parameterOrder; private VisibilityEnum visibility = VisibilityEnum.v_private; private boolean virtual; private boolean replaceDuplicates = true; @@ -47,6 +58,26 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase { return suite(ExtractFunctionRefactoringTest.class); } + @Override + public void setUp() throws Exception { + super.setUp(); + resetPreferences(); + } + + @Override + public void tearDown() throws Exception { + super.tearDown(); + resetPreferences(); + } + + private void resetPreferences() { + getPreferenceStore().setToDefault(PreferenceConstants.FUNCTION_PASS_OUTPUT_PARAMETERS_BY_POINTER); + } + + private IPreferenceStore getPreferenceStore() { + return CUIPlugin.getDefault().getPreferenceStore(); + } + @Override protected Refactoring createRefactoring() { refactoringInfo = new ExtractFunctionInformation(); @@ -61,14 +92,32 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase { if (refactoringInfo.getMandatoryReturnVariable() == null) { if (returnValue != null) { for (NameInformation nameInfo : refactoringInfo.getParameters()) { - nameInfo.setReturnValue(returnValue.equals(String.valueOf(nameInfo.getName().getSimpleID()))); + nameInfo.setReturnValue(returnValue.equals(getName(nameInfo))); } } } + if (!parameterRename.isEmpty()) { + for (NameInformation nameInfo : refactoringInfo.getParameters()) { + String newName = parameterRename.get(getName(nameInfo)); + if (newName != null) + nameInfo.setNewName(newName); + } + } + if (parameterOrder != null) { + List parameters = refactoringInfo.getParameters(); + NameInformation[] originalParameters = parameters.toArray(new NameInformation[parameters.size()]); + for (int i = 0; i < parameterOrder.length; i++) { + parameters.set(parameterOrder[i], originalParameters[i]); + } + } refactoringInfo.setVisibility(visibility); refactoringInfo.setVirtual(virtual); } + private String getName(NameInformation nameInfo) { + return String.valueOf(nameInfo.getName().getSimpleID()); + } + //A.h //#ifndef A_H_ //#define A_H_ @@ -536,7 +585,7 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase { //A.cpp //#include "A.h" // - //#define ZWO 2 + //#define TWO 2 // //A::A() { //} @@ -547,7 +596,7 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase { //int A::foo() { // int i = 2; // /*$*/++i; - // i += ZWO; + // i += TWO; // help();/*$$*/ // return i; //} @@ -558,7 +607,7 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase { //==================== //#include "A.h" // - //#define ZWO 2 + //#define TWO 2 // //A::A() { //} @@ -568,7 +617,7 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase { // //int A::extracted(int i) { // ++i; - // i += ZWO; + // i += TWO; // help(); // return i; //} @@ -698,7 +747,7 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase { // //private: // int help(); - // void extracted(int* i); + // void extracted(int* j); //}; // //#endif /*A_H_*/ @@ -731,8 +780,8 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase { //A::~A() { //} // - //void A::extracted(int* i) { - // ++*i; + //void A::extracted(int* j) { + // ++*j; // help(); //} // @@ -745,7 +794,94 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase { //int A::help() { // return 42; //} - public void testPointer() throws Exception { + public void testRenamedParameter() throws Exception { + parameterRename.put("i", "j"); + assertRefactoringSuccess(); + } + + //A.c + //struct A { + // int i; + // int j; + //}; + // + //int test() { + // struct A a = { 1, 2 }; + // return /*$*/a.i + a.j/*$$*/; + //} + //==================== + //struct A { + // int i; + // int j; + //}; + // + //int extracted(const struct A* a) { + // return a->i + a->j; + //} + // + //int test() { + // struct A a = { 1, 2 }; + // return extracted(&a); + //} + public void testInputParameterPassedByPointer() throws Exception { + assertRefactoringSuccess(); + } + + //A.c + //int test() { + // int i = 0; + // int j = 1; + // /*$*/int k = i; + // i = j; + // j = k;/*$$*/ + // return i - j; + //} + //==================== + //void swap(int* i, int* j) { + // int k = *i; + // *i = *j; + // *j = k; + //} + // + //int test() { + // int i = 0; + // int j = 1; + // swap(&i, &j); + // return i - j; + //} + public void testOutputParameterPassedByPointer() throws Exception { + extractedFunctionName = "swap"; + returnValue = NO_RETURN_VALUE; + assertRefactoringSuccess(); + } + + //A.h + //class A { + //public: + // int method(); + // int const_method() const; + //}; + + //A.cpp + //#include "A.h" + // + //int test() { + // A a, b; + // return /*$*/a.method() + b.const_method()/*$$*/ + a.const_method(); + //} + //==================== + //#include "A.h" + // + //int extracted(A b, A* a) { + // return a->method() + b.const_method(); + //} + //int test() { + // A a, b; + // return extracted(b, &a) + a.const_method(); + //} + public void _testOutputParameterWithMethodCall() throws Exception { + // Currently fails due to http://bugs.eclipse.org/bugs/show_bug.cgi?id=370887 + getPreferenceStore().setValue(PreferenceConstants.FUNCTION_PASS_OUTPUT_PARAMETERS_BY_POINTER, true); assertRefactoringSuccess(); } @@ -2562,91 +2698,6 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase { public void testDuplicates() throws Exception { assertRefactoringSuccess(); } - - //A.h - //#ifndef A_H_ - //#define A_H_ - // - //class A { - //public: - // A(); - // virtual ~A(); - // int foo(); - // - //private: - // int help(); - //}; - // - //#endif /*A_H_*/ - //==================== - //#ifndef A_H_ - //#define A_H_ - // - //class A { - //public: - // A(); - // virtual ~A(); - // int foo(); - // - //private: - // int help(); - // int extracted(int i); - //}; - // - //#endif /*A_H_*/ - - //A.cpp - //#include "A.h" - // - //A::A() { - //} - // - //A::~A() { - // int oo = 99; - // ++oo; - // help(); - //} - // - //int A::foo() { - // int i = 2; - // /*$*/++i; - // help();/*$$*/ - // return i; - //} - // - //int A::help() { - // return 42; - //} - //==================== - //#include "A.h" - // - //A::A() { - //} - // - //A::~A() { - // int oo = 99; - // oo = extracted(oo); - //} - // - //int A::extracted(int i) { - // ++i; - // help(); - // return i; - //} - // - //int A::foo() { - // int i = 2; - // i = extracted(i); - // return i; - //} - // - //int A::help() { - // return 42; - //} - public void testDuplicatesWithDifferentNames() throws Exception { - assertRefactoringSuccess(); - } - //A.h //#ifndef A_H_ //#define A_H_ @@ -2930,7 +2981,96 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase { //int A::help() { // return 42; //} - public void testDuplicatesWithDifferentNamesAndReturnType() throws Exception { + public void testDuplicatesWithDifferentNames() throws Exception { + assertRefactoringSuccess(); + } + + //A.h + //#ifndef A_H_ + //#define A_H_ + // + //class A { + //public: + // A(); + // virtual ~A(); + // int foo(); + // + //private: + // int help(); + //}; + // + //#endif /*A_H_*/ + //==================== + //#ifndef A_H_ + //#define A_H_ + // + //class A { + //public: + // A(); + // virtual ~A(); + // int foo(); + // + //private: + // int help(); + // int extracted(int j, int i); + //}; + // + //#endif /*A_H_*/ + + //A.cpp + //#include "A.h" + // + //A::A() { + //} + // + //A::~A() { + // int aa = 9; + // int bb = 99; + // aa += bb; + // help(); + //} + // + //int A::foo() { + // int i = 2; + // int j = 3; + // /*$*/i += j; + // help();/*$$*/ + // return i; + //} + // + //int A::help() { + // return 42; + //} + //==================== + //#include "A.h" + // + //A::A() { + //} + // + //A::~A() { + // int aa = 9; + // int bb = 99; + // aa = extracted(bb, aa); + //} + // + //int A::extracted(int j, int i) { + // i += j; + // help(); + // return i; + //} + // + //int A::foo() { + // int i = 2; + // int j = 3; + // i = extracted(j, i); + // return i; + //} + // + //int A::help() { + // return 42; + //} + public void testDuplicatesWithDifferentNamesAndReordering() throws Exception { + parameterOrder = new int[] { 1, 0 }; assertRefactoringSuccess(); } @@ -3105,7 +3245,7 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase { //int A::help() { // return 42; //} - public void testDuplicateNameUsedAfterwardsInDuplicateButNotInOriginalSelectionThisIsNoDuplicate() throws Exception { + public void testOutputParameterInDuplicateButNotInOriginal() throws Exception { assertRefactoringSuccess(); } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/NameInformation.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/NameInformation.java index aba38c6b706..cfb7ec04c2e 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/NameInformation.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/NameInformation.java @@ -21,7 +21,6 @@ import org.eclipse.cdt.core.dom.ast.IASTArrayDeclarator; import org.eclipse.cdt.core.dom.ast.IASTArrayModifier; import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier; import org.eclipse.cdt.core.dom.ast.IASTDeclarator; -import org.eclipse.cdt.core.dom.ast.IASTFileLocation; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNode; import org.eclipse.cdt.core.dom.ast.IASTNode.CopyStyle; @@ -30,6 +29,7 @@ import org.eclipse.cdt.core.dom.ast.IASTPointerOperator; import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration; import org.eclipse.cdt.core.dom.ast.INodeFactory; import org.eclipse.cdt.core.dom.ast.IType; +import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTranslationUnit; import org.eclipse.cdt.core.dom.ast.cpp.ICPPNodeFactory; import org.eclipse.cdt.core.dom.rewrite.TypeHelper; import org.eclipse.cdt.core.model.ITranslationUnit; @@ -40,13 +40,16 @@ import org.eclipse.cdt.internal.core.dom.rewrite.astwriter.ASTWriterVisitor; * Additional information about an IASTName in code being refactored. */ public class NameInformation { + public static enum Indirection { NONE, POINTER, REFERENCE } + public static final int INDEX_FOR_ADDED = -1; private final IASTName name; private IASTName declarationName; private final List references; - private List referencesAfterCached; - private int lastCachedReferencesHash; + private final List referencesBeforeSelection; + private final List referencesInSelection; + private final List referencesAfterSelection; private boolean isOutput; private boolean mustBeReturnValue; private boolean isWriteAccess; @@ -57,11 +60,15 @@ public class NameInformation { private boolean isDeleted; private String defaultValue; private String newTypeName; + private Indirection indirection; public NameInformation(IASTName name) { this.name = name; this.newName = String.valueOf(name.getSimpleID()); references = new ArrayList(); + referencesBeforeSelection = new ArrayList(); + referencesInSelection = new ArrayList(); + referencesAfterSelection = new ArrayList(); } public static NameInformation createInfoForAddedParameter(String type, String name, @@ -99,6 +106,7 @@ public class NameInformation { void setOutput(boolean isOutput) { this.isOutput = isOutput; + indirection = null; } public boolean isOutputParameter() { @@ -111,6 +119,7 @@ public class NameInformation { public void setMustBeReturnValue(boolean mustBeReturnValue) { this.mustBeReturnValue = mustBeReturnValue; + indirection = null; } public boolean isReturnValue() { @@ -120,6 +129,7 @@ public class NameInformation { public void setReturnValue(boolean isReturnValue) { Assert.isTrue(isReturnValue || !mustBeReturnValue); this.isReturnValue = isReturnValue; + indirection = null; } public String getNewName() { @@ -136,6 +146,7 @@ public class NameInformation { void setWriteAccess(boolean isWriteAceess) { this.isWriteAccess = isWriteAceess; + indirection = null; } public boolean isDeleted() { @@ -182,6 +193,7 @@ public class NameInformation { void setDeclarationName(IASTName declarationName) { Assert.isTrue(declarationName.getParent() instanceof IASTDeclarator); this.declarationName = declarationName; + indirection = null; } public IASTName getName() { @@ -189,11 +201,19 @@ public class NameInformation { } public boolean isRenamed() { - return name == null ? newName != null : String.valueOf(name.getSimpleID()).equals(name); + return name == null ? newName != null : !String.valueOf(name.getSimpleID()).equals(newName); } - void addReference(IASTName name) { + void addReference(IASTName name, int startOffset, int endOffset) { references.add(name); + int nodeOffset = name.getFileLocation().getNodeOffset(); + if (nodeOffset >= endOffset) { + referencesAfterSelection.add(name); + } else if (nodeOffset >= startOffset) { + referencesInSelection.add(name); + } else { + referencesBeforeSelection.add(name); + } } public String getTypeName() { @@ -224,22 +244,20 @@ public class NameInformation { return writer.toString(); } - public List getReferencesAfterSelection(int endOffset) { - if (referencesAfterCached == null || lastCachedReferencesHash != references.hashCode()) { - lastCachedReferencesHash = references.hashCode(); - referencesAfterCached = new ArrayList(); - for (IASTName ref : references) { - IASTFileLocation loc = ref.getFileLocation(); - if (loc.getNodeOffset() >= endOffset) { - referencesAfterCached.add(ref); - } - } - } - return referencesAfterCached; + public List getReferencesBeforeSelection() { + return referencesBeforeSelection; } - public boolean isReferencedAfterSelection(int endOffset) { - return !getReferencesAfterSelection(endOffset).isEmpty(); + public List getReferencesInSelection() { + return referencesInSelection; + } + + public List getReferencesAfterSelection() { + return referencesAfterSelection; + } + + public boolean isReferencedAfterSelection() { + return !referencesAfterSelection.isEmpty(); } public IASTParameterDeclaration getParameterDeclaration(INodeFactory nodeFactory) { @@ -251,29 +269,47 @@ public class NameInformation { IASTDeclSpecifier declSpec = safeCopy(getDeclSpecifier()); IASTDeclarator declarator = createDeclarator(nodeFactory, sourceDeclarator, paramName); - if (isOutputParameter()) { - if (nodeFactory instanceof ICPPNodeFactory && !passOutputByPointer) { - declarator.addPointerOperator(((ICPPNodeFactory) nodeFactory).newReferenceOperator(false)); - } else { - declarator.addPointerOperator(nodeFactory.newPointer()); - } - } else if (declSpec != null && !isWriteAccess) { - IType type = TypeHelper.createType(sourceDeclarator); - if (TypeHelper.shouldBePassedByReference(type, declarationName.getTranslationUnit())) { - if (nodeFactory instanceof ICPPNodeFactory) { - declarator.addPointerOperator(((ICPPNodeFactory) nodeFactory).newReferenceOperator(false)); - } else { - declarator.addPointerOperator(nodeFactory.newPointer()); - } - declSpec.setConst(true); - } + Indirection indirection = getIndirection(); + if (indirection == Indirection.POINTER) { + declarator.addPointerOperator(nodeFactory.newPointer()); + } else if (indirection == Indirection.REFERENCE) { + declarator.addPointerOperator(((ICPPNodeFactory) nodeFactory).newReferenceOperator(false)); + } + + if (indirection != Indirection.NONE && !isWriteAccess && declSpec != null) { + declSpec.setConst(true); } declarator.setNestedDeclarator(sourceDeclarator.getNestedDeclarator()); - return nodeFactory.newParameterDeclaration(declSpec, declarator); } + public Indirection getIndirection() { + if (indirection == null) { + indirection = Indirection.NONE; + boolean isCpp = declarationName.getTranslationUnit() instanceof ICPPASTTranslationUnit; + if (isOutputParameter()) { + if (isCpp && !passOutputByPointer) { + indirection = Indirection.REFERENCE; + } else { + indirection = Indirection.POINTER; + } + } else { + IType type = TypeHelper.createType(getDeclarator()); + if (TypeHelper.shouldBePassedByReference(type, declarationName.getTranslationUnit())) { + if (isCpp) { + if (!isWriteAccess) { + indirection = Indirection.REFERENCE; + } + } else { + indirection = Indirection.POINTER; + } + } + } + } + return indirection; + } + private IASTDeclarator createDeclarator(INodeFactory nodeFactory, IASTDeclarator sourceDeclarator, String name) { IASTName astName = name != null ? @@ -311,5 +347,6 @@ public class NameInformation { public void setPassOutputByPointer(boolean passOutputByPointer) { this.passOutputByPointer = passOutputByPointer; + indirection = null; } } \ No newline at end of file diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/NodeContainer.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/NodeContainer.java index 48131146709..0d544788747 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/NodeContainer.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/NodeContainer.java @@ -28,6 +28,7 @@ import org.eclipse.core.runtime.preferences.IPreferencesService; import org.eclipse.cdt.core.dom.ast.ASTVisitor; import org.eclipse.cdt.core.dom.ast.DOMException; import org.eclipse.cdt.core.dom.ast.IASTDeclarator; +import org.eclipse.cdt.core.dom.ast.IASTFieldReference; import org.eclipse.cdt.core.dom.ast.IASTMacroExpansionLocation; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNode; @@ -73,6 +74,8 @@ public class NodeContainer { return; } names = new ArrayList(); + final int startOffset = getStartOffset(); + final int endOffset = getEndOffset(); IPreferencesService preferences = Platform.getPreferencesService(); final boolean passOutputByPointer = preferences.getBoolean(CUIPlugin.PLUGIN_ID, @@ -87,34 +90,36 @@ public class NodeContainer { @Override public int visit(IASTName name) { - IBinding binding = name.resolveBinding(); - - if (binding instanceof ICPPBinding && !(binding instanceof ICPPTemplateTypeParameter)) { - ICPPBinding cppBinding = (ICPPBinding) binding; - try { - if (!cppBinding.isGloballyQualified()) { - NameInformation nameInfo = new NameInformation(name); - nameInfo.setPassOutputByPointer(passOutputByPointer); - IASTName[] refs = name.getTranslationUnit().getReferences(binding); - for (IASTName ref : refs) { - nameInfo.addReference(ref); + if (name.getPropertyInParent() != IASTFieldReference.FIELD_NAME) { + IBinding binding = name.resolveBinding(); + + if (binding instanceof ICPPBinding && !(binding instanceof ICPPTemplateTypeParameter)) { + ICPPBinding cppBinding = (ICPPBinding) binding; + try { + if (!cppBinding.isGloballyQualified()) { + NameInformation nameInfo = new NameInformation(name); + nameInfo.setPassOutputByPointer(passOutputByPointer); + IASTName[] refs = name.getTranslationUnit().getReferences(binding); + for (IASTName ref : refs) { + nameInfo.addReference(ref, startOffset, endOffset); + } + names.add(nameInfo); } - names.add(nameInfo); + } catch (DOMException e) { + ILog logger = CUIPlugin.getDefault().getLog(); + IStatus status = new Status(IStatus.WARNING, CUIPlugin.PLUGIN_ID, + e.getMessage(), e); + logger.log(status); } - } catch (DOMException e) { - ILog logger = CUIPlugin.getDefault().getLog(); - IStatus status = new Status(IStatus.WARNING, - CUIPlugin.PLUGIN_ID, IStatus.OK, e.getMessage(), e); - logger.log(status); + } else if (binding instanceof IVariable) { + NameInformation nameInformation = new NameInformation(name); + + IASTName[] refs = name.getTranslationUnit().getReferences(binding); + for (IASTName ref : refs) { + nameInformation.addReference(ref, startOffset, endOffset); + } + names.add(nameInformation); } - } else if (binding instanceof IVariable) { - NameInformation nameInformation = new NameInformation(name); - - IASTName[] refs = name.getTranslationUnit().getReferences(binding); - for (IASTName ref : refs) { - nameInformation.addReference(ref); - } - names.add(nameInformation); } return super.visit(name); } @@ -152,12 +157,11 @@ public class NodeContainer { Set declarations = new HashSet(); interfaceNames = new ArrayList(); - int endOffset = getEndOffset(); for (NameInformation nameInfo : names) { IASTName declarationName = nameInfo.getDeclarationName(); if (declarations.add(declarationName)) { if (isDeclaredInSelection(nameInfo)) { - if (nameInfo.isReferencedAfterSelection(endOffset)) { + if (nameInfo.isReferencedAfterSelection()) { nameInfo.setMustBeReturnValue(true); interfaceNames.add(nameInfo); } @@ -173,7 +177,7 @@ public class NodeContainer { } } } - if (nameInfo.isWriteAccess() && nameInfo.isReferencedAfterSelection(endOffset)) { + if (nameInfo.isWriteAccess() && nameInfo.isReferencedAfterSelection()) { nameInfo.setOutput(true); } } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractExpression.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractExpression.java index d7be786dfcf..9409b833d72 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractExpression.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractExpression.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik + * Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik * Rapperswil, University of applied sciences and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 @@ -8,11 +8,13 @@ * * Contributors: * Institute for Software - initial API and implementation + * Sergey Prigogin (Google) *******************************************************************************/ package org.eclipse.cdt.internal.ui.refactoring.extractfunction; import java.util.ArrayList; import java.util.List; +import java.util.Map; import org.eclipse.text.edits.TextEditGroup; @@ -24,7 +26,6 @@ import org.eclipse.cdt.core.dom.ast.IASTExpression; import org.eclipse.cdt.core.dom.ast.IASTExpressionStatement; import org.eclipse.cdt.core.dom.ast.IASTFunctionCallExpression; import org.eclipse.cdt.core.dom.ast.IASTIdExpression; -import org.eclipse.cdt.core.dom.ast.IASTLiteralExpression; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNode; import org.eclipse.cdt.core.dom.ast.IASTNode.CopyStyle; @@ -44,7 +45,6 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTBinaryExpression; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTFieldReference; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTFunctionDefinition; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTIdExpression; -import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTLiteralExpression; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTReturnStatement; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTSimpleDeclSpecifier; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTSimpleDeclaration; @@ -58,30 +58,27 @@ import org.eclipse.cdt.internal.ui.refactoring.NameInformation; * @author Mirko Stocker */ public class ExtractExpression extends ExtractedFunctionConstructionHelper { - private final static char[] ZERO= { '0' }; - @Override - public void constructMethodBody(IASTCompoundStatement compound, List list, - ASTRewrite rewrite, TextEditGroup group) { + public void constructMethodBody(IASTCompoundStatement compound, List nodes, + List parameters, ASTRewrite rewrite, TextEditGroup group) { CPPASTReturnStatement statement = new CPPASTReturnStatement(); - IASTExpression nullReturnExp = - new CPPASTLiteralExpression(IASTLiteralExpression.lk_integer_constant, ZERO); - statement.setReturnValue(nullReturnExp); - ASTRewrite nestedRewrite = rewrite.insertBefore(compound, null, statement, group); - - nestedRewrite.replace(nullReturnExp, getExpression(list), group); + statement.setReturnValue(getExpression(nodes)); + ASTRewrite subRewrite = rewrite.insertBefore(compound, null, statement, group); + Map changedParameters = getChangedParameterReferences(parameters); + INodeFactory nodeFactory = nodes.get(0).getTranslationUnit().getASTNodeFactory(); + adjustParameterReferences(statement, changedParameters, nodeFactory, subRewrite, group); } - private IASTExpression getExpression(List list) { - if (list.size() > 1) { + private IASTExpression getExpression(List nodes) { + if (nodes.size() > 1) { CPPASTBinaryExpression expression = new CPPASTBinaryExpression(); - expression.setParent(list.get(0).getParent()); - expression.setOperand1((IASTExpression) list.get(0).copy(CopyStyle.withLocations)); - expression.setOperator(((IASTBinaryExpression) list.get(1).getParent()).getOperator()); - expression.setOperand2(getExpression(list.subList(1, list.size()))); + expression.setParent(nodes.get(0).getParent()); + expression.setOperand1((IASTExpression) nodes.get(0).copy(CopyStyle.withLocations)); + expression.setOperator(((IASTBinaryExpression) nodes.get(1).getParent()).getOperator()); + expression.setOperand2(getExpression(nodes.subList(1, nodes.size()))); return expression; } else { - return (IASTExpression) list.get(0).copy(CopyStyle.withLocations); + return (IASTExpression) nodes.get(0).copy(CopyStyle.withLocations); } } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractFunctionRefactoring.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractFunctionRefactoring.java index 3e8b22e9dff..cb72987ec55 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractFunctionRefactoring.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractFunctionRefactoring.java @@ -61,6 +61,7 @@ import org.eclipse.cdt.core.dom.ast.IASTReturnStatement; import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration; import org.eclipse.cdt.core.dom.ast.IASTStandardFunctionDeclarator; import org.eclipse.cdt.core.dom.ast.IASTStatement; +import org.eclipse.cdt.core.dom.ast.IASTUnaryExpression; import org.eclipse.cdt.core.dom.ast.IBasicType; import org.eclipse.cdt.core.dom.ast.IBinding; import org.eclipse.cdt.core.dom.ast.IField; @@ -101,7 +102,6 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTQualifiedName; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTReturnStatement; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTSimpleDeclaration; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTemplateDeclaration; -import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPNodeFactory; import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil; import org.eclipse.cdt.internal.core.dom.rewrite.astwriter.ASTWriterVisitor; @@ -113,6 +113,7 @@ import org.eclipse.cdt.internal.ui.refactoring.MethodContext; import org.eclipse.cdt.internal.ui.refactoring.MethodContext.ContextType; import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector; import org.eclipse.cdt.internal.ui.refactoring.NameInformation; +import org.eclipse.cdt.internal.ui.refactoring.NameInformation.Indirection; import org.eclipse.cdt.internal.ui.refactoring.NodeContainer; import org.eclipse.cdt.internal.ui.refactoring.utils.ASTHelper; import org.eclipse.cdt.internal.ui.refactoring.utils.CPPASTAllVisitor; @@ -138,8 +139,8 @@ public class ExtractFunctionRefactoring extends CRefactoring { HashMap nameTrail; - private ExtractedFunctionConstructionHelper extractedFunctionConstructionHelper; - private final INodeFactory nodeFactory = CPPNodeFactory.getDefault(); + private ExtractedFunctionConstructionHelper functionConstructionHelper; + private INodeFactory nodeFactory; DefaultCodeFormatterOptions formattingOptions; public ExtractFunctionRefactoring(IFile file, ISelection selection, @@ -167,6 +168,7 @@ public class ExtractFunctionRefactoring extends CRefactoring { return status; } + nodeFactory = ast.getASTNodeFactory(); container = findExtractableNodes(); sm.worked(1); @@ -212,7 +214,7 @@ public class ExtractFunctionRefactoring extends CRefactoring { PreferenceConstants.getPreferenceScopes(project.getProject())); info.sortParameters(outFirst); - extractedFunctionConstructionHelper = + functionConstructionHelper = ExtractedFunctionConstructionHelper.createFor(container.getNodesToWrite()); boolean isExtractExpression = container.getNodesToWrite().get(0) instanceof IASTExpression; @@ -354,7 +356,7 @@ public class ExtractFunctionRefactoring extends CRefactoring { } } - private void createMethodCalls(final IASTName astMethodName, MethodContext context, + private void createMethodCalls(IASTName methodName, MethodContext context, ModificationCollector collector) throws CoreException { String title; if (context.getType() == MethodContext.ContextType.METHOD) { @@ -363,7 +365,7 @@ public class ExtractFunctionRefactoring extends CRefactoring { title = Messages.ExtractFunctionRefactoring_CreateFunctionCall; } - IASTNode methodCall = getMethodCall(astMethodName); + IASTNode methodCall = getMethodCall(methodName); IASTNode firstNodeToWrite = container.getNodesToWrite().get(0); ASTRewrite rewriter = collector.rewriterForTranslationUnit( @@ -377,7 +379,7 @@ public class ExtractFunctionRefactoring extends CRefactoring { insertCallIntoTree(methodCall, container.getNodesToWrite(), rewriter, editGroup); if (info.isReplaceDuplicates()) { - replaceSimilar(collector, astMethodName); + replaceSimilar(collector, methodName); } for (IASTNode node : container.getNodesToWrite()) { @@ -415,7 +417,7 @@ public class ExtractFunctionRefactoring extends CRefactoring { return binExp; } - private void createMethodDefinition(final IASTName astMethodName, MethodContext context, + private void createMethodDefinition(final IASTName methodName, MethodContext context, IASTNode firstNode, ModificationCollector collector) { IASTFunctionDefinition node = NodeHelper.findFunctionDefinitionInAncestors(firstNode); if (node != null) { @@ -427,7 +429,7 @@ public class ExtractFunctionRefactoring extends CRefactoring { } ASTRewrite rewriter = collector.rewriterForTranslationUnit(node.getTranslationUnit()); - addMethod(astMethodName, context, rewriter, node, new TextEditGroup(title)); + addMethod(methodName, context, rewriter, node, new TextEditGroup(title)); } } @@ -618,17 +620,17 @@ public class ExtractFunctionRefactoring extends CRefactoring { return true; } - private void addMethod(IASTName astMethodName, MethodContext context, ASTRewrite rewriter, + private void addMethod(IASTName methodName, MethodContext context, ASTRewrite rewrite, IASTNode insertPoint, TextEditGroup group) { ICPPASTQualifiedName qname = new CPPASTQualifiedName(); if (context.getType() == ContextType.METHOD) { if (context.getMethodQName() != null) { - for (int i = 0; i < (context.getMethodQName().getNames().length - 1); i++) { + for (int i = 0; i < context.getMethodQName().getNames().length - 1; i++) { qname.addName(new CPPASTName(context.getMethodQName().getNames()[i].toCharArray())); } } } - qname.addName(astMethodName); + qname.addName(methodName); IASTFunctionDefinition func = new CPPASTFunctionDefinition(); func.setParent(ast); @@ -637,32 +639,33 @@ public class ExtractFunctionRefactoring extends CRefactoring { func.setDeclSpecifier(returnType); IASTStandardFunctionDeclarator createdFunctionDeclarator = - extractedFunctionConstructionHelper.createFunctionDeclarator(qname, + functionConstructionHelper.createFunctionDeclarator(qname, info.getDeclarator(), info.getReturnVariable(), container.getNodesToWrite(), - info.getParameters(), ast.getASTNodeFactory()); + info.getParameters(), nodeFactory); func.setDeclarator(createdFunctionDeclarator); IASTCompoundStatement compound = new CPPASTCompoundStatement(); func.setBody(compound); - ASTRewrite subRW; - if (insertPoint.getParent() instanceof ICPPASTTemplateDeclaration) { + ASTRewrite subRewrite; + IASTNode parent = insertPoint.getParent(); + if (parent instanceof ICPPASTTemplateDeclaration) { + ICPPASTTemplateDeclaration parentTemplate = (ICPPASTTemplateDeclaration) parent; CPPASTTemplateDeclaration templateDeclaration = new CPPASTTemplateDeclaration(); templateDeclaration.setParent(ast); - for (ICPPASTTemplateParameter param : ((ICPPASTTemplateDeclaration) insertPoint.getParent()).getTemplateParameters()) { + for (ICPPASTTemplateParameter param : parentTemplate.getTemplateParameters()) { templateDeclaration.addTemplateParameter(param.copy(CopyStyle.withLocations)); } templateDeclaration.setDeclaration(func); - subRW = rewriter.insertBefore(insertPoint.getParent().getParent(), insertPoint.getParent(), - templateDeclaration, group); + subRewrite = rewrite.insertBefore(parent.getParent(), parent, templateDeclaration, group); } else { - subRW = rewriter.insertBefore(insertPoint.getParent(), insertPoint, func, group); + subRewrite = rewrite.insertBefore(parent, insertPoint, func, group); } - - extractedFunctionConstructionHelper.constructMethodBody(compound, - container.getNodesToWrite(), subRW, group); + + functionConstructionHelper.constructMethodBody(compound, container.getNodesToWrite(), + info.getParameters(), subRewrite, group); // Set return value NameInformation returnVariable = info.getReturnVariable(); @@ -675,7 +678,7 @@ public class ExtractFunctionRefactoring extends CRefactoring { expr.setName(new CPPASTName(returnVariable.getNewName().toCharArray())); } returnStmt.setReturnValue(expr); - subRW.insertBefore(compound, null, returnStmt, group); + subRewrite.insertBefore(compound, null, returnStmt, group); } } @@ -686,7 +689,7 @@ public class ExtractFunctionRefactoring extends CRefactoring { private IASTDeclSpecifier getReturnType() { IASTNode firstNodeToWrite = container.getNodesToWrite().get(0); NameInformation returnVariable = info.getReturnVariable(); - return extractedFunctionConstructionHelper.determineReturnType(firstNodeToWrite, + return functionConstructionHelper.determineReturnType(firstNodeToWrite, returnVariable); } @@ -755,28 +758,28 @@ public class ExtractFunctionRefactoring extends CRefactoring { return getReturnAssignment(stmt, callExpression, retName); } - private IASTNode getMethodCall(IASTName astMethodName) { - IASTExpressionStatement stmt = new CPPASTExpressionStatement(); + private IASTNode getMethodCall(IASTName methodName) { + IASTExpressionStatement statement = new CPPASTExpressionStatement(); IASTFunctionCallExpression callExpression = new CPPASTFunctionCallExpression(); IASTIdExpression idExpression = new CPPASTIdExpression(); - idExpression.setName(new CPPASTName(astMethodName.toCharArray())); + idExpression.setName(new CPPASTName(methodName.toCharArray())); List args = getCallParameters(); callExpression.setArguments(args.toArray(new IASTInitializerClause[args.size()])); callExpression.setFunctionNameExpression(idExpression); if (info.getReturnVariable() == null) { - return getReturnAssignment(stmt, callExpression); + return getReturnAssignment(statement, callExpression); } - IASTName retname = newName(info.getReturnVariable().getName()); - return getReturnAssignment(stmt, callExpression, retname); + IASTName retName = newName(info.getReturnVariable().getName()); + return getReturnAssignment(statement, callExpression, retName); } private IASTNode getReturnAssignment(IASTExpressionStatement stmt, IASTFunctionCallExpression callExpression, IASTName retname) { if (info.getReturnVariable().equals(info.getMandatoryReturnVariable())) { - IASTSimpleDeclaration orgDecl = NodeHelper.findSimpleDeclarationInParents(info - .getReturnVariable().getDeclarationName()); + IASTSimpleDeclaration orgDecl = NodeHelper.findSimpleDeclarationInParents( + info.getReturnVariable().getDeclarationName()); IASTSimpleDeclaration decl = new CPPASTSimpleDeclaration(); decl.setDeclSpecifier(orgDecl.getDeclSpecifier().copy(CopyStyle.withLocations)); @@ -810,15 +813,15 @@ public class ExtractFunctionRefactoring extends CRefactoring { private IASTNode getReturnAssignment(IASTExpressionStatement stmt, IASTExpression callExpression) { IASTNode node = container.getNodesToWrite().get(0); - return extractedFunctionConstructionHelper.createReturnAssignment(node, stmt, callExpression); + return functionConstructionHelper.createReturnAssignment(node, stmt, callExpression); } private IASTSimpleDeclaration getDeclaration(IASTName name) { IASTSimpleDeclaration simpleDecl = new CPPASTSimpleDeclaration(); IASTStandardFunctionDeclarator declarator = - extractedFunctionConstructionHelper.createFunctionDeclarator(name, + functionConstructionHelper.createFunctionDeclarator(name, info.getDeclarator(), info.getReturnVariable(), container.getNodesToWrite(), - info.getParameters(), ast.getASTNodeFactory()); + info.getParameters(), nodeFactory); simpleDecl.addDeclarator(declarator); return simpleDecl; } @@ -831,9 +834,9 @@ public class ExtractFunctionRefactoring extends CRefactoring { } simpleDecl.setParent(ast); IASTStandardFunctionDeclarator declarator = - extractedFunctionConstructionHelper.createFunctionDeclarator(name, + functionConstructionHelper.createFunctionDeclarator(name, info.getDeclarator(), info.getReturnVariable(), container.getNodesToWrite(), - info.getParameters(), ast.getASTNodeFactory()); + info.getParameters(), nodeFactory); simpleDecl.addDeclarator(declarator); return simpleDecl; } @@ -881,8 +884,10 @@ public class ExtractFunctionRefactoring extends CRefactoring { if (!container.isDeclaredInSelection(nameInfo)) { IASTName declaration = nameInfo.getDeclarationName(); if (declarations.add(declaration)) { - IASTIdExpression expression = new CPPASTIdExpression(); - expression.setName(newName(declaration)); + IASTExpression expression = nodeFactory.newIdExpression(newName(declaration)); + if (nameInfo.getIndirection() == Indirection.POINTER) { + expression = nodeFactory.newUnaryExpression(IASTUnaryExpression.op_amper, expression); + } args.add(expression); } } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractStatement.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractStatement.java index 5e3c0fa0cf3..b9af77c0177 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractStatement.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008 Institute for Software, HSR Hochschule fuer Technik + * Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik * Rapperswil, University of applied sciences and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 @@ -8,10 +8,12 @@ * * Contributors: * Institute for Software - initial API and implementation + * Sergey Prigogin (Google) *******************************************************************************/ package org.eclipse.cdt.internal.ui.refactoring.extractfunction; import java.util.List; +import java.util.Map; import org.eclipse.text.edits.TextEditGroup; @@ -19,9 +21,11 @@ import org.eclipse.cdt.core.dom.ast.IASTCompoundStatement; import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier; import org.eclipse.cdt.core.dom.ast.IASTExpression; import org.eclipse.cdt.core.dom.ast.IASTExpressionStatement; +import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNode; import org.eclipse.cdt.core.dom.ast.IASTNode.CopyStyle; import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclSpecifier; +import org.eclipse.cdt.core.dom.ast.INodeFactory; import org.eclipse.cdt.core.dom.rewrite.ASTRewrite; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTSimpleDeclSpecifier; @@ -35,9 +39,12 @@ import org.eclipse.cdt.internal.ui.refactoring.utils.ASTHelper; public class ExtractStatement extends ExtractedFunctionConstructionHelper { @Override public void constructMethodBody(IASTCompoundStatement compound, List nodes, - ASTRewrite rewrite, TextEditGroup group) { + List parameters, ASTRewrite rewrite, TextEditGroup group) { + Map changedParameters = getChangedParameterReferences(parameters); + INodeFactory nodeFactory = nodes.get(0).getTranslationUnit().getASTNodeFactory(); for (IASTNode node : nodes) { - rewrite.insertBefore(compound, null, node, group); + ASTRewrite subRewrite = rewrite.insertBefore(compound, null, node, group); + adjustParameterReferences(node, changedParameters, nodeFactory, subRewrite, group); } } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractedFunctionConstructionHelper.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractedFunctionConstructionHelper.java index ab3f2637d12..0ba32f0e614 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractedFunctionConstructionHelper.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractedFunctionConstructionHelper.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2009 Institute for Software, HSR Hochschule fuer Technik + * Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik * Rapperswil, University of applied sciences and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 @@ -8,31 +8,41 @@ * * Contributors: * Institute for Software - initial API and implementation + * Sergey Prigogin (Google) *******************************************************************************/ package org.eclipse.cdt.internal.ui.refactoring.extractfunction; import java.util.ArrayList; import java.util.Collection; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.eclipse.text.edits.TextEditGroup; +import org.eclipse.cdt.core.dom.ast.ASTVisitor; import org.eclipse.cdt.core.dom.ast.IASTCompoundStatement; import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier; import org.eclipse.cdt.core.dom.ast.IASTDeclarator; import org.eclipse.cdt.core.dom.ast.IASTExpression; import org.eclipse.cdt.core.dom.ast.IASTExpressionStatement; +import org.eclipse.cdt.core.dom.ast.IASTFieldReference; +import org.eclipse.cdt.core.dom.ast.IASTIdExpression; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNode; import org.eclipse.cdt.core.dom.ast.IASTNode.CopyStyle; import org.eclipse.cdt.core.dom.ast.IASTParameterDeclaration; import org.eclipse.cdt.core.dom.ast.IASTPointerOperator; import org.eclipse.cdt.core.dom.ast.IASTStandardFunctionDeclarator; +import org.eclipse.cdt.core.dom.ast.IASTUnaryExpression; import org.eclipse.cdt.core.dom.ast.INodeFactory; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTFunctionDeclarator; import org.eclipse.cdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.cdt.internal.core.dom.parser.ASTNode; + import org.eclipse.cdt.internal.ui.refactoring.NameInformation; +import org.eclipse.cdt.internal.ui.refactoring.NameInformation.Indirection; /** * @author Mirko Stocker @@ -46,8 +56,8 @@ public abstract class ExtractedFunctionConstructionHelper { return new ExtractStatement(); } - public abstract void constructMethodBody(IASTCompoundStatement compound, List list, - ASTRewrite rewrite, TextEditGroup group); + public abstract void constructMethodBody(IASTCompoundStatement compound, List nodes, + List parameters, ASTRewrite rewrite, TextEditGroup group); public abstract IASTDeclSpecifier determineReturnType(IASTNode extractedNode, NameInformation returnVariable); @@ -99,4 +109,83 @@ public abstract class ExtractedFunctionConstructionHelper { } return result; } + + /** + * Adjusts parameter references under the given node to account for renamed parameters and + * parameters passed by pointer. + * + * @param node the root node of the AST subtree to be adjusted + * @param changedParameters the map from references to changed parameters to parameters + * themselves + * @param rewrite the rewrite for the node + * @param group the edit group to add the changes to + */ + protected static void adjustParameterReferences(IASTNode node, + final Map changedParameters, final INodeFactory nodeFactory, + final ASTRewrite rewrite, final TextEditGroup group) { + if (changedParameters.isEmpty()) + return; + node.accept(new ASTVisitor() { + { + shouldVisitNames = true; + } + + @Override + public int visit(IASTName name) { + NameInformation param = changedParameters.get(((ASTNode) name).getOriginalNode()); + if (param != null) { + IASTName newName = null; + if (param.isRenamed()) { + newName = nodeFactory.newName(param.getNewName().toCharArray()); + } + if (param.getIndirection() == Indirection.POINTER && + name.getPropertyInParent() == IASTIdExpression.ID_NAME) { + IASTIdExpression idExp = (IASTIdExpression) name.getParent(); + if (idExp.getPropertyInParent() == IASTFieldReference.FIELD_OWNER && + !((IASTFieldReference) idExp.getParent()).isPointerDereference()) { + IASTFieldReference dotRef = (IASTFieldReference) idExp.getParent(); + IASTFieldReference arrowRef = dotRef.copy(CopyStyle.withLocations); + arrowRef.setIsPointerDereference(true); + if (newName != null) { + idExp = (IASTIdExpression) arrowRef.getFieldOwner(); + idExp.setName(newName); + } + rewrite.replace(dotRef, arrowRef, group); + } else { + IASTIdExpression newIdExp = idExp.copy(CopyStyle.withLocations); + IASTUnaryExpression starExp = + nodeFactory.newUnaryExpression(IASTUnaryExpression.op_star, newIdExp); + if (newName != null) { + newIdExp.setName(newName); + } + rewrite.replace(idExp, starExp, group); + } + } else if (newName != null) { + rewrite.replace(name, newName, group); + } + } + return super.visit(name); + } + }); + } + + /** + * Returns a map from references to parameters inside the body of the extracted function to + * the parameters themselves. The map includes only the parameters that are either renamed, + * or passed by pointer. + * + * @param parameters the function parameters. + * @return a map from references to parameters to parameters themselves. + */ + protected static Map getChangedParameterReferences(List parameters) { + final Map referenceLookupMap = new HashMap(); + for (NameInformation param : parameters) { + if (param.isRenamed() || param.getIndirection() == Indirection.POINTER) { + for (IASTName name : param.getReferencesInSelection()) { + referenceLookupMap.put(name, param); + } + } + } + return referenceLookupMap; + } } From 3bb26e3de2c41aeda135d699ea1847ad5220b0e6 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Tue, 7 Feb 2012 14:46:17 -0800 Subject: [PATCH 05/43] Cosmetics. --- .../dom/parser/VariableReadWriteFlags.java | 26 +++++++------------ .../dom/parser/c/CVariableReadWriteFlags.java | 2 +- .../semantics/CPPVariableReadWriteFlags.java | 6 ++--- 3 files changed, 14 insertions(+), 20 deletions(-) diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java index e968dfe3643..d13480b8fa7 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Markus Schorn - initial API and implementation + * Markus Schorn - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.internal.core.dom.parser; @@ -159,7 +159,8 @@ public abstract class VariableReadWriteFlags { return READ | WRITE; // fall back } - protected int rwArgumentForFunctionCall(final IASTFunctionCallExpression funcCall, IASTNode argument, int indirection) { + protected int rwArgumentForFunctionCall(final IASTFunctionCallExpression funcCall, + IASTNode argument, int indirection) { final IASTInitializerClause[] args = funcCall.getArguments(); for (int i = 0; i < args.length; i++) { if (args[i] == argument) { @@ -192,13 +193,11 @@ public abstract class VariableReadWriteFlags { if (node.getPropertyInParent() == IASTCaseStatement.EXPRESSION) { return READ; } - } - else if (stmt instanceof IASTDoStatement) { + } else if (stmt instanceof IASTDoStatement) { if (node.getPropertyInParent() == IASTDoStatement.CONDITION) { return READ; } - } - else if (stmt instanceof IASTExpressionStatement) { + } else if (stmt instanceof IASTExpressionStatement) { IASTNode parent= stmt.getParent(); while (parent instanceof IASTCompoundStatement) { IASTCompoundStatement compound= (IASTCompoundStatement) parent; @@ -220,24 +219,19 @@ public abstract class VariableReadWriteFlags { if (node.getPropertyInParent() == ICPPASTRangeBasedForStatement.INITIALIZER) { return READ; } - } - else if (stmt instanceof IASTIfStatement) { + } else if (stmt instanceof IASTIfStatement) { if (node.getPropertyInParent() == IASTIfStatement.CONDITION) { return READ; } - } - else if (stmt instanceof IASTProblemStatement) { + } else if (stmt instanceof IASTProblemStatement) { return READ | WRITE; - } - else if (stmt instanceof IASTReturnStatement) { + } else if (stmt instanceof IASTReturnStatement) { return indirection == 0 ? READ : WRITE; - } - else if (stmt instanceof IASTSwitchStatement) { + } else if (stmt instanceof IASTSwitchStatement) { if (node.getPropertyInParent() == IASTSwitchStatement.CONTROLLER_EXP) { return READ; } - } - else if (stmt instanceof IASTWhileStatement) { + } else if (stmt instanceof IASTWhileStatement) { if (node.getPropertyInParent() == IASTWhileStatement.CONDITIONEXPRESSION) { return READ; } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CVariableReadWriteFlags.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CVariableReadWriteFlags.java index 36d4e63ccbd..e2ca07786e5 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CVariableReadWriteFlags.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CVariableReadWriteFlags.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Markus Schorn - initial API and implementation + * Markus Schorn - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.internal.core.dom.parser.c; diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVariableReadWriteFlags.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVariableReadWriteFlags.java index d8d9464f7dc..482b1551f40 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVariableReadWriteFlags.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVariableReadWriteFlags.java @@ -6,8 +6,8 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Markus Schorn - initial API and implementation - * Patrick Hofer - [Bug 328528] + * Markus Schorn - initial API and implementation + * Patrick Hofer - [Bug 328528] *******************************************************************************/ package org.eclipse.cdt.internal.core.dom.parser.cpp.semantics; @@ -99,7 +99,7 @@ public final class CPPVariableReadWriteFlags extends VariableReadWriteFlags { } type= ((ICPPReferenceType) type).getType(); } - while(indirection > 0 && (type instanceof ITypeContainer)) { + while (indirection > 0 && (type instanceof ITypeContainer)) { if (type instanceof IPointerType) { indirection--; } From 8a58ba3dda7539670107ccee64ff54badde272bc Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Tue, 7 Feb 2012 17:48:07 -0800 Subject: [PATCH 06/43] Cosmetics. --- .../core/parser/tests/ast2/AST2CPPTests.java | 2573 ++++++++--------- .../dom/parser/VariableReadWriteFlags.java | 4 + 2 files changed, 1247 insertions(+), 1330 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 3a3d954fae9..61ebef86f9a 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 @@ -135,138 +135,18 @@ import org.eclipse.cdt.internal.core.index.IndexCPPSignatureUtil; import org.eclipse.cdt.internal.core.parser.ParserException; public class AST2CPPTests extends AST2BaseTest { - + public AST2CPPTests() { } - + public AST2CPPTests(String name) { super(name); } - + public static TestSuite suite() { return suite(AST2CPPTests.class); } - - // #define CURLOPTTYPE_OBJECTPOINT 10000 - // #define CINIT(name,type,number) CURLOPT_ ## name = CURLOPTTYPE_ ## type + number - // typedef enum { - // CINIT(FILE, OBJECTPOINT, 1), - // CINIT(URL, OBJECTPOINT, 2) - // } CURLoption ; - public void testBug102825() throws Exception { - parseAndCheckBindings(getAboveComment()); - } - - // class B { - // public: - // B(int t); - // }; - // class A : public B { - // public: - // A(int t); - // }; - // A::A(int t) : B(t - 1){} - public void testBug78883() throws Exception { - parseAndCheckBindings(getAboveComment()); - } - - // enum type {A}; - // enum type a, b; - // type c; - // enum type2 {A, B}; - // enum type2 d, e; - public void testBug77967() throws Exception { - parseAndCheckBindings(getAboveComment()); - } - - public void testBug75189() throws Exception { - 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$ - IASTSimpleDeclaration sd = (IASTSimpleDeclaration) tu.getDeclarations()[0]; - 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; } } - // class B - // { - // REF_WRAP(B); - // B(); - // void foo(); - // }; - public void testBug79540() throws Exception { - parseAndCheckBindings(getAboveComment()); - } - - // template - // class WithTemplate {}; - // int main () - // { - // WithTemplate normalInstance; - // const int localConst=10; - // WithTemplate brokenInstance; - // return 0; - // } - public void testBug103578() throws Exception { - parseAndCheckBindings(getAboveComment()); - } - - // int *p1; int *p2; - // union { - // struct {int a; int b;} A; - // struct {int a; int b;}; - // } MyStruct; - // void test (void) { - // p1 = &MyStruct.A.a; - // p2 = &MyStruct.b; - // MyStruct.b = 1; - // } - public void testBug78103() throws Exception { - parseAndCheckBindings(getAboveComment()); - } - - // signed int si(0); - // unsigned u(10U); - // signed s(-1); - // short sh(0); - // long l(0L); - // long long ll(0LL); - public void testInitializeUnsigned_Bug245070() throws Exception { - parseAndCheckBindings(getAboveComment(), ParserLanguage.CPP, true); - } - - public void testBug43579() throws Exception { - parseAndCheckBindings("class A { int m; }; \n A * a; int A::*pm; \n int f(){} \n int f(int); \n int x = f(a->*pm);"); //$NON-NLS-1$ - parseAndCheckBindings("class A { int m; }; \n A * a; int A::*pm; \n int f(){} \n int f(int); \n int x = f(a->*pm);"); //$NON-NLS-1$ - } - - // class A { int m(int); }; - // A a; - // int (A::*pm)(int) = &A::m; - // int f(){} - // int f(int); - // int x = f((a.*pm)(5)); - public void testBug43242() throws Exception { - 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$ - } - - // int *zzz1 (char); - // int (*zzz2) (char); - // int ((*zzz3)) (char); - // int (*(zzz4)) (char); - public void testBug40768() throws Exception { - IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); - CPPNameCollector col = new CPPNameCollector(); - tu.accept(col); - assertNoProblemBindings(col); - } - + protected IASTTranslationUnit parseAndCheckBindings(String code) throws Exception { IASTTranslationUnit tu = parse(code, ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); @@ -285,20 +165,231 @@ public class AST2CPPTests extends AST2BaseTest { return new BindingAssertionHelper(code, true); } + protected void assertNoProblemBindings(CPPNameCollector col) { + Iterator i = col.nameList.iterator(); + while (i.hasNext()) { + IASTName n = (IASTName) i.next(); + assertFalse(n.resolveBinding() instanceof IProblemBinding); + } + } + + private void assertProblemBinding(int id, IBinding b) { + assertTrue(b instanceof IProblemBinding); + assertEquals(id, ((IProblemBinding) b).getID()); + } + + protected void assertProblemBindings(CPPNameCollector col, int count) { + Iterator i = col.nameList.iterator(); + int sum = 0; + while (i.hasNext()) { + IASTName n = (IASTName) i.next(); + assertNotNull(n.resolveBinding()); + if (n.getBinding() instanceof IProblemBinding) + ++sum; + } + assertEquals(count, sum); + } + + private void assertDefinition(ICPPBinding b) { + assertTrue(((IASTName)((ICPPInternalBinding) b).getDefinition()).isDefinition()); + } + + private void assertDeclaration(ICPPBinding b) { + assertTrue(((IASTName)((ICPPInternalBinding) b).getDeclarations()[0]).isDeclaration()); + } + + private ICPPMethod extractSingleMethod(IBinding[] bindings) { + assertEquals(1, bindings.length); + assertTrue(bindings[0] instanceof ICPPMethod); + return (ICPPMethod) bindings[0]; + } + + private ICPPClassType extractSingleClass(IBinding[] bindings) { + assertEquals(1, bindings.length); + assertTrue(bindings[0] instanceof ICPPClassType); + return (ICPPClassType) bindings[0]; + } + + private void checkNewExpression(IASTFunctionDefinition fdef, int i_expr, Class placement, String type, Class init) { + IASTExpression expr; + ICPPASTNewExpression newExpr; + expr= getExpressionOfStatement(fdef, i_expr); + assertInstance(expr, ICPPASTNewExpression.class); + newExpr= (ICPPASTNewExpression) expr; + if (placement == null) { + assertNull(newExpr.getNewPlacement()); + } else { + assertInstance(newExpr.getNewPlacement(), placement); + } + if (init == null) { + assertNull(newExpr.getNewInitializer()); + } else { + assertInstance(newExpr.getNewInitializer(), init); + } + isTypeEqual(CPPVisitor.createType(newExpr.getTypeId()), type); + } + + private void checkDeclDef(String[] declNames, String[] defNames, IASTDeclaration[] decls) { + int i= 0, j= 0; + for (IASTDeclaration decl : decls) { + if (decl instanceof ICPPASTLinkageSpecification) { + decl= ((ICPPASTLinkageSpecification) decl).getDeclarations()[0]; + } + final IASTDeclarator[] dtors = ((IASTSimpleDeclaration) decl).getDeclarators(); + for (IASTDeclarator dtor : dtors) { + final String name = dtor.getName().toString(); + switch (dtor.getRoleForName(dtor.getName())) { + case IASTNameOwner.r_declaration: + assertTrue("Unexpected decl " + name, i < declNames.length); + assertEquals(declNames[i++], name); + break; + case IASTNameOwner.r_definition: + assertTrue("Unexpected decl " + name, j < defNames.length); + assertEquals(defNames[j++], name); + break; + default: + assertTrue(name, false); + } + } + } + assertEquals(declNames.length, i); + assertEquals(defNames.length, j); + } + + // #define CURLOPTTYPE_OBJECTPOINT 10000 + // #define CINIT(name,type,number) CURLOPT_ ## name = CURLOPTTYPE_ ## type + number + // typedef enum { + // CINIT(FILE, OBJECTPOINT, 1), + // CINIT(URL, OBJECTPOINT, 2) + // } CURLoption ; + public void testBug102825() throws Exception { + parseAndCheckBindings(getAboveComment()); + } + + // class B { + // public: + // B(int t); + // }; + // class A : public B { + // public: + // A(int t); + // }; + // A::A(int t) : B(t - 1){} + public void testBug78883() throws Exception { + parseAndCheckBindings(getAboveComment()); + } + + // enum type {A}; + // enum type a, b; + // type c; + // enum type2 {A, B}; + // enum type2 d, e; + public void testBug77967() throws Exception { + parseAndCheckBindings(getAboveComment()); + } + + public void testBug75189() throws Exception { + 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$ + IASTSimpleDeclaration sd = (IASTSimpleDeclaration) tu.getDeclarations()[0]; + 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; } } + // class B + // { + // REF_WRAP(B); + // B(); + // void foo(); + // }; + public void testBug79540() throws Exception { + parseAndCheckBindings(getAboveComment()); + } + + // template + // class WithTemplate {}; + // int main () + // { + // WithTemplate normalInstance; + // const int localConst=10; + // WithTemplate brokenInstance; + // return 0; + // } + public void testBug103578() throws Exception { + parseAndCheckBindings(getAboveComment()); + } + + // int *p1; int *p2; + // union { + // struct {int a; int b;} A; + // struct {int a; int b;}; + // } MyStruct; + // void test (void) { + // p1 = &MyStruct.A.a; + // p2 = &MyStruct.b; + // MyStruct.b = 1; + // } + public void testBug78103() throws Exception { + parseAndCheckBindings(getAboveComment()); + } + + // signed int si(0); + // unsigned u(10U); + // signed s(-1); + // short sh(0); + // long l(0L); + // long long ll(0LL); + public void testInitializeUnsigned_Bug245070() throws Exception { + parseAndCheckBindings(getAboveComment(), ParserLanguage.CPP, true); + } + + public void testBug43579() throws Exception { + parseAndCheckBindings("class A { int m; }; \n A * a; int A::*pm; \n int f(){} \n int f(int); \n int x = f(a->*pm);"); //$NON-NLS-1$ + parseAndCheckBindings("class A { int m; }; \n A * a; int A::*pm; \n int f(){} \n int f(int); \n int x = f(a->*pm);"); //$NON-NLS-1$ + } + + // class A { int m(int); }; + // A a; + // int (A::*pm)(int) = &A::m; + // int f(){} + // int f(int); + // int x = f((a.*pm)(5)); + public void testBug43242() throws Exception { + 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$ + } + + // int *zzz1 (char); + // int (*zzz2) (char); + // int ((*zzz3)) (char); + // int (*(zzz4)) (char); + public void testBug40768() throws Exception { + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); + CPPNameCollector col = new CPPNameCollector(); + tu.accept(col); + assertNoProblemBindings(col); + } + public void testBug40422() throws Exception { 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); } - + public void testBug86282() throws Exception { IASTTranslationUnit tu = parse("void foo() { int (* f[])() = new (int (*[10])()); }", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); tu.accept(col); assertNoProblemBindings(col); } - + // bool f() { // int first, last; // if (first < 1 || last > 99) @@ -310,7 +401,7 @@ public class AST2CPPTests extends AST2BaseTest { tu.accept(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$ @@ -319,19 +410,18 @@ public class AST2CPPTests extends AST2BaseTest { IASTExpressionStatement es = (IASTExpressionStatement) cs.getStatements()[0]; assertTrue(es.getExpression() instanceof IASTFunctionCallExpression); } - + // class A { } a; public void testSimpleClass() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); - IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu - .getDeclarations()[0]; - IASTCompositeTypeSpecifier compTypeSpec = (IASTCompositeTypeSpecifier) decl - .getDeclSpecifier(); + IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu.getDeclarations()[0]; + IASTCompositeTypeSpecifier compTypeSpec = + (IASTCompositeTypeSpecifier) decl.getDeclSpecifier(); IASTName name_A = compTypeSpec.getName(); - + IASTDeclarator dtor = decl.getDeclarators()[0]; IASTName name_a = dtor.getName(); - + ICompositeType A = (ICompositeType) name_A.resolveBinding(); IVariable a = (IVariable) name_a.resolveBinding(); ICompositeType A_2 = (ICompositeType) a.getType(); @@ -339,7 +429,7 @@ public class AST2CPPTests extends AST2BaseTest { assertNotNull(a); assertSame(A, A_2); } - + // class A { // public: // int x; @@ -359,191 +449,174 @@ public class AST2CPPTests extends AST2BaseTest { tu.accept(nameCol); assertNoProblemBindings(nameCol); } - + // class A; class A {}; public void testClassForwardDecl() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); - - IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu - .getDeclarations()[0]; + + IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu.getDeclarations()[0]; assertEquals(decl.getDeclarators().length, 0); - IASTElaboratedTypeSpecifier elabSpec = (IASTElaboratedTypeSpecifier) decl - .getDeclSpecifier(); + IASTElaboratedTypeSpecifier elabSpec = (IASTElaboratedTypeSpecifier) decl.getDeclSpecifier(); IASTName name_elab = elabSpec.getName(); - + decl = (IASTSimpleDeclaration) tu.getDeclarations()[1]; assertEquals(decl.getDeclarators().length, 0); - IASTCompositeTypeSpecifier compSpec = (IASTCompositeTypeSpecifier) decl - .getDeclSpecifier(); + IASTCompositeTypeSpecifier compSpec = (IASTCompositeTypeSpecifier) decl.getDeclSpecifier(); IASTName name_comp = compSpec.getName(); - + ICompositeType A = (ICompositeType) name_elab.resolveBinding(); ICompositeType A_2 = (ICompositeType) name_comp.resolveBinding(); - + assertNotNull(A); assertSame(A, A_2); } - + // class A {}; A a; public void testVariable() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); - - IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu - .getDeclarations()[0]; + + IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu.getDeclarations()[0]; assertEquals(decl.getDeclarators().length, 0); - IASTCompositeTypeSpecifier compType = (IASTCompositeTypeSpecifier) decl - .getDeclSpecifier(); + IASTCompositeTypeSpecifier compType = (IASTCompositeTypeSpecifier) decl.getDeclSpecifier(); IASTName name_A = compType.getName(); - + decl = (IASTSimpleDeclaration) tu.getDeclarations()[1]; IASTDeclarator dtor = decl.getDeclarators()[0]; IASTName name_a = dtor.getName(); - IASTNamedTypeSpecifier namedSpec = (IASTNamedTypeSpecifier) decl - .getDeclSpecifier(); + IASTNamedTypeSpecifier namedSpec = (IASTNamedTypeSpecifier) decl.getDeclSpecifier(); IASTName name_A2 = namedSpec.getName(); - + IVariable a = (IVariable) name_a.resolveBinding(); ICompositeType A1 = (ICompositeType) a.getType(); ICompositeType A2 = (ICompositeType) name_A2.resolveBinding(); ICompositeType A = (ICompositeType) name_A.resolveBinding(); - + assertNotNull(a); assertNotNull(A); assertSame(A, A1); assertSame(A1, A2); } - + // class A { int f; }; public void testField() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); - - IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu - .getDeclarations()[0]; + + IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu.getDeclarations()[0]; assertEquals(decl.getDeclarators().length, 0); - ICPPASTCompositeTypeSpecifier comp = (ICPPASTCompositeTypeSpecifier) decl - .getDeclSpecifier(); + ICPPASTCompositeTypeSpecifier comp = (ICPPASTCompositeTypeSpecifier) decl.getDeclSpecifier(); IASTName name_A = comp.getName(); - + decl = (IASTSimpleDeclaration) comp.getMembers()[0]; IASTDeclarator dtor = decl.getDeclarators()[0]; IASTName name_f = dtor.getName(); - + ICPPClassType A = (ICPPClassType) name_A.resolveBinding(); IField f = (IField) name_f.resolveBinding(); - + assertNotNull(A); assertNotNull(f); assertSame(f.getScope(), A.getCompositeScope()); } - + // class A { int f(); }; public void testMethodDeclaration() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); - - IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu - .getDeclarations()[0]; + + IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu.getDeclarations()[0]; assertEquals(decl.getDeclarators().length, 0); - IASTCompositeTypeSpecifier comp = (IASTCompositeTypeSpecifier) decl - .getDeclSpecifier(); + IASTCompositeTypeSpecifier comp = (IASTCompositeTypeSpecifier) decl.getDeclSpecifier(); IASTName name_A = comp.getName(); - + decl = (IASTSimpleDeclaration) comp.getMembers()[0]; IASTDeclarator dtor = decl.getDeclarators()[0]; IASTName name_f = dtor.getName(); - + ICPPClassType A = (ICPPClassType) name_A.resolveBinding(); ICPPMethod f = (ICPPMethod) name_f.resolveBinding(); - + assertNotNull(A); assertNotNull(f); assertSame(f.getScope(), A.getCompositeScope()); } - + // class A { void f(); }; // void A::f() { } public void testMethodDefinition() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); - - IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu - .getDeclarations()[0]; + + IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu.getDeclarations()[0]; assertEquals(decl.getDeclarators().length, 0); - IASTCompositeTypeSpecifier comp = (IASTCompositeTypeSpecifier) decl - .getDeclSpecifier(); + IASTCompositeTypeSpecifier comp = (IASTCompositeTypeSpecifier) decl.getDeclSpecifier(); IASTName name_A = comp.getName(); - + decl = (IASTSimpleDeclaration) comp.getMembers()[0]; IASTDeclarator dtor = decl.getDeclarators()[0]; IASTName name_f1 = dtor.getName(); - - IASTFunctionDefinition def = (IASTFunctionDefinition) tu - .getDeclarations()[1]; + + IASTFunctionDefinition def = (IASTFunctionDefinition) tu.getDeclarations()[1]; IASTFunctionDeclarator fdtor = def.getDeclarator(); ICPPASTQualifiedName name_f2 = (ICPPASTQualifiedName) fdtor.getName(); - + ICPPClassType A = (ICPPClassType) name_A.resolveBinding(); ICPPMethod f1 = (ICPPMethod) name_f1.resolveBinding(); ICPPMethod f2 = (ICPPMethod) name_f2.resolveBinding(); - + IASTName[] names = name_f2.getNames(); assertEquals(names.length, 2); IASTName qn1 = names[0]; IASTName qn2 = names[1]; - + ICPPClassType A2 = (ICPPClassType) qn1.resolveBinding(); ICPPMethod f3 = (ICPPMethod) qn2.resolveBinding(); - + assertNotNull(A); assertNotNull(f1); assertSame(f1, f2); assertSame(f2, f3); assertSame(A, A2); } - + // class A { void f(); int i; }; // void A::f() { i; } public void testMemberReference() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); - - IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu - .getDeclarations()[0]; + + IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu.getDeclarations()[0]; assertEquals(decl.getDeclarators().length, 0); - IASTCompositeTypeSpecifier comp = (IASTCompositeTypeSpecifier) decl - .getDeclSpecifier(); + IASTCompositeTypeSpecifier comp = (IASTCompositeTypeSpecifier) decl.getDeclSpecifier(); IASTName name_A = comp.getName(); - + decl = (IASTSimpleDeclaration) comp.getMembers()[0]; IASTDeclarator dtor = decl.getDeclarators()[0]; IASTName name_f1 = dtor.getName(); - + decl = (IASTSimpleDeclaration) comp.getMembers()[1]; dtor = decl.getDeclarators()[0]; IASTName name_i = dtor.getName(); - - IASTFunctionDefinition def = (IASTFunctionDefinition) tu - .getDeclarations()[1]; + + IASTFunctionDefinition def = (IASTFunctionDefinition) tu.getDeclarations()[1]; IASTFunctionDeclarator fdtor = def.getDeclarator(); ICPPASTQualifiedName name_f2 = (ICPPASTQualifiedName) fdtor.getName(); - + IASTCompoundStatement compound = (IASTCompoundStatement) def.getBody(); - IASTExpressionStatement statement = (IASTExpressionStatement) compound - .getStatements()[0]; + IASTExpressionStatement statement = (IASTExpressionStatement) compound.getStatements()[0]; IASTIdExpression idExp = (IASTIdExpression) statement.getExpression(); IASTName name_i2 = idExp.getName(); - + ICPPClassType A = (ICPPClassType) name_A.resolveBinding(); ICPPMethod f1 = (ICPPMethod) name_f1.resolveBinding(); ICPPMethod f2 = (ICPPMethod) name_f2.resolveBinding(); ICPPField i1 = (ICPPField) name_i.resolveBinding(); ICPPField i2 = (ICPPField) name_i2.resolveBinding(); - + IASTName[] names = name_f2.getNames(); assertEquals(names.length, 2); IASTName qn1 = names[0]; IASTName qn2 = names[1]; - + ICPPClassType A2 = (ICPPClassType) qn1.resolveBinding(); ICPPMethod f3 = (ICPPMethod) qn2.resolveBinding(); - + assertNotNull(A); assertNotNull(f1); assertNotNull(i1); @@ -552,53 +625,48 @@ public class AST2CPPTests extends AST2BaseTest { assertSame(A, A2); assertSame(i1, i2); } - + // class A { int i; }; // class B : public A { void f(); }; // void B::f() { i; } public void testBasicInheritance() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); - - IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu - .getDeclarations()[0]; - ICPPASTCompositeTypeSpecifier comp = (ICPPASTCompositeTypeSpecifier) decl - .getDeclSpecifier(); + + IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu.getDeclarations()[0]; + ICPPASTCompositeTypeSpecifier comp = (ICPPASTCompositeTypeSpecifier) decl.getDeclSpecifier(); IASTName name_A1 = comp.getName(); - + decl = (IASTSimpleDeclaration) comp.getMembers()[0]; IASTName name_i1 = decl.getDeclarators()[0].getName(); - + decl = (IASTSimpleDeclaration) tu.getDeclarations()[1]; comp = (ICPPASTCompositeTypeSpecifier) decl.getDeclSpecifier(); IASTName name_B1 = comp.getName(); - + ICPPASTBaseSpecifier base = comp.getBaseSpecifiers()[0]; IASTName name_A2 = base.getName(); - + decl = (IASTSimpleDeclaration) comp.getMembers()[0]; IASTName name_f1 = decl.getDeclarators()[0].getName(); - - IASTFunctionDefinition def = (IASTFunctionDefinition) tu - .getDeclarations()[2]; - ICPPASTQualifiedName name_f2 = (ICPPASTQualifiedName) def - .getDeclarator().getName(); + + IASTFunctionDefinition def = (IASTFunctionDefinition) tu.getDeclarations()[2]; + ICPPASTQualifiedName name_f2 = (ICPPASTQualifiedName) def.getDeclarator().getName(); IASTName name_B2 = name_f2.getNames()[0]; IASTName name_f3 = name_f2.getNames()[1]; - + IASTCompoundStatement compound = (IASTCompoundStatement) def.getBody(); - IASTExpressionStatement statement = (IASTExpressionStatement) compound - .getStatements()[0]; + IASTExpressionStatement statement = (IASTExpressionStatement) compound.getStatements()[0]; IASTIdExpression idExp = (IASTIdExpression) statement.getExpression(); IASTName name_i2 = idExp.getName(); - + ICPPField i2 = (ICPPField) name_i2.resolveBinding(); ICPPField i1 = (ICPPField) name_i1.resolveBinding(); - + ICPPClassType A2 = (ICPPClassType) name_A2.resolveBinding(); ICPPClassType A1 = (ICPPClassType) name_A1.resolveBinding(); ICPPClassType B2 = (ICPPClassType) name_B2.resolveBinding(); ICPPClassType B1 = (ICPPClassType) name_B1.resolveBinding(); - + ICPPMethod f3 = (ICPPMethod) name_f3.resolveBinding(); ICPPMethod f2 = (ICPPMethod) name_f2.resolveBinding(); ICPPMethod f1 = (ICPPMethod) name_f1.resolveBinding(); @@ -612,7 +680,7 @@ public class AST2CPPTests extends AST2BaseTest { assertSame(f1, f2); assertSame(f2, f3); } - + // namespace A{ // int a; // } @@ -633,17 +701,16 @@ public class AST2CPPTests extends AST2BaseTest { // } public void testNamespaces() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); - + CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - + assertEquals(collector.size(), 13); ICPPNamespace A = (ICPPNamespace) collector.getName(0).resolveBinding(); IVariable a = (IVariable) collector.getName(1).resolveBinding(); ICPPNamespace B = (ICPPNamespace) collector.getName(2).resolveBinding(); ICPPNamespace C = (ICPPNamespace) collector.getName(4).resolveBinding(); - ICPPNamespace BC = (ICPPNamespace) collector.getName(6) - .resolveBinding(); + ICPPNamespace BC = (ICPPNamespace) collector.getName(6).resolveBinding(); IFunction f = (IFunction) collector.getName(9).resolveBinding(); assertInstances(collector, A, 3); assertInstances(collector, a, 3); @@ -652,7 +719,7 @@ public class AST2CPPTests extends AST2BaseTest { assertInstances(collector, BC, 2); assertInstances(collector, f, 1); } - + // int A; // class A {}; // void f() { @@ -662,30 +729,29 @@ public class AST2CPPTests extends AST2BaseTest { public void testNameHiding() throws Exception { String content= getAboveComment(); IASTTranslationUnit tu = parse(content, ParserLanguage.CPP); - + CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - + assertEquals(collector.size(), 6); IVariable vA = (IVariable) collector.getName(0).resolveBinding(); - ICompositeType cA = (ICompositeType) collector.getName(1) - .resolveBinding(); + ICompositeType cA = (ICompositeType) collector.getName(1).resolveBinding(); IVariable a = (IVariable) collector.getName(5).resolveBinding(); - + assertSame(a.getType(), cA); assertInstances(collector, vA, 2); assertInstances(collector, cA, 2); - + tu = parse(content, ParserLanguage.CPP); collector = new CPPNameCollector(); tu.accept(collector); - + cA = (ICompositeType) collector.getName(1).resolveBinding(); IBinding A = collector.getName(3).resolveBinding(); vA = (IVariable) collector.getName(0).resolveBinding(); assertSame(vA, A); } - + // class A { void f(); }; // class B; // void A::f() { @@ -696,14 +762,12 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - + assertEquals(collector.size(), 9); - ICompositeType A = (ICompositeType) collector.getName(0) - .resolveBinding(); + ICompositeType A = (ICompositeType) collector.getName(0).resolveBinding(); ICPPMethod f = (ICPPMethod) collector.getName(1).resolveBinding(); - ICompositeType B = (ICompositeType) collector.getName(2) - .resolveBinding(); - + ICompositeType B = (ICompositeType) collector.getName(2).resolveBinding(); + IVariable b = (IVariable) collector.getName(7).resolveBinding(); IVariable B2 = (IVariable) collector.getName(8).resolveBinding(); assertSame(b.getType(), B); @@ -713,7 +777,7 @@ public class AST2CPPTests extends AST2BaseTest { assertInstances(collector, b, 1); assertInstances(collector, B2, 1); } - + // void f(int i); // void f(char c); // void main() { @@ -726,11 +790,11 @@ public class AST2CPPTests extends AST2BaseTest { tu.accept(collector); IFunction f1 = (IFunction) collector.getName(0).resolveBinding(); IFunction f2 = (IFunction) collector.getName(2).resolveBinding(); - + assertInstances(collector, f1, 2); assertInstances(collector, f2, 2); } - + // typedef struct { // int x; // } S; @@ -742,20 +806,19 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - ICPPClassType anonStruct = (ICPPClassType) collector.getName(0) - .resolveBinding(); + ICPPClassType anonStruct = (ICPPClassType) collector.getName(0).resolveBinding(); ICPPField x = (ICPPField) collector.getName(1).resolveBinding(); ITypedef S = (ITypedef) collector.getName(2).resolveBinding(); IFunction f = (IFunction) collector.getName(3).resolveBinding(); IVariable myS = (IVariable) collector.getName(5).resolveBinding(); - + assertInstances(collector, anonStruct, 1); assertInstances(collector, x, 2); assertInstances(collector, S, 2); assertInstances(collector, f, 1); assertInstances(collector, myS, 2); } - + // struct A; // void f(){ // struct A; @@ -765,13 +828,11 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - - ICPPClassType A1 = (ICPPClassType) collector.getName(0) - .resolveBinding(); - ICPPClassType A2 = (ICPPClassType) collector.getName(2) - .resolveBinding(); + + ICPPClassType A1 = (ICPPClassType) collector.getName(0).resolveBinding(); + ICPPClassType A2 = (ICPPClassType) collector.getName(2).resolveBinding(); IVariable a = (IVariable) collector.getName(4).resolveBinding(); - + assertNotNull(a); assertNotNull(A1); assertNotNull(A2); @@ -779,7 +840,7 @@ public class AST2CPPTests extends AST2BaseTest { assertInstances(collector, A1, 1); assertInstances(collector, A2, 2); } - + // struct A; // void f(){ // struct A * a; @@ -788,20 +849,18 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - - ICPPClassType A1 = (ICPPClassType) collector.getName(0) - .resolveBinding(); - ICPPClassType A2 = (ICPPClassType) collector.getName(2) - .resolveBinding(); + + ICPPClassType A1 = (ICPPClassType) collector.getName(0).resolveBinding(); + ICPPClassType A2 = (ICPPClassType) collector.getName(2).resolveBinding(); IVariable a = (IVariable) collector.getName(3).resolveBinding(); - + assertNotNull(a); assertNotNull(A1); assertNotNull(A2); assertSame(A1, A2); assertInstances(collector, A1, 2); } - + // struct A; // struct A * a; // struct A { int i; }; @@ -812,17 +871,16 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - - ICPPClassType A1 = (ICPPClassType) collector.getName(0) - .resolveBinding(); + + ICPPClassType A1 = (ICPPClassType) collector.getName(0).resolveBinding(); IVariable a = (IVariable) collector.getName(2).resolveBinding(); ICPPField i = (ICPPField) collector.getName(4).resolveBinding(); - + assertInstances(collector, A1, 3); assertInstances(collector, a, 2); assertInstances(collector, i, 2); } - + // struct x {}; // void f(int x) { // struct x i; @@ -831,12 +889,12 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - + ICPPClassType x = (ICPPClassType) collector.getName(0).resolveBinding(); - + assertInstances(collector, x, 2); } - + // void f(int a); // void f(int b){ // b; @@ -845,18 +903,18 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - + IFunction f = (IFunction) collector.getName(0).resolveBinding(); IParameter a = (IParameter) collector.getName(1).resolveBinding(); - + assertInstances(collector, f, 2); assertInstances(collector, a, 3); - + IScope scope = a.getScope(); assertNotNull(scope); assertSame(scope.getParent(), f.getScope()); } - + // void f(); // void g() { // f(); @@ -866,14 +924,14 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - + IFunction f = (IFunction) collector.getName(0).resolveBinding(); IFunction g = (IFunction) collector.getName(1).resolveBinding(); - + assertInstances(collector, f, 3); assertInstances(collector, g, 1); } - + // void f() { // for(int i = 0; i < 5; i++) { // i; @@ -883,12 +941,12 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - + IVariable i = (IVariable) collector.getName(1).resolveBinding(); - + assertInstances(collector, i, 4); } - + // struct A { int x; }; // void f(){ // ((struct A *) 1)->x; @@ -897,14 +955,14 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - + ICPPClassType A = (ICPPClassType) collector.getName(0).resolveBinding(); IField x = (IField) collector.getName(1).resolveBinding(); - + assertInstances(collector, A, 2); assertInstances(collector, x, 2); } - + // enum hue { red, blue, green }; // enum hue col, *cp; // void f() { @@ -917,26 +975,26 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - + IEnumeration hue = (IEnumeration) collector.getName(0).resolveBinding(); IEnumerator red = (IEnumerator) collector.getName(1).resolveBinding(); IEnumerator blue = (IEnumerator) collector.getName(2).resolveBinding(); IEnumerator green = (IEnumerator) collector.getName(3).resolveBinding(); IVariable col = (IVariable) collector.getName(5).resolveBinding(); IVariable cp = (IVariable) collector.getName(6).resolveBinding(); - + assertInstances(collector, hue, 2); assertInstances(collector, red, 2); assertInstances(collector, blue, 2); assertInstances(collector, green, 1); assertInstances(collector, col, 3); assertInstances(collector, cp, 3); - + assertTrue(cp.getType() instanceof IPointerType); IPointerType pt = (IPointerType) cp.getType(); assertSame(pt.getType(), hue); } - + public void testPointerToFunction() throws Exception { IASTTranslationUnit tu = parse("int (*pfi)();", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector collector = new CPPNameCollector(); @@ -944,7 +1002,7 @@ public class AST2CPPTests extends AST2BaseTest { IVariable pf = (IVariable) collector.getName(0).resolveBinding(); IPointerType pt = (IPointerType) pf.getType(); assertTrue(pt.getType() instanceof IFunctionType); - + tu = parse( "struct A; int (*pfi)(int, struct A *);", ParserLanguage.CPP); //$NON-NLS-1$ collector = new CPPNameCollector(); @@ -960,33 +1018,30 @@ public class AST2CPPTests extends AST2BaseTest { pt = (IPointerType) params[1]; assertSame(pt.getType(), A); } - + // struct A; // int * f(int i, char c); // void (*g) (A *); // void (* (*h)(A**)) (int); public void testFunctionTypes() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); - - IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu - .getDeclarations()[0]; - IASTElaboratedTypeSpecifier elabSpec = (IASTElaboratedTypeSpecifier) decl - .getDeclSpecifier(); + + IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu.getDeclarations()[0]; + IASTElaboratedTypeSpecifier elabSpec = (IASTElaboratedTypeSpecifier) decl.getDeclSpecifier(); ICompositeType A = (ICompositeType) elabSpec.getName().resolveBinding(); - + decl = (IASTSimpleDeclaration) tu.getDeclarations()[1]; - IFunction f = (IFunction) decl.getDeclarators()[0].getName() - .resolveBinding(); - + IFunction f = (IFunction) decl.getDeclarators()[0].getName().resolveBinding(); + decl = (IASTSimpleDeclaration) tu.getDeclarations()[2]; IVariable g = (IVariable) decl.getDeclarators()[0] .getNestedDeclarator().getName().resolveBinding(); - + decl = (IASTSimpleDeclaration) tu.getDeclarations()[3]; IVariable h = (IVariable) decl.getDeclarators()[0] .getNestedDeclarator().getNestedDeclarator().getName() .resolveBinding(); - + IFunctionType t_f = f.getType(); IType t_f_return = t_f.getReturnType(); assertTrue(t_f_return instanceof IPointerType); @@ -995,7 +1050,7 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals(t_f_params.length, 2); assertTrue(t_f_params[0] instanceof IBasicType); assertTrue(t_f_params[1] instanceof IBasicType); - + // g is a pointer to a function that returns void and has 1 parameter // struct A * IType t_g = g.getType(); @@ -1009,7 +1064,7 @@ public class AST2CPPTests extends AST2BaseTest { IType t_g_func_p1 = t_g_func_params[0]; assertTrue(t_g_func_p1 instanceof IPointerType); assertSame(((IPointerType) t_g_func_p1).getType(), A); - + // h is a pointer to a function that returns a pointer to a function // the returned pointer to function returns void and takes 1 parameter // int @@ -1024,33 +1079,30 @@ public class AST2CPPTests extends AST2BaseTest { IType t_h_func_p1 = t_h_func_params[0]; assertTrue(t_h_func_p1 instanceof IPointerType); assertTrue(((IPointerType) t_h_func_p1).getType() instanceof IPointerType); - assertSame(((IPointerType) ((IPointerType) t_h_func_p1).getType()) - .getType(), A); - + assertSame(((IPointerType) ((IPointerType) t_h_func_p1).getType()).getType(), A); + assertTrue(t_h_func_return instanceof IPointerType); - IFunctionType h_return = (IFunctionType) ((IPointerType) t_h_func_return) - .getType(); + IFunctionType h_return = (IFunctionType) ((IPointerType) t_h_func_return).getType(); IType h_r = h_return.getReturnType(); IType[] h_ps = h_return.getParameterTypes(); assertTrue(h_r instanceof IBasicType); assertEquals(h_ps.length, 1); assertTrue(h_ps[0] instanceof IBasicType); } - + public void testFnReturningPtrToFn() throws Exception { IASTTranslationUnit tu = parse( "void (* f(int))(){}", ParserLanguage.CPP); //$NON-NLS-1$ - - IASTFunctionDefinition def = (IASTFunctionDefinition) tu - .getDeclarations()[0]; + + IASTFunctionDefinition def = (IASTFunctionDefinition) tu.getDeclarations()[0]; IFunction f = (IFunction) def.getDeclarator().getName().resolveBinding(); - + IFunctionType ft = f.getType(); assertTrue(ft.getReturnType() instanceof IPointerType); assertTrue(((IPointerType) ft.getReturnType()).getType() instanceof IFunctionType); assertEquals(ft.getParameterTypes().length, 1); } - + // void f(); // namespace A { // void g(); @@ -1067,27 +1119,25 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - + IFunction f = (IFunction) collector.getName(0).resolveBinding(); ICPPNamespace A = (ICPPNamespace) collector.getName(1).resolveBinding(); IFunction g = (IFunction) collector.getName(2).resolveBinding(); ICPPNamespace X = (ICPPNamespace) collector.getName(3).resolveBinding(); - - ICPPUsingDeclaration using = (ICPPUsingDeclaration) collector - .getName(5).resolveBinding(); + + ICPPUsingDeclaration using = (ICPPUsingDeclaration) collector.getName(5).resolveBinding(); IBinding[] delegates = using.getDelegates(); assertEquals(delegates.length, 1); assertSame(delegates[0], f); assertInstances(collector, delegates[0], 3); // decl + using-decl + ref assertInstances(collector, A, 2); assertInstances(collector, X, 3); - - ICPPUsingDeclaration using_g = (ICPPUsingDeclaration) collector - .getName(8).resolveBinding(); + + ICPPUsingDeclaration using_g = (ICPPUsingDeclaration) collector.getName(8).resolveBinding(); assertSame(using_g.getDelegates()[0], g); assertInstances(collector, using_g.getDelegates()[0], 3); // decl + using-decl + ref } - + // typedef int Int; // void f(int i); // void f(const int); @@ -1100,19 +1150,19 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - + IFunction f = (IFunction) collector.getName(1).resolveBinding(); isTypeEqual(f.getType(), "void (int)"); IFunction g = (IFunction) collector.getName(8).resolveBinding(); isTypeEqual(g.getType(), "void (char *)"); IFunction h = (IFunction) collector.getName(12).resolveBinding(); isTypeEqual(h.getType(), "void (int (*)())"); - + assertInstances(collector, f, 3); assertInstances(collector, g, 2); assertInstances(collector, h, 2); } - + // class P1 { public: int x; }; // class P2 { public: int x; }; // class B : public P1, public P2 {}; @@ -1124,12 +1174,11 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - - IProblemBinding x = (IProblemBinding) collector.getName(12) - .resolveBinding(); + + IProblemBinding x = (IProblemBinding) collector.getName(12).resolveBinding(); assertEquals(x.getID(), IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP); } - + // class D { public: int x; }; // class C : public virtual D {}; // class B : public virtual D {}; @@ -1142,9 +1191,9 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - + assertEquals(collector.size(), 15); - + ICPPClassType D = (ICPPClassType) collector.getName(0).resolveBinding(); ICPPField x = (ICPPField) collector.getName(1).resolveBinding(); ICPPClassType C = (ICPPClassType) collector.getName(2).resolveBinding(); @@ -1158,7 +1207,7 @@ public class AST2CPPTests extends AST2BaseTest { assertInstances(collector, ctor, 1); assertInstances(collector, x, 2); } - + // class D { public: int x; }; // class C : public D {}; // class B : public D {}; @@ -1171,19 +1220,18 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - + assertEquals(collector.size(), 15); - + ICPPClassType D = (ICPPClassType) collector.getName(0).resolveBinding(); ICPPField x1 = (ICPPField) collector.getName(1).resolveBinding(); ICPPClassType C = (ICPPClassType) collector.getName(2).resolveBinding(); ICPPClassType B = (ICPPClassType) collector.getName(4).resolveBinding(); ICPPClassType A = (ICPPClassType) collector.getName(6).resolveBinding(); ICPPConstructor ctor = A.getConstructors()[0]; - IProblemBinding x2 = (IProblemBinding) collector.getName(14) - .resolveBinding(); + IProblemBinding x2 = (IProblemBinding) collector.getName(14).resolveBinding(); assertEquals(x2.getID(), IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP); - + assertInstances(collector, D, 3); assertInstances(collector, C, 2); assertInstances(collector, B, 2); @@ -1191,7 +1239,7 @@ public class AST2CPPTests extends AST2BaseTest { assertInstances(collector, ctor, 1); assertInstances(collector, x1, 1); } - + // namespace A { // int x; // } @@ -1203,40 +1251,38 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector collector = new CPPNameCollector(); tu.accept(collector); - + assertEquals(collector.size(), 6); - + ICPPNamespace A = (ICPPNamespace) collector.getName(0).resolveBinding(); IVariable x1 = (IVariable) collector.getName(1).resolveBinding(); IVariable x2 = (IVariable) collector.getName(2).resolveBinding(); - + assertInstances(collector, A, 2); assertInstances(collector, x1, 2); assertInstances(collector, x2, 1); } - + // class A { }; public void testImplicitConstructors() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); - - IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu - .getDeclarations()[0]; - IASTCompositeTypeSpecifier compSpec = (IASTCompositeTypeSpecifier) decl - .getDeclSpecifier(); + + IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu.getDeclarations()[0]; + IASTCompositeTypeSpecifier compSpec = (IASTCompositeTypeSpecifier) decl.getDeclSpecifier(); ICPPClassType A = (ICPPClassType) compSpec.getName().resolveBinding(); ICPPConstructor[] ctors = A.getConstructors(); - + assertNotNull(ctors); assertEquals(ctors.length, 2); - + assertEquals(ctors[0].getParameters().length, 1); - + IType t = ctors[0].getParameters()[0].getType(); assertTrue(t instanceof IBasicType); assertEquals(((IBasicType) t).getType(), IBasicType.t_void); - + assertEquals(ctors[1].getParameters().length, 1); - + t = ctors[1].getParameters()[0].getType(); assertTrue(t instanceof ICPPReferenceType); assertTrue(((ICPPReferenceType) t).getType() instanceof IQualifierType); @@ -1244,24 +1290,22 @@ public class AST2CPPTests extends AST2BaseTest { assertTrue(qt.isConst()); assertSame(qt.getType(), A); } - + // class A { A(void); A(const A &); }; public void testConstructors() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); - - IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu - .getDeclarations()[0]; - IASTCompositeTypeSpecifier compSpec = (IASTCompositeTypeSpecifier) decl - .getDeclSpecifier(); + + IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu.getDeclarations()[0]; + IASTCompositeTypeSpecifier compSpec = (IASTCompositeTypeSpecifier) decl.getDeclSpecifier(); ICPPClassType A = (ICPPClassType) compSpec.getName().resolveBinding(); ICPPConstructor[] ctors = A.getConstructors(); - + assertNotNull(ctors); assertEquals(ctors.length, 2); - + assertEquals(ctors[0].getParameters().length, 1); assertEquals(ctors[1].getParameters().length, 1); - + IType t = ctors[1].getParameters()[0].getType(); assertTrue(t instanceof ICPPReferenceType); assertTrue(((ICPPReferenceType) t).getType() instanceof IQualifierType); @@ -1269,27 +1313,27 @@ public class AST2CPPTests extends AST2BaseTest { assertTrue(qt.isConst()); assertSame(qt.getType(), A); } - + // class A {~A(); }; // class B {~B(void); }; public void testExplicitDestructor_183160() throws Exception { // class F {(~)F(); }; // class G {(~)G(void); }; - + BufferedReader br= new BufferedReader(new StringReader(getAboveComment())); for(String line= br.readLine(); line!=null; line= br.readLine()) { IASTTranslationUnit tu = parse(line, ParserLanguage.CPP); IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu.getDeclarations()[0]; IASTCompositeTypeSpecifier compSpec = (IASTCompositeTypeSpecifier) decl.getDeclSpecifier(); ICPPClassType A = (ICPPClassType) compSpec.getName().resolveBinding(); - + ICPPMethod[] methods = ((ICPPClassScope)A.getCompositeScope()).getImplicitMethods(); assertNotNull(methods); int count=0; for (ICPPMethod method : methods) count+= method.getName().startsWith("~") ? 1 : 0; assertEquals(line, 0, count); - + methods = A.getDeclaredMethods(); assertNotNull(methods); count=0; @@ -1298,7 +1342,7 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals(line, 1, count); } } - + // class C {}; // class D {D();}; // class E {E(void);}; @@ -1309,14 +1353,14 @@ public class AST2CPPTests extends AST2BaseTest { IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu.getDeclarations()[0]; IASTCompositeTypeSpecifier compSpec = (IASTCompositeTypeSpecifier) decl.getDeclSpecifier(); ICPPClassType A = (ICPPClassType) compSpec.getName().resolveBinding(); - + ICPPMethod[] methods = ((ICPPClassScope)A.getCompositeScope()).getImplicitMethods(); assertNotNull(methods); int count=0; for (ICPPMethod method : methods) count+= method.getName().startsWith("~") ? 1 : 0; assertEquals(line, 1, count); - + methods = A.getDeclaredMethods(); assertNotNull(methods); count=0; @@ -1325,7 +1369,7 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals(line, 0, count); } } - + // class A {public: A();}; // class B {public: B() {}}; // class C {public: C() {}}; @@ -1354,12 +1398,12 @@ public class AST2CPPTests extends AST2BaseTest { IASTCompositeTypeSpecifier compSpec = (IASTCompositeTypeSpecifier) decl.getDeclSpecifier(); ICPPClassType A = (ICPPClassType) compSpec.getName().resolveBinding(); ICPPConstructor[] ctors = A.getConstructors(); - + assertNotNull(ctors); assertEquals(2, ctors.length); // one user-declared default constructor, one implicit copy constructor } } - + // class Q {public: Q(int k);}; // class R {public: R(int k=5, long k);}; // class S {public: S(int k=5, int* ip);}; @@ -1372,12 +1416,12 @@ public class AST2CPPTests extends AST2BaseTest { IASTCompositeTypeSpecifier compSpec = (IASTCompositeTypeSpecifier) decl.getDeclSpecifier(); ICPPClassType A = (ICPPClassType) compSpec.getName().resolveBinding(); ICPPConstructor[] ctors = A.getConstructors(); - + assertNotNull(ctors); assertEquals(2, ctors.length); // one user-declared non-default constructor, one implicit copy constructor } } - + // class A {public: A(A &);}; // class B {private: B(const B &);}; // class C {protected: C(volatile C &);}; @@ -1394,13 +1438,13 @@ public class AST2CPPTests extends AST2BaseTest { IASTCompositeTypeSpecifier compSpec = (IASTCompositeTypeSpecifier) decl.getDeclSpecifier(); ICPPClassType A = (ICPPClassType) compSpec.getName().resolveBinding(); ICPPConstructor[] ctors = A.getConstructors(); - + assertNotNull(ctors); // one copy constructor, no implicit default constructor assertEquals(1, ctors.length); } } - + // class I {public: I(I *, int k=5);}; // I * rather than I & // class J {private: J(const J *, int j, int k=3);}; // J * rather than J & // class K {protected: K(volatile K *, int i=4, int l=2);}; // K * rather than K & @@ -1413,13 +1457,13 @@ public class AST2CPPTests extends AST2BaseTest { IASTCompositeTypeSpecifier compSpec = (IASTCompositeTypeSpecifier) decl.getDeclSpecifier(); ICPPClassType A = (ICPPClassType) compSpec.getName().resolveBinding(); ICPPConstructor[] ctors = A.getConstructors(); - + assertNotNull(ctors); // one copy constructor, one user declared constructor (not a copy constructor) assertEquals(2, ctors.length); } } - + // class A {public: void operator=(int); }; // legitimate, but not a copy assignment operator // class B {public: void operator=(B &, int); }; // compile error // class C {public: void operator=(C &c, int k=5) {} }; // compile error @@ -1438,9 +1482,9 @@ public class AST2CPPTests extends AST2BaseTest { boolean eq= Arrays.equals(method.getName().toCharArray(), OverloadableOperator.ASSIGN.toCharArray()); count+= eq ? 1 : 0; } - + assertEquals(1, count); // check for one implicit operator= method - + methods = A.getDeclaredMethods(); assertNotNull(methods); count=0; @@ -1448,11 +1492,11 @@ public class AST2CPPTests extends AST2BaseTest { boolean eq= Arrays.equals(method.getName().toCharArray(), OverloadableOperator.ASSIGN.toCharArray()); count+= eq ? 1 : 0; } - + assertEquals(1, count); // check for the user declared } } - + // class A {public: void operator=(A &); }; // class B {protected: void operator=(const B &); }; // class C {private: void operator=(volatile C &) {} }; @@ -1471,9 +1515,9 @@ public class AST2CPPTests extends AST2BaseTest { boolean eq= Arrays.equals(method.getName().toCharArray(), OverloadableOperator.ASSIGN.toCharArray()); count+= eq ? 1 : 0; } - + assertEquals(0, count); // check for no implicit operator= methods - + methods = A.getDeclaredMethods(); assertNotNull(methods); count=0; @@ -1481,11 +1525,11 @@ public class AST2CPPTests extends AST2BaseTest { boolean eq= Arrays.equals(method.getName().toCharArray(), OverloadableOperator.ASSIGN.toCharArray()); count+= eq ? 1 : 0; } - + assertEquals(1, count); // only should get the user declared } } - + // namespace A { int x; } // namespace B = A; // int f(){ B::x; } @@ -1493,19 +1537,19 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertEquals(col.size(), 8); ICPPNamespace A = (ICPPNamespace) col.getName(0).resolveBinding(); IVariable x = (IVariable) col.getName(1).resolveBinding(); ICPPNamespace B = (ICPPNamespace) col.getName(2).resolveBinding(); assertTrue(B instanceof ICPPNamespaceAlias); assertSame(((ICPPNamespaceAlias) B).getBinding(), A); - + assertInstances(col, A, 2); assertInstances(col, B, 2); assertInstances(col, x, 3); } - + // public void testBug84250() throws Exception { // assertTrue(((IASTDeclarationStatement) ((IASTCompoundStatement) // ((IASTFunctionDefinition) parse( @@ -1513,7 +1557,7 @@ public class AST2CPPTests extends AST2BaseTest { // ParserLanguage.CPP).getDeclarations()[0]).getBody()).getStatements()[0]).getDeclaration() // instanceof IASTSimpleDeclaration); //$NON-NLS-1$ // } - + // void f() { // int (*p) [2]; // (&p)[0] = 1; @@ -1522,17 +1566,17 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertEquals(col.size(), 3); IVariable p = (IVariable) col.getName(1).resolveBinding(); assertTrue(p.getType() instanceof IPointerType); assertTrue(((IPointerType) p.getType()).getType() instanceof IArrayType); IArrayType at = (IArrayType) ((IPointerType) p.getType()).getType(); assertTrue(at.getType() instanceof IBasicType); - + assertInstances(col, p, 2); } - + // void f() { // int (*p) [2]; // (&p)[0] = 1; @@ -1541,51 +1585,50 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertEquals(col.size(), 3); - + IVariable p_ref = (IVariable) col.getName(2).resolveBinding(); IVariable p_decl = (IVariable) col.getName(1).resolveBinding(); - + assertSame(p_ref, p_decl); } - + // struct s { double i; } f(void); // struct s f(void){} public void testBug84266() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertEquals(col.size(), 7); - + ICompositeType s_ref = (ICompositeType) col.getName(4).resolveBinding(); - ICompositeType s_decl = (ICompositeType) col.getName(0) - .resolveBinding(); - + ICompositeType s_decl = (ICompositeType) col.getName(0).resolveBinding(); + assertSame(s_ref, s_decl); } - + public void testBug84266_2() throws Exception { IASTTranslationUnit tu = parse("struct s f(void);", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertEquals(col.size(), 3); - + ICompositeType s = (ICompositeType) col.getName(0).resolveBinding(); assertNotNull(s); - + tu = parse("struct s f(void){}", ParserLanguage.CPP); //$NON-NLS-1$ col = new CPPNameCollector(); tu.accept(col); - + assertEquals(col.size(), 3); - + s = (ICompositeType) col.getName(0).resolveBinding(); assertNotNull(s); } - + // void f(int m, int c[m][m]); // void f(int m, int c[m][m]){ // int x; @@ -1595,22 +1638,22 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertEquals(col.size(), 13); - + IParameter m = (IParameter) col.getName(3).resolveBinding(); IVariable x3 = (IVariable) col.getName(12).resolveBinding(); IVariable x2 = (IVariable) col.getName(11).resolveBinding(); IVariable x1 = (IVariable) col.getName(10).resolveBinding(); - + assertSame(x2, x3); assertNotSame(x1, x2); - + assertInstances(col, m, 6); assertInstances(col, x1, 1); assertInstances(col, x2, 2); } - + // class A { public : static int n; }; // int main() { // int A; @@ -1621,21 +1664,20 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertEquals(col.size(), 9); - + ICPPClassType A = (ICPPClassType) col.getName(0).resolveBinding(); ICPPField n = (ICPPField) col.getName(1).resolveBinding(); IBinding Aref = col.getName(5).resolveBinding(); IBinding nref = col.getName(6).resolveBinding(); - IProblemBinding prob = (IProblemBinding) col.getName(7) - .resolveBinding(); - + IProblemBinding prob = (IProblemBinding) col.getName(7).resolveBinding(); + assertSame(A, Aref); assertSame(n, nref); assertNotNull(prob); } - + public void testBug84371() throws Exception { String code = "int x = ::ABC::DEF::ghi;"; //$NON-NLS-1$ IASTTranslationUnit tu = parse(code, ParserLanguage.CPP); @@ -1649,7 +1691,7 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals(name.getNames()[1].toString(), "DEF"); //$NON-NLS-1$ assertEquals(name.getNames()[2].toString(), "ghi"); //$NON-NLS-1$ } - + // namespace Y { void f(float); } // namespace A { using namespace Y; void f(int); } // namespace B { void f(char); } @@ -1663,12 +1705,12 @@ public class AST2CPPTests extends AST2BaseTest { false, false); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPNamespace Y = (ICPPNamespace) col.getName(0).resolveBinding(); ICPPNamespace A = (ICPPNamespace) col.getName(3).resolveBinding(); ICPPNamespace B = (ICPPNamespace) col.getName(7).resolveBinding(); ICPPNamespace AB = (ICPPNamespace) col.getName(10).resolveBinding(); - + IFunction f = (IFunction) col.getName(16).resolveBinding(); IFunction fdef = (IFunction) col.getName(5).resolveBinding(); assertTrue(col.getName(19).resolveBinding() instanceof IProblemBinding); @@ -1679,7 +1721,7 @@ public class AST2CPPTests extends AST2BaseTest { assertInstances(col, B, 2); assertInstances(col, AB, 3); } - + // struct Node { // struct Node* Next; // struct Data* Data; @@ -1691,7 +1733,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testBug84692() throws Exception { // also tests bug 234042. CPPASTNameBase.sAllowRecursionBindings= false; - + IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); @@ -1705,7 +1747,7 @@ public class AST2CPPTests extends AST2BaseTest { assertInstances(col, Node, 3); assertInstances(col, Data, 2); } - + // namespace B { int b; } // namespace A { using namespace B; int a; } // namespace B { using namespace A; } @@ -1714,14 +1756,14 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertEquals(col.size(), 11); - + ICPPVariable a1 = (ICPPVariable) col.getName(4).resolveBinding(); IVariable a2 = (IVariable) col.getName(10).resolveBinding(); assertSame(a1, a2); } - + // struct C { // void f(); // const C& operator=(const C&); @@ -1738,14 +1780,14 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertEquals(col.size(), 17); - + ICPPMethod f = (ICPPMethod) col.getName(1).resolveBinding(); IASTName[] refs = tu.getReferences(f); assertEquals(1, refs.length); assertSame(f, refs[0].resolveBinding()); - + ICPPClassType C = (ICPPClassType) col.getName(0).resolveBinding(); ICPPMethod op = (ICPPMethod) col.getName(3).resolveBinding(); IParameter other = (IParameter) col.getName(11).resolveBinding(); @@ -1753,43 +1795,41 @@ public class AST2CPPTests extends AST2BaseTest { assertNotNull(dtor); assertEquals(dtor.getName(), "~C"); //$NON-NLS-1$ assertInstances(col, C, 6); - + assertInstances(col, op, 3); assertInstances(col, other, 4); } - + // class A { void f(); void g() const; }; // void A::f(){ this; } // void A::g() const { *this; } public void testThis() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); - - IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu - .getDeclarations()[0]; - ICPPClassType A = (ICPPClassType) ((IASTCompositeTypeSpecifier) decl - .getDeclSpecifier()).getName().resolveBinding(); - - IASTFunctionDefinition def = (IASTFunctionDefinition) tu - .getDeclarations()[1]; - IASTExpressionStatement expStatement = (IASTExpressionStatement) ((IASTCompoundStatement) def - .getBody()).getStatements()[0]; + + IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu.getDeclarations()[0]; + ICPPClassType A = + (ICPPClassType) ((IASTCompositeTypeSpecifier) decl.getDeclSpecifier()).getName().resolveBinding(); + + IASTFunctionDefinition def = (IASTFunctionDefinition) tu.getDeclarations()[1]; + IASTExpressionStatement expStatement = + (IASTExpressionStatement) ((IASTCompoundStatement) def.getBody()).getStatements()[0]; assertTrue(expStatement.getExpression() instanceof IASTLiteralExpression); IType type = expStatement.getExpression().getExpressionType(); - + assertTrue(type instanceof IPointerType); assertSame(((IPointerType) type).getType(), A); - + def = (IASTFunctionDefinition) tu.getDeclarations()[2]; - expStatement = (IASTExpressionStatement) ((IASTCompoundStatement) def - .getBody()).getStatements()[0]; + expStatement = + (IASTExpressionStatement) ((IASTCompoundStatement) def.getBody()).getStatements()[0]; IASTUnaryExpression ue = (IASTUnaryExpression) expStatement.getExpression(); type = ue.getExpressionType(); - + assertTrue(type instanceof IQualifierType); assertSame(((IQualifierType) type).getType(), A); assertTrue(((IQualifierType) type).isConst()); } - + public void testBug84710() throws Exception { IASTTranslationUnit tu = parse("class T { T(); };", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); @@ -1799,7 +1839,7 @@ public class AST2CPPTests extends AST2BaseTest { "T".toCharArray())); //$NON-NLS-1$ assertEquals(T.getName(), "T"); //$NON-NLS-1$ } - + // namespace NS { // class T {}; // void f(T); @@ -1812,18 +1852,18 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPNamespace NS = (ICPPNamespace) col.getName(0).resolveBinding(); ICPPClassType T = (ICPPClassType) col.getName(1).resolveBinding(); IFunction f = (IFunction) col.getName(2).resolveBinding(); IVariable parm = (IVariable) col.getName(8).resolveBinding(); - + assertInstances(col, NS, 2); assertInstances(col, T, 4); assertInstances(col, f, 2); assertInstances(col, parm, 2); } - + // namespace NS1{ // void f(void *); // } @@ -1840,16 +1880,16 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction fref = (IFunction) col.getName(14).resolveBinding(); IFunction f1 = (IFunction) col.getName(1).resolveBinding(); IFunction f2 = (IFunction) col.getName(6).resolveBinding(); - + assertSame(f2, fref); assertNotNull(f1); assertNotNull(f2); } - + // namespace { int i; } //1 // void f(){ i; } // namespace A { @@ -1869,22 +1909,21 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertEquals(17, col.size()); - + IVariable i1 = (IVariable) col.getName(1).resolveBinding(); IVariable i2 = (IVariable) col.getName(6).resolveBinding(); IVariable j = (IVariable) col.getName(7).resolveBinding(); - + assertInstances(col, i1, 2); assertInstances(col, i2, 4); assertInstances(col, j, 2); - - IProblemBinding problem = (IProblemBinding) col.getName(12) - .resolveBinding(); + + IProblemBinding problem = (IProblemBinding) col.getName(12).resolveBinding(); assertEquals(IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, problem.getID()); } - + // struct B { // void mutate(); // }; @@ -1896,18 +1935,18 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertEquals(8, col.size()); - + ICPPMethod mutate = (ICPPMethod) col.getName(1).resolveBinding(); ICPPClassType B = (ICPPClassType) col.getName(0).resolveBinding(); IVariable pb = (IVariable) col.getName(4).resolveBinding(); - + assertInstances(col, pb, 2); assertInstances(col, mutate, 2); assertInstances(col, B, 2); } - + // struct S { int i; }; // void f() { ; // int S::* pm = &S::i; @@ -1916,21 +1955,21 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertEquals(9, col.size()); } - + public void testPointerToMemberType() throws Exception { IASTTranslationUnit tu = parse("struct S; int S::* pm;", //$NON-NLS-1$ ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertEquals(4, col.size()); - + IVariable pm = (IVariable) col.getName(3).resolveBinding(); ICPPClassType S = (ICPPClassType) col.getName(0).resolveBinding(); - + IType t = pm.getType(); assertNotNull(t); assertTrue(t instanceof ICPPPointerToMemberType); @@ -1938,7 +1977,7 @@ public class AST2CPPTests extends AST2BaseTest { assertSame(S, cls); assertTrue(((ICPPPointerToMemberType) t).getType() instanceof IBasicType); } - + // struct S { int i ; } *s; // int S::* pm = &S::i; // void f() { @@ -1948,13 +1987,13 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IBinding ref = col.getName(11).resolveBinding(); IVariable pm = (IVariable) col.getName(5).resolveBinding(); - + assertSame(pm, ref); } - + // struct S { // int i; // S* f(); @@ -1967,27 +2006,27 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType S = (ICPPClassType) col.getName(0).resolveBinding(); IVariable pm = (IVariable) col.getName(8).resolveBinding(); IField i = (IField) col.getName(1).resolveBinding(); ICPPMethod f = (ICPPMethod) col.getName(3).resolveBinding(); - + IType t = pm.getType(); assertTrue(t instanceof ICPPPointerToMemberType); IFunctionType ft = (IFunctionType) ((ICPPPointerToMemberType) t).getType(); IType ST = ((ICPPPointerToMemberType) t).getMemberOfClass(); - + assertTrue(ft.getReturnType() instanceof IPointerType); assertSame(ST, ((IPointerType) ft.getReturnType()).getType()); assertSame(S, ST); - + assertInstances(col, S, 5); assertInstances(col, pm, 2); assertInstances(col, i, 2); assertInstances(col, f, 3); } - + // public void testFindTypeBinding_1() throws Exception { // IASTTranslationUnit tu = parse( // "int x = 5; int y(x);", ParserLanguage.CPP); //$NON-NLS-1$ @@ -2028,7 +2067,7 @@ public class AST2CPPTests extends AST2BaseTest { // assertNotNull(binding); // assertTrue(binding instanceof ICPPClassType); // } - + // struct B { }; // void g() { // B * bp; //1 @@ -2039,7 +2078,7 @@ public class AST2CPPTests extends AST2BaseTest { IASTCompoundStatement body = (IASTCompoundStatement) g.getBody(); assertTrue(body.getStatements()[0] instanceof IASTDeclarationStatement); } - + // class A { public: int i; }; // class B : public A {}; // void f(int B::*); @@ -2051,20 +2090,20 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction f = (IFunction) col.getName(15).resolveBinding(); ICPPClassType A = (ICPPClassType) col.getName(0).resolveBinding(); ICPPField i = (ICPPField) col.getName(1).resolveBinding(); ICPPClassType B = (ICPPClassType) col.getName(2).resolveBinding(); IVariable pm = (IVariable) col.getName(11).resolveBinding(); - + assertInstances(col, f, 2); assertInstances(col, A, 4); assertInstances(col, i, 3); assertInstances(col, B, 2); assertInstances(col, pm, 2); } - + // namespace N { // class A { public: int i; }; // void f(int A::*); @@ -2077,16 +2116,16 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction f = (IFunction) col.getName(16).resolveBinding(); ICPPNamespace N = (ICPPNamespace) col.getName(0).resolveBinding(); ICPPClassType A = (ICPPClassType) col.getName(1).resolveBinding(); - + assertInstances(col, f, 2); assertInstances(col, N, 3); assertInstances(col, A, 4); } - + // namespace M { // class B { }; // void f(B*); @@ -2103,14 +2142,14 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction f = (IFunction) col.getName(27).resolveBinding(); ICPPNamespace M = (ICPPNamespace) col.getName(0).resolveBinding(); ICPPClassType B = (ICPPClassType) col.getName(1).resolveBinding(); ICPPNamespace N = (ICPPNamespace) col.getName(5).resolveBinding(); ICPPClassType A = (ICPPClassType) col.getName(6).resolveBinding(); IVariable pm = (IVariable) col.getName(17).resolveBinding(); - + assertInstances(col, f, 2); assertInstances(col, M, 3); assertInstances(col, B, 6); @@ -2118,7 +2157,7 @@ public class AST2CPPTests extends AST2BaseTest { assertInstances(col, A, 5); assertInstances(col, pm, 2); } - + // class A { // friend void set(); // friend class B; @@ -2129,14 +2168,14 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType A = (ICPPClassType) col.getName(0).resolveBinding(); IFunction set = (IFunction) col.getName(1).resolveBinding(); ICPPClassType B = (ICPPClassType) col.getName(2).resolveBinding(); - + assertInstances(col, set, 2); assertInstances(col, B, 2); - + IBinding[] friends = A.getFriends(); assertEquals(2, friends.length); assertSame(friends[0], set); @@ -2155,12 +2194,12 @@ public class AST2CPPTests extends AST2BaseTest { ICPPClassType A = bh.assertNonProblem("A", 1); IFunction set = bh.assertNonProblem("set()", 3); IFunction m = bh.assertNonProblem("Other::m()", 8); - + IBinding[] friends = A.getFriends(); assertEquals(2, friends.length); assertSame(friends[0], set); assertSame(friends[1], m); - + IBinding[] declaredMethods= A.getAllDeclaredMethods(); assertEquals(0, declaredMethods.length); declaredMethods= A.getDeclaredMethods(); @@ -2173,17 +2212,17 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType B = (ICPPClassType) col.getName(2).resolveBinding(); ICPPClassType A = (ICPPClassType) col.getName(0).resolveBinding(); - + assertInstances(col, B, 3); - + IBinding[] friends = A.getFriends(); assertEquals(friends.length, 1); assertSame(friends[0], B); } - + // class A { // public: class N {}; // }; @@ -2194,20 +2233,20 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType N = (ICPPClassType) col.getName(5).resolveBinding(); ICPPClassType A = (ICPPClassType) col.getName(0).resolveBinding(); ICPPClassType B = (ICPPClassType) col.getName(2).resolveBinding(); assertInstances(col, N, 3); - + IBinding[] friends = B.getFriends(); assertEquals(friends.length, 1); assertSame(friends[0], N); - + assertEquals(A.getFriends().length, 0); assertEquals(N.getFriends().length, 0); } - + // class A { // friend class B *helper(); // }; @@ -2215,19 +2254,19 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction helper = (IFunction) col.getName(2).resolveBinding(); assertSame(helper.getScope(), tu.getScope()); - + ICPPClassType B = (ICPPClassType) col.getName(1).resolveBinding(); ICPPClassType A = (ICPPClassType) col.getName(0).resolveBinding(); assertSame(B.getScope(), A.getScope()); - + IBinding[] friends = A.getFriends(); assertEquals(friends.length, 1); assertSame(friends[0], helper); } - + // void f(int); // void f(char); // void (*pf) (int) = &f; @@ -2238,16 +2277,16 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction f1 = (IFunction) col.getName(0).resolveBinding(); IFunction f2 = (IFunction) col.getName(2).resolveBinding(); IVariable pf = (IVariable) col.getName(4).resolveBinding(); - + assertInstances(col, pf, 2); assertInstances(col, f1, 3); assertInstances(col, f2, 1); } - + // void f(char); // void f(int); // void g(void (*)(int)) {} @@ -2260,18 +2299,18 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction f1 = (IFunction) col.getName(0).resolveBinding(); IFunction f2 = (IFunction) col.getName(2).resolveBinding(); IFunction g = (IFunction) col.getName(4).resolveBinding(); IVariable pg = (IVariable) col.getName(7).resolveBinding(); - + assertInstances(col, f1, 1); assertInstances(col, f2, 3); assertInstances(col, g, 2); assertInstances(col, pg, 2); } - + // void f(int); // void f(char); // void (* bar ()) (int) { @@ -2281,16 +2320,16 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction f1 = (IFunction) col.getName(0).resolveBinding(); IFunction f2 = (IFunction) col.getName(2).resolveBinding(); IFunction bar = (IFunction) col.getName(4).resolveBinding(); assertNotNull(bar); - + assertInstances(col, f1, 2); assertInstances(col, f2, 1); } - + // void f(int); // void f(char); // void foo () { @@ -2300,16 +2339,16 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction f1 = (IFunction) col.getName(0).resolveBinding(); IFunction f2 = (IFunction) col.getName(2).resolveBinding(); IFunction bar = (IFunction) col.getName(4).resolveBinding(); assertNotNull(bar); - + assertInstances(col, f1, 2); assertInstances(col, f2, 1); } - + // extern int g; // int g; // void f() { g = 1; } @@ -2317,11 +2356,11 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IVariable g = (IVariable) col.getName(3).resolveBinding(); assertInstances(col, g, 3); } - + // struct A { // int a2; // }; @@ -2338,11 +2377,11 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IASTName name = col.getName(11); assertEquals("a", name.toString()); IBinding[] bs = CPPSemantics.findBindingsForContentAssist(name, true, null); - + // check the result HashSet result= new HashSet(); for (IBinding binding : bs) { @@ -2369,11 +2408,11 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IASTName name = col.getName(5); assertEquals("v_", name.toString()); IBinding[] bs = CPPSemantics.findBindingsForContentAssist(name, true, new String[] {"ns::inner"}); - + // check the result HashSet result= new HashSet(); for (IBinding binding : bs) { @@ -2389,12 +2428,12 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction f = (IFunction) col.getName(1).resolveBinding(); assertTrue(f.isStatic()); assertInstances(col, f, 2); } - + // // void f() { // // if (__io.flags() & ios_base::showbase // // || __i < 2 || __sign.size() > 1 @@ -2411,7 +2450,7 @@ public class AST2CPPTests extends AST2BaseTest { // IASTCPPIfStatement if_stmt = (IASTCPPIfStatement) body.getStatements()[0]; // assertNotNull(if_stmt.getCondition()); // } - + // struct B { void mutate(); }; // struct D1 : B {}; // struct D2 : B {}; @@ -2425,20 +2464,20 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType D1 = (ICPPClassType) col.getName(2).resolveBinding(); ICPPClassType D2 = (ICPPClassType) col.getName(4).resolveBinding(); - + ICPPConstructor[] ctors = D1.getConstructors(); ICPPConstructor d1_ctor = ctors[0]; - + ctors = D2.getConstructors(); ICPPConstructor d2_ctor = ctors[0]; - + assertInstances(col, d1_ctor, 1); assertInstances(col, d2_ctor, 1); } - + // struct C { // void f(); // const C& operator =(const C&); @@ -2455,20 +2494,20 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType C = (ICPPClassType) col.getName(0).resolveBinding(); ICPPMethod f = (ICPPMethod) col.getName(1).resolveBinding(); ICPPMethod op = (ICPPMethod) col.getName(3).resolveBinding(); IParameter other = (IParameter) col.getName(5).resolveBinding(); - + assertInstances(col, C, 6); assertInstances(col, f, 2); assertInstances(col, op, 3); assertInstances(col, other, 4); - + assertEquals(other.getName(), "other"); //$NON-NLS-1$ } - + // extern "C" { // void printf(const char *); // void sprintf(const char *); @@ -2482,15 +2521,15 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction r1 = (IFunction) col.getName(6).resolveBinding(); IFunction r2 = (IFunction) col.getName(8).resolveBinding(); IFunction printf = (IFunction) col.getName(0).resolveBinding(); - + assertSame(printf, r1); assertSame(printf, r2); } - + // struct S; // extern S a; // void g(S); @@ -2501,42 +2540,42 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType S = (ICPPClassType) col.getName(0).resolveBinding(); IFunction g = (IFunction) col.getName(3).resolveBinding(); - + assertInstances(col, S, 3); assertInstances(col, g, 2); } - + public void testBug86288() throws Exception { 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]; + IASTFunctionDefinition function = (IASTFunctionDefinition) tu.getDeclarations()[0]; + IASTReturnStatement r = + (IASTReturnStatement) ((IASTCompoundStatement) function.getBody()).getStatements()[0]; assertTrue(r.getReturnValue() instanceof IASTCastExpression); } - + // void foo() { // struct B { // int f(); - // }; + // }; // int (B::*pb)() = &B::f; // } public void testBug84476() throws Exception { String code = getAboveComment(); IASTFunctionDefinition foo = (IASTFunctionDefinition) parse(code, ParserLanguage.CPP).getDeclarations()[0]; - IASTDeclarationStatement decl = (IASTDeclarationStatement) ((IASTCompoundStatement) foo - .getBody()).getStatements()[1]; - IASTSimpleDeclaration pb = (IASTSimpleDeclaration) decl - .getDeclaration(); + IASTDeclarationStatement decl = + (IASTDeclarationStatement) ((IASTCompoundStatement) foo.getBody()).getStatements()[1]; + IASTSimpleDeclaration pb = (IASTSimpleDeclaration) decl.getDeclaration(); IASTDeclarator d = pb.getDeclarators()[0]; assertEquals(d.getNestedDeclarator().getPointerOperators().length, 1); assertEquals(d.getNestedDeclarator().getName().toString(), "pb"); //$NON-NLS-1$ assertTrue(d.getNestedDeclarator().getPointerOperators()[0] instanceof ICPPASTPointerToMember); } - + // struct T1 { // T1 operator() (int x) { // return T1(x); @@ -2547,9 +2586,8 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - - ICPPConstructor T1_ctor = (ICPPConstructor) col.getName(6) - .resolveBinding(); + + ICPPConstructor T1_ctor = (ICPPConstructor) col.getName(6).resolveBinding(); ICPPClassType T1 = (ICPPClassType) col.getName(0).resolveBinding(); assertInstances(col, T1_ctor, 1); assertInstances(col, T1, 3); @@ -2558,7 +2596,7 @@ public class AST2CPPTests extends AST2BaseTest { IBinding ctor2 = fc.getImplicitNames()[0].resolveBinding(); assertSame(T1_ctor, ctor2); } - + // struct S { int i; }; // void foo() { // int S::* pm = &S::i; @@ -2567,17 +2605,17 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType S = (ICPPClassType) col.getName(0).resolveBinding(); - + assertInstances(col, S, 3); - + IASTName[] refs = tu.getReferences(S); assertEquals(refs.length, 2); assertSame(refs[0], col.getName(4)); assertSame(refs[1], col.getName(7)); } - + // class A { // public: // template void f(T); @@ -2593,7 +2631,7 @@ public class AST2CPPTests extends AST2BaseTest { CPPNameCollector col = new CPPNameCollector(); tu.accept(col); } - + // void foo() { // int i = 42; // int a[10]; @@ -2605,15 +2643,15 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IVariable i1 = (IVariable) col.getName(1).resolveBinding(); IVariable i2 = (IVariable) col.getName(3).resolveBinding(); - + assertNotSame(i1, i2); assertInstances(col, i1, 2); assertInstances(col, i2, 4); } - + // class X { int i, j; }; // class Y { X x; }; // void foo() { @@ -2628,16 +2666,16 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPField i = (ICPPField) col.getName(1).resolveBinding(); ICPPField j = (ICPPField) col.getName(2).resolveBinding(); ICPPField x = (ICPPField) col.getName(5).resolveBinding(); - + assertInstances(col, i, 3); assertInstances(col, j, 3); assertInstances(col, x, 5); } - + // void foo() { // struct A { // int val; @@ -2653,12 +2691,12 @@ public class AST2CPPTests extends AST2BaseTest { public void testBug84478() throws Exception { IASTFunctionDefinition foo = (IASTFunctionDefinition) parse( getAboveComment(), ParserLanguage.CPP).getDeclarations()[0]; - ICPPASTWhileStatement whileStatement = (ICPPASTWhileStatement) ((IASTCompoundStatement) foo - .getBody()).getStatements()[2]; + ICPPASTWhileStatement whileStatement = + (ICPPASTWhileStatement) ((IASTCompoundStatement) foo.getBody()).getStatements()[2]; assertNull(whileStatement.getCondition()); assertNotNull(whileStatement.getConditionDeclaration()); } - + // void foo() { // const int x = 12; // { enum { x = x }; } @@ -2668,28 +2706,28 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IEnumerator enum_x = (IEnumerator) col.getName(3).resolveBinding(); IBinding x_ref = col.getName(4).resolveBinding(); IEnumerator RED = (IEnumerator) col.getName(6).resolveBinding(); - + String[] s = ((ICPPBinding) RED).getQualifiedName(); assertEquals(s[0], "RED"); //$NON-NLS-1$ assertTrue(((ICPPBinding) RED).isGloballyQualified()); - + IASTName[] decls = tu.getDeclarationsInAST(enum_x); assertEquals(decls.length, 1); assertSame(decls[0], col.getName(3)); - + decls = tu.getDeclarationsInAST(x_ref); assertEquals(decls.length, 1); assertSame(decls[0], col.getName(1)); - + decls = tu.getDeclarationsInAST(RED); assertEquals(decls.length, 1); assertSame(decls[0], col.getName(6)); } - + // class D {}; // D d1; // const D d2; @@ -2702,16 +2740,16 @@ public class AST2CPPTests extends AST2BaseTest { CPPNameCollector col = new CPPNameCollector(); tu.accept(col); assertEquals(col.size(), 10); - + IVariable d1 = (IVariable) col.getName(6).resolveBinding(); IVariable d2 = (IVariable) col.getName(7).resolveBinding(); ICPPClassType D = (ICPPClassType) col.getName(8).resolveBinding(); - + assertInstances(col, D, 4); assertInstances(col, d1, 2); assertInstances(col, d2, 3); } - + // void point (int = 3, int = 4); // void foo() { // point(1, 2); @@ -2722,12 +2760,12 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction point = (IFunction) col.getName(0).resolveBinding(); - + assertInstances(col, point, 4); } - + // namespace Outer{ // int i; // namespace Inner { @@ -2740,14 +2778,14 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IVariable i = (IVariable) col.getName(4).resolveBinding(); IVariable i2 = (IVariable) col.getName(7).resolveBinding(); - + assertInstances(col, i, 2); assertInstances(col, i2, 2); } - + // namespace Q { // namespace V { // void f(); @@ -2760,23 +2798,23 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction f1 = (IFunction) col.getName(2).resolveBinding(); ICPPFunction f2 = (ICPPFunction) col.getName(5).resolveBinding(); assertSame(f1, f2); - + IASTName[] decls = tu.getDeclarationsInAST(f2); assertEquals(decls.length, 2); assertSame(decls[0], col.getName(2)); assertSame(decls[1], col.getName(5)); - + String[] s = f2.getQualifiedName(); assertEquals(s[0], "Q"); //$NON-NLS-1$ assertEquals(s[1], "V"); //$NON-NLS-1$ assertEquals(s[2], "f"); //$NON-NLS-1$ assertTrue(f2.isGloballyQualified()); } - + // struct B { // void f (char); // void g (char); @@ -2790,30 +2828,30 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPFunction f_ref = (ICPPFunction) col.getName(12).resolveBinding(); ICPPFunction g_ref = (ICPPFunction) col.getName(15).resolveBinding(); - + ICPPFunction f = (ICPPFunction) col.getName(1).resolveBinding(); assertSame(f_ref, f); - + IFunction g = (IFunction) col.getName(13).resolveBinding(); assertSame(g, g_ref); - + assertInstances(col, f_ref, 2); assertInstances(col, g_ref, 2); - + String[] s = f_ref.getQualifiedName(); assertEquals(s[0], "B"); //$NON-NLS-1$ assertEquals(s[1], "f"); //$NON-NLS-1$ assertTrue(f_ref.isGloballyQualified()); - + s = g_ref.getQualifiedName(); assertEquals(s[0], "D"); //$NON-NLS-1$ assertEquals(s[1], "g"); //$NON-NLS-1$ assertTrue(f.isGloballyQualified()); } - + // namespace Company_with_veryblahblah {} // namespace CWVLN = Company_with_veryblahblah; // namespace CWVLN = Company_with_veryblahblah; @@ -2822,38 +2860,38 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPNamespace ns = (ICPPNamespace) col.getName(0).resolveBinding(); ICPPNamespace alias = (ICPPNamespace) col.getName(1).resolveBinding(); - + String[] s = ns.getQualifiedName(); assertEquals(s[0], "Company_with_veryblahblah"); //$NON-NLS-1$ s = alias.getQualifiedName(); assertEquals(s[0], "CWVLN"); //$NON-NLS-1$ - + assertTrue(alias instanceof ICPPNamespaceAlias); assertSame(((ICPPNamespaceAlias) alias).getBinding(), ns); - + IASTName[] refs = tu.getReferences(ns); assertEquals(refs.length, 2); assertSame(refs[0], col.getName(2)); assertSame(refs[1], col.getName(4)); - + IASTName[] decls = tu.getDeclarationsInAST(ns); assertEquals(decls.length, 1); assertSame(decls[0], col.getName(0)); - + refs = tu.getReferences(alias); assertEquals(refs.length, 1); assertSame(refs[0], col.getName(6)); - + decls = tu.getDeclarationsInAST(alias); assertEquals(decls.length, 3); assertSame(decls[0], col.getName(1)); assertSame(decls[1], col.getName(3)); assertSame(decls[2], col.getName(5)); } - + // namespace A { // void f(char); // void f(int); @@ -2863,28 +2901,27 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - - ICPPUsingDeclaration u = (ICPPUsingDeclaration) col.getName(7) - .resolveBinding(); - + + ICPPUsingDeclaration u = (ICPPUsingDeclaration) col.getName(7).resolveBinding(); + IASTName[] decls = tu.getDeclarationsInAST(u); assertEquals(3, decls.length); // 2 function-decls + using-decl assertSame(decls[0], col.getName(1)); assertSame(decls[1], col.getName(3)); - + IBinding[] delegates = u.getDelegates(); assertEquals(delegates.length, 2); - + decls = tu.getDeclarationsInAST(delegates[0]); assertEquals(2, decls.length); // function-decl + using-decl assertSame(decls[0], col.getName(1)); assertSame(decls[1], col.getName(7)); - + decls = tu.getDeclarationsInAST(delegates[0]); assertEquals(2, decls.length); // function-decl + using-decl assertSame(decls[0], col.getName(1)); } - + // namespace A { // void f(int); // void f(double); @@ -2903,12 +2940,12 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction f_decl = (IFunction) col.getName(10).resolveBinding(); IFunction f_ref = (IFunction) col.getName(19).resolveBinding(); assertSame(f_decl, f_ref); } - + // namespace A { // struct g {}; // void g (char); @@ -2922,26 +2959,24 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IBinding ref1 = col.getName(8).resolveBinding(); IBinding ref2 = col.getName(9).resolveBinding(); - - ICPPClassType g_struct = (ICPPClassType) col.getName(1) - .resolveBinding(); + + ICPPClassType g_struct = (ICPPClassType) col.getName(1).resolveBinding(); IFunction g_func = (IFunction) col.getName(2).resolveBinding(); - + assertSame(g_struct,ref2); assertSame(g_func, ref1); - - ICPPUsingDeclaration comp = (ICPPUsingDeclaration) col.getName(7) - .resolveBinding(); + + ICPPUsingDeclaration comp = (ICPPUsingDeclaration) col.getName(7).resolveBinding(); IASTName[] decls = tu.getDeclarationsInAST(comp); assertEquals(3, decls.length); // struct, func and using-decl assertSame(decls[0], col.getName(1)); assertSame(decls[1], col.getName(2)); assertSame(decls[2], col.getName(7)); } - + // namespace A { // int x; // } @@ -2958,33 +2993,32 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPBinding ref1 = (ICPPBinding) col.getName(11).resolveBinding(); ICPPBinding ref2 = (ICPPBinding) col.getName(12).resolveBinding(); - - ICPPClassType x_struct = (ICPPClassType) col.getName(3) - .resolveBinding(); + + ICPPClassType x_struct = (ICPPClassType) col.getName(3).resolveBinding(); IVariable x_var = (IVariable) col.getName(1).resolveBinding(); - + assertSame(x_struct, ref2); assertSame(x_var, ref1); - + IASTName[] refs = tu.getReferences(x_struct); assertEquals(2, refs.length); // 1 ref + using-decl assertSame(refs[0], col.getName(10)); assertSame(refs[1], col.getName(12)); - + String[] s = ref2.getQualifiedName(); assertEquals(s[0], "B"); //$NON-NLS-1$ assertEquals(s[1], "x"); //$NON-NLS-1$ assertTrue(ref2.isGloballyQualified()); - + s = x_struct.getQualifiedName(); assertEquals(s[0], "B"); //$NON-NLS-1$ assertEquals(s[1], "x"); //$NON-NLS-1$ assertTrue(x_struct.isGloballyQualified()); } - + // namespace A { // void f(int); // void f(double); @@ -2998,23 +3032,23 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPFunction f = (ICPPFunction) col.getName(3).resolveBinding(); - + ICPPFunction f_ref = (ICPPFunction) col.getName(11).resolveBinding(); assertSame(f_ref, f); - + String[] s = f_ref.getQualifiedName(); assertEquals(s[0], "A"); //$NON-NLS-1$ assertEquals(s[1], "f"); //$NON-NLS-1$ assertTrue(f_ref.isGloballyQualified()); - + s = f.getQualifiedName(); assertEquals(s[0], "A"); //$NON-NLS-1$ assertEquals(s[1], "f"); //$NON-NLS-1$ assertTrue(f.isGloballyQualified()); } - + // class B; // class A { // int i; @@ -3028,16 +3062,16 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType B = (ICPPClassType) col.getName(6).resolveBinding(); ICPPField i = (ICPPField) col.getName(12).resolveBinding(); IParameter p = (IParameter) col.getName(10).resolveBinding(); - + assertInstances(col, B, 4); assertInstances(col, i, 2); assertInstances(col, p, 3); } - + // int printf(const char *, ...); // void foo(){ // int a, b; @@ -3048,11 +3082,11 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction printf = (IFunction) col.getName(6).resolveBinding(); assertInstances(col, printf, 3); } - + // int max(int a, int b, int c) { // int m = (a > b) ? a : b; // return (m > c) ? m : c; @@ -3061,22 +3095,22 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IVariable m = (IVariable) col.getName(11).resolveBinding(); IParameter a = (IParameter) col.getName(1).resolveBinding(); IParameter b = (IParameter) col.getName(2).resolveBinding(); IParameter c = (IParameter) col.getName(3).resolveBinding(); - + String[] s = ((ICPPBinding) a).getQualifiedName(); assertEquals(s[0], "a"); //$NON-NLS-1$ assertFalse(((ICPPBinding) a).isGloballyQualified()); - + assertInstances(col, m, 3); assertInstances(col, a, 3); assertInstances(col, b, 3); assertInstances(col, c, 3); } - + // int g(); // struct X { static int g(); }; // struct Y : X { static int i ; }; @@ -3085,23 +3119,23 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPFunction g1 = (ICPPFunction) col.getName(0).resolveBinding(); ICPPMethod g2 = (ICPPMethod) col.getName(9).resolveBinding(); - + String[] s = g1.getQualifiedName(); assertEquals(s[0], "g"); //$NON-NLS-1$ assertTrue(g1.isGloballyQualified()); - + s = g2.getQualifiedName(); assertEquals(s[0], "X"); //$NON-NLS-1$ assertEquals(s[1], "g"); //$NON-NLS-1$ assertTrue(g2.isGloballyQualified()); - + assertInstances(col, g1, 1); assertInstances(col, g2, 2); } - + // class V { int f(); int x; }; // class W { int g(); int y; }; // class B : public virtual V, public W { @@ -3122,30 +3156,30 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPField x = (ICPPField) col.getName(23).resolveBinding(); ICPPMethod f = (ICPPMethod) col.getName(24).resolveBinding(); - + String[] s = f.getQualifiedName(); assertEquals(s[0], "B"); //$NON-NLS-1$ assertEquals(s[1], "f"); //$NON-NLS-1$ assertTrue(f.isGloballyQualified()); - + s = x.getQualifiedName(); assertEquals(s[0], "B"); //$NON-NLS-1$ assertEquals(s[1], "x"); //$NON-NLS-1$ assertTrue(x.isGloballyQualified()); - + IProblemBinding y = (IProblemBinding) col.getName(25).resolveBinding(); IProblemBinding g = (IProblemBinding) col.getName(26).resolveBinding(); - + assertEquals(y.getID(), IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP); assertEquals(g.getID(), IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP); - + assertInstances(col, x, 2); assertInstances(col, f, 2); } - + // struct C { // int c; // C() : c(0) { } @@ -3154,20 +3188,20 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPVariable c = (ICPPVariable) col.getName(1).resolveBinding(); - + String[] s = c.getQualifiedName(); assertEquals(s.length, 2); assertEquals(s[0], "C"); //$NON-NLS-1$ assertEquals(s[1], "c"); //$NON-NLS-1$ assertTrue(c.isGloballyQualified()); - + IASTName[] refs = tu.getReferences(c); assertEquals(refs.length, 1); assertSame(refs[0], col.getName(3)); } - + // void f(int par) { // int v1; // { @@ -3178,24 +3212,24 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPVariable v1 = (ICPPVariable) col.getName(2).resolveBinding(); ICPPVariable v2 = (ICPPVariable) col.getName(3).resolveBinding(); - + String[] s = v1.getQualifiedName(); assertEquals(s[0], "v1"); //$NON-NLS-1$ assertFalse(v1.isGloballyQualified()); - + s = v2.getQualifiedName(); assertEquals(s[0], "v2"); //$NON-NLS-1$ assertFalse(v2.isGloballyQualified()); - + ICPPBlockScope scope = (ICPPBlockScope) v2.getScope(); IBinding[] bs = scope.find("v1"); //$NON-NLS-1$ assertEquals(bs.length, 1); assertSame(bs[0], v1); } - + // class A { int a; }; // class B : public A { // void f(); @@ -3206,26 +3240,26 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType A = (ICPPClassType) col.getName(0).resolveBinding(); ICPPField a = (ICPPField) col.getName(1).resolveBinding(); ICPPMethod f = (ICPPMethod) col.getName(7).resolveBinding(); - + IScope scope = f.getFunctionScope(); IBinding[] bs = scope.find("a"); //$NON-NLS-1$ assertEquals(bs.length, 1); assertSame(bs[0], a); - + bs = scope.find("~B"); //$NON-NLS-1$ assertEquals(bs.length, 1); assertTrue(bs[0] instanceof ICPPMethod); assertTrue(bs[0].getName().equals("~B")); //$NON-NLS-1$ - + bs = scope.find("A"); //$NON-NLS-1$ assertEquals(bs.length, 1); assertSame(bs[0], A); } - + // namespace A { // void f(int); // void f(double); @@ -3238,11 +3272,11 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction f1 = (IFunction) col.getName(1).resolveBinding(); IFunction f2 = (IFunction) col.getName(3).resolveBinding(); IFunction f3 = (IFunction) col.getName(6).resolveBinding(); - + IASTFunctionDefinition def = (IASTFunctionDefinition) col.getName(5).getParent().getParent(); IScope scope = ((IASTCompoundStatement) def.getBody()).getScope(); IBinding[] bs = scope.find("f"); //$NON-NLS-1$ @@ -3250,14 +3284,14 @@ public class AST2CPPTests extends AST2BaseTest { assertSame(bs[0], f3); assertSame(bs[1], f1); assertSame(bs[2], f2); - + String[] s = ((ICPPBinding) bs[1]).getQualifiedName(); assertEquals(s.length, 2); assertEquals(s[0], "A"); //$NON-NLS-1$ assertEquals(s[1], "f"); //$NON-NLS-1$ assertTrue(((ICPPBinding) bs[1]).isGloballyQualified()); } - + // namespace A { // struct f; // void f(); @@ -3276,13 +3310,12 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType f = (ICPPClassType) col.getName(1).resolveBinding(); IFunction f1 = (IFunction) col.getName(2).resolveBinding(); IFunction f2 = (IFunction) col.getName(4).resolveBinding(); - - IASTFunctionDefinition def = (IASTFunctionDefinition) col.getName(8) - .getParent().getParent(); + + IASTFunctionDefinition def = (IASTFunctionDefinition) col.getName(8).getParent().getParent(); IScope scope = ((IASTCompoundStatement) def.getBody()).getScope(); IBinding[] bs = scope.find("f"); //$NON-NLS-1$ assertEquals(3, bs.length); @@ -3290,7 +3323,7 @@ public class AST2CPPTests extends AST2BaseTest { assertSame(bs[1], f1); assertSame(bs[2], f2); } - + // class A { // public: // A(); @@ -3301,43 +3334,31 @@ public class AST2CPPTests extends AST2BaseTest { // B(); // void bf(); // }; - public void testFind_bug185408() throws Exception { + public void testFind_bug185408() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction f1 = (IFunction) col.getName(6).resolveBinding(); IScope classScope= f1.getScope(); assertTrue(classScope instanceof ICPPClassScope); IBinding[] bindings = classScope.find("bf"); ICPPMethod method= extractSingleMethod(bindings); assertEquals(method.getQualifiedName()[0], "B"); - + bindings= classScope.find("f"); method= extractSingleMethod(bindings); assertEquals(method.getQualifiedName()[0], "A"); - + bindings= classScope.find("B"); ICPPClassType classType= extractSingleClass(bindings); assertEquals(classType.getQualifiedName()[0], "B"); - + bindings= classScope.find("A"); classType= extractSingleClass(bindings); assertEquals(classType.getQualifiedName()[0], "A"); } - - private ICPPMethod extractSingleMethod(IBinding[] bindings) { - assertEquals(1, bindings.length); - assertTrue(bindings[0] instanceof ICPPMethod); - return (ICPPMethod) bindings[0]; - } - - private ICPPClassType extractSingleClass(IBinding[] bindings) { - assertEquals(1, bindings.length); - assertTrue(bindings[0] instanceof ICPPClassType); - return (ICPPClassType) bindings[0]; - } - + // class A { // int a; // void fa(); @@ -3350,48 +3371,46 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType A = (ICPPClassType) col.getName(0).resolveBinding(); ICPPClassType B = (ICPPClassType) col.getName(3).resolveBinding(); ICPPField a = (ICPPField) col.getName(1).resolveBinding(); ICPPMethod fa = (ICPPMethod) col.getName(2).resolveBinding(); ICPPField b = (ICPPField) col.getName(5).resolveBinding(); ICPPMethod fb = (ICPPMethod) col.getName(6).resolveBinding(); - + Object[] result = B.getDeclaredFields(); assertEquals(result.length, 1); assertSame(result[0], b); - + result = B.getFields(); assertEquals(result.length, 2); assertSame(result[0], b); assertSame(result[1], a); - + result = B.getDeclaredMethods(); assertEquals(result.length, 1); assertSame(result[0], fb); - + result = B.getAllDeclaredMethods(); assertEquals(result.length, 2); assertSame(result[0], fb); assertSame(result[1], fa); - - ICPPMethod[] B_implicit = ((ICPPClassScope) B.getCompositeScope()) - .getImplicitMethods(); + + ICPPMethod[] B_implicit = ((ICPPClassScope) B.getCompositeScope()).getImplicitMethods(); assertEquals(B_implicit.length, 4); assertTrue(B_implicit[0].getName().equals("B")); //$NON-NLS-1$ assertTrue(B_implicit[1].getName().equals("B")); //$NON-NLS-1$ assertTrue(B_implicit[2].getName().equals("operator =")); //$NON-NLS-1$ assertTrue(B_implicit[3].getName().equals("~B")); //$NON-NLS-1$ - - ICPPMethod[] A_implicit = ((ICPPClassScope) A.getCompositeScope()) - .getImplicitMethods(); + + ICPPMethod[] A_implicit = ((ICPPClassScope) A.getCompositeScope()).getImplicitMethods(); assertEquals(A_implicit.length, 4); assertTrue(A_implicit[0].getName().equals("A")); //$NON-NLS-1$ assertTrue(A_implicit[1].getName().equals("A")); //$NON-NLS-1$ assertTrue(A_implicit[2].getName().equals("operator =")); //$NON-NLS-1$ assertTrue(A_implicit[3].getName().equals("~A")); //$NON-NLS-1$ - + result = B.getMethods(); assertEquals(result.length, 10); assertSame(result[0], fb); @@ -3405,60 +3424,60 @@ public class AST2CPPTests extends AST2BaseTest { assertSame(result[8], A_implicit[2]); assertSame(result[9], A_implicit[3]); } - + public void testBug87424() throws Exception { IASTTranslationUnit tu = parse( "int * __restrict x;", ParserLanguage.CPP, true); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IVariable x = (IVariable) col.getName(0).resolveBinding(); IType t = x.getType(); assertTrue(t instanceof IPointerType); assertTrue(((IPointerType) t).isRestrict()); - + tu = parse("class A {}; int A::* __restrict x;", ParserLanguage.CPP, true); //$NON-NLS-1$ col = new CPPNameCollector(); tu.accept(col); - + x = (IVariable) col.getName(3).resolveBinding(); t = x.getType(); assertTrue(t instanceof ICPPPointerToMemberType); assertTrue(((ICPPPointerToMemberType) t).isRestrict()); } - + public void testBug87705() throws Exception { IASTTranslationUnit tu = parse( "class A { friend class B::C; };", ParserLanguage.CPP, true); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IProblemBinding B = (IProblemBinding) col.getName(2).resolveBinding(); assertEquals(B.getID(), IProblemBinding.SEMANTIC_NAME_NOT_FOUND); IProblemBinding C = (IProblemBinding) col.getName(3).resolveBinding(); assertEquals(C.getID(), IProblemBinding.SEMANTIC_NAME_NOT_FOUND); } - + public void testBug88459() throws Exception { IASTTranslationUnit tu = parse("int f(); ", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction f = (IFunction) col.getName(0).resolveBinding(); assertFalse(f.isStatic()); } - + public void testBug88501_1() throws Exception { IASTTranslationUnit tu = parse( "void f(); void f(int); struct f;", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertTrue(col.getName(0).resolveBinding() instanceof IFunction); assertTrue(col.getName(1).resolveBinding() instanceof IFunction); assertTrue(col.getName(3).resolveBinding() instanceof ICPPClassType); } - + // public void testBug8342_1() throws Exception { // IASTTranslationUnit tu = parse("int a; int a;", ParserLanguage.CPP); // //$NON-NLS-1$ @@ -3469,18 +3488,18 @@ public class AST2CPPTests extends AST2BaseTest { // IProblemBinding p = (IProblemBinding) col.getName(1).resolveBinding(); // assertEquals(p.getID(), IProblemBinding.SEMANTIC_INVALID_REDEFINITION); // } - + public void testBug8342_2() throws Exception { IASTTranslationUnit tu = parse( "extern int a; extern char a;", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertTrue(col.getName(0).resolveBinding() instanceof IVariable); IProblemBinding p = (IProblemBinding) col.getName(1).resolveBinding(); assertEquals(p.getID(), IProblemBinding.SEMANTIC_INVALID_REDECLARATION); } - + // namespace A { int i; } // namespace B = A; // void f() { @@ -3490,26 +3509,25 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPNamespace A = (ICPPNamespace) col.getName(0).resolveBinding(); - ICPPNamespaceAlias alias = (ICPPNamespaceAlias) col.getName(6) - .resolveBinding(); + ICPPNamespaceAlias alias = (ICPPNamespaceAlias) col.getName(6).resolveBinding(); ICPPVariable i = (ICPPVariable) col.getName(7).resolveBinding(); - + assertInstances(col, A, 2); assertInstances(col, alias, 2); assertInstances(col, i, 3); - + String[] s = i.getQualifiedName(); assertEquals(s[0], "A"); //$NON-NLS-1$ assertEquals(s[1], "i"); //$NON-NLS-1$ assertTrue(i.isGloballyQualified()); - + s = alias.getQualifiedName(); assertEquals(s[0], "B"); //$NON-NLS-1$ assertTrue(alias.isGloballyQualified()); } - + // class A{}; // class B : public A { // B () : A() {} @@ -3519,21 +3537,21 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(content, ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType A1 = (ICPPClassType) col.getName(0).resolveBinding(); ICPPClassType A2 = (ICPPClassType) col.getName(2).resolveBinding(); assertSame(A1, A2); - + ICPPConstructor A3 = (ICPPConstructor) col.getName(4).resolveBinding(); assertSame(A3.getScope(), A1.getCompositeScope()); - + tu = parse(content, ParserLanguage.CPP); col = new CPPNameCollector(); tu.accept(col); - + assertTrue(col.getName(4).resolveBinding() instanceof ICPPConstructor); } - + // class B * b; // class A { // A * a; @@ -3543,31 +3561,31 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertTrue(col.getName(0).resolveBinding() instanceof ICPPClassType); assertTrue(col.getName(1).resolveBinding() instanceof ICPPVariable); assertTrue(col.getName(2).resolveBinding() instanceof ICPPClassType); assertTrue(col.getName(3).resolveBinding() instanceof ICPPClassType); } - + public void testBug89828() throws Exception { IASTTranslationUnit tu = parse( "class B * b; void f(); void f(int);", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertTrue(col.getName(0).resolveBinding() instanceof ICPPClassType); assertTrue(col.getName(1).resolveBinding() instanceof ICPPVariable); IFunction f1 = (IFunction) col.getName(2).resolveBinding(); IFunction f2 = (IFunction) col.getName(3).resolveBinding(); - + IScope scope = tu.getScope(); IBinding[] bs = scope.find("f"); //$NON-NLS-1$ assertEquals(bs.length, 2); assertSame(bs[0], f1); assertSame(bs[1], f2); } - + // class A { // enum type { t1, t2 }; // void f(type t); @@ -3581,14 +3599,14 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction f = (IFunction) col.getName(10).resolveBinding(); IEnumerator t1 = (IEnumerator) col.getName(13).resolveBinding(); - + assertInstances(col, f, 2); assertInstances(col, t1, 3); } - + // void f(void) { // enum { one }; // } @@ -3602,7 +3620,7 @@ public class AST2CPPTests extends AST2BaseTest { IEnumerator one = (IEnumerator) col.getName(3).resolveBinding(); assertSame(one.getType(), e); } - + // class Foo { // public: // operator int(); @@ -3612,23 +3630,23 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IASTName name1 = col.getName(1); IASTName name2 = col.getName(2); - + assertNotNull(name1); assertNotNull(name2); - + assertTrue(name1 instanceof ICPPASTConversionName); assertTrue(name2 instanceof ICPPASTOperatorName); - + IASTTypeId typeId = ((ICPPASTConversionName) name1).getTypeId(); assertNotNull(typeId); - assertEquals(((IASTSimpleDeclSpecifier) typeId.getDeclSpecifier()) - .getType(), IASTSimpleDeclSpecifier.t_int); - + assertEquals(((IASTSimpleDeclSpecifier) typeId.getDeclSpecifier()).getType(), + IASTSimpleDeclSpecifier.t_int); + } - + // class X { operator int(); }; // X::operator int() { } // template class X { operator int(); }; @@ -3637,15 +3655,15 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + // 1,4,12,21 - conversion // 2, 16 .isConversion - + final IASTName int1 = col.getName(1); assertNotNull(int1); assertTrue(int1 instanceof ICPPASTConversionName); assertNotNull(((ICPPASTConversionName) int1).getTypeId()); - + IASTFunctionDefinition fdef= getDeclaration(tu, 1); final IASTName x_int = fdef.getDeclarator().getName(); assertNotNull(x_int); @@ -3656,7 +3674,7 @@ public class AST2CPPTests extends AST2BaseTest { assertNotNull(int2); assertTrue(int2 instanceof ICPPASTConversionName); assertNotNull(((ICPPASTConversionName) int2).getTypeId()); - + final IASTName int3 = col.getName(12); assertNotNull(int3); assertTrue(int3 instanceof ICPPASTConversionName); @@ -3674,55 +3692,51 @@ public class AST2CPPTests extends AST2BaseTest { assertTrue(int4 instanceof ICPPASTConversionName); assertNotNull(((ICPPASTConversionName) int4).getTypeId()); } - + public void testBug88662() throws Exception { IASTTranslationUnit tu = parse( "int foo() { return int();}", ParserLanguage.CPP); //$NON-NLS-1$ - IASTReturnStatement returnStatement = (IASTReturnStatement) ((IASTCompoundStatement) ((IASTFunctionDefinition) tu - .getDeclarations()[0]).getBody()).getStatements()[0]; - ICPPASTSimpleTypeConstructorExpression expression = (ICPPASTSimpleTypeConstructorExpression) returnStatement - .getReturnValue(); + IASTReturnStatement returnStatement = + (IASTReturnStatement) ((IASTCompoundStatement) ((IASTFunctionDefinition) tu.getDeclarations()[0]).getBody()).getStatements()[0]; + ICPPASTSimpleTypeConstructorExpression expression = + (ICPPASTSimpleTypeConstructorExpression) returnStatement.getReturnValue(); assertEquals(expression.getInitialValue(), null); - assertEquals(expression.getSimpleType(), - ICPPASTSimpleTypeConstructorExpression.t_int); + assertEquals(expression.getSimpleType(), ICPPASTSimpleTypeConstructorExpression.t_int); } - + public void testBug90498_1() throws Exception { IASTTranslationUnit tu = parse( "typedef int INT;\ntypedef INT (FOO) (INT);", ParserLanguage.CPP); //$NON-NLS-1$ - - IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu - .getDeclarations()[1]; + + IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu.getDeclarations()[1]; IASTDeclSpecifier declSpec = decl.getDeclSpecifier(); assertTrue(declSpec instanceof ICPPASTNamedTypeSpecifier); - assertEquals(((ICPPASTNamedTypeSpecifier) declSpec).getName() - .toString(), "INT"); //$NON-NLS-1$ - + assertEquals(((ICPPASTNamedTypeSpecifier) declSpec).getName().toString(), "INT"); //$NON-NLS-1$ + IASTDeclarator dtor = decl.getDeclarators()[0]; assertTrue(dtor instanceof IASTFunctionDeclarator); assertNotNull(dtor.getNestedDeclarator()); IASTDeclarator nested = dtor.getNestedDeclarator(); assertEquals(nested.getName().toString(), "FOO"); //$NON-NLS-1$ } - + public void testBug90498_2() throws Exception { IASTTranslationUnit tu = parse( "int (* foo) (int) (0);", ParserLanguage.CPP); //$NON-NLS-1$ - - IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu - .getDeclarations()[0]; + + IASTSimpleDeclaration decl = (IASTSimpleDeclaration) tu.getDeclarations()[0]; IASTDeclSpecifier declSpec = decl.getDeclSpecifier(); assertTrue(declSpec instanceof IASTSimpleDeclSpecifier); - + IASTDeclarator dtor = decl.getDeclarators()[0]; assertTrue(dtor instanceof IASTFunctionDeclarator); assertNotNull(dtor.getNestedDeclarator()); IASTDeclarator nested = dtor.getNestedDeclarator(); assertEquals(nested.getName().toString(), "foo"); //$NON-NLS-1$ - + assertNotNull(dtor.getInitializer()); } - + // class D { /* ... */ }; // D d1; // const D d2; @@ -3732,46 +3746,38 @@ public class AST2CPPTests extends AST2BaseTest { // } public void testBug866274() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); - IASTFunctionDefinition foo = (IASTFunctionDefinition) tu - .getDeclarations()[3]; + IASTFunctionDefinition foo = (IASTFunctionDefinition) tu.getDeclarations()[3]; IASTCompoundStatement cs = (IASTCompoundStatement) foo.getBody(); IASTStatement[] subs = cs.getStatements(); for (int i = 0; i < subs.length; ++i) { - IASTBinaryExpression be = (IASTBinaryExpression) ((IASTExpressionStatement) subs[i]) - .getExpression(); + IASTBinaryExpression be = + (IASTBinaryExpression) ((IASTExpressionStatement) subs[i]).getExpression(); if (i == 1) { - IASTTypeIdExpression expression = (IASTTypeIdExpression) be - .getOperand1(); + IASTTypeIdExpression expression = (IASTTypeIdExpression) be.getOperand1(); IASTTypeId typeId = expression.getTypeId(); - assertTrue(((IASTNamedTypeSpecifier) typeId.getDeclSpecifier()) - .getName().resolveBinding() instanceof IType); + IASTName name = ((IASTNamedTypeSpecifier) typeId.getDeclSpecifier()).getName(); + assertTrue(name.resolveBinding() instanceof IType); } else { - IASTUnaryExpression expression = (IASTUnaryExpression) be - .getOperand1(); - IASTIdExpression idExpression = (IASTIdExpression) expression - .getOperand(); + IASTUnaryExpression expression = (IASTUnaryExpression) be.getOperand1(); + IASTIdExpression idExpression = (IASTIdExpression) expression.getOperand(); assertTrue(idExpression.getName().resolveBinding() instanceof IVariable); } - IASTUnaryExpression expression = (IASTUnaryExpression) be - .getOperand2(); - IASTIdExpression idExpression = (IASTIdExpression) expression - .getOperand(); + IASTUnaryExpression expression = (IASTUnaryExpression) be.getOperand2(); + IASTIdExpression idExpression = (IASTIdExpression) expression.getOperand(); assertTrue(idExpression.getName().resolveBinding() instanceof IVariable); - } } - + public void testTypedefFunction() throws Exception { - IASTTranslationUnit tu = parse( - "typedef int foo (int);", ParserLanguage.CPP); //$NON-NLS-1$ + IASTTranslationUnit tu = parse("typedef int foo (int);", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IBinding binding = col.getName(0).resolveBinding(); assertTrue(binding instanceof ITypedef); assertTrue(((ITypedef) binding).getType() instanceof IFunctionType); } - + // void f(int); // void foo(){ // f((1, 2)); @@ -3780,33 +3786,33 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction f1 = (IFunction) col.getName(0).resolveBinding(); IFunction f2 = (IFunction) col.getName(3).resolveBinding(); assertSame(f1, f2); } - + public void testBug90603() throws Exception { IASTTranslationUnit tu = parse( "class X { void f(){} };", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType X = (ICPPClassType) col.getName(0).resolveBinding(); ICPPMethod f1 = (ICPPMethod) col.getName(1).resolveBinding(); - + assertFalse(f1.isStatic()); - + String[] qns = f1.getQualifiedName(); assertEquals(qns.length, 2); assertEquals(qns[0], "X"); //$NON-NLS-1$ assertEquals(qns[1], "f"); //$NON-NLS-1$ assertTrue(f1.isGloballyQualified()); assertEquals(f1.getVisibility(), ICPPMember.v_private); - + assertSame(f1.getScope(), X.getCompositeScope()); } - + // class X { }; // X x; // class X { }; @@ -3814,16 +3820,15 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType X = (ICPPClassType) col.getName(0).resolveBinding(); IVariable x = (IVariable) col.getName(2).resolveBinding(); - IProblemBinding problem = (IProblemBinding) col.getName(3) - .resolveBinding(); + IProblemBinding problem = (IProblemBinding) col.getName(3).resolveBinding(); assertSame(x.getType(), X); assertEquals(problem.getID(), IProblemBinding.SEMANTIC_INVALID_REDEFINITION); } - + // struct C { // void* operator new [ ] (unsigned int); // void* operator new (unsigned int); @@ -3865,7 +3870,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& operator // ! /**/ (const C&); // const C& operator <(const C&); // const C& operator>(const C&); @@ -3874,7 +3879,7 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertEquals(col.size(), 161); assertEquals(col.getName(1).toString(), "operator new[]"); //$NON-NLS-1$ assertEquals(col.getName(3).toString(), "operator new"); //$NON-NLS-1$ @@ -3919,7 +3924,7 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals(col.getName(154).toString(), "operator <"); //$NON-NLS-1$ assertEquals(col.getName(158).toString(), "operator >"); //$NON-NLS-1$ } - + // typedef int I; // typedef int I; // typedef I I; @@ -3932,7 +3937,7 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ITypedef I1 = (ITypedef) col.getName(0).resolveBinding(); ITypedef I2 = (ITypedef) col.getName(1).resolveBinding(); ITypedef I3 = (ITypedef) col.getName(2).resolveBinding(); @@ -3942,7 +3947,7 @@ public class AST2CPPTests extends AST2BaseTest { ITypedef I6 = (ITypedef) col.getName(7).resolveBinding(); ITypedef I7 = (ITypedef) col.getName(6).resolveBinding(); // ITypedef I8 = (ITypedef) col.getName(5).resolveBinding(); - + assertSame(I1, I2); assertSame(I2, I3); assertSame(I3, I4); @@ -3950,14 +3955,14 @@ public class AST2CPPTests extends AST2BaseTest { assertSame(I5, I6); assertSame(I6, I7); assertSame(I7, I8); - + assertTrue(I1.getType() instanceof IBasicType); assertEquals(((IBasicType) I1.getType()).getType(), IBasicType.t_int); - + assertTrue(I8.getType() instanceof IBasicType); assertEquals(((IBasicType) I8.getType()).getType(), IBasicType.t_char); } - + // typedef int I; // void f11(I i); // void main(){ f a; } @@ -3965,11 +3970,11 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IASTName f = col.getName(5); f.getCompletionContext().findBindings(f, true); } - + // class X { // X(const X &); // }; @@ -3982,14 +3987,12 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - - ICPPConstructor ctor1 = (ICPPConstructor) col.getName(1) - .resolveBinding(); - ICPPConstructor ctor = (ICPPConstructor) col.getName(11) - .resolveBinding(); + + ICPPConstructor ctor1 = (ICPPConstructor) col.getName(1).resolveBinding(); + ICPPConstructor ctor = (ICPPConstructor) col.getName(11).resolveBinding(); assertSame(ctor, ctor1); } - + // struct A { // operator short(); // } a; @@ -4000,12 +4003,12 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction f1 = (IFunction) col.getName(3).resolveBinding(); IFunction f2 = (IFunction) col.getName(8).resolveBinding(); assertSame(f1, f2); } - + // struct A {}; // struct B : public A { // B& operator = (const B &); @@ -4018,19 +4021,19 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType A = (ICPPClassType) col.getName(0).resolveBinding(); ICPPMethod implicit = A.getMethods()[2]; - + ICPPMethod op1 = (ICPPMethod) col.getName(4).resolveBinding(); ICPPMethod op2 = (ICPPMethod) col.getName(10).resolveBinding(); - + ICPPMethod op = (ICPPMethod) col.getName(15).resolveBinding(); - + assertSame(op1, op2); assertSame(op, implicit); } - + // void f(char *); // void foo() { // f("test"); @@ -4039,11 +4042,11 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction f = (IFunction) col.getName(0).resolveBinding(); assertInstances(col, f, 2); } - + // void f(int (*pf) (char)); // int g(char); // void foo () { @@ -4053,17 +4056,17 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPFunction f1 = (ICPPFunction) col.getName(0).resolveBinding(); ICPPFunction g1 = (ICPPFunction) col.getName(3).resolveBinding(); - + IBinding f2 = col.getName(6).resolveBinding(); IBinding g2 = col.getName(7).resolveBinding(); - + assertSame(f1, f2); assertSame(g1, g2); } - + // class ABC { // class DEF { }; // static int GHI; @@ -4078,13 +4081,12 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); IASTDeclaration[] declarations = tu.getDeclarations(); assertEquals(3, declarations.length); - IASTCompoundStatement cs = (IASTCompoundStatement) ((IASTFunctionDefinition) declarations[2]) - .getBody(); + IASTCompoundStatement cs = (IASTCompoundStatement) ((IASTFunctionDefinition) declarations[2]).getBody(); assertTrue(cs.getStatements()[1] instanceof IASTDeclarationStatement); assertTrue(cs.getStatements()[2] instanceof IASTExpressionStatement); - + } - + // void f(){ // union { int a; char* p; }; // a = 1; @@ -4093,12 +4095,12 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPField a = (ICPPField) col.getName(2).resolveBinding(); ICPPField a2 = (ICPPField) col.getName(4).resolveBinding(); assertSame(a, a2); } - + // void f () { // int aa1, aa2; // a; @@ -4107,17 +4109,17 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IVariable a1 = (IVariable) col.getName(1).resolveBinding(); IVariable a2 = (IVariable) col.getName(2).resolveBinding(); - + IBinding[] bs = col.getName(3).getCompletionContext().findBindings( col.getName(3), true); assertEquals(bs.length, 2); assertSame(bs[0], a1); assertSame(bs[1], a2); } - + // struct Ex { // int d(); // int d() const; @@ -4132,25 +4134,25 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPFunction d1 = (ICPPFunction) col.getName(1).resolveBinding(); ICPPFunction d2 = (ICPPFunction) col.getName(2).resolveBinding(); - + assertNotSame(d1, d2); - + assertFalse(d1.getType().isConst()); assertTrue((d2.getType()).isConst()); - + ICPPFunction dr1 = (ICPPFunction) col.getName(5).resolveBinding(); ICPPFunction dr2 = (ICPPFunction) col.getName(8).resolveBinding(); - + assertSame(d1, dr1); assertSame(d2, dr2); - + IBinding r = col.getName(13).resolveBinding(); assertSame(d2, r); } - + // class Point { // Point() : xCoord(0) {} // int xCoord; @@ -4159,48 +4161,44 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPField x = (ICPPField) col.getName(2).resolveBinding(); ICPPField x2 = (ICPPField) col.getName(3).resolveBinding(); assertSame(x, x2); } - + public void testBug90648() throws ParserException { IASTTranslationUnit tu = parse( "int f() { int (&ra)[3] = a; }", ParserLanguage.CPP); //$NON-NLS-1$ - IASTFunctionDefinition f = (IASTFunctionDefinition) tu - .getDeclarations()[0]; + IASTFunctionDefinition f = (IASTFunctionDefinition) tu.getDeclarations()[0]; IASTCompoundStatement body = (IASTCompoundStatement) f.getBody(); - final IASTDeclarationStatement statement = (IASTDeclarationStatement) body - .getStatements()[0]; - IASTSimpleDeclaration d = (IASTSimpleDeclaration) statement - .getDeclaration(); - IASTSimpleDeclSpecifier declSpec = (IASTSimpleDeclSpecifier) d - .getDeclSpecifier(); + final IASTDeclarationStatement statement = (IASTDeclarationStatement) body.getStatements()[0]; + IASTSimpleDeclaration d = (IASTSimpleDeclaration) statement.getDeclaration(); + IASTSimpleDeclSpecifier declSpec = (IASTSimpleDeclSpecifier) d.getDeclSpecifier(); assertEquals(IASTSimpleDeclSpecifier.t_int, declSpec.getType()); final IASTDeclarator[] declarators = d.getDeclarators(); assertEquals(declarators.length, 1); assertTrue(declarators[0] instanceof IASTArrayDeclarator); } - + public void testBug92980() throws Exception { String code = "struct A { A(); A(const A&) throw(1); ~A() throw(X); };"; //$NON-NLS-1$ parse(code, ParserLanguage.CPP, true, false); } - + // class Dummy { int v(); int d; }; // void Dummy::v(int){ d++; } public void testBug92882() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertTrue(col.getName(5).resolveBinding() instanceof IProblemBinding); ICPPField d1 = (ICPPField) col.getName(2).resolveBinding(); ICPPField d2 = (ICPPField) col.getName(7).resolveBinding(); assertSame(d1, d2); } - + // void f(int, int); // void f(int, int = 3); // void f(int = 2, int); @@ -4212,16 +4210,16 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction f1 = (IFunction) col.getName(0).resolveBinding(); assertInstances(col, f1, 5); } - + public void testBug90647() throws Exception { parse( "char msg[] = \"Syntax error on line %s\\n\";", ParserLanguage.CPP); //$NON-NLS-1$ } - + // int main(int argc, char **argv) // { // int sum=0; @@ -4241,7 +4239,7 @@ public class AST2CPPTests extends AST2BaseTest { tu.accept(col); assertNoProblemBindings(col); } - + // int main(int argc, char *argv[]) // { // unsigned long l = 0; @@ -4254,7 +4252,7 @@ public class AST2CPPTests extends AST2BaseTest { tu.accept(col); assertNoProblemBindings(col); } - + public void testBug83997() throws Exception { IASTTranslationUnit tu = parse( "namespace { int x; }", ParserLanguage.CPP); //$NON-NLS-1$ @@ -4262,32 +4260,7 @@ public class AST2CPPTests extends AST2BaseTest { tu.accept(col); assertNoProblemBindings(col); } - - protected void assertNoProblemBindings(CPPNameCollector col) { - Iterator i = col.nameList.iterator(); - while (i.hasNext()) { - IASTName n = (IASTName) i.next(); - assertFalse(n.resolveBinding() instanceof IProblemBinding); - } - } - - private void assertProblemBinding(int id, IBinding b) { - assertTrue(b instanceof IProblemBinding); - assertEquals(id, ((IProblemBinding) b).getID()); - } - protected void assertProblemBindings(CPPNameCollector col, int count) { - Iterator i = col.nameList.iterator(); - int sum = 0; - while (i.hasNext()) { - IASTName n = (IASTName) i.next(); - assertNotNull(n.resolveBinding()); - if (n.getBinding() instanceof IProblemBinding) - ++sum; - } - assertEquals(count, sum); - } - 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$ @@ -4295,7 +4268,7 @@ public class AST2CPPTests extends AST2BaseTest { tu.accept(nameResolver); assertNoProblemBindings(nameResolver); } - + // class C { // static const int n = 1; // static int arr[ n ]; @@ -4305,13 +4278,13 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPField n = (ICPPField) col.getName(1).resolveBinding(); assertTrue(n.isStatic()); - + assertInstances(col, n, 3); } - + // int a; // extern int b; // extern int c = 1; @@ -4330,7 +4303,7 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertTrue(col.getName(0).isDefinition()); // a assertFalse(col.getName(1).isDefinition()); // b assertTrue(col.getName(2).isDefinition()); // c @@ -4347,7 +4320,7 @@ public class AST2CPPTests extends AST2BaseTest { assertFalse(col.getName(15).isDefinition()); // g assertTrue(col.getName(18).isDefinition()); // pf } - + // int f(double); // int f(int); // int (&rfi)(int) = f; @@ -4356,39 +4329,38 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPFunction f1 = (ICPPFunction) col.getName(0).resolveBinding(); ICPPFunction f2 = (ICPPFunction) col.getName(2).resolveBinding(); - + assertSame(col.getName(6).resolveBinding(), f2); assertSame(col.getName(9).resolveBinding(), f1); } - + public void testBug95425() throws Exception { IASTTranslationUnit tu = parse("class A { A(); };", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType A = (ICPPClassType) col.getName(0).resolveBinding(); - ICPPConstructor ctor = (ICPPConstructor) col.getName(1) - .resolveBinding(); - + ICPPConstructor ctor = (ICPPConstructor) col.getName(1).resolveBinding(); + ICPPConstructor[] ctors = A.getConstructors(); 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$ col = new CPPNameCollector(); tu.accept(col); - + A = (ICPPClassType) col.getName(0).resolveBinding(); ctor = (ICPPConstructor) col.getName(1).resolveBinding(); - + ctors = A.getConstructors(); assertEquals(2, ctors.length); // one user declared constructor, one copy constructor assertSame(ctor, ctors[1]); } - + // void f(char *); // void g(){ // char x[100]; @@ -4398,11 +4370,11 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPFunction f1 = (ICPPFunction) col.getName(0).resolveBinding(); assertSame(f1, col.getName(4).resolveBinding()); } - + // class A { }; // int f() { // A * b = 0; @@ -4411,20 +4383,17 @@ public class AST2CPPTests extends AST2BaseTest { public void testAmbiguity() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); IASTSimpleDeclaration A = (IASTSimpleDeclaration) tu.getDeclarations()[0]; - IASTFunctionDefinition f = (IASTFunctionDefinition) tu - .getDeclarations()[1]; + IASTFunctionDefinition f = (IASTFunctionDefinition) tu.getDeclarations()[1]; IASTCompoundStatement body = (IASTCompoundStatement) f.getBody(); for (int i = 0; i < 2; ++i) { - IASTDeclarationStatement ds = (IASTDeclarationStatement) body - .getStatements()[i]; - String s1 = ((IASTNamedTypeSpecifier) ((IASTSimpleDeclaration) ds - .getDeclaration()).getDeclSpecifier()).getName().toString(); - String s2 = ((IASTCompositeTypeSpecifier) A.getDeclSpecifier()) - .getName().toString(); + IASTDeclarationStatement ds = (IASTDeclarationStatement) body.getStatements()[i]; + String s1 = ((IASTNamedTypeSpecifier) ((IASTSimpleDeclaration) ds.getDeclaration()) + .getDeclSpecifier()).getName().toString(); + String s2 = ((IASTCompositeTypeSpecifier) A.getDeclSpecifier()).getName().toString(); assertEquals(s1, s2); } } - + // struct A { // int a; // }; @@ -4443,19 +4412,19 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertEquals(col.size(), 26); - + ICPPClassType A = (ICPPClassType) col.getName(0).resolveBinding(); ICPPClassType B = (ICPPClassType) col.getName(2).resolveBinding(); - + assertNotNull(A); assertNotNull(B); - + assertInstances(col, A, 4); assertInstances(col, B, 4); } - + // class X { // public: // void f(int); @@ -4465,14 +4434,12 @@ public class AST2CPPTests extends AST2BaseTest { public void testBasicPointerToMember() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); assertEquals(tu.getDeclarations().length, 2); - IASTSimpleDeclaration p2m = (IASTSimpleDeclaration) tu - .getDeclarations()[1]; + IASTSimpleDeclaration p2m = (IASTSimpleDeclaration) tu.getDeclarations()[1]; IASTDeclarator d = p2m.getDeclarators()[0]; - ICPPASTPointerToMember po = (ICPPASTPointerToMember) d - .getPointerOperators()[0]; + ICPPASTPointerToMember po = (ICPPASTPointerToMember) d.getPointerOperators()[0]; assertEquals("X::", po.getName().toString()); //$NON-NLS-1$ } - + // struct B {}; // struct D : B {}; // void foo(D* dp) @@ -4481,46 +4448,46 @@ public class AST2CPPTests extends AST2BaseTest { // } public void testBug84466() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); - ICPPASTCastExpression dynamic_cast = (ICPPASTCastExpression) ((IASTEqualsInitializer) ((IASTSimpleDeclaration) ((IASTDeclarationStatement) ((IASTCompoundStatement) ((IASTFunctionDefinition) tu + ICPPASTCastExpression dynamic_cast = + (ICPPASTCastExpression) ((IASTEqualsInitializer) ((IASTSimpleDeclaration) ((IASTDeclarationStatement) ((IASTCompoundStatement) ((IASTFunctionDefinition) tu .getDeclarations()[2]).getBody()).getStatements()[0]) .getDeclaration()).getDeclarators()[0].getInitializer()) .getInitializerClause(); - + assertEquals(dynamic_cast.getOperator(), ICPPASTCastExpression.op_dynamic_cast); } - + public void testBug88338_CPP() throws Exception { IASTTranslationUnit tu = parse( "struct A; struct A* a;", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertTrue(col.getName(0).isDeclaration()); assertFalse(col.getName(0).isReference()); assertTrue(col.getName(1).isReference()); assertFalse(col.getName(1).isDeclaration()); - + tu = parse("struct A* a;", ParserLanguage.CPP); //$NON-NLS-1$ col = new CPPNameCollector(); tu.accept(col); - + assertTrue(col.getName(0).isDeclaration()); assertFalse(col.getName(0).isReference()); } - + public void testPointerToFunction_CPP() throws Exception { IASTTranslationUnit tu = parse("int (*pfi)();", ParserLanguage.CPP); //$NON-NLS-1$ assertEquals(tu.getDeclarations().length, 1); IASTSimpleDeclaration d = (IASTSimpleDeclaration) tu.getDeclarations()[0]; assertEquals(d.getDeclarators().length, 1); - IASTStandardFunctionDeclarator f = (IASTStandardFunctionDeclarator) d - .getDeclarators()[0]; + IASTStandardFunctionDeclarator f = (IASTStandardFunctionDeclarator) d.getDeclarators()[0]; assertEquals(f.getName().toString(), ""); //$NON-NLS-1$ assertNotNull(f.getNestedDeclarator()); assertEquals(f.getNestedDeclarator().getName().toString(), "pfi"); //$NON-NLS-1$ } - + // class X { public: int bar; }; // void f(){ // X a[10]; @@ -4530,11 +4497,11 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPField bar = (ICPPField) col.getName(1).resolveBinding(); assertSame(bar, col.getName(6).resolveBinding()); } - + // int strcmp(const char *); // void f(const char * const * argv){ // strcmp(*argv); @@ -4543,11 +4510,11 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPFunction strcmp = (ICPPFunction) col.getName(0).resolveBinding(); assertSame(strcmp, col.getName(4).resolveBinding()); } - + // class Other; // class Base { // public: Base(Other *); @@ -4558,12 +4525,12 @@ public class AST2CPPTests extends AST2BaseTest { // Sub::Sub(Other * b) : Base(b) {} public void testBug95673() throws Exception { BindingAssertionHelper ba= getAssertionHelper(); - + 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 f() { // char *x; int offset; @@ -4574,12 +4541,12 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPFunction mem = (ICPPFunction) col.getName(0).resolveBinding(); assertSame(mem, col.getName(6).resolveBinding()); assertSame(mem, col.getName(8).resolveBinding()); } - + // void trace(const void *); // class Foo { // public: int import(); @@ -4591,11 +4558,11 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPFunction trace = (ICPPFunction) col.getName(0).resolveBinding(); assertSame(trace, col.getName(7).resolveBinding()); } - + // class RTCharacter { // char value; // public: operator char (void) const; @@ -4607,11 +4574,11 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPMethod op = (ICPPMethod) col.getName(2).resolveBinding(); assertSame(op, col.getName(6).resolveBinding()); } - + // int str(const char *); // void f(){ // str(0); @@ -4621,13 +4588,13 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPFunction str = (ICPPFunction) col.getName(0).resolveBinding(); assertSame(str, col.getName(3).resolveBinding()); assertSame(str, col.getName(4).resolveBinding()); assertSame(str, col.getName(5).resolveBinding()); } - + // int str(bool); // enum { ONE }; // void f(char * p){ @@ -4638,26 +4605,26 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPFunction str = (ICPPFunction) col.getName(0).resolveBinding(); assertSame(str, col.getName(6).resolveBinding()); assertSame(str, col.getName(7).resolveBinding()); assertSame(str, col.getName(9).resolveBinding()); } - + // void f() { // char * value; // ::operator delete(value); // } public void testBug95786() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); - + CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertFalse(col.getName(2).resolveBinding() instanceof IProblemBinding); } - + // int foo() // try // { @@ -4670,19 +4637,19 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); assertEquals(tu.getDeclarations().length, 1); } - + // void f(int t){ // int s (t); // } public void testBug94779() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); - IASTDeclarationStatement ds = (IASTDeclarationStatement) ((IASTCompoundStatement) ((IASTFunctionDefinition) tu + IASTDeclarationStatement ds = + (IASTDeclarationStatement) ((IASTCompoundStatement) ((IASTFunctionDefinition) tu .getDeclarations()[0]).getBody()).getStatements()[0]; - IASTDeclarator d = ((IASTSimpleDeclaration) ds.getDeclaration()) - .getDeclarators()[0]; + IASTDeclarator d = ((IASTSimpleDeclaration) ds.getDeclaration()).getDeclarators()[0]; assertTrue(d.getName().resolveBinding() instanceof IVariable); } - + // int t= 0; // int s (t); public void testBug211756() throws Exception { @@ -4691,7 +4658,7 @@ public class AST2CPPTests extends AST2BaseTest { IASTDeclarator d = sd.getDeclarators()[0]; assertTrue(d.getName().resolveBinding() instanceof IVariable); } - + // typedef struct xs { // int state; // } xs; @@ -4703,24 +4670,24 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPField state = (ICPPField) col.getName(1).resolveBinding(); assertSame(state, col.getName(7).resolveBinding()); assertSame(state, col.getName(9).resolveBinding()); } - + // float _Complex x; // double _Complex y; public void testBug95757() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); IASTDeclaration[] decls = tu.getDeclarations(); - + assertTrue(((IASTSimpleDeclSpecifier)((IASTSimpleDeclaration)decls[0]).getDeclSpecifier()).isComplex()); assertEquals(((IASTSimpleDeclSpecifier)((IASTSimpleDeclaration)decls[0]).getDeclSpecifier()).getType(), IASTSimpleDeclSpecifier.t_float); assertTrue(((IASTSimpleDeclSpecifier)((IASTSimpleDeclaration)decls[1]).getDeclSpecifier()).isComplex()); assertEquals(((IASTSimpleDeclSpecifier)((IASTSimpleDeclaration)decls[1]).getDeclSpecifier()).getType(), IASTSimpleDeclSpecifier.t_double); } - + // class _A { // static int i; // }; @@ -4732,11 +4699,11 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPField i = (ICPPField) col.getName(1).resolveBinding(); assertSame(i, col.getName(7).resolveBinding()); } - + // int f() { // return 5; // } @@ -4751,7 +4718,7 @@ public class AST2CPPTests extends AST2BaseTest { tu.accept(col); assertNoProblemBindings(col); } - + // void copy(void *); // typedef struct {} A; // void f(A * a) { @@ -4761,15 +4728,15 @@ public class AST2CPPTests extends AST2BaseTest { 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()); } - + public void testBug96678() throws Exception { parse("int x; // comment \r\n", ParserLanguage.CPP, false, true); //$NON-NLS-1$ } - + // struct A {}; // void copy(A *); // void f() { @@ -4779,11 +4746,11 @@ public class AST2CPPTests extends AST2BaseTest { 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()); } - + // class A { // A(int i = 0); // }; @@ -4791,15 +4758,15 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType A = (ICPPClassType) col.getName(0).resolveBinding(); ICPPConstructor ctor = (ICPPConstructor) col.getName(1).resolveBinding(); - + ICPPConstructor [] cs = A.getConstructors(); assertTrue(cs.length == 2); assertSame(cs[1], ctor); } - + // class C { public: int foo; }; // class B { // C* operator ->(); @@ -4814,13 +4781,13 @@ public class AST2CPPTests extends AST2BaseTest { 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()); } - + // class A; // class A { // class B; @@ -4831,17 +4798,17 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPClassType A = (ICPPClassType) col.getName(0).resolveBinding(); ICPPClassType B = (ICPPClassType) col.getName(2).resolveBinding(); ICPPClassType C = (ICPPClassType) col.getName(3).resolveBinding(); - + ICPPClassType [] classes = A.getNestedClasses(); assertEquals(classes.length, 2); assertSame(classes[0], B); assertSame(classes[1], C); } - + // namespace A { // struct F {} f; // void f(int a) {} @@ -4850,7 +4817,7 @@ public class AST2CPPTests extends AST2BaseTest { 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); @@ -4858,26 +4825,26 @@ public class AST2CPPTests extends AST2BaseTest { 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); } - + // void f(); // void f(void) {} public void testBug_AIOOBE() throws Exception { 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()); IParameter p = (IParameter) col.getName(2).resolveBinding(); assertNotNull(p); } - + // void f(const int); // void f(int); // void g() { f(1); } @@ -4885,10 +4852,10 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertSame(col.getName(2).resolveBinding(), col.getName(5).resolveBinding()); } - + // void f(const volatile int); // void f(const int); // void g() { f(1); } @@ -4896,10 +4863,10 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertSame(col.getName(2).resolveBinding(), col.getName(5).resolveBinding()); } - + // void f(const int&); // void f(int&); // void g(const int&); @@ -4931,7 +4898,7 @@ public class AST2CPPTests extends AST2BaseTest { ICPPFunction h2= bh.assertNonProblem("h(int *)", 1); ICPPFunction i1= bh.assertNonProblem("i(int * const &)", 1); ICPPFunction i2= bh.assertNonProblem("i(const int *)", 1); - + ICPPFunction ref; ref= bh.assertNonProblem("f(ca)", 1); assertSame(f1, ref); @@ -4948,7 +4915,7 @@ public class AST2CPPTests extends AST2BaseTest { ref= bh.assertNonProblem("i(&a)", 1); assertSame(i1, ref); } - + // namespace n { // namespace m { // class A; @@ -4968,21 +4935,21 @@ public class AST2CPPTests extends AST2BaseTest { 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()); - + ICPPClassType A = (ICPPClassType) col.getName(2).resolveBinding(); assertSame(A, col.getName(5).resolveBinding()); - + ICPPMethod f = (ICPPMethod) col.getName(9).resolveBinding(); assertSame(f, col.getName(11).resolveBinding()); } - + // struct A { // struct { int i; } B; // struct { int j; } C; @@ -4995,17 +4962,17 @@ public class AST2CPPTests extends AST2BaseTest { 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()); } - + public void testBug99262() throws Exception { parse("void foo() {void *f; f=__null;}", ParserLanguage.CPP, true, true); //$NON-NLS-1$ } - + // void f1(int*) { // } // void f2() { @@ -5015,14 +4982,14 @@ public class AST2CPPTests extends AST2BaseTest { BindingAssertionHelper bh= getAssertionHelper(); bh.assertNonProblem("f1(__null", 2, ICPPFunction.class); } - + public void testBug100408() throws Exception { IASTTranslationUnit tu = parse("int foo() { int x=1; (x)*3; }", ParserLanguage.CPP); //$NON-NLS-1$ CPPNameCollector col = new CPPNameCollector(); 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$ CPPNameCollector col = new CPPNameCollector(); @@ -5036,7 +5003,7 @@ public class AST2CPPTests extends AST2BaseTest { tu.accept(col); assertNoProblemBindings(col); } - + // void f(){ // if (int x = 1) x++; // else x--; @@ -5050,22 +5017,22 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertNoProblemBindings(col); IVariable x = (IVariable) col.getName(1).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()); - + 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()); } - + // void free(void*); // void f(char** p) { // free(p); @@ -5074,11 +5041,11 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + IFunction free = (IFunction) col.getName(0).resolveBinding(); assertSame(free, col.getName(4).resolveBinding()); } - + // class X; // void f() { // class A { @@ -5094,13 +5061,13 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); CPPNameCollector col = new CPPNameCollector(); 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()); } - + // class m { // int m::f(); // }; @@ -5109,11 +5076,11 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + ICPPMethod f = (ICPPMethod) col.getName(3).resolveBinding(); assertSame(f, col.getName(6).resolveBinding()); } - + // struct A { // typedef int AT; // void f1(AT); @@ -5128,18 +5095,18 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); CPPNameCollector col = new CPPNameCollector(); 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()); } - + // struct Except { int blah; }; // void f() { // try { } @@ -5151,18 +5118,18 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); CPPNameCollector col = new CPPNameCollector(); 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()); } - + public void testBug78800() throws Exception { parseAndCheckBindings("class Matrix { public: Matrix & operator *(Matrix &); }; Matrix rotate, translate; Matrix transform = rotate * translate;"); //$NON-NLS-1$ } - + // struct U { static int i; }; // struct V : U { }; // struct W : U { using U::i; }; @@ -5174,16 +5141,16 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); CPPNameCollector col = new CPPNameCollector(); 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]); - + assertSame(i, col.getName(16).resolveBinding()); } - + // int f() { // int x = 4; while(x < 10) blah: ++x; // } @@ -5197,7 +5164,7 @@ public class AST2CPPTests extends AST2BaseTest { IASTExpressionStatement es = (IASTExpressionStatement) labelStmt.getNestedStatement(); assertTrue(es.getExpression() instanceof IASTUnaryExpression); } - + // int f() { // int i; // do { ++i; } while(i < 10); @@ -5209,7 +5176,7 @@ public class AST2CPPTests extends AST2BaseTest { IASTCompoundStatement body = (IASTCompoundStatement) f.getBody(); assertEquals(body.getStatements().length, 3); } - + public void testBug107150() throws Exception { StringBuffer buffer = new StringBuffer(); buffer.append("#define FUNC_PROTOTYPE_PARAMS(list) list\r\n"); //$NON-NLS-1$ @@ -5222,7 +5189,7 @@ public class AST2CPPTests extends AST2BaseTest { buffer.append("}\r\n"); //$NON-NLS-1$ IASTTranslationUnit tu = parse(buffer.toString(), ParserLanguage.CPP); assertFalse(tu.getDeclarations()[1] instanceof IASTProblemDeclaration); - + buffer = new StringBuffer(); buffer.append("#define FUNC_PROTOTYPE_PARAMS(list) list\n"); //$NON-NLS-1$ buffer.append("int func1 FUNC_PROTOTYPE_PARAMS((int arg1)){\n"); //$NON-NLS-1$ @@ -5235,7 +5202,7 @@ public class AST2CPPTests extends AST2BaseTest { tu = parse(buffer.toString(), ParserLanguage.CPP); assertFalse(tu.getDeclarations()[1] instanceof IASTProblemDeclaration); } - + // class __attribute__((visibility("default"))) FooClass // { // int foo(); @@ -5246,7 +5213,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testBug108202() throws Exception { parse(getAboveComment(), ParserLanguage.CPP, true, true); } - + // // Test redundant class specifiers // class MyClass { @@ -5256,11 +5223,11 @@ public class AST2CPPTests extends AST2BaseTest { // int MyClass::static_field; public void testBug174791() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); - + // check class IASTSimpleDeclaration sd = (IASTSimpleDeclaration) tu.getDeclarations()[0]; ICPPASTCompositeTypeSpecifier cts = (ICPPASTCompositeTypeSpecifier) sd.getDeclSpecifier(); - + IASTSimpleDeclaration md = (IASTSimpleDeclaration) cts.getMembers()[0]; IASTName name = md.getDeclarators()[0].getName(); IField field = (IField) name.resolveBinding(); @@ -5269,7 +5236,7 @@ public class AST2CPPTests extends AST2BaseTest { assertFalse(field.isExtern()); assertFalse(field.isAuto()); assertFalse(field.isRegister()); - + md = (IASTSimpleDeclaration) cts.getMembers()[1]; name = md.getDeclarators()[0].getName(); field = (IField) name.resolveBinding(); @@ -5278,14 +5245,14 @@ public class AST2CPPTests extends AST2BaseTest { assertFalse(field.isExtern()); assertFalse(field.isAuto()); assertFalse(field.isRegister()); - + // check real static defn sd = (IASTSimpleDeclaration) tu.getDeclarations()[1]; name = sd.getDeclarators()[0].getName(); field = (IField) name.resolveBinding(); assertTrue(field.isStatic()); } - + // namespace nsSplit {} // namespace nsSplit { // void a(); @@ -5294,7 +5261,7 @@ public class AST2CPPTests extends AST2BaseTest { // } public void testBug180979() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); - + // check class IASTFunctionDefinition fd = (IASTFunctionDefinition) tu.getDeclarations()[2]; IASTDeclarator fdecl= fd.getDeclarator(); @@ -5303,7 +5270,7 @@ public class AST2CPPTests extends AST2BaseTest { assertTrue(binding instanceof IFunction); assertFalse(binding instanceof IProblemBinding); } - + // #define _GLIBCXX_VISIBILITY(V) __attribute__ ((__visibility__ (#V))) // #define _GLIBCXX_BEGIN_NAMESPACE(X) namespace X _GLIBCXX_VISIBILITY(default) { // _GLIBCXX_BEGIN_NAMESPACE(std) @@ -5311,7 +5278,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testBug195701() throws Exception { parse(getAboveComment(), ParserLanguage.CPP, true, true); } - + // class A { // double operator*(const A&); // }; @@ -5322,14 +5289,14 @@ public class AST2CPPTests extends AST2BaseTest { public void testBug178059() throws Exception { 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))); public void testBug179712() throws Exception { parse(getAboveComment(), ParserLanguage.CPP, true, true); } - + // namespace outer { // namespace inner { // class foo{}; @@ -5341,7 +5308,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testAttributeInUsingDirective_351228() throws Exception { parseAndCheckBindings(); } - + // class C { // public: // int i; @@ -5374,31 +5341,31 @@ public class AST2CPPTests extends AST2BaseTest { // } public void testBug214335() throws Exception { BindingAssertionHelper bh= getAssertionHelper(); - + IBinding b00= bh.assertProblem("problem1(\"", 8); IBinding b01= bh.assertProblem("problem2(\"", 8); IBinding b02= bh.assertProblem("problem3(\"", 8); IBinding b03= bh.assertNonProblem("nonproblem1(\"", 11); IBinding b04= bh.assertProblem("problem4(\"", 8); IBinding b05= bh.assertProblem("problem5(\"", 8); - + IBinding b06= bh.assertProblem("problem1(ptm", 8); IBinding b07= bh.assertProblem("problem2(ptm", 8); IBinding b08= bh.assertProblem("problem3(ptm", 8); IBinding b09= bh.assertNonProblem("nonproblem1(ptm", 11); IBinding b10= bh.assertProblem("problem4(ptm", 8); IBinding b11= bh.assertProblem("problem5(ptm", 8); - + assertInstance(b03, ICPPFunction.class); assertInstance(b09, ICPPFunction.class); } - + // namespace source { // class cls { // }; // void fs(); // void fs(int a); - // + // // } // void test1() { // source::fs(); @@ -5416,29 +5383,29 @@ public class AST2CPPTests extends AST2BaseTest { // } public void testReferencesOfUsingDecls() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP, true, true); - + IASTDeclaration[] decls = tu.getDeclarations(); ICPPASTNamespaceDefinition nsdef= (ICPPASTNamespaceDefinition) decls[0]; ICPPASTUsingDeclaration udcl= (ICPPASTUsingDeclaration) decls[2]; ICPPASTUsingDeclaration udf= (ICPPASTUsingDeclaration) decls[3]; IASTFunctionDefinition fdef= (IASTFunctionDefinition) decls[4]; - + IASTDeclaration[] nsdecls= nsdef.getDeclarations(); ICPPASTCompositeTypeSpecifier cldef= (ICPPASTCompositeTypeSpecifier) ((IASTSimpleDeclaration) nsdecls[0]).getDeclSpecifier(); ICPPASTFunctionDeclarator fdecl1= (ICPPASTFunctionDeclarator) ((IASTSimpleDeclaration) nsdecls[1]).getDeclarators()[0]; ICPPASTFunctionDeclarator fdecl2= (ICPPASTFunctionDeclarator) ((IASTSimpleDeclaration) nsdecls[2]).getDeclarators()[0]; - + IASTStatement[] stmts= ((IASTCompoundStatement) fdef.getBody()).getStatements(); IASTName clname= ((IASTNamedTypeSpecifier) ((IASTSimpleDeclaration)((IASTDeclarationStatement) stmts[0]).getDeclaration()).getDeclSpecifier()).getName(); IASTName fnname1= ((IASTIdExpression) ((IASTFunctionCallExpression) ((IASTExpressionStatement) stmts[1]).getExpression()).getFunctionNameExpression()).getName(); IASTName fnname2= ((IASTIdExpression) ((IASTFunctionCallExpression) ((IASTExpressionStatement) stmts[2]).getExpression()).getFunctionNameExpression()).getName(); - + // check class IBinding b= cldef.getName().resolveBinding(); assertEquals(3, tu.getReferences(b).length); // 2 refs + using-decl assertEquals(1, tu.getDefinitionsInAST(b).length); // class-def assertEquals(2, tu.getDeclarationsInAST(b).length); // class-def + using-decl - + // check functions b= fdecl1.getName().resolveBinding(); assertEquals(3, tu.getReferences(b).length); // 2 refs + using-decl @@ -5448,27 +5415,27 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals(3, tu.getReferences(b).length); // 2 refs + using-decl assertEquals(0, tu.getDefinitionsInAST(b).length); // function is not defined assertEquals(2, tu.getDeclarationsInAST(b).length); // func-decl + using-decl - + // check using declaration class b= udcl.getName().resolveBinding(); assertEquals(3, tu.getReferences(b).length); // 2 refs + using-decl assertEquals(1, tu.getDefinitionsInAST(b).length); // class-def assertEquals(2, tu.getDeclarationsInAST(b).length); // class-def + using-decl - + // check using declaration function b= udf.getName().resolveBinding(); assertEquals(5, tu.getReferences(b).length); // 4 refs + using-decl assertEquals(0, tu.getDefinitionsInAST(b).length); // function is not defined assertEquals(3, tu.getDeclarationsInAST(b).length); // using-decl + 2 func-decls - + // check class reference b= clname.resolveBinding(); assertEquals(3, tu.getReferences(b).length); // 2 refs + using-decl assertEquals(1, tu.getDefinitionsInAST(b).length); // class-def assertEquals(2, tu.getDeclarationsInAST(b).length); // class-def + using-decl - + // check function references - b= fnname1.resolveBinding(); + b= fnname1.resolveBinding(); assertEquals(3, tu.getReferences(b).length); // 2 refs + using-decl assertEquals(0, tu.getDefinitionsInAST(b).length); // function is not defined assertEquals(2, tu.getDeclarationsInAST(b).length); // using-decl + func-decl @@ -5477,7 +5444,7 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals(0, tu.getDefinitionsInAST(b).length); // function is not defined assertEquals(2, tu.getDeclarationsInAST(b).length); // using-decl + func-decl } - + // namespace x { // int a; // } @@ -5492,11 +5459,11 @@ public class AST2CPPTests extends AST2BaseTest { // } public void testUsingDirectiveWithNestedClass_Bug209582() throws Exception { BindingAssertionHelper bh= getAssertionHelper(); - + IBinding b= bh.assertNonProblem("a=", 1); assertEquals("x", b.getScope().getScopeName().toString()); } - + // class Test { // public: // Test(int, int *) {} @@ -5511,12 +5478,12 @@ public class AST2CPPTests extends AST2BaseTest { // } public void testCastAmbiguity_Bug211756() throws Exception { BindingAssertionHelper bh= getAssertionHelper(); - + bh.assertNonProblem("foo1", 4); bh.assertNonProblem("foo2", 4); bh.assertNonProblem("foo3", 4); } - + // int foo2() { // int relayIndex = -1; // int numRelays = 0; @@ -5525,7 +5492,7 @@ public class AST2CPPTests extends AST2BaseTest { // } public void testTemplateIDAmbiguity_Bug104706() throws Exception { BindingAssertionHelper bh= getAssertionHelper(); - + bh.assertNonProblem("relayIndex <", 10); bh.assertNonProblem("relayIndex >", 10); bh.assertNonProblem("numRelays)", 9); @@ -5563,13 +5530,13 @@ public class AST2CPPTests extends AST2BaseTest { // } public void testScopeOfUsingDelegates_Bug219424() throws Exception { BindingAssertionHelper bh= getAssertionHelper(); - + bh.assertNonProblem("cl c", 2); bh.assertNonProblem("func(qualified)", 4); bh.assertNonProblem("func(unqualified)", 4); } - - + + // class Test { // void Test::member1(); // void Test::member2() {}; @@ -5580,7 +5547,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testQualifiedMemberDeclaration_Bug222026() throws Exception { final String code = getAboveComment(); BindingAssertionHelper bh= new BindingAssertionHelper(code, true); - + IBinding b= bh.assertNonProblem("member1", 7); IBinding b2= bh.assertNonProblem("member1(){", 7); assertTrue(b instanceof ICPPMethod); @@ -5588,7 +5555,7 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals("member1", m1.getName()); assertEquals("Test", m1.getScope().getScopeName().toString()); assertSame(b, b2); - + bh= new BindingAssertionHelper(code, true); b= bh.assertNonProblem("member2", 7); b2= bh.assertNonProblem("member2();", 7); @@ -5597,7 +5564,7 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals("member2", m1.getName()); assertEquals("Test", m1.getScope().getScopeName().toString()); assertSame(b, b2); - + // different resolution order bh= new BindingAssertionHelper(code, true); b2= bh.assertNonProblem("member1(){", 7); @@ -5607,7 +5574,7 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals("member1", m1.getName()); assertEquals("Test", m1.getScope().getScopeName().toString()); assertSame(b, b2); - + bh= new BindingAssertionHelper(code, true); b2= bh.assertNonProblem("member2();", 7); b= bh.assertNonProblem("member2", 7); @@ -5617,7 +5584,7 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals("Test", m1.getScope().getScopeName().toString()); assertSame(b, b2); } - + // namespace Test { // void Test::member1(); // void Test::member2() {}; @@ -5628,7 +5595,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testQualifiedMemberDeclarationInNamespace_Bug222026() throws Exception { final String code = getAboveComment(); BindingAssertionHelper bh= new BindingAssertionHelper(code, true); - + IBinding b= bh.assertNonProblem("member1", 7); IBinding b2= bh.assertNonProblem("member1(){", 7); assertTrue(b instanceof ICPPFunction); @@ -5636,7 +5603,7 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals("member1", m1.getName()); assertEquals("Test", m1.getScope().getScopeName().toString()); assertSame(b, b2); - + bh= new BindingAssertionHelper(code, true); b= bh.assertNonProblem("member2", 7); b2= bh.assertNonProblem("member2();", 7); @@ -5645,7 +5612,7 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals("member2", m1.getName()); assertEquals("Test", m1.getScope().getScopeName().toString()); assertSame(b, b2); - + // different resolution order bh= new BindingAssertionHelper(code, true); b2= bh.assertNonProblem("member1(){", 7); @@ -5655,7 +5622,7 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals("member1", m1.getName()); assertEquals("Test", m1.getScope().getScopeName().toString()); assertSame(b, b2); - + bh= new BindingAssertionHelper(code, true); b2= bh.assertNonProblem("member2();", 7); b= bh.assertNonProblem("member2", 7); @@ -5665,14 +5632,14 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals("Test", m1.getScope().getScopeName().toString()); assertSame(b, b2); } - + // namespace ns { typedef int ns::TINT; } // illegal, still no CCE is expected. public void testQualifiedTypedefs_Bug222093() throws Exception{ BindingAssertionHelper bh= getAssertionHelper(); IBinding td= bh.assertProblem("TINT", 4); bh.assertProblem("ns::", 2); } - + // void func() { // int a, b; // a < b || (a==b && a < b); @@ -5682,7 +5649,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testResettingTemplateIdScopesStack_Bug223777() throws Exception{ parseAndCheckBindings(getAboveComment()); } - + // long x= 10L; public void testLongLiteral_225534() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); @@ -5692,7 +5659,7 @@ public class AST2CPPTests extends AST2BaseTest { ICPPBasicType type= (ICPPBasicType) exp.getExpressionType(); assertTrue(type.isLong()); } - + // void foo/*_a*/(int x) {} // void foo/*_b*/(unsigned int) {} // void foo/*_c*/(short x) {} @@ -5734,10 +5701,10 @@ public class AST2CPPTests extends AST2BaseTest { // // foo/*i1*/(11.1F); // foo/*i2*/(11E1F); - // + // // foo/*j1*/(11.1); // foo/*j2*/(11.1E1); - // + // // foo/*k1*/(11.1L); // foo/*k2*/(11.1E1L); // } @@ -5752,7 +5719,7 @@ public class AST2CPPTests extends AST2BaseTest { } } } - + // class A { // public: // void doA() {} @@ -5788,7 +5755,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testBug235196() throws Exception { parseAndCheckBindings(getAboveComment()); } - + // typedef int tint; // class X { // typedef int xtint; @@ -5839,7 +5806,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testNewPlacement() throws Exception { IASTTranslationUnit tu= parseAndCheckBindings(getAboveComment()); IASTFunctionDefinition fdef= getDeclaration(tu, 3); - + checkNewExpression(fdef, 0, null, "int", null); checkNewExpression(fdef, 1, null, "int", IASTExpressionList.class); checkNewExpression(fdef, 2, null, "int", IASTIdExpression.class); @@ -5859,25 +5826,6 @@ public class AST2CPPTests extends AST2BaseTest { checkNewExpression(fdef, 15, IASTIdExpression.class, "int [][]", null); } - private void checkNewExpression(IASTFunctionDefinition fdef, int i_expr, Class placement, String type, Class init) { - IASTExpression expr; - ICPPASTNewExpression newExpr; - expr= getExpressionOfStatement(fdef, i_expr); - assertInstance(expr, ICPPASTNewExpression.class); - newExpr= (ICPPASTNewExpression) expr; - if (placement == null) { - assertNull(newExpr.getNewPlacement()); - } else { - assertInstance(newExpr.getNewPlacement(), placement); - } - if (init == null) { - assertNull(newExpr.getNewInitializer()); - } else { - assertInstance(newExpr.getNewInitializer(), init); - } - isTypeEqual(CPPVisitor.createType(newExpr.getTypeId()), type); - } - // namespace ns { // void test() {} // + @@ -5955,18 +5903,18 @@ public class AST2CPPTests extends AST2BaseTest { ICPPFunction pt2= ba.assertNonProblem("foo(this);/*2*/", 3, ICPPFunction.class); ICPPFunction pt3= ba.assertNonProblem("foo(this);/*3*/", 3, ICPPFunction.class); ICPPFunction pt4= ba.assertNonProblem("foo(this);/*4*/", 3, ICPPFunction.class); - + IType t1= ((IPointerType)pt1.getType().getParameterTypes()[0]).getType(); IQualifierType t2= (IQualifierType) ((IPointerType) pt2.getType().getParameterTypes()[0]).getType(); IQualifierType t3= (IQualifierType)((IPointerType) pt3.getType().getParameterTypes()[0]).getType(); IQualifierType t4= (IQualifierType)((IPointerType) pt4.getType().getParameterTypes()[0]).getType(); - + assertTrue(!(t1 instanceof IQualifierType)); assertTrue(t2.isConst()); assertTrue(!t2.isVolatile()); assertTrue(!t3.isConst()); assertTrue(t3.isVolatile()); assertTrue(t4.isConst()); assertTrue(t4.isVolatile()); } - + // class A { // public: // void foo() {} @@ -5983,7 +5931,7 @@ public class AST2CPPTests extends AST2BaseTest { ba.assertProblem("foo();/*1*/", 3); ba.assertNonProblem("foo();/*2*/", 3); } - + // class A { // public: // void foo() {}; @@ -6008,7 +5956,7 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals(m1.getClassOwner().getName(), "A"); assertEquals(m2.getClassOwner().getName(), "B"); } - + // class A { public: void foo(); }; // class B { public: A* operator->() {return new A();} }; // class C { public: B operator->() {return *new B();} }; @@ -6021,7 +5969,7 @@ public class AST2CPPTests extends AST2BaseTest { BindingAssertionHelper ba= getAssertionHelper(); ba.assertNonProblem("foo();/**/", 3); } - + // class A { public: void foo(); }; // class B { public: A* operator->() {return new A();} }; // class C { public: B* operator->() {return new B();} }; @@ -6034,7 +5982,7 @@ public class AST2CPPTests extends AST2BaseTest { BindingAssertionHelper ba= getAssertionHelper(); ba.assertProblem("foo();/**/", 3); } - + // class A { public: void foo(); }; // typedef A A2; // class B { public: A2* operator->() {return new A();} }; @@ -6050,7 +5998,7 @@ public class AST2CPPTests extends AST2BaseTest { BindingAssertionHelper ba= getAssertionHelper(); ba.assertNonProblem("foo();/**/", 3); } - + // namespace std {class type_info{public: const char* name() const;};} // int main() { // int s; @@ -6125,14 +6073,14 @@ public class AST2CPPTests extends AST2BaseTest { public void testTypeIdForPtrToMember_Bug242197() throws Exception { parseAndCheckBindings(getAboveComment(), ParserLanguage.CPP); } - + // void restrict(); public void testRestrictIsNoCPPKeyword_Bug228826() throws Exception { final String code = getAboveComment(); parseAndCheckBindings(code, ParserLanguage.CPP, false); parseAndCheckBindings(getAboveComment(), ParserLanguage.CPP, true); // even with gnu extensions } - + // void test1(); // void test2() throw (); // void test3() throw (int); @@ -6156,7 +6104,7 @@ public class AST2CPPTests extends AST2BaseTest { specs= fdtor.getExceptionSpecification(); assertEquals(1, specs.length); } - + // int test() { // try { // } catch (const int &ex) { @@ -6185,7 +6133,7 @@ public class AST2CPPTests extends AST2BaseTest { // const char& operator[](int pos) const; // char& operator[](int pos); // }; - // + // // void func(const char& c); // void func(char& c); // @@ -6199,7 +6147,7 @@ public class AST2CPPTests extends AST2BaseTest { ICPPFunction func2= helper.assertNonProblem("func(y[0])", 4, ICPPFunction.class); assertNotSame(func1, func2); } - + // class NonVirt { // void m();//0 // }; @@ -6217,7 +6165,7 @@ public class AST2CPPTests extends AST2BaseTest { // }; // class C5 : C1 { // void m();//5 - // }; + // }; public void testOverridden_248846() throws Exception { BindingAssertionHelper helper= getAssertionHelper(); ICPPMethod m0= helper.assertNonProblem("m();//0", 1, ICPPMethod.class); @@ -6226,14 +6174,14 @@ public class AST2CPPTests extends AST2BaseTest { ICPPMethod m3= helper.assertNonProblem("m(int);", 1, ICPPMethod.class); ICPPMethod m4= helper.assertNonProblem("m();//4", 1, ICPPMethod.class); ICPPMethod m5= helper.assertNonProblem("m();//5", 1, ICPPMethod.class); - + assertFalse(ClassTypeHelper.isVirtual(m0)); assertFalse(ClassTypeHelper.isVirtual(m3)); assertTrue(ClassTypeHelper.isVirtual(m1)); assertTrue(ClassTypeHelper.isVirtual(m2)); assertTrue(ClassTypeHelper.isVirtual(m4)); assertTrue(ClassTypeHelper.isVirtual(m5)); - + assertFalse(ClassTypeHelper.isOverrider(m0, m0)); assertFalse(ClassTypeHelper.isOverrider(m1, m0)); assertFalse(ClassTypeHelper.isOverrider(m2, m0)); @@ -6254,7 +6202,7 @@ public class AST2CPPTests extends AST2BaseTest { assertFalse(ClassTypeHelper.isOverrider(m3, m2)); assertFalse(ClassTypeHelper.isOverrider(m5, m2)); assertTrue(ClassTypeHelper.isOverrider(m4, m2)); - + ICPPMethod[] ors= ClassTypeHelper.findOverridden(m0); assertEquals(0, ors.length); ors= ClassTypeHelper.findOverridden(m1); @@ -6312,7 +6260,7 @@ public class AST2CPPTests extends AST2BaseTest { } // void f(); - // + // // void test(int p) { // f(p); // } @@ -6322,7 +6270,7 @@ public class AST2CPPTests extends AST2BaseTest { } // void f(...); - // + // // void test(int* p) { // f(p); // } @@ -6673,7 +6621,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testOverloadedUnaryOperator_259927_6() throws Exception { BindingAssertionHelper ba= getAssertionHelper(); for(int i = 1; i <=6; i++) - ba.assertNonProblem("xx; // "+i, 2, ICPPField.class); + ba.assertNonProblem("xx; // "+i, 2, ICPPField.class); } @@ -6722,7 +6670,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testFriendFunctionResolution_86368_1() throws Exception { final String code= getAboveComment(); parseAndCheckBindings(code); - + BindingAssertionHelper bh= new BindingAssertionHelper(code, true); IFunction f1= bh.assertNonProblem("f(int)", 1); IFunction f2= bh.assertNonProblem("f(1)", 1); @@ -6757,7 +6705,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testFriendFunctionResolution_86368_2() throws Exception { final String code= getAboveComment(); parseAndCheckBindings(code); - + BindingAssertionHelper bh= new BindingAssertionHelper(code, true); IFunction f1= bh.assertNonProblem("f(int)", 1); IFunction f2= bh.assertNonProblem("f('i')", 1); @@ -6803,7 +6751,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testMemberFunctionDisambiguationByCVness_238409() throws Exception { final String code= getAboveComment(); BindingAssertionHelper bh= new BindingAssertionHelper(code, true); - + ICPPMethod bar_cv= bh.assertNonProblem("bar();/*1*/", 3, ICPPMethod.class); ICPPMethod bar_v= bh.assertNonProblem("bar();/*2*/", 3, ICPPMethod.class); ICPPMethod bar_c= bh.assertNonProblem("bar();/*3*/", 3, ICPPMethod.class); @@ -6812,7 +6760,7 @@ public class AST2CPPTests extends AST2BaseTest { ICPPFunctionType bar_v_ft= bar_v.getType(); ICPPFunctionType bar_c_ft= bar_c.getType(); ICPPFunctionType bar_ft= bar.getType(); - + assertTrue(bar_cv_ft.isConst()); assertTrue(bar_cv_ft.isVolatile()); assertTrue(!bar_v_ft.isConst()); assertTrue(bar_v_ft.isVolatile()); assertTrue(bar_c_ft.isConst()); assertTrue(!bar_c_ft.isVolatile()); @@ -6826,7 +6774,7 @@ public class AST2CPPTests extends AST2BaseTest { bar_v_ft= bar_v.getType(); bar_c_ft= bar_c.getType(); bar_ft= bar.getType(); - + assertTrue(bar_cv_ft.isConst()); assertTrue(bar_cv_ft.isVolatile()); assertTrue(!bar_v_ft.isConst()); assertTrue(bar_v_ft.isVolatile()); assertTrue(bar_c_ft.isConst()); assertTrue(!bar_c_ft.isVolatile()); @@ -6863,7 +6811,7 @@ public class AST2CPPTests extends AST2BaseTest { final String code= getAboveComment(); parseAndCheckBindings(code); } - + // struct A {}; // A a(); // @@ -6923,7 +6871,7 @@ public class AST2CPPTests extends AST2BaseTest { ba.assertNonProblem("A*", 1, ICPPClassType.class); ba.assertNonProblem("a", 1, ICPPVariable.class); ba.assertNonProblem("B*", 1, ICPPVariable.class); - + parseAndCheckBindings(code, ParserLanguage.CPP); } @@ -6959,7 +6907,7 @@ public class AST2CPPTests extends AST2BaseTest { ba.assertNonProblem("fip(0)", 3, ICPPFunction.class); ba.assertNonProblem("fia(0)", 3, ICPPFunction.class); } - + // class cl {}; // typedef cl tl; // void reset(cl* ptr){}; @@ -6972,7 +6920,7 @@ public class AST2CPPTests extends AST2BaseTest { String code= getAboveComment(); parseAndCheckBindings(code, ParserLanguage.CPP); } - + // template class range { // public: // template range(const Range& r) {} @@ -6988,7 +6936,7 @@ public class AST2CPPTests extends AST2BaseTest { ba.assertNonProblem("onRange(ir)", 7); parseAndCheckBindings(code, ParserLanguage.CPP); } - + // typedef int * pi; // typedef int *const* pcpi; // typedef const pi* pcpi2; @@ -7009,10 +6957,10 @@ public class AST2CPPTests extends AST2BaseTest { IBinding ct1= ba.assertNonProblem("CT", 8); IBinding ct2= ba.assertNonProblem("CT", 9); assertSame(ct1, ct2); - + parseAndCheckBindings(code, ParserLanguage.CPP); } - + // class X { // public: // int f; @@ -7078,7 +7026,7 @@ public class AST2CPPTests extends AST2BaseTest { BindingAssertionHelper ba= getAssertionHelper(); ba.assertNonProblem("f(!p)", 1); } - + // class S { // S(int); // }; @@ -7094,7 +7042,7 @@ public class AST2CPPTests extends AST2BaseTest { final String code = getAboveComment(); parseAndCheckBindings(code, ParserLanguage.CPP); } - + // void f(char *(names[2])= 0); // void f2(const char *(n[])) { // if (n && 1){} @@ -7110,10 +7058,10 @@ public class AST2CPPTests extends AST2BaseTest { assertInstance(t, IPointerType.class); t= ((IPointerType) t).getType(); assertInstance(t, IBasicType.class); - + parseAndCheckBindings(code, ParserLanguage.CPP); } - + // class X { // virtual void pv() = 0; // void (*ptrToFunc) ()= 0; @@ -7134,7 +7082,7 @@ public class AST2CPPTests extends AST2BaseTest { parseAndCheckBindings(code, ParserLanguage.CPP); } - + // namespace ns { // struct S { // int a; @@ -7154,8 +7102,8 @@ public class AST2CPPTests extends AST2BaseTest { final String code = getAboveComment(); parseAndCheckBindings(code, ParserLanguage.CPP); } - - + + // struct A {int a;}; // // int foo(); @@ -7168,19 +7116,19 @@ public class AST2CPPTests extends AST2BaseTest { final String code = getAboveComment(); parseAndCheckBindings(code, ParserLanguage.CPP); } - + // void f(int volatile * const *) {} // void f(int const volatile * const *) {} // void test() { // int ** x; // f(x); // problem binding here // } - public void testRankingOfQualificationConversion_Bug269321() throws Exception { + public void testRankingOfQualificationConversion_Bug269321() throws Exception { final String code = getAboveComment(); parseAndCheckBindings(code, ParserLanguage.CPP); } - - + + // struct A { int a; }; // struct B { int b; }; // @@ -7203,8 +7151,8 @@ public class AST2CPPTests extends AST2BaseTest { ba.assertNonProblem("a; //2", 1, ICPPField.class); ba.assertNonProblem("b; //3", 1, ICPPField.class); } - - + + // struct A { int a; }; // struct X { // A operator+(X); @@ -7236,7 +7184,7 @@ public class AST2CPPTests extends AST2BaseTest { BindingAssertionHelper ba= getAssertionHelper(); ba.assertProblem("test(c)", 4); } - + // int foo(char * x); // int foo(wchar_t * x); @@ -7253,7 +7201,7 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu = parse(getAboveComment(), ParserLanguage.CPP); CPPNameCollector col = new CPPNameCollector(); tu.accept(col); - + assertSame(col.getName(0).resolveBinding(), col.getName(9).resolveBinding()); assertSame(col.getName(2).resolveBinding(), col.getName(10).resolveBinding()); assertSame(col.getName(4).resolveBinding(), col.getName(11).resolveBinding()); @@ -7270,7 +7218,7 @@ public class AST2CPPTests extends AST2BaseTest { BindingAssertionHelper ba= getAssertionHelper(); ba.assertNonProblem("A a;", 1, ICPPClassType.class); } - + // template class Moo; // bool getFile(Moo & res); public void testScopeOfClassFwdDecl_270831() throws Exception { @@ -7279,7 +7227,7 @@ public class AST2CPPTests extends AST2BaseTest { IScope scope= t.getScope(); assertEquals(EScopeKind.eGlobal, scope.getKind()); } - + // class C {}; // class D : public C {}; // class E { @@ -7307,7 +7255,7 @@ public class AST2CPPTests extends AST2BaseTest { parseAndCheckBindings(code, ParserLanguage.CPP); } - + // int foo(int x); // int bar(int x); // @@ -7341,8 +7289,8 @@ public class AST2CPPTests extends AST2BaseTest { ICPPField[] fields= c.getDeclaredFields(); assertEquals(1, fields.length); assertEquals("s", fields[0].getName()); - } - + } + // class C3 { // C3(int); // }; @@ -7353,7 +7301,7 @@ public class AST2CPPTests extends AST2BaseTest { final String code = getAboveComment(); parseAndCheckBindings(code, ParserLanguage.CPP); } - + // template class Compare { // Compare(); // ~Compare(); @@ -7365,7 +7313,7 @@ public class AST2CPPTests extends AST2BaseTest { final String code = getAboveComment(); parseAndCheckBindings(code, ParserLanguage.CPP); } - + // class IBase { // public: // virtual void base() = 0; @@ -7395,7 +7343,7 @@ public class AST2CPPTests extends AST2BaseTest { final String code = getAboveComment(); parseAndCheckBindings(code, ParserLanguage.CPP); } - + // class C { // C& operator()() {return *this;} // }; @@ -7465,7 +7413,7 @@ public class AST2CPPTests extends AST2BaseTest { BindingAssertionHelper ba= getAssertionHelper(); ba.assertProblem("enum_name", 9); } - + // class CL { // typedef int x; // friend void test() { @@ -7475,7 +7423,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testLookupFromInlineFriend_284690() throws Exception { parseAndCheckBindings(getAboveComment(), ParserLanguage.CPP); } - + // class XInterface {}; // class OWeakObject : public XInterface{}; // class XTypeProvider : public XInterface{}; @@ -7492,7 +7440,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testTypeLookupWithMultipleInheritance_286213() throws Exception { parseAndCheckBindings(getAboveComment(), ParserLanguage.CPP); } - + // int v1; // static int v2; // extern int v3; @@ -7533,33 +7481,6 @@ public class AST2CPPTests extends AST2BaseTest { checkDeclDef(declNames, defNames, cls.getMembers()); } - private void checkDeclDef(String[] declNames, String[] defNames, IASTDeclaration[] decls) { - int i= 0, j= 0; - for (IASTDeclaration decl : decls) { - if (decl instanceof ICPPASTLinkageSpecification) { - decl= ((ICPPASTLinkageSpecification) decl).getDeclarations()[0]; - } - final IASTDeclarator[] dtors = ((IASTSimpleDeclaration) decl).getDeclarators(); - for (IASTDeclarator dtor : dtors) { - final String name = dtor.getName().toString(); - switch (dtor.getRoleForName(dtor.getName())) { - case IASTNameOwner.r_declaration: - assertTrue("Unexpected decl " + name, i < declNames.length); - assertEquals(declNames[i++], name); - break; - case IASTNameOwner.r_definition: - assertTrue("Unexpected decl " + name, j < defNames.length); - assertEquals(defNames[j++], name); - break; - default: - assertTrue(name, false); - } - } - } - assertEquals(declNames.length, i); - assertEquals(defNames.length, j); - } - // class X { // struct S* m1; // struct T; @@ -7598,7 +7519,7 @@ public class AST2CPPTests extends AST2BaseTest { IASTImplicitNameOwner expr= (IASTImplicitNameOwner) rstmt.getReturnValue(); assertEquals(0, expr.getImplicitNames().length); } - + // class Test { // template void t() {} // inline void t(); @@ -7614,7 +7535,7 @@ public class AST2CPPTests extends AST2BaseTest { ICPPMethod m= bh.assertNonProblem("t<1>", 1); assertTrue(m.isInline()); } - + // class B {}; // class A { // public: @@ -7635,7 +7556,7 @@ public class AST2CPPTests extends AST2BaseTest { final String code = getAboveComment(); parseAndCheckBindings(code, ParserLanguage.CPP); } - + // class From {}; // class To1 { // public: @@ -7663,7 +7584,7 @@ public class AST2CPPTests extends AST2BaseTest { final String code = getAboveComment(); parseAndCheckBindings(code, ParserLanguage.CPP); } - + // class A {}; // class B : public A {}; // @@ -7686,7 +7607,7 @@ public class AST2CPPTests extends AST2BaseTest { bh.assertNonProblem("foo(c);", 3); bh.assertProblem("foo(cc);", 3); } - + // class ULONGLONG { // public : // ULONGLONG (unsigned long long val) {} @@ -7704,7 +7625,7 @@ public class AST2CPPTests extends AST2BaseTest { IASTImplicitNameOwner no= (IASTImplicitNameOwner) stmt.getReturnValue(); assertEquals(0, no.getImplicitNames().length); } - + // typedef int Fixed_Array[20]; // void f(const ::Fixed_Array message) {} // @@ -7716,7 +7637,7 @@ public class AST2CPPTests extends AST2BaseTest { final String code = getAboveComment(); parseAndCheckBindings(code, ParserLanguage.CPP); } - + // template struct CT { // CT(int) {} // }; @@ -7735,7 +7656,7 @@ public class AST2CPPTests extends AST2BaseTest { bh.assertNonProblem("B>(1)", 1); parseAndCheckBindings(code, ParserLanguage.CPP); } - + // namespace ns { // enum E { e1, e2 }; // E operator|(E __a, E __b) { return e1; } @@ -7781,7 +7702,7 @@ public class AST2CPPTests extends AST2BaseTest { assertNotNull(methodTemplate.getType()); assertEquals(1, methodTemplate.getParameters().length); } - + // void x(const char (&)[1]) {}; // // typedef char Array[12]; @@ -7798,8 +7719,8 @@ public class AST2CPPTests extends AST2BaseTest { public void testCVQualifiersWithArrays_293982() throws Exception { final String code = getAboveComment(); parseAndCheckBindings(code, ParserLanguage.CPP); - } - + } + // template char (&func(T (&array)[N]))[N]; // void f(const int (&a)[1]) {} // typedef int TA[]; @@ -7813,8 +7734,8 @@ public class AST2CPPTests extends AST2BaseTest { public void testArrayTypeSizeFromInitializer_294144() throws Exception { final String code = getAboveComment(); parseAndCheckBindings(code, ParserLanguage.CPP); - } - + } + // struct A { // template void m() { // C c; @@ -7823,9 +7744,9 @@ public class AST2CPPTests extends AST2BaseTest { // }; public void testLookupInClassScopeForTemplateIDs_294904() throws Exception { final String code = getAboveComment(); - parseAndCheckBindings(code, ParserLanguage.CPP); + parseAndCheckBindings(code, ParserLanguage.CPP); } - + // template char (&func(T (&array)[N]))[N]; // struct A { // static int array[]; @@ -7837,18 +7758,18 @@ public class AST2CPPTests extends AST2BaseTest { // } public void testCompleteArrayTypeWithIncompleteDeclaration_294144() throws Exception { final String code = getAboveComment(); - parseAndCheckBindings(code, ParserLanguage.CPP); + parseAndCheckBindings(code, ParserLanguage.CPP); } - + // void test() { // int x,y; // return y < x ? -1 : y > x ? 1 : 0; // } public void testSyntax1_295064() throws Exception { final String code = getAboveComment(); - parseAndCheckBindings(code, ParserLanguage.CPP); + parseAndCheckBindings(code, ParserLanguage.CPP); } - + // typedef int TInt; // template class CT { // CT(TInt); @@ -7856,7 +7777,7 @@ public class AST2CPPTests extends AST2BaseTest { // template inline CT::CT(TInt) {} public void testSyntax2_295064() throws Exception { final String code = getAboveComment(); - parseAndCheckBindings(code, ParserLanguage.CPP); + parseAndCheckBindings(code, ParserLanguage.CPP); } // const unsigned int EIGHT= 8; @@ -7876,7 +7797,7 @@ public class AST2CPPTests extends AST2BaseTest { final String code= getAboveComment(); parseAndCheckBindings(code, ParserLanguage.CPP); } - + // struct A {}; // // void foo(const A&); // #1 @@ -7942,7 +7863,7 @@ public class AST2CPPTests extends AST2BaseTest { b= bh.assertNonProblem("foo(source_const_rvalue_ref())", 3); assertSame(b, foo1); } - + // int i; // typedef int& LRI; @@ -7967,7 +7888,7 @@ public class AST2CPPTests extends AST2BaseTest { v= bh.assertNonProblem("r5", 2); assertEquals("int &&", ASTTypeUtil.getType(v.getType())); } - + // void dref(double&); // void drref(double&&); // void cdref(const double&); @@ -7985,7 +7906,7 @@ public class AST2CPPTests extends AST2BaseTest { // double d = 2.0; // const volatile double cvd = 1; // int i = 2; - // dref(d); + // dref(d); // cdref(d); // aref(b); // caref(b); @@ -8028,7 +7949,7 @@ public class AST2CPPTests extends AST2BaseTest { final String code= getAboveComment(); parseAndCheckBindings(code, ParserLanguage.CPP); } - + // template struct enable_if_same {}; // template struct enable_if_same { // typedef char type; @@ -8078,7 +7999,7 @@ public class AST2CPPTests extends AST2BaseTest { // sink3(source()); // sink3(csource()); // sink3(z7); - + // } public void testInitOfClassObjectsByRValues_294730() throws Exception { final CharSequence[] contents = getContents(3); @@ -8110,7 +8031,7 @@ public class AST2CPPTests extends AST2BaseTest { String code= getAboveComment(); parseAndCheckBindings(code, ParserLanguage.CPP); } - + // namespace ns { // struct A{}; // void f(ns::A, char) {} @@ -8128,14 +8049,14 @@ public class AST2CPPTests extends AST2BaseTest { BindingAssertionHelper bh= new BindingAssertionHelper(code, true); IFunction inns= bh.assertNonProblem("f(ns::A, char)", 1); IFunction glob= bh.assertNonProblem("f(ns::A, int)", 1); - + IBinding b= bh.assertNonProblem("f(a, '1')", 1); assertSame(b, inns); - + b= bh.assertNonProblem("f(a, 1)", 1); assertSame(b, glob); } - + // const int&& foo(); // int i; // struct A { double x; }; @@ -8171,7 +8092,7 @@ public class AST2CPPTests extends AST2BaseTest { f= bh.assertNonProblem("t8", 2); assertEquals("const double", ASTTypeUtil.getType(f.getType().getReturnType())); } - + // typedef int TInt; // void test() { // int a1= {}, a2{}; // Initializer for declarator @@ -8243,7 +8164,7 @@ public class AST2CPPTests extends AST2BaseTest { String code= getAboveComment(); parseAndCheckBindings(code, ParserLanguage.CPP); } - + // namespace std { // template class initializer_list; // } @@ -8271,7 +8192,7 @@ public class AST2CPPTests extends AST2BaseTest { bh.assertProblem("f({1.0})", 1); bh.assertNonProblem("g({ \"foo\", \"bar\" })", 1); } - + // namespace std { // template class initializer_list; // } @@ -8344,7 +8265,7 @@ public class AST2CPPTests extends AST2BaseTest { // not detected by CDT // bh.assertProblem("f({1.0})", 1); } - + // namespace std { // template class initializer_list; // } @@ -8387,7 +8308,7 @@ public class AST2CPPTests extends AST2BaseTest { // // fG(1); // G(1) // fG({1}); // G(1) - // + // // new H(1); // H(G(1)) // new H({1}); // H(G(1)) or H(H(G(1))) // fH(1); // no conversion from int to H @@ -8475,10 +8396,10 @@ public class AST2CPPTests extends AST2BaseTest { public void testNewFunctionDeclaratorSyntax_305972() throws Exception { String code= getAboveComment(); BindingAssertionHelper bh= new BindingAssertionHelper(code, true); - + ICPPFunction f= bh.assertNonProblem("fpif1", 0); assertEquals("int (* (int))(int)", ASTTypeUtil.getType(f.getType())); - + f= bh.assertNonProblem("fpif2", 0); assertEquals("int (* (int))(int)", ASTTypeUtil.getType(f.getType())); } @@ -8492,7 +8413,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testScopedEnums_305975a() throws Exception { String code= getAboveComment(); BindingAssertionHelper bh= new BindingAssertionHelper(code, true); - + ICPPEnumeration e; ICPPBinding ei; e= bh.assertNonProblem("EScoped1", 0); @@ -8502,7 +8423,7 @@ public class AST2CPPTests extends AST2BaseTest { ei= bh.assertNonProblem("a1", 0); assertSame(e, ei.getOwner()); assertEquals(2, ei.getQualifiedName().length); - + e= bh.assertNonProblem("EScoped2", 0); assertTrue(e.isScoped()); assertEquals("short int", ASTTypeUtil.getType(e.getFixedType())); @@ -8510,7 +8431,7 @@ public class AST2CPPTests extends AST2BaseTest { ei= bh.assertNonProblem("a2", 0); assertSame(e, ei.getOwner()); assertEquals(2, ei.getQualifiedName().length); - + e= bh.assertNonProblem("EScoped3", 0); assertTrue(e.isScoped()); assertEquals("int", ASTTypeUtil.getType(e.getFixedType())); @@ -8538,14 +8459,6 @@ public class AST2CPPTests extends AST2BaseTest { assertDeclaration(e); } - private void assertDefinition(ICPPBinding b) { - assertTrue(((IASTName)((ICPPInternalBinding) b).getDefinition()).isDefinition()); - } - - private void assertDeclaration(ICPPBinding b) { - assertTrue(((IASTName)((ICPPInternalBinding) b).getDeclarations()[0]).isDeclaration()); - } - // enum class E { a, b }; // enum E x1 = E::a; // OK // enum F { a, b }; @@ -8583,7 +8496,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testScopedEnums_305975d() throws Exception { String code= getAboveComment(); BindingAssertionHelper bh= new BindingAssertionHelper(code, true); - + bh.assertNonProblem("fCol(Col::red)", 4); bh.assertProblem("fint(Col::red)", 4); bh.assertProblem("fbool(Col::red)", 5); @@ -8629,7 +8542,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testScopedEnums_305975f() throws Exception { String code= getAboveComment(); BindingAssertionHelper bh= new BindingAssertionHelper(code, true); - + bh.assertProblem("high;", -1); bh.assertProblem("xdir d", -2); bh.assertProblem("xl;", -1); @@ -8657,7 +8570,7 @@ public class AST2CPPTests extends AST2BaseTest { String code= getAboveComment(); parseAndCheckBindings(code); } - + // void f(int); // void f(unsigned int); // void test() { @@ -8676,7 +8589,7 @@ public class AST2CPPTests extends AST2BaseTest { b= bh.assertNonProblem("f(c32)", 1); assertSame(f2, b); } - + // int test() { // void (11); // return 42; @@ -8684,16 +8597,16 @@ public class AST2CPPTests extends AST2BaseTest { public void testCastToVoid_309155() throws Exception { String code= getAboveComment(); parseAndCheckBindings(code); - } - + } + // void test() { // void *libHandle (0); // } public void testCTorInitializerForVoidPtr_314113() throws Exception { String code= getAboveComment(); parseAndCheckBindings(code); - } - + } + // struct D {}; // struct C { // operator D(); @@ -8713,8 +8626,8 @@ public class AST2CPPTests extends AST2BaseTest { IFunction fint= bh.assertNonProblem("f(int)", 1); IFunction f= bh.assertNonProblem("f(c+1)", 1); assertSame(fint, f); - } - + } + // struct A { // operator long& (); // }; @@ -8732,10 +8645,10 @@ public class AST2CPPTests extends AST2BaseTest { IFunction f= bh.assertNonProblem("f(a= 1)", 1); assertSame(fA, f); } - - - - + + + + // struct X {}; // struct Y : X {}; // struct A { @@ -8752,24 +8665,24 @@ public class AST2CPPTests extends AST2BaseTest { ICPPMethod m1= helper.assertNonProblem("m(X*);//1", 1, ICPPMethod.class); ICPPMethod m2= helper.assertNonProblem("m();//2", 1, ICPPMethod.class); ICPPMethod m3= helper.assertNonProblem("m(Y*);//3", 1, ICPPMethod.class); - + assertTrue(ClassTypeHelper.isVirtual(m0)); assertTrue(ClassTypeHelper.isVirtual(m1)); assertTrue(ClassTypeHelper.isVirtual(m2)); assertFalse(ClassTypeHelper.isVirtual(m3)); - + assertFalse(ClassTypeHelper.isOverrider(m0, m0)); assertFalse(ClassTypeHelper.isOverrider(m0, m1)); - + assertFalse(ClassTypeHelper.isOverrider(m1, m0)); assertFalse(ClassTypeHelper.isOverrider(m1, m1)); - + assertTrue(ClassTypeHelper.isOverrider(m2, m0)); assertFalse(ClassTypeHelper.isOverrider(m2, m1)); - + assertFalse(ClassTypeHelper.isOverrider(m3, m0)); assertFalse(ClassTypeHelper.isOverrider(m3, m1)); - + ICPPMethod[] ors= ClassTypeHelper.findOverridden(m0); assertEquals(0, ors.length); ors= ClassTypeHelper.findOverridden(m1); @@ -8780,7 +8693,7 @@ public class AST2CPPTests extends AST2BaseTest { ors= ClassTypeHelper.findOverridden(m3); assertEquals(0, ors.length); } - + // struct X { // X(); // }; @@ -8790,11 +8703,11 @@ public class AST2CPPTests extends AST2BaseTest { public void testDefaultedAndDeletedFunctions_305978() throws Exception { String code= getAboveComment(); IASTTranslationUnit tu= parseAndCheckBindings(code); - + ICPPASTFunctionDefinition f= getDeclaration(tu, 1); assertTrue(f.isDefaulted()); assertFalse(f.isDeleted()); - + f= getDeclaration(tu, 2); assertFalse(f.isDefaulted()); assertTrue(f.isDeleted()); @@ -8802,7 +8715,7 @@ public class AST2CPPTests extends AST2BaseTest { f= getDeclaration(tu, 3); assertFalse(f.isDefaulted()); assertTrue(f.isDeleted()); - + BindingAssertionHelper bh= new BindingAssertionHelper(code, true); ICPPFunction fb= bh.assertNonProblem("X() =", 1); assertFalse(fb.isDeleted()); @@ -8813,14 +8726,14 @@ public class AST2CPPTests extends AST2BaseTest { fb= bh.assertNonProblem("g()", 1); assertTrue(fb.isDeleted()); } - + // const int b=12; // void f(int a= b) = delete ; public void testDefaultedAndDeletedFunctions_305978b() throws Exception { String code= getAboveComment(); parseAndCheckBindings(code); } - + // namespace ns { // struct S {}; // } @@ -8861,7 +8774,7 @@ public class AST2CPPTests extends AST2BaseTest { String code= getAboveComment(); parseAndCheckBindings(code); } - + // namespace ns { // inline namespace m { // int a; @@ -8875,7 +8788,7 @@ public class AST2CPPTests extends AST2BaseTest { String code= getAboveComment(); parseAndCheckBindings(code); } - + // namespace out { // void f(int); // } @@ -8901,7 +8814,7 @@ public class AST2CPPTests extends AST2BaseTest { IFunction fo= bh.assertNonProblem("f(int)", 1); IFunction g= bh.assertNonProblem("g(int)", 1); IFunction fi= bh.assertNonProblem("f(char)", 1); - + IFunction ref= bh.assertNonProblem("f(1)", 1); assertSame(fi, ref); ref= bh.assertNonProblem("g(1)", 1); @@ -8923,7 +8836,7 @@ public class AST2CPPTests extends AST2BaseTest { IFunction f2= bh.assertNonProblem("f() {", 1); assertSame(f1, f2); } - + // struct C { // void test() { // int a; @@ -8950,7 +8863,7 @@ public class AST2CPPTests extends AST2BaseTest { parseAndCheckBindings(code); } - + // template void sort(T from, T to, C compare) {} // float abs(float f); // @@ -8963,7 +8876,7 @@ public class AST2CPPTests extends AST2BaseTest { String code= getAboveComment(); parseAndCheckBindings(code); } - + // typedef int MyType; // // void f(const MyType& val); @@ -8979,7 +8892,7 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals("MyType &", ASTTypeUtil.getType(g.getType().getParameterTypes()[0], false)); assertEquals("int &", ASTTypeUtil.getType(g.getType().getParameterTypes()[0], true)); } - + // class container { // public: // void constBegin() const; @@ -8998,7 +8911,7 @@ public class AST2CPPTests extends AST2BaseTest { IFunction f= bh.assertNonProblem("constBegin(); //ref", 10); bh.assertProblem("begin(); //ref", 5); } - + // template class PE { // explicit operator bool() const; // }; @@ -9018,7 +8931,7 @@ public class AST2CPPTests extends AST2BaseTest { bh.assertProblem("fint(pe + pe);", 4); bh.assertNonProblem("fint(p + p);", 4); } - + // struct C { // C(const C& c) {} // }; @@ -9039,26 +8952,26 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals(1, names.length); assertTrue(names[0].resolveBinding() instanceof ICPPConstructor); } - + // void g(char *); // void f(char *); // void f(const char *); // void testa() { // f("abc"); - // g("abc"); + // g("abc"); // } public void testRankingOfDeprecatedConversionOnStringLiteral() throws Exception { String code= getAboveComment(); BindingAssertionHelper bh= new BindingAssertionHelper(code, true); IFunction g= bh.assertNonProblem("g(char *)", 1); IFunction fconst= bh.assertNonProblem("f(const char *)", 1); - + IBinding ref= bh.assertNonProblem("f(\"abc\")", 1); assertSame(fconst, ref); ref= bh.assertNonProblem("g(\"abc\")", 1); assertSame(g, ref); } - + // struct A { // int m; // }; @@ -9078,7 +8991,7 @@ public class AST2CPPTests extends AST2BaseTest { IASTTranslationUnit tu= parseAndCheckBindings(code); ICPPASTFunctionDefinition fdef= getDeclaration(tu, 5); IASTExpression expr; - + expr= getExpressionOfStatement(fdef, 0); assertEquals(XVALUE, expr.getValueCategory()); assertEquals("A", ASTTypeUtil.getType(expr.getExpressionType())); @@ -9100,7 +9013,7 @@ public class AST2CPPTests extends AST2BaseTest { assertEquals(LVALUE, expr.getValueCategory()); assertEquals("A", ASTTypeUtil.getType(expr.getExpressionType())); } - + // void f() { // int i; // int f1(); @@ -9116,7 +9029,7 @@ public class AST2CPPTests extends AST2BaseTest { BindingAssertionHelper bh= new BindingAssertionHelper(code, true); IFunction g1= bh.assertNonProblem("g(const int&)", 1); IFunction g2= bh.assertNonProblem("g(const int&&)", 1); - + IFunction ref; ref= bh.assertNonProblem("g(i);", 1); assertSame(g1, ref); @@ -9125,7 +9038,7 @@ public class AST2CPPTests extends AST2BaseTest { ref= bh.assertNonProblem("g(f2());", 1); assertSame(g2, ref); } - + // namespace std { // template class initializer_list; // } @@ -9143,7 +9056,7 @@ public class AST2CPPTests extends AST2BaseTest { IFunction ctor1= bh.assertNonProblem("S(std::initializer_list);", 1); IFunction ctor2= bh.assertNonProblem("S(std::initializer_list);", 1); IFunction ctor3= bh.assertNonProblem("S();", 1); - + IASTName name; IASTImplicitNameOwner dtor; name= bh.findName("s1", 2); @@ -9156,7 +9069,7 @@ public class AST2CPPTests extends AST2BaseTest { dtor= (IASTImplicitNameOwner) name.getParent(); assertSame(ctor3, dtor.getImplicitNames()[0].resolveBinding()); } - + // namespace A { // inline namespace B { // namespace C { @@ -9170,7 +9083,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testInlineNamespaceLookup_324096() throws Exception { parseAndCheckBindings(); } - + // struct C { // operator int(); // }; @@ -9186,7 +9099,7 @@ public class AST2CPPTests extends AST2BaseTest { IBinding ref= bh.assertNonProblem("f(true ? c : 1)", 1); assertSame(f, ref); } - + // void f(char*); // void f(const char*); // void g(char*); @@ -9205,7 +9118,7 @@ public class AST2CPPTests extends AST2BaseTest { assertSame(fc, ref); bh.assertNonProblem("g(0 ? p : \"\")", 1); // } - + // struct C { // C(); // C(int a, int b); @@ -9221,7 +9134,7 @@ public class AST2CPPTests extends AST2BaseTest { BindingAssertionHelper bh= new BindingAssertionHelper(code, true); IFunction ctor1= bh.assertNonProblem("C();", 1); IFunction ctor2= bh.assertNonProblem("C(int a, int b);", 1); - + IASTName name; IASTImplicitNameOwner dtor; name= bh.findName("c1", 2); @@ -9258,7 +9171,7 @@ public class AST2CPPTests extends AST2BaseTest { ref= bh.assertNonProblem("g(&number)", 1); assertSame(g, ref); } - + // void f(int * __restrict* a) {} // void f(int ** a) {} // different function // @@ -9279,7 +9192,7 @@ public class AST2CPPTests extends AST2BaseTest { ref= bh.assertNonProblem("f(&number)", 1); assertSame(f2, ref); } - + // struct S { // class C {}; // }; @@ -9288,7 +9201,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testCVQualifiedClassName_328063() throws Exception { parseAndCheckBindings(); } - + // void test() { // int array[5] = { 1, 2, 3, 4, 5 }; // for (int& x : array) @@ -9297,7 +9210,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testRangeBasedForLoop_327223() throws Exception { parseAndCheckBindings(); } - + // struct A{}; // struct B : A {}; // struct C { @@ -9315,7 +9228,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testOverrideUsingDeclaredMethod_328802() throws Exception { parseAndCheckBindings(); } - + // class A { // A(int a = f()); // problem on f // static int f(); @@ -9323,7 +9236,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testFwdLookupForDefaultArgument() throws Exception { parseAndCheckBindings(); } - + // auto f2 (); // missing late return type. public void testBug332114a() throws Exception { BindingAssertionHelper bh= new BindingAssertionHelper(getAboveComment(), true); @@ -9331,7 +9244,7 @@ public class AST2CPPTests extends AST2BaseTest { // Must not throw a NPE IndexCPPSignatureUtil.getSignature(b); } - + // enum E: short; // enum E: short; // enum E: short {e1, e2}; @@ -9350,7 +9263,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testAutoTypeInRangeBasedFor_332883a() throws Exception { parseAndCheckBindings(); } - + // struct S { // void f(); // }; @@ -9367,7 +9280,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testAutoTypeInRangeBasedFor_332883b() throws Exception { parseAndCheckBindings(); } - + // namespace std { // template struct pair { // T1 first; @@ -9419,7 +9332,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testMemberInitializer_333200() throws Exception { parseAndCheckBindings(); } - + // template auto add(T t, U u) -> decltype(t + u); // template auto add(T t, U u) -> decltype(t + u) { // return t + u; @@ -9427,7 +9340,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testResolutionInTrailingReturnType_333256() throws Exception { parseAndCheckBindings(); } - + // struct CHAINER { // CHAINER const & operator,(int x) const; // }; @@ -9438,7 +9351,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testOverloadedCommaOpWithConstClassRef_334955() throws Exception { parseAndCheckBindings(); } - + // struct OK {int ok;}; // struct NOK {}; // @@ -9455,7 +9368,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testOverloadedOperatorWithInheritanceDistance_335387() throws Exception { parseAndCheckBindings(); } - + // namespace ns {int a;} // using ns::a; public void testPropertyOfUsingDeclaration() throws Exception { @@ -9467,7 +9380,7 @@ public class AST2CPPTests extends AST2BaseTest { assertTrue(qn.isDeclaration()); assertTrue(qn.getLastName().isDeclaration()); } - + // struct S{ // void foo(){} // }; @@ -9478,7 +9391,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testMemberAccessForArray_347298() throws Exception { parseAndCheckBindings(); } - + // struct X {}; // struct Y : X { // Y(){} @@ -9492,26 +9405,26 @@ public class AST2CPPTests extends AST2BaseTest { public void testReferenceToCopyConstructor() throws Exception { IASTTranslationUnit tu= parseAndCheckBindings(); ICPPASTFunctionDefinition fdef= getDeclaration(tu, 2); - - IASTDeclarationStatement dst= getStatement(fdef, 0); + + IASTDeclarationStatement dst= getStatement(fdef, 0); IASTDeclarator dtor= ((IASTSimpleDeclaration) dst.getDeclaration()).getDeclarators()[0]; IBinding ctor= ((IASTImplicitNameOwner) dtor).getImplicitNames()[0].resolveBinding(); assertTrue(ctor instanceof ICPPConstructor); assertEquals(0, ((ICPPConstructor) ctor).getType().getParameterTypes().length); - dst= getStatement(fdef, 1); + dst= getStatement(fdef, 1); dtor= ((IASTSimpleDeclaration) dst.getDeclaration()).getDeclarators()[0]; ctor= ((IASTImplicitNameOwner) dtor).getImplicitNames()[0].resolveBinding(); assertTrue(ctor instanceof ICPPConstructor); assertEquals(1, ((ICPPConstructor) ctor).getType().getParameterTypes().length); - dst= getStatement(fdef, 2); + dst= getStatement(fdef, 2); dtor= ((IASTSimpleDeclaration) dst.getDeclaration()).getDeclarators()[0]; ctor= ((IASTImplicitNameOwner) dtor).getImplicitNames()[0].resolveBinding(); assertTrue(ctor instanceof ICPPConstructor); assertEquals(1, ((ICPPConstructor) ctor).getType().getParameterTypes().length); } - + // struct Foo { // void Method(int) {} // void Method() const {} @@ -9527,7 +9440,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testTypedefAsClassNameWithFunctionPtrArgument_350345() throws Exception { parseAndCheckBindings(); } - + // int func1(int input) { // return input; // } @@ -9577,7 +9490,7 @@ public class AST2CPPTests extends AST2BaseTest { assertNotSame(g1, g2); assertSame(g2, g3); } - + // class A : A { // }; @@ -9586,7 +9499,7 @@ public class AST2CPPTests extends AST2BaseTest { ICPPClassType c= bh.assertNonProblem("A", 1); assertEquals(0, ClassTypeHelper.getPureVirtualMethods(c).length); } - + // template struct CT1 {}; // template struct CT2 {}; // typedef char Tdef; @@ -9598,7 +9511,7 @@ public class AST2CPPTests extends AST2BaseTest { public void testAmbiguityResolution_Bug359364() throws Exception { parseAndCheckBindings(); } - + // template struct C { // C(const C& c) {} // }; @@ -9622,11 +9535,11 @@ public class AST2CPPTests extends AST2BaseTest { ctors = c.getConstructors(); assertEquals(1, ctors.length); assertFalse(ctors[0].isImplicit()); - + IBinding ctor= bh.assertNonProblem("E(){}", 1); assertTrue(ctor instanceof ICPPConstructor); } - + // struct S; // struct S { // S(); @@ -9639,7 +9552,7 @@ public class AST2CPPTests extends AST2BaseTest { IASTCompositeTypeSpecifier S; IASTProblemDeclaration p; IASTSimpleDeclaration s; - + S= getCompositeType(tu, 1); s= getDeclaration(S, 0); s= getDeclaration(S, 1); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java index d13480b8fa7..396c470c61d 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java @@ -138,6 +138,10 @@ public abstract class VariableReadWriteFlags { if (node.getPropertyInParent() == IASTFieldReference.FIELD_NAME) { return rwAnyNode(expr, indirection); } +// if (node.getPropertyInParent() == IASTFieldReference.FIELD_OWNER && +// !((IASTFieldReference) expr).isPointerDereference()) { +// return rwAnyNode(expr, indirection); +// } return READ; } if (expr instanceof IASTFunctionCallExpression) { From 104a413f124b4b8f0362cf71ba5c0b2a982318ab Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Tue, 7 Feb 2012 17:52:23 -0800 Subject: [PATCH 07/43] Unit test for CPPVariableReadWriteFlags class. --- .../parser/tests/ast2/DOMParserTestSuite.java | 1 + .../ast2/VariableReadWriteFlagsTest.java | 146 ++++++++++++++++++ 2 files changed, 147 insertions(+) create mode 100644 core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/VariableReadWriteFlagsTest.java diff --git a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/DOMParserTestSuite.java b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/DOMParserTestSuite.java index 1aa2dc3e859..aff28ece1a5 100644 --- a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/DOMParserTestSuite.java +++ b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/DOMParserTestSuite.java @@ -56,6 +56,7 @@ public class DOMParserTestSuite extends TestCase { suite.addTest(LanguageExtensionsTest.suite()); suite.addTest(ASTInactiveCodeTests.suite()); suite.addTest(AccessControlTests.suite()); + suite.addTest(VariableReadWriteFlagsTest.suite()); return suite; } } diff --git a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/VariableReadWriteFlagsTest.java b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/VariableReadWriteFlagsTest.java new file mode 100644 index 00000000000..0ee39a109a9 --- /dev/null +++ b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/VariableReadWriteFlagsTest.java @@ -0,0 +1,146 @@ +/******************************************************************************* + * Copyright (c) 2012 Google, Inc and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Sergey Prigogin (Google) - initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.core.parser.tests.ast2; + +import java.io.IOException; + +import junit.framework.TestSuite; + +import org.eclipse.cdt.core.dom.ast.IASTName; +import org.eclipse.cdt.internal.core.dom.parser.c.CVariableReadWriteFlags; +import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVariableReadWriteFlags; +import org.eclipse.cdt.internal.core.parser.ParserException; +import org.eclipse.cdt.internal.core.pdom.dom.PDOMName; + +/** + * Unit tests for CPPVariableReadWriteFlags and CVariableReadWriteFlags classes. + */ +public class VariableReadWriteFlagsTest extends AST2BaseTest { + private static final int READ = PDOMName.READ_ACCESS; + private static final int WRITE = PDOMName.WRITE_ACCESS; + + protected class AssertionHelper extends BindingAssertionHelper { + AssertionHelper(String contents, boolean isCPP) throws ParserException { + super(contents, isCPP); + } + + void assertReadWriteFlags(String section, int expectedFlags) throws Exception { + int len; + for (len = 0; len < section.length(); len++) { + if (!Character.isJavaIdentifierPart(section.charAt(len))) + break; + } + assertReadWriteFlags(section, len, expectedFlags); + } + + void assertReadWriteFlags(String section, int len, int expectedFlags) throws Exception { + IASTName variable = findName(section, len); + assertNotNull(variable); + assertEquals(flagsToString(expectedFlags), flagsToString(getReadWriteFlags(variable))); + } + + int getReadWriteFlags(IASTName variable) { + return isCPP ? + CPPVariableReadWriteFlags.getReadWriteFlags(variable) : + CVariableReadWriteFlags.getReadWriteFlags(variable); + } + + private String flagsToString(int flags) { + StringBuilder buf = new StringBuilder(); + if ((flags & READ) != 0) { + buf.append("READ"); + } + if ((flags & WRITE) != 0) { + if (buf.length() != 0) + buf.append(" | "); + buf.append("WRITE"); + } + if (buf.length() == 0) + buf.append("0"); + return buf.toString(); + } + } + + public VariableReadWriteFlagsTest() { + } + + public VariableReadWriteFlagsTest(String name) { + super(name); + } + + public static TestSuite suite() { + return suite(VariableReadWriteFlagsTest.class); + } + + protected AssertionHelper getCAssertionHelper() throws ParserException, IOException { + String code= getAboveComment(); + return new AssertionHelper(code, false); + } + + protected AssertionHelper getCPPAssertionHelper() throws ParserException, IOException { + String code= getAboveComment(); + return new AssertionHelper(code, true); + } + + // int test() { + // int a; + // a = 2; + // return a + 1; + // } + public void testSimpleAccess() throws Exception { + AssertionHelper a = getCPPAssertionHelper(); + a.assertReadWriteFlags("a = 2", WRITE); + a.assertReadWriteFlags("a +", READ); + } + + // int a = 1; + public void _testEqualsInitializer() throws Exception { + AssertionHelper a = getCPPAssertionHelper(); + a.assertReadWriteFlags("a", WRITE); + } + + // struct A { int x; }; + // + // void test() { + // A a; + // a.x = 1; + // }; + public void _testFieldAccess() throws Exception { + AssertionHelper a = getCPPAssertionHelper(); + a.assertReadWriteFlags("a.", WRITE); + } + + // struct A { int x; }; + // + // void test(A* a) { + // a->x = 1; + // }; + public void testFieldAccessWithDereference() throws Exception { + AssertionHelper a = getCPPAssertionHelper(); + a.assertReadWriteFlags("a->", READ); + } + + // struct A { + // void m1(); + // void m2() const; + // }; + // + // void test() { + // A a; + // a.m1(); + // a.m2(); + // }; + public void _testMethodCall() throws Exception { + AssertionHelper a = getCPPAssertionHelper(); + a.assertReadWriteFlags("a.m1", READ | WRITE); + a.assertReadWriteFlags("a.m2", READ); + } +} From f0be3d2a6bffc796b4cab976963031add4d97a21 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Tue, 7 Feb 2012 20:02:53 -0800 Subject: [PATCH 08/43] Fixed VariableReadWriteFlagsTest.testFieldAccess. --- .../ast2/VariableReadWriteFlagsTest.java | 28 ++++++++++++++----- .../dom/parser/VariableReadWriteFlags.java | 28 ++++++++----------- 2 files changed, 33 insertions(+), 23 deletions(-) diff --git a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/VariableReadWriteFlagsTest.java b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/VariableReadWriteFlagsTest.java index 0ee39a109a9..de6ed76f3be 100644 --- a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/VariableReadWriteFlagsTest.java +++ b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/VariableReadWriteFlagsTest.java @@ -68,14 +68,14 @@ public class VariableReadWriteFlagsTest extends AST2BaseTest { return buf.toString(); } } - + public VariableReadWriteFlagsTest() { } - + public VariableReadWriteFlagsTest(String name) { super(name); } - + public static TestSuite suite() { return suite(VariableReadWriteFlagsTest.class); } @@ -113,11 +113,11 @@ public class VariableReadWriteFlagsTest extends AST2BaseTest { // A a; // a.x = 1; // }; - public void _testFieldAccess() throws Exception { + public void testFieldAccess() throws Exception { AssertionHelper a = getCPPAssertionHelper(); a.assertReadWriteFlags("a.", WRITE); } - + // struct A { int x; }; // // void test(A* a) { @@ -127,7 +127,21 @@ public class VariableReadWriteFlagsTest extends AST2BaseTest { AssertionHelper a = getCPPAssertionHelper(); a.assertReadWriteFlags("a->", READ); } - + + // void f(int* x); + // void g(const int* x); + // + // void test() { + // int a, b; + // f(&a); + // g(&b); + // }; + public void testExplicitArgument() throws Exception { + AssertionHelper a = getCPPAssertionHelper(); + a.assertReadWriteFlags("a)", READ | WRITE); + a.assertReadWriteFlags("b)", READ); + } + // struct A { // void m1(); // void m2() const; @@ -138,7 +152,7 @@ public class VariableReadWriteFlagsTest extends AST2BaseTest { // a.m1(); // a.m2(); // }; - public void _testMethodCall() throws Exception { + public void _testImplicitArgument() throws Exception { AssertionHelper a = getCPPAssertionHelper(); a.assertReadWriteFlags("a.m1", READ | WRITE); a.assertReadWriteFlags("a.m2", READ); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java index 396c470c61d..6f2c0a4342e 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java @@ -105,9 +105,19 @@ public abstract class VariableReadWriteFlags { } protected int rwInExpression(IASTExpression expr, IASTNode node, int indirection) { + if (expr instanceof IASTIdExpression) { + return rwAnyNode(expr, indirection); + } if (expr instanceof IASTBinaryExpression) { return rwInBinaryExpression(node, (IASTBinaryExpression) expr, indirection); } + if (expr instanceof IASTFieldReference) { + if (node.getPropertyInParent() != IASTFieldReference.FIELD_OWNER || + !((IASTFieldReference) expr).isPointerDereference()) { + return rwAnyNode(expr, indirection); + } + return READ; + } if (expr instanceof IASTCastExpression) { // must be ahead of unary return rwAnyNode(expr, indirection); } @@ -134,25 +144,12 @@ public abstract class VariableReadWriteFlags { } return 0; } - if (expr instanceof IASTFieldReference) { - if (node.getPropertyInParent() == IASTFieldReference.FIELD_NAME) { - return rwAnyNode(expr, indirection); - } -// if (node.getPropertyInParent() == IASTFieldReference.FIELD_OWNER && -// !((IASTFieldReference) expr).isPointerDereference()) { -// return rwAnyNode(expr, indirection); -// } - return READ; - } if (expr instanceof IASTFunctionCallExpression) { if (node.getPropertyInParent() == IASTFunctionCallExpression.FUNCTION_NAME) { return READ; } return rwArgumentForFunctionCall((IASTFunctionCallExpression) expr, node, indirection); } - if (expr instanceof IASTIdExpression) { - return rwAnyNode(expr, indirection); - } if (expr instanceof IASTProblemExpression) { return READ | WRITE; } @@ -181,7 +178,6 @@ public abstract class VariableReadWriteFlags { return READ | WRITE; // fallback } - protected int rwArgumentForFunctionCall(IFunctionType type, int parameterIdx, int indirection) { IType[] ptypes= type.getParameterTypes(); if (ptypes != null && ptypes.length > parameterIdx) { @@ -249,11 +245,11 @@ public abstract class VariableReadWriteFlags { return rwAnyNode(expr, indirection); case IASTUnaryExpression.op_amper: - return rwAnyNode(expr, indirection+1); + return rwAnyNode(expr, indirection + 1); case IASTUnaryExpression.op_star: if (indirection > 0) { - return rwAnyNode(expr, indirection-1); + return rwAnyNode(expr, indirection - 1); } return READ; From eae1dbf5f8104ad7db01c6e29397b8b44c021628 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Tue, 7 Feb 2012 20:05:15 -0800 Subject: [PATCH 09/43] Cosmetics. --- .../cpp/CPPASTFunctionCallExpression.java | 32 +++++++++++-------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTFunctionCallExpression.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTFunctionCallExpression.java index 1dc12637de6..ac5ffdf6792 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTFunctionCallExpression.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTFunctionCallExpression.java @@ -14,8 +14,15 @@ package org.eclipse.cdt.internal.core.dom.parser.cpp; import static org.eclipse.cdt.core.dom.ast.IASTExpression.ValueCategory.LVALUE; import static org.eclipse.cdt.core.dom.ast.IASTExpression.ValueCategory.PRVALUE; -import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.*; -import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.*; +import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.prvalueType; +import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.typeFromFunctionCall; +import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.typeFromReturnType; +import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.valueCategoryFromFunctionCall; +import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.valueCategoryFromReturnType; +import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.CVTYPE; +import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.REF; +import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.TDEF; +import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.getNestedType; import org.eclipse.cdt.core.dom.ast.ASTVisitor; import org.eclipse.cdt.core.dom.ast.DOMException; @@ -46,17 +53,14 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPTemplates; import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.LookupData; import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil; - -public class CPPASTFunctionCallExpression extends ASTNode implements - ICPPASTFunctionCallExpression, IASTAmbiguityParent { - +public class CPPASTFunctionCallExpression extends ASTNode + implements ICPPASTFunctionCallExpression, IASTAmbiguityParent { private IASTExpression functionName; private IASTInitializerClause[] fArguments; private IASTImplicitName[] implicitNames; private ICPPFunction overload= UNINITIALIZED_FUNCTION; - public CPPASTFunctionCallExpression() { setArguments(null); } @@ -144,7 +148,7 @@ public class CPPASTFunctionCallExpression extends ASTNode implements } } - // create separate implicit names for the two brackets + // Create separate implicit names for the two brackets CPPASTImplicitName n1 = new CPPASTImplicitName(OverloadableOperator.PAREN, this); n1.setBinding(overload); @@ -158,16 +162,18 @@ public class CPPASTFunctionCallExpression extends ASTNode implements IToken lparen = functionName.getTrailingSyntax(); IToken rparen = lparen.getNext(); - if (lparen.getType() == IToken.tLPAREN) + if (lparen.getType() == IToken.tLPAREN) { n1.setOffsetAndLength(idEndOffset + lparen.getOffset(), 1); - else + } else { n1.setOffsetAndLength(idEndOffset + lparen.getEndOffset(), 0); + } - if (rparen.getType() == IToken.tRPAREN) + if (rparen.getType() == IToken.tRPAREN) { n2.setOffsetAndLength(idEndOffset + rparen.getOffset(), 1); - else + } else { n2.setOffsetAndLength(idEndOffset + rparen.getEndOffset(), 0); - } catch(ExpansionOverlapsBoundaryException e) { + } + } catch (ExpansionOverlapsBoundaryException e) { n1.setOffsetAndLength(idEndOffset, 0); n2.setOffsetAndLength(idEndOffset, 0); } From b9255e88a54c84de5af5774cecb4bdad0373e5fa Mon Sep 17 00:00:00 2001 From: Scott Tepavich Date: Tue, 31 Jan 2012 21:21:26 -0800 Subject: [PATCH 10/43] Bug 360280 - [breakpoints] Reposition breakpoints when planted on invalid line --- .../eclipse/cdt/debug/core/CDIDebugModel.java | 19 ++ .../eclipse/cdt/debug/core/CDebugUtils.java | 18 +- .../cdt/debug/core/model/ICBreakpoint.java | 2 +- .../cdt/debug/core/model/ICBreakpoint2.java | 39 ++++ .../debug/core/model/ICLineBreakpoint2.java | 178 ++++++++++++++++++ .../breakpoints/AbstractLineBreakpoint.java | 115 ++++++++++- .../breakpoints/BreakpointMessages.properties | 2 + .../core/breakpoints/CAddressBreakpoint.java | 5 +- .../core/breakpoints/CAddressTracepoint.java | 2 +- .../core/breakpoints/CBreakpoint.java | 20 +- .../core/breakpoints/CFunctionBreakpoint.java | 7 +- .../core/breakpoints/CFunctionTracepoint.java | 2 +- .../core/breakpoints/CLineBreakpoint.java | 28 ++- .../core/breakpoints/CLineTracepoint.java | 117 +++++++++++- .../core/breakpoints/CWatchpoint.java | 6 +- .../CBreakpointPropertyPage.java | 11 +- 16 files changed, 532 insertions(+), 39 deletions(-) create mode 100644 debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICBreakpoint2.java create mode 100644 debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICLineBreakpoint2.java diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/CDIDebugModel.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/CDIDebugModel.java index 1d445fade22..ea88c2b8ef5 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/CDIDebugModel.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/CDIDebugModel.java @@ -33,6 +33,7 @@ import org.eclipse.cdt.debug.core.model.ICBreakpointType; import org.eclipse.cdt.debug.core.model.ICEventBreakpoint; import org.eclipse.cdt.debug.core.model.ICFunctionBreakpoint; import org.eclipse.cdt.debug.core.model.ICLineBreakpoint; +import org.eclipse.cdt.debug.core.model.ICLineBreakpoint2; import org.eclipse.cdt.debug.core.model.ICWatchpoint; import org.eclipse.cdt.debug.core.model.ICWatchpoint2; import org.eclipse.cdt.debug.internal.core.breakpoints.CAddressBreakpoint; @@ -269,6 +270,24 @@ public class CDIDebugModel { attributes.put( ICBreakpoint.CONDITION, condition ); attributes.put( ICBreakpoint.SOURCE_HANDLE, sourceHandle ); attributes.put( ICBreakpointType.TYPE, type ); + + // Added for source relocated breakpoints. + if (!attributes.containsKey(ICLineBreakpoint2.REQUESTED_SOURCE_HANDLE)) { + attributes.put( ICLineBreakpoint2.REQUESTED_SOURCE_HANDLE, sourceHandle ); + } + if (!attributes.containsKey( ICLineBreakpoint2.REQUESTED_LINE )) { + attributes.put( ICLineBreakpoint2.REQUESTED_LINE, new Integer( lineNumber )); + } + if (attributes.containsKey(IMarker.CHAR_START) && + !attributes.containsKey( ICLineBreakpoint2.REQUESTED_CHAR_START )) + { + attributes.put( ICLineBreakpoint2.REQUESTED_CHAR_START, attributes.get(IMarker.CHAR_START)); + } + if (attributes.containsKey(IMarker.CHAR_END) && + !attributes.containsKey( ICLineBreakpoint2.REQUESTED_CHAR_END )) + { + attributes.put( ICLineBreakpoint2.REQUESTED_CHAR_END, attributes.get(IMarker.CHAR_END)); + } } /** diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/CDebugUtils.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/CDebugUtils.java index b70f911ef9e..b5795ec4946 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/CDebugUtils.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/CDebugUtils.java @@ -396,7 +396,7 @@ public class CDebugUtils { int lineNumber = breakpoint.getLineNumber(); if (lineNumber > 0) { label.append(' '); - label.append(MessageFormat.format(DebugCoreMessages.getString("CDebugUtils.0"), new String[]{ Integer.toString(lineNumber) })); //$NON-NLS-1$ + label.append(MessageFormat.format(DebugCoreMessages.getString("CDebugUtils.0"), (Object[])new String[]{ Integer.toString(lineNumber) })); //$NON-NLS-1$ } return label; } @@ -404,7 +404,7 @@ public class CDebugUtils { protected static StringBuffer appendAddress(ICAddressBreakpoint breakpoint, StringBuffer label) throws CoreException { try { label.append(' '); - label.append(MessageFormat.format(DebugCoreMessages.getString("CDebugUtils.1"), new String[]{ breakpoint.getAddress() })); //$NON-NLS-1$ + label.append(MessageFormat.format(DebugCoreMessages.getString("CDebugUtils.1"), (Object[])new String[]{ breakpoint.getAddress() })); //$NON-NLS-1$ } catch (NumberFormatException e) { } return label; @@ -414,7 +414,7 @@ public class CDebugUtils { String function = breakpoint.getFunction(); if (function != null && function.trim().length() > 0) { label.append(' '); - label.append(MessageFormat.format(DebugCoreMessages.getString("CDebugUtils.2"), new String[]{ function.trim() })); //$NON-NLS-1$ + label.append(MessageFormat.format(DebugCoreMessages.getString("CDebugUtils.2"), (Object[])new String[]{ function.trim() })); //$NON-NLS-1$ } return label; } @@ -423,7 +423,7 @@ public class CDebugUtils { int ignoreCount = breakpoint.getIgnoreCount(); if (ignoreCount > 0) { label.append(' '); - label.append(MessageFormat.format(DebugCoreMessages.getString("CDebugUtils.3"), new String[]{ Integer.toString(ignoreCount) })); //$NON-NLS-1$ + label.append(MessageFormat.format(DebugCoreMessages.getString("CDebugUtils.3"), (Object[])new String[]{ Integer.toString(ignoreCount) })); //$NON-NLS-1$ } return label; } @@ -432,7 +432,7 @@ public class CDebugUtils { String condition = breakpoint.getCondition(); if (condition != null && condition.length() > 0) { buffer.append(' '); - buffer.append(MessageFormat.format(DebugCoreMessages.getString("CDebugUtils.4"), new String[] { condition })); //$NON-NLS-1$ + buffer.append(MessageFormat.format(DebugCoreMessages.getString("CDebugUtils.4"), (Object[])new String[] { condition })); //$NON-NLS-1$ } } @@ -440,7 +440,7 @@ public class CDebugUtils { String expression = watchpoint.getExpression(); if (expression != null && expression.length() > 0) { label.append(' '); - label.append(MessageFormat.format( DebugCoreMessages.getString("CDebugUtils.5"), new String[] { expression })); //$NON-NLS-1$ + label.append(MessageFormat.format( DebugCoreMessages.getString("CDebugUtils.5"), (Object[])new String[] { expression })); //$NON-NLS-1$ } } @@ -448,7 +448,7 @@ public class CDebugUtils { String memorySpace = watchpoint.getMemorySpace(); if (memorySpace != null && memorySpace.length() > 0) { label.append(' '); - label.append(MessageFormat.format( DebugCoreMessages.getString("CDebugUtils.6"), new String[] { memorySpace })); //$NON-NLS-1$ + label.append(MessageFormat.format( DebugCoreMessages.getString("CDebugUtils.6"), (Object[])new String[] { memorySpace })); //$NON-NLS-1$ } } @@ -456,7 +456,7 @@ public class CDebugUtils { String range = watchpoint.getRange().toString(); if (range.length() > 0 && !range.equals("0")) { //$NON-NLS-1$ label.append(' '); - label.append(MessageFormat.format(DebugCoreMessages.getString("CDebugUtils.7"), new String[]{ range })); //$NON-NLS-1$ + label.append(MessageFormat.format(DebugCoreMessages.getString("CDebugUtils.7"), (Object[])new String[]{ range })); //$NON-NLS-1$ } } @@ -489,7 +489,7 @@ public class CDebugUtils { if (typeString.length() > 0) { label.append(' '); label.append(MessageFormat.format( - DebugCoreMessages.getString("CDebugUtils.8"), new String[] { typeString })); //$NON-NLS-1$ + DebugCoreMessages.getString("CDebugUtils.8"), (Object[])new String[] { typeString })); //$NON-NLS-1$ } } return label; diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICBreakpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICBreakpoint.java index 41c463630a2..4d00e6c4528 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICBreakpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICBreakpoint.java @@ -236,5 +236,5 @@ public interface ICBreakpoint extends IBreakpoint { * @return Extension instance. * @throws CoreException Throws exception in case the extension doesn't exist or cannot be initialized. */ - public ICBreakpointExtension getExtension(String debugModelId, Class extensionType) throws CoreException ; + public V getExtension(String debugModelId, Class extensionType) throws CoreException; } diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICBreakpoint2.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICBreakpoint2.java new file mode 100644 index 00000000000..3e7acd6b207 --- /dev/null +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICBreakpoint2.java @@ -0,0 +1,39 @@ +/******************************************************************************* + * Copyright (c) 2012 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wind River Systems - initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.debug.core.model; + +import org.eclipse.core.runtime.CoreException; + +/** + * Extension that allows client to force breakpoint message to refresh. + * + * @since 7.2 + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + */ +public interface ICBreakpoint2 extends ICBreakpoint { + /** + * Refresh the marker message for the breakpoint. + *

+ * Many of breakpoint settings are backed by marker attributes and it is + * sometimes more convenient to modify those attributes in the marker + * directly rather than through accessor methods of the breakpoint. This + * method allows the client to force the breakpoint to refresh its + * {@link org.eclipse.core.resources.IMarker#MESSAGE} attribute to reflect + * its current attribute values. + *

+ * + * @throws CoreException if unable to access the property + * on this breakpoint's underlying marker + */ + public void refreshMessage() throws CoreException; + +} diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICLineBreakpoint2.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICLineBreakpoint2.java new file mode 100644 index 00000000000..b2f67e2350c --- /dev/null +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/core/model/ICLineBreakpoint2.java @@ -0,0 +1,178 @@ +/******************************************************************************* + * Copyright (c) 2012 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wind River Systems - initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.debug.core.model; + +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.runtime.CoreException; + +/** + * Line breakpoint extension that allows a breakpoint to be relocated by a + * debugger to a valid source line. + *

Clients which can determine a valid source based on debuggers symbol + * information should call the various setInstalled... methods with + * the corrected location attributes. Note, there is no setInstalledSourceHandle, + * clients should call {@link ICBreakpoint#setSourceHandle(String)}. If multiple + * clients try to change the installed breakpoint location, the last call will + * take precedence. This way debuggers may update the location upon active debug + * context change.
+ * The original breakpoint location as configured by the user can always be + * retrieved using the getRequested... methods. + *

+ * @since 7.2 + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + */ +public interface ICLineBreakpoint2 extends ICLineBreakpoint, ICBreakpoint2 { + + /** + * Breakpoint attribute storing the original requested line for this breakpoint + * This attribute is a int. + */ + public static final String REQUESTED_LINE = "requestedLine"; //$NON-NLS-1$ + + /** + * Breakpoint attribute storing the original requested column for this breakpoint + * This attribute is a int. + */ + public static final String REQUESTED_CHAR_START = "requestedCharStart"; //$NON-NLS-1$ + + /** + * Breakpoint attribute storing the original requested column for this breakpoint + * This attribute is a int. + */ + public static final String REQUESTED_CHAR_END = "requestedCharEnd"; //$NON-NLS-1$ + + /** + * Breakpoint attribute storing the original requested file name this breakpoint + * is set in. + * This attribute is a String. + */ + public static final String REQUESTED_SOURCE_HANDLE = "requestedSourceHandle"; //$NON-NLS-1$ + + /** + * Returns the line number where the breakpoint was set before it was relocated to a + * valid source line. + * + * @return Returns the requested line number attribute. + * @exception CoreException if unable to access the property on this breakpoint's + * underlying marker + */ + public int getRequestedLine() throws CoreException; + + /** + * Sets the line number where the breakpoint should be set. + * + * @param The requested line number attribute. + * @exception CoreException if unable to access the property on this breakpoint's + * underlying marker + */ + public void setRequestedLine(int line) throws CoreException; + + /** + * Returns starting source index where the breakpoint was set before it + * was moved to a valid source location. + * + * @return Returns the requested start index attribute. + * @exception CoreException if unable to access the property on this breakpoint's + * underlying marker + */ + public int getRequestedCharStart() throws CoreException; + + + /** + * Sets the starting source index where the breakpoint should be set. + * + * @param The requested start index attribute. + * @exception CoreException if unable to access the property on this breakpoint's + * underlying marker + */ + public void setRequestedCharStart(int charStart) throws CoreException; + + /** + * Returns ending source index where the breakpoint was set before it + * was moved to a valid source location. + * + * @return Returns the requested end index attribute. + * @exception CoreException if unable to access the property on this breakpoint's + * underlying marker + */ + public int getRequestedCharEnd() throws CoreException; + + /** + * Sets the staring source index where the breakpoint should be set. + * + * @param The requested end index attribute. + * @exception CoreException if unable to access the property on this breakpoint's + * underlying marker + */ + public void setRequestedCharEnd(int charEnd) throws CoreException; + + /** + * Returns the file name where the breakpoint was set before it was relocated to a + * valid file. + * + * @return Returns the requested file name. + * @exception CoreException if unable to access the property on this breakpoint's + * underlying marker + */ + public String getRequestedSourceHandle() throws CoreException; + + /** + * Sets the file name where the breakpoint should be set. May be an empty string + * if the file is not known. + * + * @param Requested file name. + * @exception CoreException if unable to access the property on this breakpoint's + * underlying marker + */ + public void setRequestedSourceHandle(String fileName) throws CoreException; + + /** + * Sets the line number where the breakpoint is actually installed. This + * method only updates the {@link IMarker#LINE_NUMBER} attribute and the + * breakpoint message. + * + * @param line Installed line number + * @throws CoreException if unable to access the property + * on this breakpoint's underlying marker + */ + public void setInstalledLineNumber(int line) throws CoreException; + + /** + * Sets the start index where the breakpoint is actually installed. This method + * only updates the {@link IMarker#CHAR_START} attribute and the breakpoint + * message. + * + * @param charStart Installed char start + * @throws CoreException + */ + public void setInstalledCharStart(int charStart) throws CoreException; + + /** + * Sets the end index where the breakpoint is actually installed. This method + * only updates the {@link IMarker#CHAR_END} attribute and the breakpoint + * message. + * + * @param charEnd Installed char start + * @throws CoreException + */ + public void setInstalledCharEnd(int charStart) throws CoreException; + + /** + * Resets the breakpoint location back to the values specified by the + * REQUESTED_* attributes. This operation should be called automatically + * by the implementation when the install count is reset to 0, and does + * not need to be called by the client at that time. + * + * @throws CoreException + */ + public void resetInstalledLocation() throws CoreException; +} diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/AbstractLineBreakpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/AbstractLineBreakpoint.java index ee0004fd4db..d5150ff1f75 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/AbstractLineBreakpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/AbstractLineBreakpoint.java @@ -14,6 +14,7 @@ import java.util.Map; import org.eclipse.cdt.debug.core.model.ICBreakpoint; import org.eclipse.cdt.debug.core.model.ICLineBreakpoint; +import org.eclipse.cdt.debug.core.model.ICLineBreakpoint2; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; @@ -23,7 +24,7 @@ import org.eclipse.core.runtime.Path; /** * Base class for different types of location breakponts. */ -public abstract class AbstractLineBreakpoint extends CBreakpoint implements ICLineBreakpoint { +public abstract class AbstractLineBreakpoint extends CBreakpoint implements ICLineBreakpoint2 { /** * Constructor for AbstractLineBreakpoint. @@ -41,7 +42,7 @@ public abstract class AbstractLineBreakpoint extends CBreakpoint implements ICLi * @param add * @throws CoreException */ - public AbstractLineBreakpoint( IResource resource, String markerType, Map attributes, boolean add ) throws CoreException { + public AbstractLineBreakpoint( IResource resource, String markerType, Map attributes, boolean add ) throws CoreException { super( resource, markerType, attributes, add ); } @@ -110,4 +111,114 @@ public abstract class AbstractLineBreakpoint extends CBreakpoint implements ICLi public void setFunction( String function ) throws CoreException { setAttribute( ICLineBreakpoint.FUNCTION, function ); } + + @Override + public int getRequestedLine() throws CoreException { + return ensureMarker().getAttribute( ICLineBreakpoint2.REQUESTED_LINE, -1 ); + } + + @Override + public void setRequestedLine(int line) throws CoreException { + setAttribute( ICLineBreakpoint2.REQUESTED_LINE, line ); + } + + @Override + public int getRequestedCharStart() throws CoreException { + return ensureMarker().getAttribute( ICLineBreakpoint2.REQUESTED_CHAR_START, -1 ); + } + + @Override + public void setRequestedCharStart(int charStart) throws CoreException { + setAttribute( ICLineBreakpoint2.REQUESTED_CHAR_START, charStart ); + } + + @Override + public int getRequestedCharEnd() throws CoreException { + return ensureMarker().getAttribute( ICLineBreakpoint2.REQUESTED_CHAR_END, -1 ); + } + + @Override + public void setRequestedCharEnd(int charEnd) throws CoreException { + setAttribute( ICLineBreakpoint2.REQUESTED_CHAR_END, charEnd ); + } + + @Override + public String getRequestedSourceHandle() throws CoreException { + return ensureMarker().getAttribute( ICLineBreakpoint2.REQUESTED_SOURCE_HANDLE, "" ); //$NON-NLS-1$ + } + + @Override + public void setRequestedSourceHandle(String fileName) throws CoreException { + setAttribute( ICLineBreakpoint2.REQUESTED_SOURCE_HANDLE, fileName ); + } + + @Override + public synchronized int decrementInstallCount() throws CoreException { + int count = super.decrementInstallCount(); + if (count == 0) { + resetInstalledLocation(); + } + return count; + } + + @Override + public void setInstalledLineNumber(int line) throws CoreException { + int existingValue = ensureMarker().getAttribute(IMarker.LINE_NUMBER, -1); + if (line != existingValue) { + setAttribute(IMarker.LINE_NUMBER, line); + setAttribute( IMarker.MESSAGE, getMarkerMessage() ); + } + } + + @Override + public void setInstalledCharStart(int charStart) throws CoreException { + int existingValue = ensureMarker().getAttribute(IMarker.CHAR_START, -1); + if (charStart != existingValue) { + setAttribute(IMarker.CHAR_START, charStart); + setAttribute( IMarker.MESSAGE, getMarkerMessage() ); + } + } + + @Override + public void setInstalledCharEnd(int charEnd) throws CoreException { + int existingValue = ensureMarker().getAttribute(IMarker.CHAR_END, -1); + if (charEnd != existingValue) { + setAttribute(IMarker.CHAR_END, charEnd); + setAttribute( IMarker.MESSAGE, getMarkerMessage() ); + } + } + + @Override + public void resetInstalledLocation() throws CoreException { + boolean locationReset = false; + if (this.getMarker().getAttribute(REQUESTED_LINE) != null) { + int line = this.getMarker().getAttribute(REQUESTED_LINE, -1); + setAttribute(IMarker.LINE_NUMBER, line); + locationReset = true; + } + if (this.getMarker().getAttribute(REQUESTED_CHAR_START) != null) { + int charStart = this.getMarker().getAttribute(REQUESTED_CHAR_START, -1); + setAttribute(IMarker.CHAR_START, charStart); + locationReset = true; + } + if (this.getMarker().getAttribute(REQUESTED_CHAR_END) != null) { + int charEnd = this.getMarker().getAttribute(REQUESTED_CHAR_END, -1); + setAttribute(IMarker.CHAR_END, charEnd); + locationReset = true; + } + if (this.getMarker().getAttribute(REQUESTED_SOURCE_HANDLE) != null) { + String file = this.getMarker().getAttribute(REQUESTED_SOURCE_HANDLE, ""); //$NON-NLS-1$ + setAttribute(ICBreakpoint.SOURCE_HANDLE, file); + locationReset = true; + } + if (locationReset) { + setAttribute( IMarker.MESSAGE, getMarkerMessage() ); + } + } + + @Override + public void refreshMessage() throws CoreException { + IMarker marker = ensureMarker(); + marker.setAttribute(IMarker.MESSAGE, getMarkerMessage()); + } } diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/BreakpointMessages.properties b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/BreakpointMessages.properties index 9824818bd46..e4dacfadbf3 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/BreakpointMessages.properties +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/BreakpointMessages.properties @@ -25,6 +25,8 @@ CFunctionTracepoint.0=Function tracepoint: {0} # The marker message of a line breakpoint. CLineBreakpoint.0=Line breakpoint: {0} +# The marker message of a relocated line breakpoint. +CLineBreakpoint.1=Line breakpoint (relocated): {0} # The marker message of a line tracepoint. CLineTracepoint.0=Line tracepoint: {0} diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CAddressBreakpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CAddressBreakpoint.java index bb10180f928..7d31ce0ae1c 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CAddressBreakpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CAddressBreakpoint.java @@ -16,6 +16,7 @@ import org.eclipse.cdt.debug.core.CDebugUtils; import org.eclipse.cdt.debug.core.model.ICAddressBreakpoint; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; + import com.ibm.icu.text.MessageFormat; /** @@ -34,7 +35,7 @@ public class CAddressBreakpoint extends AbstractLineBreakpoint implements ICAddr /** * Constructor for CAddressBreakpoint. */ - public CAddressBreakpoint( IResource resource, Map attributes, boolean add ) throws CoreException { + public CAddressBreakpoint( IResource resource, Map attributes, boolean add ) throws CoreException { super( resource, getMarkerType(), attributes, add ); } @@ -52,6 +53,6 @@ public class CAddressBreakpoint extends AbstractLineBreakpoint implements ICAddr */ @Override protected String getMarkerMessage() throws CoreException { - return MessageFormat.format( BreakpointMessages.getString( "CAddressBreakpoint.0" ), new String[] { CDebugUtils.getBreakpointText( this, false ) } ); //$NON-NLS-1$ + return MessageFormat.format( BreakpointMessages.getString( "CAddressBreakpoint.0" ), (Object[])new String[] { CDebugUtils.getBreakpointText( this, false ) } ); //$NON-NLS-1$ } } diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CAddressTracepoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CAddressTracepoint.java index 1b13c3eb632..0106803b448 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CAddressTracepoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CAddressTracepoint.java @@ -56,6 +56,6 @@ public class CAddressTracepoint extends AbstractTracepoint implements ICAddressB */ @Override protected String getMarkerMessage() throws CoreException { - return MessageFormat.format( BreakpointMessages.getString( "CAddressTracepoint.0" ), new String[] { CDebugUtils.getBreakpointText( this, false ) } ); //$NON-NLS-1$ + return MessageFormat.format( BreakpointMessages.getString( "CAddressTracepoint.0" ), (Object[])new String[] { CDebugUtils.getBreakpointText( this, false ) } ); //$NON-NLS-1$ } } diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CBreakpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CBreakpoint.java index 7d8efe54df2..b8a8ccdb11d 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CBreakpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CBreakpoint.java @@ -48,7 +48,7 @@ public abstract class CBreakpoint extends Breakpoint implements ICBreakpoint, IC * Map of breakpoint extensions. The keys to the map are debug model IDs * and values are arrays of breakpoint extensions. */ - private Map fExtensions = new HashMap(1); + private Map fExtensions = new HashMap(1); /** * The number of debug targets the breakpoint is installed in. We don't use @@ -67,7 +67,7 @@ public abstract class CBreakpoint extends Breakpoint implements ICBreakpoint, IC /** * Constructor for CBreakpoint. */ - public CBreakpoint( final IResource resource, final String markerType, final Map attributes, final boolean add ) throws CoreException { + public CBreakpoint( final IResource resource, final String markerType, final Map attributes, final boolean add ) throws CoreException { this(); IWorkspaceRunnable wr = new IWorkspaceRunnable() { @@ -86,7 +86,7 @@ public abstract class CBreakpoint extends Breakpoint implements ICBreakpoint, IC run( wr ); } - public void createMarker( final IResource resource, final String markerType, final Map attributes, final boolean add ) throws DebugException { + public void createMarker( final IResource resource, final String markerType, final Map attributes, final boolean add ) throws DebugException { IWorkspaceRunnable wr = new IWorkspaceRunnable() { @Override public void run( IProgressMonitor monitor ) throws CoreException { @@ -338,11 +338,11 @@ public abstract class CBreakpoint extends Breakpoint implements ICBreakpoint, IC StringBuffer sb = new StringBuffer(); int ignoreCount = getIgnoreCount(); if ( ignoreCount > 0 ) { - sb.append( MessageFormat.format( BreakpointMessages.getString( "CBreakpoint.1" ), new Integer[] { new Integer( ignoreCount ) } ) ); //$NON-NLS-1$ + sb.append( MessageFormat.format( BreakpointMessages.getString( "CBreakpoint.1" ), new Object[] { new Integer( ignoreCount ) } ) ); //$NON-NLS-1$ } String condition = getCondition(); if ( condition != null && condition.length() > 0 ) { - sb.append( MessageFormat.format( BreakpointMessages.getString( "CBreakpoint.2" ), new String[] { condition } ) ); //$NON-NLS-1$ + sb.append( MessageFormat.format( BreakpointMessages.getString( "CBreakpoint.2" ), new Object[] { condition } ) ); //$NON-NLS-1$ } return sb.toString(); } @@ -376,11 +376,13 @@ public abstract class CBreakpoint extends Breakpoint implements ICBreakpoint, IC } @Override - public ICBreakpointExtension getExtension(String debugModelId, Class extensionType) throws CoreException { + public V getExtension(String debugModelId, Class extensionType) throws CoreException { ICBreakpointExtension[] extensions = getExtensionsForModelId(debugModelId); for (int i = 0; i < extensions.length; i++) { if ( extensionType.isAssignableFrom(extensions[i].getClass()) ) { - return extensions[i]; + @SuppressWarnings("unchecked") + V retVal = (V) extensions[i]; + return retVal; } } throw new CoreException(new Status(IStatus.ERROR, CDebugCorePlugin.getUniqueIdentifier(), DebugPlugin.ERROR, "Extension " + extensionType + " not defined for breakpoint " + this, null)); //$NON-NLS-1$ //$NON-NLS-2$ @@ -402,7 +404,7 @@ public abstract class CBreakpoint extends Breakpoint implements ICBreakpoint, IC IMarker marker = ensureMarker(); // Read the extension registry and create applicable extensions. - List extensions = new ArrayList(4); + List extensions = new ArrayList(4); IExtensionPoint ep = Platform.getExtensionRegistry().getExtensionPoint(CDebugCorePlugin.getUniqueIdentifier(), CDebugCorePlugin.BREAKPOINT_EXTENSION_EXTENSION_POINT_ID); IConfigurationElement[] elements = ep.getConfigurationElements(); for (int i= 0; i < elements.length; i++) { @@ -432,7 +434,7 @@ public abstract class CBreakpoint extends Breakpoint implements ICBreakpoint, IC } fExtensions.put(debugModelId, extensions.toArray(new ICBreakpointExtension[extensions.size()])); } - return (ICBreakpointExtension[])fExtensions.get(debugModelId); + return fExtensions.get(debugModelId); } diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CFunctionBreakpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CFunctionBreakpoint.java index 2d56d76629f..a9f27aeb4fa 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CFunctionBreakpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CFunctionBreakpoint.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.cdt.debug.internal.core.breakpoints; -import com.ibm.icu.text.MessageFormat; import java.util.Map; import org.eclipse.cdt.debug.core.CDebugUtils; @@ -18,6 +17,8 @@ import org.eclipse.cdt.debug.core.model.ICFunctionBreakpoint; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; +import com.ibm.icu.text.MessageFormat; + /** * A breakpoint that suspends the execution when a function is entered. */ @@ -34,7 +35,7 @@ public class CFunctionBreakpoint extends AbstractLineBreakpoint implements ICFun /** * Constructor for CFunctionBreakpoint. */ - public CFunctionBreakpoint( IResource resource, Map attributes, boolean add ) throws CoreException { + public CFunctionBreakpoint( IResource resource, Map attributes, boolean add ) throws CoreException { super( resource, getMarkerType(), attributes, add ); } @@ -50,6 +51,6 @@ public class CFunctionBreakpoint extends AbstractLineBreakpoint implements ICFun */ @Override protected String getMarkerMessage() throws CoreException { - return MessageFormat.format( BreakpointMessages.getString( "CFunctionBreakpoint.0" ), new String[] { CDebugUtils.getBreakpointText( this, false ) } ); //$NON-NLS-1$ + return MessageFormat.format( BreakpointMessages.getString( "CFunctionBreakpoint.0" ), (Object[])new String[] { CDebugUtils.getBreakpointText( this, false ) } ); //$NON-NLS-1$ } } diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CFunctionTracepoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CFunctionTracepoint.java index 81f939ef616..ea0503cf0d6 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CFunctionTracepoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CFunctionTracepoint.java @@ -54,6 +54,6 @@ public class CFunctionTracepoint extends AbstractTracepoint implements ICFunctio */ @Override protected String getMarkerMessage() throws CoreException { - return MessageFormat.format( BreakpointMessages.getString( "CFunctionTracepoint.0" ), new String[] { CDebugUtils.getBreakpointText( this, false ) } ); //$NON-NLS-1$ + return MessageFormat.format( BreakpointMessages.getString( "CFunctionTracepoint.0" ), (Object[])new String[] { CDebugUtils.getBreakpointText( this, false ) } ); //$NON-NLS-1$ } } diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CLineBreakpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CLineBreakpoint.java index e35fb4d3866..37f16afd8fd 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CLineBreakpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CLineBreakpoint.java @@ -14,6 +14,9 @@ import com.ibm.icu.text.MessageFormat; import java.util.Map; import org.eclipse.cdt.debug.core.CDebugUtils; +import org.eclipse.cdt.debug.core.model.ICBreakpoint; +import org.eclipse.cdt.debug.core.model.ICLineBreakpoint2; +import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; @@ -34,7 +37,7 @@ public class CLineBreakpoint extends AbstractLineBreakpoint { /** * Constructor for CLineBreakpoint. */ - public CLineBreakpoint( IResource resource, Map attributes, boolean add ) throws CoreException { + public CLineBreakpoint( IResource resource, Map attributes, boolean add ) throws CoreException { super( resource, getMarkerType(), attributes, add ); } @@ -50,6 +53,27 @@ public class CLineBreakpoint extends AbstractLineBreakpoint { */ @Override protected String getMarkerMessage() throws CoreException { - return MessageFormat.format( BreakpointMessages.getString( "CLineBreakpoint.0" ), new String[] { CDebugUtils.getBreakpointText( this, false ) } ); //$NON-NLS-1$ + IMarker marker = this.getMarker(); + int bp_line = 0; + int bp_request_line = 0; + String bp_file = null; + String bp_reqest_file = null; + + if (marker != null) { + bp_line = marker.getAttribute(IMarker.LINE_NUMBER, -1); + bp_request_line = marker.getAttribute(ICLineBreakpoint2.REQUESTED_LINE, -1); + bp_file = marker.getAttribute(ICBreakpoint.SOURCE_HANDLE, (String)null); + bp_reqest_file = marker.getAttribute(ICLineBreakpoint2.REQUESTED_SOURCE_HANDLE, (String)null); + } + + if (bp_line != bp_request_line || + (bp_file == null && bp_reqest_file != null) || + (bp_file != null && !bp_file.equals(bp_reqest_file)) ) + { + return MessageFormat.format( BreakpointMessages.getString( "CLineBreakpoint.1" ), (Object[])new String[] { CDebugUtils.getBreakpointText( this, false ) } ); //$NON-NLS-1$ + } + else { + return MessageFormat.format( BreakpointMessages.getString( "CLineBreakpoint.0" ), (Object[])new String[] { CDebugUtils.getBreakpointText( this, false ) } ); //$NON-NLS-1$ + } } } diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CLineTracepoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CLineTracepoint.java index 803d59389d6..c911cc63daf 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CLineTracepoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CLineTracepoint.java @@ -13,7 +13,10 @@ package org.eclipse.cdt.debug.internal.core.breakpoints; import java.util.Map; import org.eclipse.cdt.debug.core.CDebugUtils; +import org.eclipse.cdt.debug.core.model.ICBreakpoint; +import org.eclipse.cdt.debug.core.model.ICLineBreakpoint2; import org.eclipse.cdt.debug.core.model.ICTracepoint; +import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; @@ -24,7 +27,7 @@ import com.ibm.icu.text.MessageFormat; * * @since 6.1 */ -public class CLineTracepoint extends AbstractTracepoint implements ICTracepoint { +public class CLineTracepoint extends AbstractTracepoint implements ICTracepoint, ICLineBreakpoint2 { private static final String C_LINE_TRACEPOINT_MARKER = "org.eclipse.cdt.debug.core.cLineTracepointMarker"; //$NON-NLS-1$ @@ -48,11 +51,121 @@ public class CLineTracepoint extends AbstractTracepoint implements ICTracepoint return C_LINE_TRACEPOINT_MARKER; } + @Override + public synchronized int decrementInstallCount() throws CoreException { + int count = super.decrementInstallCount(); + if (count == 0) { + resetInstalledLocation(); + } + return count; + } + /*(non-Javadoc) * @see org.eclipse.cdt.debug.internal.core.breakpoints.CBreakpoint#getMarkerMessage() */ @Override protected String getMarkerMessage() throws CoreException { - return MessageFormat.format( BreakpointMessages.getString( "CLineTracepoint.0" ), new String[] { CDebugUtils.getBreakpointText( this, false ) } ); //$NON-NLS-1$ + return MessageFormat.format( BreakpointMessages.getString( "CLineTracepoint.0" ), (Object[])new String[] { CDebugUtils.getBreakpointText( this, false ) } ); //$NON-NLS-1$ } + + @Override + public int getRequestedLine() throws CoreException { + return ensureMarker().getAttribute( ICLineBreakpoint2.REQUESTED_LINE, -1 ); + } + + @Override + public void setRequestedLine(int line) throws CoreException { + setAttribute( ICLineBreakpoint2.REQUESTED_LINE, line ); + } + + @Override + public int getRequestedCharStart() throws CoreException { + return ensureMarker().getAttribute( ICLineBreakpoint2.REQUESTED_CHAR_START, -1 ); + } + + @Override + public void setRequestedCharStart(int charStart) throws CoreException { + setAttribute( ICLineBreakpoint2.REQUESTED_CHAR_START, charStart ); + } + + @Override + public int getRequestedCharEnd() throws CoreException { + return ensureMarker().getAttribute( ICLineBreakpoint2.REQUESTED_CHAR_END, -1 ); + } + + @Override + public void setRequestedCharEnd(int charEnd) throws CoreException { + setAttribute( ICLineBreakpoint2.REQUESTED_CHAR_END, charEnd ); + } + + @Override + public String getRequestedSourceHandle() throws CoreException { + return ensureMarker().getAttribute( ICLineBreakpoint2.REQUESTED_SOURCE_HANDLE, "" ); //$NON-NLS-1$ + } + + @Override + public void setRequestedSourceHandle(String fileName) throws CoreException { + setAttribute( ICLineBreakpoint2.REQUESTED_SOURCE_HANDLE, fileName ); + } + + @Override + public void setInstalledLineNumber(int line) throws CoreException { + int existingValue = ensureMarker().getAttribute(IMarker.LINE_NUMBER, -1); + if (line != existingValue) { + setAttribute(IMarker.LINE_NUMBER, line); + setAttribute( IMarker.MESSAGE, getMarkerMessage() ); + } + } + + @Override + public void setInstalledCharStart(int charStart) throws CoreException { + int existingValue = ensureMarker().getAttribute(IMarker.CHAR_START, -1); + if (charStart != existingValue) { + setAttribute(IMarker.CHAR_START, charStart); + setAttribute( IMarker.MESSAGE, getMarkerMessage() ); + } + } + + @Override + public void setInstalledCharEnd(int charEnd) throws CoreException { + int existingValue = ensureMarker().getAttribute(IMarker.CHAR_END, -1); + if (charEnd != existingValue) { + setAttribute(IMarker.CHAR_END, charEnd); + setAttribute( IMarker.MESSAGE, getMarkerMessage() ); + } + } + + @Override + public void resetInstalledLocation() throws CoreException { + boolean locationReset = false; + if (this.getMarker().getAttribute(REQUESTED_LINE) != null) { + int line = this.getMarker().getAttribute(REQUESTED_LINE, -1); + setAttribute(IMarker.LINE_NUMBER, line); + locationReset = true; + } + if (this.getMarker().getAttribute(REQUESTED_CHAR_START) != null) { + int charStart = this.getMarker().getAttribute(REQUESTED_CHAR_START, -1); + setAttribute(IMarker.CHAR_START, charStart); + locationReset = true; + } + if (this.getMarker().getAttribute(REQUESTED_CHAR_END) != null) { + int charEnd = this.getMarker().getAttribute(REQUESTED_CHAR_END, -1); + setAttribute(IMarker.CHAR_END, charEnd); + locationReset = true; + } + if (this.getMarker().getAttribute(REQUESTED_SOURCE_HANDLE) != null) { + String file = this.getMarker().getAttribute(REQUESTED_SOURCE_HANDLE, ""); //$NON-NLS-1$ + setAttribute(ICBreakpoint.SOURCE_HANDLE, file); + locationReset = true; + } + if (locationReset) { + setAttribute( IMarker.MESSAGE, getMarkerMessage() ); + } + } + + @Override + public void refreshMessage() throws CoreException { + IMarker marker = ensureMarker(); + marker.setAttribute(IMarker.MESSAGE, getMarkerMessage()); + } } diff --git a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CWatchpoint.java b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CWatchpoint.java index b995859cab8..75f992d126d 100644 --- a/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CWatchpoint.java +++ b/debug/org.eclipse.cdt.debug.core/src/org/eclipse/cdt/debug/internal/core/breakpoints/CWatchpoint.java @@ -36,11 +36,11 @@ public class CWatchpoint extends CBreakpoint implements ICWatchpoint2 { /** * Constructor for CWatchpoint. */ - public CWatchpoint( IResource resource, Map attributes, boolean add ) throws CoreException { + public CWatchpoint( IResource resource, Map attributes, boolean add ) throws CoreException { super( resource, getMarkerType(), attributes, add ); } - protected CWatchpoint( IResource resource, String marker, Map attributes, boolean add ) throws CoreException { + protected CWatchpoint( IResource resource, String marker, Map attributes, boolean add ) throws CoreException { super( resource, marker, attributes, add ); } @@ -87,7 +87,7 @@ public class CWatchpoint extends CBreakpoint implements ICWatchpoint2 { format = BreakpointMessages.getString( "CWatchpoint.1" ); //$NON-NLS-1$ else if ( isWriteType() && isReadType() ) format = BreakpointMessages.getString( "CWatchpoint.2" ); //$NON-NLS-1$ - return MessageFormat.format( format, new String[] { CDebugUtils.getBreakpointText( this, false ) } ); + return MessageFormat.format( format, new Object[] { CDebugUtils.getBreakpointText( this, false ) } ); } /* (non-Javadoc) diff --git a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/CBreakpointPropertyPage.java b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/CBreakpointPropertyPage.java index 1b188d0660f..006f98937e8 100644 --- a/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/CBreakpointPropertyPage.java +++ b/debug/org.eclipse.cdt.debug.ui/src/org/eclipse/cdt/debug/internal/ui/propertypages/CBreakpointPropertyPage.java @@ -21,6 +21,7 @@ import org.eclipse.cdt.debug.core.model.ICBreakpoint; import org.eclipse.cdt.debug.core.model.ICEventBreakpoint; import org.eclipse.cdt.debug.core.model.ICFunctionBreakpoint; import org.eclipse.cdt.debug.core.model.ICLineBreakpoint; +import org.eclipse.cdt.debug.core.model.ICLineBreakpoint2; import org.eclipse.cdt.debug.core.model.ICWatchpoint; import org.eclipse.cdt.debug.ui.CDebugUIPlugin; import org.eclipse.cdt.debug.ui.breakpoints.CBreakpointUIContributionFactory; @@ -424,12 +425,12 @@ public class CBreakpointPropertyPage extends FieldEditorPreferencePage implement fElement = element; } - @Override + @Override public IPreferenceStore getPreferenceStore() { return fCBreakpointPreferenceStore; } - @Override + @Override public boolean performOk() { final List changedProperties = new ArrayList( 5 ); getPreferenceStore().addPropertyChangeListener( new IPropertyChangeListener() { @@ -437,7 +438,7 @@ public class CBreakpointPropertyPage extends FieldEditorPreferencePage implement /** * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ - @Override + @Override public void propertyChange( PropertyChangeEvent event ) { changedProperties.add( event.getProperty() ); } @@ -450,7 +451,7 @@ public class CBreakpointPropertyPage extends FieldEditorPreferencePage implement protected void setBreakpointProperties( final List changedProperties ) { IWorkspaceRunnable wr = new IWorkspaceRunnable() { - @Override + @Override public void run( IProgressMonitor monitor ) throws CoreException { ICBreakpoint breakpoint = getBreakpoint(); Iterator changed = changedProperties.iterator(); @@ -468,6 +469,7 @@ public class CBreakpointPropertyPage extends FieldEditorPreferencePage implement else if ( property.equals( CBreakpointPreferenceStore.LINE ) ) { // already workspace runnable, setting markers are safe breakpoint.getMarker().setAttribute(IMarker.LINE_NUMBER, getPreferenceStore().getInt(CBreakpointPreferenceStore.LINE)); + breakpoint.getMarker().setAttribute(ICLineBreakpoint2.REQUESTED_LINE, getPreferenceStore().getInt(CBreakpointPreferenceStore.LINE)); } else { // this allow set attributes contributed by other plugins String value = getPropertyAsString(property); @@ -483,6 +485,7 @@ public class CBreakpointPropertyPage extends FieldEditorPreferencePage implement CDebugUIPlugin.log( ce ); } } + /** * Creates field editors contributed using breakpointUIContribution extension point * @param breakpoint From 1dbaf3c1baad7a1fd713b8b2c211f13d442eda7a Mon Sep 17 00:00:00 2001 From: Pawel Piech Date: Mon, 30 Jan 2012 21:49:01 -0800 Subject: [PATCH 11/43] Bug 360280 - [breakpoints] Reposition breakpoints when planted on invalid line (PDA Example - Added updating of C Breakpoint status to set installed flag and update line number) --- .../debug/service/BreakpointsMediator2.java | 55 ++++---- .../META-INF/MANIFEST.MF | 3 +- .../pda/launch/PDAServicesInitSequence.java | 4 +- .../launch/PDAServicesShutdownSequence.java | 4 +- .../PDABreakpointAttributeTranslator.java | 123 ++++++++++++++++-- 5 files changed, 150 insertions(+), 39 deletions(-) diff --git a/dsf/org.eclipse.cdt.dsf/src/org/eclipse/cdt/dsf/debug/service/BreakpointsMediator2.java b/dsf/org.eclipse.cdt.dsf/src/org/eclipse/cdt/dsf/debug/service/BreakpointsMediator2.java index d77e185869b..035a41991eb 100644 --- a/dsf/org.eclipse.cdt.dsf/src/org/eclipse/cdt/dsf/debug/service/BreakpointsMediator2.java +++ b/dsf/org.eclipse.cdt.dsf/src/org/eclipse/cdt/dsf/debug/service/BreakpointsMediator2.java @@ -14,6 +14,7 @@ package org.eclipse.cdt.dsf.debug.service; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -181,8 +182,8 @@ public class BreakpointsMediator2 extends AbstractDsfService implements IBreakpo * - Modified on breakpointChanged() * - Diminished on breakpointRemoved() */ - private Map>> fPlatformBPs = - new HashMap>>(); + private Map>> fPlatformBPs = + new HashMap>>(); /** * BreakpointsTargetDMContext's that are being removed from {@link #fPlatformBPs}. @@ -352,7 +353,7 @@ public class BreakpointsMediator2 extends AbstractDsfService implements IBreakpo // - Install the platform breakpoints on the selected target // Make sure a mapping for this execution context does not already exist - Map> platformBPs = fPlatformBPs.get(dmc); + Map> platformBPs = fPlatformBPs.get(dmc); if (platformBPs != null) { rm.setStatus(new Status(IStatus.ERROR, getPluginID(), INTERNAL_ERROR, "Context already initialized", null)); //$NON-NLS-1$ rm.done(); @@ -361,7 +362,7 @@ public class BreakpointsMediator2 extends AbstractDsfService implements IBreakpo // Create entries in the breakpoint tables for the new context. These entries should only // be removed when this service stops tracking breakpoints for the given context. - fPlatformBPs.put(dmc, new HashMap>()); + fPlatformBPs.put(dmc, new HashMap>()); // Install the platform breakpoints (stored in fPlatformBPs) on the target. // We need to use a background thread for this operation because we are @@ -391,7 +392,7 @@ public class BreakpointsMediator2 extends AbstractDsfService implements IBreakpo // - Remove the target breakpoints for the given DMC // - Remove the given DMC from the internal maps. // - Map> platformBPs = fPlatformBPs.get(dmc); + Map> platformBPs = fPlatformBPs.get(dmc); if (platformBPs == null) { rm.setStatus(new Status(IStatus.INFO /* NOT error */, getPluginID(), INTERNAL_ERROR, "Breakpoints not installed for given context", null)); //$NON-NLS-1$ rm.done(); @@ -449,11 +450,11 @@ public class BreakpointsMediator2 extends AbstractDsfService implements IBreakpo public ITargetBreakpointInfo[] getTargetBreakpoints(IBreakpointsTargetDMContext dmc, IBreakpoint platformBp) { assert getExecutor().isInExecutorThread(); - Map> platformBPs = fPlatformBPs.get(dmc); + Map> platformBPs = fPlatformBPs.get(dmc); if (platformBPs != null) { - List bpInfo = platformBPs.get(platformBp); + List bpInfo = platformBPs.get(platformBp); if (bpInfo != null) { return bpInfo.toArray(new ITargetBreakpointInfo[bpInfo.size()]); } @@ -475,14 +476,14 @@ public class BreakpointsMediator2 extends AbstractDsfService implements IBreakpo if (dmc != null && !dmc.equals(bpContext)) continue; - Map> platformBPs = fPlatformBPs.get(bpContext); + Map> platformBPs = fPlatformBPs.get(bpContext); if (platformBPs != null && platformBPs.size() > 0) { - for(Map.Entry> e: platformBPs.entrySet()) + for(Map.Entry> e: platformBPs.entrySet()) { // Stop at the first occurrence - for (TargetBP tbp : e.getValue()) + for (ITargetBreakpointInfo tbp : e.getValue()) if(tbp.getTargetBreakpoint().equals(bp)) return e.getKey(); } @@ -510,7 +511,7 @@ public class BreakpointsMediator2 extends AbstractDsfService implements IBreakpo final List> attrsList, final DataRequestMonitor> rm) { // Retrieve the set of breakpoints for this context - final Map> platformBPs = fPlatformBPs.get(dmc); + final Map> platformBPs = fPlatformBPs.get(dmc); assert platformBPs != null; // Ensure the breakpoint is not already installed @@ -521,7 +522,7 @@ public class BreakpointsMediator2 extends AbstractDsfService implements IBreakpo targetBPsAttempted.add(new TargetBP(attrsList.get(i))); } - final ArrayList targetBPsInstalled = new ArrayList(attrsList.size()); + final ArrayList targetBPsInstalled = new ArrayList(attrsList.size()); // Update the breakpoint status when all back-end breakpoints have been installed final CountingRequestMonitor installRM = new CountingRequestMonitor(getExecutor(), rm) { @@ -575,17 +576,17 @@ public class BreakpointsMediator2 extends AbstractDsfService implements IBreakpo * regardless of success or failure in the removal. */ private void uninstallBreakpoint(final IBreakpointsTargetDMContext dmc, final IBreakpoint breakpoint, - final DataRequestMonitor> drm) + final DataRequestMonitor> drm) { // Remove the back-end breakpoints - final Map> platformBPs = fPlatformBPs.get(dmc); + final Map> platformBPs = fPlatformBPs.get(dmc); if (platformBPs == null) { drm.setStatus(new Status(IStatus.ERROR, getPluginID(), INVALID_HANDLE, "Invalid breakpoint", null)); //$NON-NLS-1$ drm.done(); return; } - final List bpList = platformBPs.get(breakpoint); + final List bpList = platformBPs.get(breakpoint); assert bpList != null; // Only try to remove those targetBPs that are successfully installed. @@ -604,7 +605,7 @@ public class BreakpointsMediator2 extends AbstractDsfService implements IBreakpo int count = 0; for (int i = 0; i < bpList.size(); i++) { - final TargetBP bp = bpList.get(i); + final ITargetBreakpointInfo bp = bpList.get(i); if (bp.getTargetBreakpoint() != null) { fBreakpointsService.removeBreakpoint( bp.getTargetBreakpoint(), @@ -612,16 +613,16 @@ public class BreakpointsMediator2 extends AbstractDsfService implements IBreakpo @Override protected void handleCompleted() { // Remember result of the removal, success or failure. - bp.setStatus(getStatus()); + ((TargetBP)bp).setStatus(getStatus()); if (isSuccess()) { - bp.setTargetBreakpoint(null); + ((TargetBP)bp).setTargetBreakpoint(null); } countingRm.done(); } }); count++; } else { - bp.setStatus(Status.OK_STATUS); + ((TargetBP)bp).setStatus(Status.OK_STATUS); } } countingRm.setDoneCount(count); @@ -712,6 +713,11 @@ public class BreakpointsMediator2 extends AbstractDsfService implements IBreakpo @Override protected void handleCompleted() { processPendingRequests(); + for (Map.Entry> eventEntry : eventBPs.entrySet()) { + for (Map.Entry bpEntry : eventEntry.getValue().entrySet()) { + fPlatformBPs.get(bpEntry.getKey()).put(eventEntry.getKey(), Arrays.asList( bpEntry.getValue() )); + } + } fireUpdateBreakpointsStatus(eventBPs, BreakpointEventType.ADDED); if (rm != null) // don't call this if "rm" is null as this will @@ -930,9 +936,9 @@ public class BreakpointsMediator2 extends AbstractDsfService implements IBreakpo fRunningEvents.add(bp); for (IBreakpointsTargetDMContext context : updateContexts) { - List targetBPs = fPlatformBPs.get(context).get(bp); + List targetBPs = fPlatformBPs.get(context).get(bp); if (targetBPs != null) { - for (TargetBP tbp : targetBPs) { + for (ITargetBreakpointInfo tbp : targetBPs) { // this must be an installed breakpoint. assert (tbp.getTargetBreakpoint() != null); @@ -1016,6 +1022,11 @@ public class BreakpointsMediator2 extends AbstractDsfService implements IBreakpo protected void handleCompleted() { processPendingRequests(); fireUpdateBreakpointsStatus(eventBPs, BreakpointEventType.REMOVED); + for (Map.Entry> eventEntry : eventBPs.entrySet()) { + for (IBreakpointsTargetDMContext bpTarget : eventEntry.getValue().keySet()) { + fPlatformBPs.get(bpTarget).remove(eventEntry.getKey()); + } + } if (rm != null) // don't call this if "rm" is null as this will // log errors if any and pack Eclipse error @@ -1063,7 +1074,7 @@ public class BreakpointsMediator2 extends AbstractDsfService implements IBreakpo uninstallBreakpoint( dmc, breakpoint, - new DataRequestMonitor>(getExecutor(), bpTargetsCountingRM) { + new DataRequestMonitor>(getExecutor(), bpTargetsCountingRM) { @Override protected void handleSuccess() { targetBPs.put(dmc, getData().toArray(new ITargetBreakpointInfo[getData().size()])); diff --git a/dsf/org.eclipse.cdt.examples.dsf.pda/META-INF/MANIFEST.MF b/dsf/org.eclipse.cdt.examples.dsf.pda/META-INF/MANIFEST.MF index 2b3f03a1738..556e410a81e 100644 --- a/dsf/org.eclipse.cdt.examples.dsf.pda/META-INF/MANIFEST.MF +++ b/dsf/org.eclipse.cdt.examples.dsf.pda/META-INF/MANIFEST.MF @@ -10,7 +10,8 @@ Require-Bundle: org.eclipse.core.runtime, org.eclipse.core.variables, org.eclipse.debug.core, org.eclipse.cdt.dsf, - org.eclipse.cdt.core;bundle-version="5.0.0" + org.eclipse.cdt.core;bundle-version="5.0.0", + org.eclipse.cdt.debug.core;bundle-version="7.2.0" Bundle-ActivationPolicy: lazy Export-Package: org.eclipse.cdt.examples.dsf.pda, org.eclipse.cdt.examples.dsf.pda.breakpoints, diff --git a/dsf/org.eclipse.cdt.examples.dsf.pda/src/org/eclipse/cdt/examples/dsf/pda/launch/PDAServicesInitSequence.java b/dsf/org.eclipse.cdt.examples.dsf.pda/src/org/eclipse/cdt/examples/dsf/pda/launch/PDAServicesInitSequence.java index 450de109ba6..5fa3d499afc 100644 --- a/dsf/org.eclipse.cdt.examples.dsf.pda/src/org/eclipse/cdt/examples/dsf/pda/launch/PDAServicesInitSequence.java +++ b/dsf/org.eclipse.cdt.examples.dsf.pda/src/org/eclipse/cdt/examples/dsf/pda/launch/PDAServicesInitSequence.java @@ -13,7 +13,7 @@ package org.eclipse.cdt.examples.dsf.pda.launch; import org.eclipse.cdt.dsf.concurrent.RequestMonitor; import org.eclipse.cdt.dsf.concurrent.Sequence; import org.eclipse.cdt.dsf.datamodel.DataModelInitializedEvent; -import org.eclipse.cdt.dsf.debug.service.BreakpointsMediator; +import org.eclipse.cdt.dsf.debug.service.BreakpointsMediator2; import org.eclipse.cdt.dsf.service.DsfSession; import org.eclipse.cdt.examples.dsf.pda.service.PDABackend; import org.eclipse.cdt.examples.dsf.pda.service.PDABreakpointAttributeTranslator; @@ -75,7 +75,7 @@ public class PDAServicesInitSequence extends Sequence { public void execute(final RequestMonitor requestMonitor) { // Create the breakpoint mediator and start tracking PDA breakpoints. - final BreakpointsMediator bpmService = new BreakpointsMediator( + final BreakpointsMediator2 bpmService = new BreakpointsMediator2( fSession, new PDABreakpointAttributeTranslator()); bpmService.initialize(new RequestMonitor(getExecutor(), requestMonitor) { @Override diff --git a/dsf/org.eclipse.cdt.examples.dsf.pda/src/org/eclipse/cdt/examples/dsf/pda/launch/PDAServicesShutdownSequence.java b/dsf/org.eclipse.cdt.examples.dsf.pda/src/org/eclipse/cdt/examples/dsf/pda/launch/PDAServicesShutdownSequence.java index 37873d6048c..ac6e81d48bb 100644 --- a/dsf/org.eclipse.cdt.examples.dsf.pda/src/org/eclipse/cdt/examples/dsf/pda/launch/PDAServicesShutdownSequence.java +++ b/dsf/org.eclipse.cdt.examples.dsf.pda/src/org/eclipse/cdt/examples/dsf/pda/launch/PDAServicesShutdownSequence.java @@ -14,7 +14,7 @@ import org.eclipse.cdt.dsf.concurrent.DsfExecutor; import org.eclipse.cdt.dsf.concurrent.IDsfStatusConstants; import org.eclipse.cdt.dsf.concurrent.RequestMonitor; import org.eclipse.cdt.dsf.concurrent.Sequence; -import org.eclipse.cdt.dsf.debug.service.BreakpointsMediator; +import org.eclipse.cdt.dsf.debug.service.BreakpointsMediator2; import org.eclipse.cdt.dsf.service.DsfServicesTracker; import org.eclipse.cdt.dsf.service.IDsfService; import org.eclipse.cdt.examples.dsf.pda.PDAPlugin; @@ -77,7 +77,7 @@ public class PDAServicesShutdownSequence extends Sequence { new Step() { @Override public void execute(RequestMonitor requestMonitor) { - shutdownService(BreakpointsMediator.class, requestMonitor); + shutdownService(BreakpointsMediator2.class, requestMonitor); } }, new Step() { @Override diff --git a/dsf/org.eclipse.cdt.examples.dsf.pda/src/org/eclipse/cdt/examples/dsf/pda/service/PDABreakpointAttributeTranslator.java b/dsf/org.eclipse.cdt.examples.dsf.pda/src/org/eclipse/cdt/examples/dsf/pda/service/PDABreakpointAttributeTranslator.java index c404806cfb8..1a082761534 100644 --- a/dsf/org.eclipse.cdt.examples.dsf.pda/src/org/eclipse/cdt/examples/dsf/pda/service/PDABreakpointAttributeTranslator.java +++ b/dsf/org.eclipse.cdt.examples.dsf.pda/src/org/eclipse/cdt/examples/dsf/pda/service/PDABreakpointAttributeTranslator.java @@ -15,9 +15,14 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.eclipse.cdt.debug.core.model.ICLineBreakpoint; +import org.eclipse.cdt.dsf.concurrent.DataRequestMonitor; import org.eclipse.cdt.dsf.debug.service.BreakpointsMediator; -import org.eclipse.cdt.dsf.debug.service.IBreakpointAttributeTranslator; -import org.eclipse.cdt.dsf.debug.service.IBreakpoints.IBreakpointDMContext; +import org.eclipse.cdt.dsf.debug.service.BreakpointsMediator2; +import org.eclipse.cdt.dsf.debug.service.BreakpointsMediator2.BreakpointEventType; +import org.eclipse.cdt.dsf.debug.service.BreakpointsMediator2.ITargetBreakpointInfo; +import org.eclipse.cdt.dsf.debug.service.IBreakpointAttributeTranslator2; +import org.eclipse.cdt.dsf.debug.service.IBreakpoints.IBreakpointsTargetDMContext; import org.eclipse.cdt.examples.dsf.pda.PDAPlugin; import org.eclipse.cdt.examples.dsf.pda.breakpoints.PDALineBreakpoint; import org.eclipse.cdt.examples.dsf.pda.breakpoints.PDAWatchpoint; @@ -38,7 +43,7 @@ import org.eclipse.debug.core.model.IBreakpoint; * functionality of synchronizing target side and IDE-side breakpoint objects. *

*/ -public class PDABreakpointAttributeTranslator implements IBreakpointAttributeTranslator { +public class PDABreakpointAttributeTranslator implements IBreakpointAttributeTranslator2 { // Arrays of common attributes between the two breakpoint types. These // attributes can be copied directly without translation. @@ -56,14 +61,60 @@ public class PDABreakpointAttributeTranslator implements IBreakpointAttributeTra // PDA breakpoints translator doesn't keep any state and it doesn't // need to initialize or clean up. - public void initialize(BreakpointsMediator mediator) { + public void initialize(BreakpointsMediator2 mediator) { } + public void dispose() { } - public List> getBreakpointAttributes(IBreakpoint bp, boolean bpManagerEnabled) - throws CoreException + private List> getBreakpointAttributes(IBreakpoint bp, boolean bpManagerEnabled) + throws CoreException + { + if (bp instanceof ICLineBreakpoint) { + return getCBreakpointAttributes((ICLineBreakpoint)bp, bpManagerEnabled); + } else { + return getPDABreakpointAttributes(bp, bpManagerEnabled); + } + } + + private List> getCBreakpointAttributes(ICLineBreakpoint bp, boolean bpManagerEnabled) + throws CoreException + { + Map attrs = new HashMap(); + + // Check that the marker exists and retrieve its attributes. + // Due to accepted race conditions, the breakpiont marker may become null + // while this method is being invoked. In this case throw an exception + // and let the caller handle it. + IMarker marker = bp.getMarker(); + if (marker == null || !marker.exists()) { + throw new DebugException(new Status(IStatus.ERROR, PDAPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Breakpoint marker does not exist", null)); + } + // Suppress cast warning: platform is still on Java 1.3 + Map platformBpAttrs = marker.getAttributes(); + + // Copy breakpoint attributes. + attrs.put(PDABreakpoints.ATTR_BREAKPOINT_TYPE, PDABreakpoints.PDA_LINE_BREAKPOINT); + attrs.put(PDABreakpoints.ATTR_PROGRAM_PATH, bp.getFileName()); + + copyAttributes(platformBpAttrs, attrs, fgPDALineBreakpointAttributes); + + // If the breakpoint manager is disabled, override the enabled attribute. + if (!bpManagerEnabled) { + attrs.put(IBreakpoint.ENABLED, false); + } + + // The breakpoint mediator allows for multiple target-side breakpoints + // to be created for each IDE breakpoint. Although in case of PDA this + // feature is never used, we still have to return a list of attributes. + List> retVal = new ArrayList>(1); + retVal.add(attrs); + return retVal; + } + + private List> getPDABreakpointAttributes(IBreakpoint bp, boolean bpManagerEnabled) + throws CoreException { Map attrs = new HashMap(); @@ -76,7 +127,6 @@ public class PDABreakpointAttributeTranslator implements IBreakpointAttributeTra throw new DebugException(new Status(IStatus.ERROR, PDAPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Breakpoint marker does not exist", null)); } // Suppress cast warning: platform is still on Java 1.3 - @SuppressWarnings("unchecked") Map platformBpAttrs = marker.getAttributes(); // Copy breakpoint attributes. @@ -112,11 +162,13 @@ public class PDABreakpointAttributeTranslator implements IBreakpointAttributeTra } } - public boolean canUpdateAttributes(IBreakpointDMContext bp, Map delta) { + public boolean canUpdateAttributes(IBreakpoint bp, IBreakpointsTargetDMContext context, + Map attributes) + { // PDA debugger only allows updating of the action property of the watchpoint. // All other breakpoint updates will require a re-installation. if (bp instanceof PDAWatchpoint) { - Map deltaCopy = new HashMap(delta); + Map deltaCopy = new HashMap(attributes); deltaCopy.remove(PDAWatchpoint.ACCESS); deltaCopy.remove(PDAWatchpoint.MODIFICATION); return !deltaCopy.isEmpty(); @@ -125,11 +177,58 @@ public class PDABreakpointAttributeTranslator implements IBreakpointAttributeTra } public boolean supportsBreakpoint(IBreakpoint bp) { - return bp.getModelIdentifier().equals(PDAPlugin.ID_PDA_DEBUG_MODEL); + return bp.getModelIdentifier().equals(PDAPlugin.ID_PDA_DEBUG_MODEL) || + bp instanceof ICLineBreakpoint; } - public void updateBreakpointStatus(IBreakpoint bp) { - // PDA breakpoints do not support status reporting + public void updateBreakpointsStatus( + Map> bpsInfo, + BreakpointEventType eventType) + { + for (IBreakpoint bp : bpsInfo.keySet()) { + if (!(bp instanceof ICLineBreakpoint)) { + continue; + } + ICLineBreakpoint cbp = (ICLineBreakpoint)bp; + try { + if (eventType == BreakpointEventType.ADDED) { + cbp.incrementInstallCount(); +// Testing for Bug 360280 - [breakpoints] Reposition breakpoints when planted on invalid line +// if (cbp instanceof ICLineBreakpoint2) { +// ICLineBreakpoint2 lbp2 = (ICLineBreakpoint2)cbp; +// lbp2.setInstalledLineNumber(lbp2.getRequestedLine() + 1); +// } + } else if (eventType == BreakpointEventType.REMOVED) { + cbp.decrementInstallCount(); + } + } catch (CoreException e) {} + } } + public void resolveBreakpoint(IBreakpointsTargetDMContext context, IBreakpoint breakpoint, + Map bpAttributes, DataRequestMonitor>> drm) + { + try { + drm.setData( getBreakpointAttributes(breakpoint, true) ); + } catch (CoreException e) { + drm.setStatus(e.getStatus()); + } + drm.done(); + } + + public Map getAllBreakpointAttributes(IBreakpoint platformBP, boolean bpManagerEnabled) + throws CoreException + { + IMarker marker = platformBP.getMarker(); + if (marker == null) { + throw new DebugException(new Status(IStatus.ERROR, PDAPlugin.PLUGIN_ID, "Null marker for breakpoint: " + platformBP)); + } + return marker.getAttributes(); + } + + public Map convertAttributes(Map platformBPAttr) { + return platformBPAttr; + } + + } From e683d197ac8c35be9e86a5fa9976e2e2432d77a4 Mon Sep 17 00:00:00 2001 From: Doug Schaefer Date: Wed, 8 Feb 2012 17:03:38 -0500 Subject: [PATCH 12/43] Added ability to select toolchains for templates that have multiple. --- .../plugin.xml | 23 ++++ .../managedbuilder/internal/ui/Messages.java | 2 + .../internal/ui/Messages.properties | 2 + .../ui/wizards/ToolChainSelectionPage.java | 100 +++++++++++++++ core/org.eclipse.cdt.ui/plugin.properties | 1 + core/org.eclipse.cdt.ui/plugin.xml | 1 + .../schema/projectTypePages.exsd | 118 ++++++++++++++++++ .../eclipse/cdt/internal/ui/CUIMessages.java | 7 ++ .../cdt/internal/ui/CUIMessages.properties | 8 ++ .../org/eclipse/cdt/ui/wizards/Messages.java | 31 ----- .../cdt/ui/wizards/NewCDTProjectWizard.java | 16 +-- .../cdt/ui/wizards/ProjectTypePage.java | 33 +++++ .../cdt/ui/wizards/TemplateSelectionPage.java | 56 ++++++++- .../cdt/ui/wizards/messages.properties | 17 --- 14 files changed, 355 insertions(+), 60 deletions(-) create mode 100644 build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/ui/wizards/ToolChainSelectionPage.java create mode 100644 core/org.eclipse.cdt.ui/schema/projectTypePages.exsd delete mode 100644 core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/Messages.java create mode 100644 core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/ProjectTypePage.java delete mode 100644 core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/messages.properties diff --git a/build/org.eclipse.cdt.managedbuilder.ui/plugin.xml b/build/org.eclipse.cdt.managedbuilder.ui/plugin.xml index 94449d3aaf7..9a6cb9b7870 100644 --- a/build/org.eclipse.cdt.managedbuilder.ui/plugin.xml +++ b/build/org.eclipse.cdt.managedbuilder.ui/plugin.xml @@ -648,5 +648,28 @@ + + + + + + + + + + diff --git a/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/internal/ui/Messages.java b/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/internal/ui/Messages.java index 94f8c37d3f6..9a53359c5c2 100644 --- a/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/internal/ui/Messages.java +++ b/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/internal/ui/Messages.java @@ -279,6 +279,8 @@ public class Messages extends NLS { public static String WizardDefaultsTab_0; public static String WizardDefaultsTab_1; public static String RefreshPolicyTab_resourcesTreeLabel; + public static String ToolChainSelectionPage_Description; + public static String ToolChainSelectionPage_Title; static { // Initialize resource bundle. diff --git a/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/internal/ui/Messages.properties b/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/internal/ui/Messages.properties index 3fdd4bfe8fb..6501855af3d 100644 --- a/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/internal/ui/Messages.properties +++ b/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/internal/ui/Messages.properties @@ -300,3 +300,5 @@ NewCfgDialog_3=-- not selected -- NewCfgDialog_4=Import from projects NewCfgDialog_5=Import predefined +ToolChainSelectionPage_Description=Select the initial toolchain for this project. +ToolChainSelectionPage_Title=Select Tool Chain diff --git a/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/ui/wizards/ToolChainSelectionPage.java b/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/ui/wizards/ToolChainSelectionPage.java new file mode 100644 index 00000000000..5c0079ff92c --- /dev/null +++ b/build/org.eclipse.cdt.managedbuilder.ui/src/org/eclipse/cdt/managedbuilder/ui/wizards/ToolChainSelectionPage.java @@ -0,0 +1,100 @@ +/******************************************************************************* + * Copyright (c) 2012 Doug Schaefer and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Doug Schaefer - initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.managedbuilder.ui.wizards; + +import org.eclipse.cdt.managedbuilder.core.IToolChain; +import org.eclipse.cdt.managedbuilder.core.ManagedBuildManager; +import org.eclipse.cdt.managedbuilder.internal.ui.Messages; +import org.eclipse.cdt.ui.templateengine.Template; +import org.eclipse.cdt.ui.wizards.ProjectTypePage; +import org.eclipse.jface.wizard.IWizard; +import org.eclipse.jface.wizard.IWizardPage; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.List; + +/** + * @since 8.1 + * + */ +public class ToolChainSelectionPage extends WizardPage implements ProjectTypePage { + + private IWizardPage nextPage; + private String[] toolChainIds; + private String selectedToolChainId; + private List toolChainList; + + public ToolChainSelectionPage() { + super("ToolChainSelectionPage"); //$NON-NLS-1$ + setTitle(Messages.ToolChainSelectionPage_Title); + setDescription(Messages.ToolChainSelectionPage_Description); + } + + @Override + public void createControl(Composite parent) { + Composite comp = new Composite(parent, SWT.NONE); + comp.setLayout(new GridLayout(1, true)); + + toolChainList = new List(comp, SWT.BORDER | SWT.SINGLE); + toolChainList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + + for (String toolChainId : toolChainIds) { + IToolChain toolChain = ManagedBuildManager.getExtensionToolChain(toolChainId); + if (toolChain != null) + toolChainList.add(toolChain.getName()); + } + + toolChainList.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent e) { + if (toolChainList.getSelectionCount() == 0) + selectedToolChainId = null; + else + selectedToolChainId = toolChainIds[toolChainList.getSelectionIndex()]; + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + widgetSelected(e); + } + }); + + setControl(comp); + } + + @Override + public boolean init(Template template, IWizard wizard, IWizardPage nextPage) { + this.nextPage = nextPage; + setWizard(wizard); + toolChainIds = template.getTemplateInfo().getToolChainIds(); + + // only need this page if there are multiple toolChains to select from. + return toolChainIds != null && toolChainIds.length > 1; + } + + @Override + public IWizardPage getNextPage() { + if (nextPage != null) + return nextPage; + return super.getNextPage(); + } + + @Override + public boolean isPageComplete() { + return selectedToolChainId != null; + } + +} diff --git a/core/org.eclipse.cdt.ui/plugin.properties b/core/org.eclipse.cdt.ui/plugin.properties index 87d10a5f7ee..f50ea9bbbe8 100644 --- a/core/org.eclipse.cdt.ui/plugin.properties +++ b/core/org.eclipse.cdt.ui/plugin.properties @@ -631,3 +631,4 @@ extension-point.name = Refresh Exclusion Contributor # New New Project Wizard newProjectWizard.name = C/C++ Project (prototype) +projectTypePages = Project Type Pages \ No newline at end of file diff --git a/core/org.eclipse.cdt.ui/plugin.xml b/core/org.eclipse.cdt.ui/plugin.xml index 213506932b9..a04963c4b9d 100644 --- a/core/org.eclipse.cdt.ui/plugin.xml +++ b/core/org.eclipse.cdt.ui/plugin.xml @@ -27,6 +27,7 @@ + diff --git a/core/org.eclipse.cdt.ui/schema/projectTypePages.exsd b/core/org.eclipse.cdt.ui/schema/projectTypePages.exsd new file mode 100644 index 00000000000..c3268a79163 --- /dev/null +++ b/core/org.eclipse.cdt.ui/schema/projectTypePages.exsd @@ -0,0 +1,118 @@ + + + + + + + + + This extension is used to register a page in the CDT new project wizard to support +specifying additional information based on the project type associated with a template. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + [Enter the first release in which this extension point appears.] + + + + + + + + + [Enter extension point usage example here.] + + + + + + + + + [Enter API information here.] + + + + + + + + + [Enter information about supplied implementation of this extension point.] + + + + + diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/CUIMessages.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/CUIMessages.java index c6a0008048c..c50e1e9744d 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/CUIMessages.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/CUIMessages.java @@ -71,6 +71,13 @@ public final class CUIMessages extends NLS { public static String FileTransferDragAdapter_refreshing; public static String FileTransferDragAdapter_problem; public static String FileTransferDragAdapter_problemTitle; + public static String NewCDTProjectWizard_mainPageDesc; + public static String NewCDTProjectWizard_mainPageTitle; + public static String NewCDTProjectWizard_refPageDesc; + public static String NewCDTProjectWizard_refPageTitle; + public static String NewCDTProjectWizard_templatePageDesc; + public static String NewCDTProjectWizard_templatePageTitle; + public static String NewCDTProjectWizard_windowTitle; static { NLS.initializeMessages(BUNDLE_NAME, CUIMessages.class); diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/CUIMessages.properties b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/CUIMessages.properties index 581ad5ed2d5..f200d3d2a42 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/CUIMessages.properties +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/CUIMessages.properties @@ -73,3 +73,11 @@ CStructureCreatorVisitor_translationUnitName=Translation Unit FileTransferDragAdapter_refreshing=Refreshing... FileTransferDragAdapter_problem=Problem while moving or copying files. FileTransferDragAdapter_problemTitle=Drag & Drop + +NewCDTProjectWizard_mainPageDesc=Create a new C/C++ Project +NewCDTProjectWizard_mainPageTitle=Project +NewCDTProjectWizard_refPageDesc=Select referenced projects +NewCDTProjectWizard_refPageTitle=Project References +NewCDTProjectWizard_templatePageDesc=Select a project template for the new project +NewCDTProjectWizard_templatePageTitle=Project Template +NewCDTProjectWizard_windowTitle=New C/C++ Project diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/Messages.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/Messages.java deleted file mode 100644 index 37a94c7a97a..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/Messages.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 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 - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Doug Schaefer - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.ui.wizards; - -import org.eclipse.osgi.util.NLS; - -class Messages extends NLS { - private static final String BUNDLE_NAME = "org.eclipse.cdt.ui.wizards.messages"; //$NON-NLS-1$ - public static String NewCDTProjectWizard_mainPageDesc; - public static String NewCDTProjectWizard_mainPageTitle; - public static String NewCDTProjectWizard_refPageDesc; - public static String NewCDTProjectWizard_refPageTitle; - public static String NewCDTProjectWizard_templatePageDesc; - public static String NewCDTProjectWizard_templatePageTitle; - public static String NewCDTProjectWizard_windowTitle; - static { - // initialize resource bundle - NLS.initializeMessages(BUNDLE_NAME, Messages.class); - } - - private Messages() { - } -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/NewCDTProjectWizard.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/NewCDTProjectWizard.java index 282d6e93b5c..df418029cc3 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/NewCDTProjectWizard.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/NewCDTProjectWizard.java @@ -11,6 +11,8 @@ import org.eclipse.ui.IWorkbench; import org.eclipse.ui.dialogs.WizardNewProjectCreationPage; import org.eclipse.ui.dialogs.WizardNewProjectReferencePage; +import org.eclipse.cdt.internal.ui.CUIMessages; + /** * This is the new CDT project wizard. * @@ -32,7 +34,7 @@ public class NewCDTProjectWizard extends Wizard implements INewWizard { public void init(IWorkbench workbench, IStructuredSelection selection) { this.selection = selection; setNeedsProgressMonitor(true); - setWindowTitle(Messages.NewCDTProjectWizard_windowTitle); + setWindowTitle(CUIMessages.NewCDTProjectWizard_windowTitle); } @Override @@ -56,22 +58,22 @@ public class NewCDTProjectWizard extends Wizard implements INewWizard { Dialog.applyDialogFont(getControl()); } }; - mainPage.setTitle(Messages.NewCDTProjectWizard_mainPageTitle); - mainPage.setDescription(Messages.NewCDTProjectWizard_mainPageDesc); + mainPage.setTitle(CUIMessages.NewCDTProjectWizard_mainPageTitle); + mainPage.setDescription(CUIMessages.NewCDTProjectWizard_mainPageDesc); addPage(mainPage); templatePage = new TemplateSelectionPage(); - templatePage.setTitle(Messages.NewCDTProjectWizard_templatePageTitle); - templatePage.setDescription(Messages.NewCDTProjectWizard_templatePageDesc); + templatePage.setTitle(CUIMessages.NewCDTProjectWizard_templatePageTitle); + templatePage.setDescription(CUIMessages.NewCDTProjectWizard_templatePageDesc); addPage(templatePage); // only add page if there are already projects in the workspace if (ResourcesPlugin.getWorkspace().getRoot().getProjects().length > 0) { referencePage = new WizardNewProjectReferencePage( "basicReferenceProjectPage");//$NON-NLS-1$ - referencePage.setTitle(Messages.NewCDTProjectWizard_refPageTitle); + referencePage.setTitle(CUIMessages.NewCDTProjectWizard_refPageTitle); referencePage - .setDescription(Messages.NewCDTProjectWizard_refPageDesc); + .setDescription(CUIMessages.NewCDTProjectWizard_refPageDesc); this.addPage(referencePage); } } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/ProjectTypePage.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/ProjectTypePage.java new file mode 100644 index 00000000000..ad5eae3b08d --- /dev/null +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/ProjectTypePage.java @@ -0,0 +1,33 @@ +/******************************************************************************* + * Copyright (c) 2012 Doug Schaefer and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Doug Schaefer - initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.ui.wizards; + +import org.eclipse.jface.wizard.IWizard; +import org.eclipse.jface.wizard.IWizardPage; + +import org.eclipse.cdt.ui.templateengine.Template; + +/** + * @since 5.4 + */ +public interface ProjectTypePage extends IWizardPage { + + /** + * Init the page. Return false if the page isn't needed. + * + * @param template The selected template + * @param wizard The wizard object + * @param nextPage The next page after this one + * @return whether page is really needed + */ + boolean init(Template template, IWizard wizard, IWizardPage nextPage); + +} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/TemplateSelectionPage.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/TemplateSelectionPage.java index 64920103516..2608bce5a5d 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/TemplateSelectionPage.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/TemplateSelectionPage.java @@ -14,7 +14,13 @@ package org.eclipse.cdt.ui.wizards; import java.util.LinkedList; import java.util.List; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IExtension; +import org.eclipse.core.runtime.IExtensionPoint; +import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; @@ -90,7 +96,7 @@ public class TemplateSelectionPage extends WizardPage { private TreeViewer templateTree; private Template selectedTemplate; - private IWizardPage[] nextPages; + private IWizardPage nextPage; public TemplateSelectionPage() { super("templateSelection"); //$NON-NLS-1$ @@ -179,7 +185,7 @@ public class TemplateSelectionPage extends WizardPage { @Override public void selectionChanged(SelectionChangedEvent event) { selectedTemplate = null; - nextPages = null; + nextPage = null; IStructuredSelection selection = (IStructuredSelection)templateTree.getSelection(); Object selObj = selection.getFirstElement(); if (selObj instanceof Node) { @@ -187,8 +193,19 @@ public class TemplateSelectionPage extends WizardPage { if (object instanceof Template) { IWizard wizard = getWizard(); selectedTemplate = (Template)object; - nextPages = selectedTemplate.getTemplateWizardPages(TemplateSelectionPage.this, + + // Get the template pages + IWizardPage[] templatePages = selectedTemplate.getTemplateWizardPages(TemplateSelectionPage.this, wizard.getNextPage(TemplateSelectionPage.this), wizard); + if (templatePages != null && templatePages.length > 0) + nextPage = templatePages[0]; + + String projectType = selectedTemplate.getTemplateInfo().getProjectType(); + ProjectTypePage projectTypePage = getProjectTypePage(projectType); + if (projectTypePage != null) { + if (projectTypePage.init(selectedTemplate, wizard, nextPage)) + nextPage = projectTypePage; + } setPageComplete(true); } else { setPageComplete(false); @@ -215,8 +232,8 @@ public class TemplateSelectionPage extends WizardPage { @Override public IWizardPage getNextPage() { - if (nextPages != null && nextPages.length > 0) - return nextPages[0]; + if (nextPage != null) + return nextPage; return super.getNextPage(); } @@ -288,4 +305,33 @@ public class TemplateSelectionPage extends WizardPage { return nodes; } + private ProjectTypePage getProjectTypePage(String projectType) { + if (projectType != null && !projectType.isEmpty()) { + IExtensionRegistry reg = Platform.getExtensionRegistry(); + IExtensionPoint point = reg.getExtensionPoint(CUIPlugin.PLUGIN_ID, "projectTypePages"); //$NON-NLS-1$ + if (point == null) + return null; + IExtension[] exts = point.getExtensions(); + for (IExtension ext : exts) { + IConfigurationElement[] elems = ext.getConfigurationElements(); + for (IConfigurationElement elem : elems) { + if (elem.getName().equals("projectTypePage")) { //$NON-NLS-1$ + String ept = elem.getAttribute("projectType"); //$NON-NLS-1$ + if (projectType.equals(ept)) { + try { + Object obj = elem.createExecutableExtension("class"); //$NON-NLS-1$ + if (obj instanceof ProjectTypePage) + return (ProjectTypePage)obj; + } catch (CoreException e) { + CUIPlugin.log(e.getStatus()); + } + } + } + } + } + } + + return null; + } + } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/messages.properties b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/messages.properties deleted file mode 100644 index e44a79ce2d9..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/messages.properties +++ /dev/null @@ -1,17 +0,0 @@ -################################################################################# -# Copyright (c) 2012 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 -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# Doug Schaefer - initial API and implementation -################################################################################# -NewCDTProjectWizard_mainPageDesc=Create a new C/C++ Project -NewCDTProjectWizard_mainPageTitle=Project -NewCDTProjectWizard_refPageDesc=Select referenced projects -NewCDTProjectWizard_refPageTitle=Project References -NewCDTProjectWizard_templatePageDesc=Select a project template for the new project -NewCDTProjectWizard_templatePageTitle=Project Template -NewCDTProjectWizard_windowTitle=New C/C++ Project From a9662b7f9ffddce0b0c9c0d1b157dd5e98f5cbbf Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Tue, 7 Feb 2012 20:40:29 -0800 Subject: [PATCH 13/43] Fixed VariableReadWriteFlagsTest.testImplicitArgument. --- .../parser/tests/ast2/VariableReadWriteFlagsTest.java | 2 +- .../core/dom/parser/VariableReadWriteFlags.java | 6 +++++- .../cpp/semantics/CPPVariableReadWriteFlags.java | 10 ++++++++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/VariableReadWriteFlagsTest.java b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/VariableReadWriteFlagsTest.java index de6ed76f3be..43b4926929c 100644 --- a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/VariableReadWriteFlagsTest.java +++ b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/VariableReadWriteFlagsTest.java @@ -152,7 +152,7 @@ public class VariableReadWriteFlagsTest extends AST2BaseTest { // a.m1(); // a.m2(); // }; - public void _testImplicitArgument() throws Exception { + public void testImplicitArgument() throws Exception { AssertionHelper a = getCPPAssertionHelper(); a.assertReadWriteFlags("a.m1", READ | WRITE); a.assertReadWriteFlags("a.m2", READ); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java index 6f2c0a4342e..29e5bb8fdb7 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java @@ -146,7 +146,7 @@ public abstract class VariableReadWriteFlags { } if (expr instanceof IASTFunctionCallExpression) { if (node.getPropertyInParent() == IASTFunctionCallExpression.FUNCTION_NAME) { - return READ; + return rwFunctionName((IASTExpression) node); } return rwArgumentForFunctionCall((IASTFunctionCallExpression) expr, node, indirection); } @@ -160,6 +160,10 @@ public abstract class VariableReadWriteFlags { return READ | WRITE; // fall back } + protected int rwFunctionName(IASTExpression node) { + return READ; + } + protected int rwArgumentForFunctionCall(final IASTFunctionCallExpression funcCall, IASTNode argument, int indirection) { final IASTInitializerClause[] args = funcCall.getArguments(); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVariableReadWriteFlags.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVariableReadWriteFlags.java index 482b1551f40..40a7d9b50d9 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVariableReadWriteFlags.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVariableReadWriteFlags.java @@ -12,6 +12,7 @@ package org.eclipse.cdt.internal.core.dom.parser.cpp.semantics; import org.eclipse.cdt.core.dom.ast.IASTDeclarator; +import org.eclipse.cdt.core.dom.ast.IASTExpression; import org.eclipse.cdt.core.dom.ast.IASTImplicitName; import org.eclipse.cdt.core.dom.ast.IASTImplicitNameOwner; import org.eclipse.cdt.core.dom.ast.IASTName; @@ -25,6 +26,7 @@ import org.eclipse.cdt.core.dom.ast.IVariable; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTConstructorInitializer; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTUnaryExpression; import org.eclipse.cdt.core.dom.ast.cpp.ICPPConstructor; +import org.eclipse.cdt.core.dom.ast.cpp.ICPPFunctionType; import org.eclipse.cdt.core.dom.ast.cpp.ICPPReferenceType; import org.eclipse.cdt.internal.core.dom.parser.ITypeContainer; import org.eclipse.cdt.internal.core.dom.parser.VariableReadWriteFlags; @@ -91,6 +93,14 @@ public final class CPPVariableReadWriteFlags extends VariableReadWriteFlags { return super.rwInUnaryExpression(node, expr, indirection); } + @Override + protected int rwFunctionName(IASTExpression node) { + IType type= node.getExpressionType(); + if (type instanceof ICPPFunctionType && !((ICPPFunctionType) type).isConst()) + return READ | WRITE; + return READ; + } + @Override protected int rwAssignmentToType(IType type, int indirection) { if (indirection == 0) { From 9601bcdd24ea566b65c13d3e1a26a0d1c0de2fd8 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Tue, 7 Feb 2012 20:55:57 -0800 Subject: [PATCH 14/43] Corrected test expectations. --- .../extractfunction/ExtractFunctionRefactoringTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java index 2d03fbd4db7..847c1575454 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java @@ -875,6 +875,7 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase { //int extracted(A b, A* a) { // return a->method() + b.const_method(); //} + // //int test() { // A a, b; // return extracted(b, &a) + a.const_method(); From 69457e8aecb3e0b8b76b3b473fcc3c64e39b6f96 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Wed, 8 Feb 2012 12:39:17 -0800 Subject: [PATCH 15/43] Cosmetics. --- .../cdt/core/dom/ast/IASTFieldReference.java | 26 ++++++++----------- .../core/dom/ast/cpp/ICPPFunctionType.java | 2 -- 2 files changed, 11 insertions(+), 17 deletions(-) diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTFieldReference.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTFieldReference.java index 36d43ae27e6..4ece8ac9a10 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTFieldReference.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTFieldReference.java @@ -6,20 +6,19 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Doug Schaefer (IBM) - Initial API and implementation + * Doug Schaefer (IBM) - Initial API and implementation *******************************************************************************/ package org.eclipse.cdt.core.dom.ast; /** - * This interface represents expressions that access a field reference. e.g. a.b => - * a is the expression, b is the field name. e.g. a()->def => a() is the + * This interface represents expressions that access a field reference. e.g. a.b => a + * is the expression, b is the field name. e.g. a()->def => a() is the * expression, def is the field name. * * @noextend This interface is not intended to be extended by clients. * @noimplement This interface is not intended to be implemented by clients. */ public interface IASTFieldReference extends IASTExpression, IASTNameOwner { - /** * FIELD_OWNER represents the relationship between a * IASTFieldReference and its IASTExpression @@ -37,46 +36,44 @@ public interface IASTFieldReference extends IASTExpression, IASTNameOwner { "IASTFieldReference.FIELD_NAME - IASTName for IASTFieldReference"); //$NON-NLS-1$ /** - * This returns an expression for the object containing the field. + * Returns an expression for the object containing the field. * * @return the field owner */ public IASTExpression getFieldOwner(); /** - * Set the expression for the object containing the field. + * Sets the expression for the object containing the field. * * @param expression */ public void setFieldOwner(IASTExpression expression); /** - * This returns the name of the field being dereferenced. + * Returns the name of the field being dereferenced. * * @return the name of the field (IASTName) */ public IASTName getFieldName(); /** - * Set the name of the field. + * Sets the name of the field. * - * @param name - * IASTName + * @param name the new name */ public void setFieldName(IASTName name); /** - * This returns true of this is the arrow operator and not the dot operator. + * Returns true of this is the arrow operator and not the dot operator. * * @return is this a pointer dereference */ public boolean isPointerDereference(); /** - * Set whether or not this is a pointer dereference (default == no). + * Sets whether or not this is a pointer dereference (default == no). * - * @param value - * boolean + * @param value the new value */ public void setIsPointerDereference(boolean value); @@ -91,5 +88,4 @@ public interface IASTFieldReference extends IASTExpression, IASTNameOwner { */ @Override public IASTFieldReference copy(CopyStyle style); - } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/cpp/ICPPFunctionType.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/cpp/ICPPFunctionType.java index f4d01264e3d..8bb23b2cbb2 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/cpp/ICPPFunctionType.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/cpp/ICPPFunctionType.java @@ -20,7 +20,6 @@ import org.eclipse.cdt.core.dom.ast.IPointerType; * @noimplement This interface is not intended to be implemented by clients. */ public interface ICPPFunctionType extends IFunctionType { - /** * Returns true for a constant method */ @@ -37,7 +36,6 @@ public interface ICPPFunctionType extends IFunctionType { */ public boolean takesVarArgs(); - /** * @deprecated function types don't relate to this pointers at all. * @noreference This method is not intended to be referenced by clients and should be removed. From 61e9d699ba21775a06748d2fbf3183d064411c37 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Wed, 8 Feb 2012 17:30:00 -0800 Subject: [PATCH 16/43] Bug 370887 - CPPVariableReadWriteFlags.getReadWriteFlags returns incorrect results. --- .../core/parser/tests/ast2/AST2BaseTest.java | 18 ++- .../ast2/VariableReadWriteFlagsTest.java | 123 +++++++++++------- .../dom/parser/VariableReadWriteFlags.java | 38 ++++-- .../core/dom/parser/cpp/ClassTypeHelper.java | 36 +++++ .../semantics/CPPVariableReadWriteFlags.java | 25 +++- .../ExtractFunctionRefactoringTest.java | 1 - .../cdt/ui/tests/text/MarkOccurrenceTest.java | 2 +- 7 files changed, 175 insertions(+), 68 deletions(-) diff --git a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2BaseTest.java b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2BaseTest.java index 51a2daceaa1..8305b215918 100644 --- a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2BaseTest.java +++ b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2BaseTest.java @@ -597,11 +597,27 @@ public class AST2BaseTest extends BaseTestCase { public IASTName findName(String section, int len) { final int offset = contents.indexOf(section); - assertTrue(offset >= 0); + assertTrue("Section \"" + section + "\" not found", offset >= 0); IASTNodeSelector selector = tu.getNodeSelector(null); return selector.findName(offset, len); } + public IASTName findName(String context, String name) { + if (context == null) { + context = contents; + } + int offset = contents.indexOf(context); + assertTrue("Context \"" + context + "\" not found", offset >= 0); + int nameOffset = context.indexOf(name); + assertTrue("Name \"" + name + "\" not found", nameOffset >= 0); + IASTNodeSelector selector = tu.getNodeSelector(null); + return selector.findName(offset + nameOffset, name.length()); + } + + public IASTName findName(String name) { + return findName(contents, name); + } + public IASTName findImplicitName(String section, int len) { final int offset = contents.indexOf(section); assertTrue(offset >= 0); diff --git a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/VariableReadWriteFlagsTest.java b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/VariableReadWriteFlagsTest.java index 43b4926929c..c0ef5db339e 100644 --- a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/VariableReadWriteFlagsTest.java +++ b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/VariableReadWriteFlagsTest.java @@ -32,21 +32,16 @@ public class VariableReadWriteFlagsTest extends AST2BaseTest { super(contents, isCPP); } - void assertReadWriteFlags(String section, int expectedFlags) throws Exception { - int len; - for (len = 0; len < section.length(); len++) { - if (!Character.isJavaIdentifierPart(section.charAt(len))) - break; - } - assertReadWriteFlags(section, len, expectedFlags); - } - - void assertReadWriteFlags(String section, int len, int expectedFlags) throws Exception { - IASTName variable = findName(section, len); + void assertReadWriteFlags(String context, String name, int expectedFlags) throws Exception { + IASTName variable = findName(context, name); assertNotNull(variable); assertEquals(flagsToString(expectedFlags), flagsToString(getReadWriteFlags(variable))); } + void assertReadWriteFlags(String name, int expectedFlags) throws Exception { + assertReadWriteFlags(null, name, expectedFlags); + } + int getReadWriteFlags(IASTName variable) { return isCPP ? CPPVariableReadWriteFlags.getReadWriteFlags(variable) : @@ -90,71 +85,101 @@ public class VariableReadWriteFlagsTest extends AST2BaseTest { return new AssertionHelper(code, true); } - // int test() { - // int a; + // int test(int a) { // a = 2; + // a *= 3; // return a + 1; // } public void testSimpleAccess() throws Exception { AssertionHelper a = getCPPAssertionHelper(); - a.assertReadWriteFlags("a = 2", WRITE); - a.assertReadWriteFlags("a +", READ); + a.assertReadWriteFlags("a = 2", "a", WRITE); + a.assertReadWriteFlags("a *= 3", "a", READ | WRITE); + a.assertReadWriteFlags("a + 1", "a", READ); } - // int a = 1; - public void _testEqualsInitializer() throws Exception { + // class C { + // public: + // C(int); + // }; + // + // class D { + // public: + // D(); + // }; + // + // int a; + // int b = 1; + // C c; + // D d; + // C e(1); + // template void foo(T p) { + // T f; + // } + public void testVariableDeclaration() throws Exception { AssertionHelper a = getCPPAssertionHelper(); - a.assertReadWriteFlags("a", WRITE); + a.assertReadWriteFlags("int a", "a", 0); + a.assertReadWriteFlags("int b = 1", "b", WRITE); + a.assertReadWriteFlags("C c", "c", 0); + a.assertReadWriteFlags("D d", "d", WRITE); + a.assertReadWriteFlags("C e(1)", "e", WRITE); + a.assertReadWriteFlags("T f", "f", WRITE); } // struct A { int x; }; // - // void test() { - // A a; + // void test(A a, A* ap) { // a.x = 1; + // (&a)->x = 1; + // ap->x = 1; // }; public void testFieldAccess() throws Exception { AssertionHelper a = getCPPAssertionHelper(); - a.assertReadWriteFlags("a.", WRITE); + a.assertReadWriteFlags("a.x", "a", WRITE); + a.assertReadWriteFlags("a.x", "x", WRITE); + a.assertReadWriteFlags("(&a)->x", "a", WRITE); + a.assertReadWriteFlags("(&a)->x", "x", WRITE); + a.assertReadWriteFlags("ap->x", "ap", READ); + a.assertReadWriteFlags("ap->x", "x", WRITE); } - // struct A { int x; }; + // void f(int* x, int& y); + // void g(const int* x, const int& y, int z); // - // void test(A* a) { - // a->x = 1; + // void test(int a, int b, int c) { + // f(&a, b); + // g(&a, b, c); // }; - public void testFieldAccessWithDereference() throws Exception { + public void testFunctionCall() throws Exception { AssertionHelper a = getCPPAssertionHelper(); - a.assertReadWriteFlags("a->", READ); - } - - // void f(int* x); - // void g(const int* x); - // - // void test() { - // int a, b; - // f(&a); - // g(&b); - // }; - public void testExplicitArgument() throws Exception { - AssertionHelper a = getCPPAssertionHelper(); - a.assertReadWriteFlags("a)", READ | WRITE); - a.assertReadWriteFlags("b)", READ); + a.assertReadWriteFlags("f(&a, b)", "a", READ | WRITE); + a.assertReadWriteFlags("f(&a, b)", "b", READ | WRITE); + a.assertReadWriteFlags("f(&a, b)", "f", READ); + a.assertReadWriteFlags("g(&a, b, c)", "a", READ); + a.assertReadWriteFlags("g(&a, b, c)", "b", READ); + a.assertReadWriteFlags("g(&a, b, c)", "c", READ); } // struct A { - // void m1(); - // void m2() const; + // void m(); + // void mc() const; // }; // - // void test() { - // A a; - // a.m1(); - // a.m2(); + // void test(A a, A* ap) { + // a.m(); + // a.mc(); + // (&a)->m(); + // (&a)->mc(); + // ap->m(); + // (*ap).m(); // }; - public void testImplicitArgument() throws Exception { + public void testMethodCall() throws Exception { AssertionHelper a = getCPPAssertionHelper(); - a.assertReadWriteFlags("a.m1", READ | WRITE); - a.assertReadWriteFlags("a.m2", READ); + a.assertReadWriteFlags("a.m()", "a", READ | WRITE); + a.assertReadWriteFlags("a.m()", "m", READ); + a.assertReadWriteFlags("a.mc()", "a", READ); + a.assertReadWriteFlags("(&a)->m()", "a", READ | WRITE); + a.assertReadWriteFlags("(&a)->m()", "m", READ); + a.assertReadWriteFlags("ap->m()", "ap", READ); + a.assertReadWriteFlags("(*ap).m()", "ap", READ); } } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java index 29e5bb8fdb7..881a069faf8 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/VariableReadWriteFlags.java @@ -57,15 +57,14 @@ public abstract class VariableReadWriteFlags { protected static final int READ = PDOMName.READ_ACCESS; protected static final int WRITE = PDOMName.WRITE_ACCESS; - protected VariableReadWriteFlags() { - } - protected int rwAnyNode(IASTNode node, int indirection) { final IASTNode parent = node.getParent(); if (parent instanceof IASTExpression) { return rwInExpression((IASTExpression) parent, node, indirection); } else if (parent instanceof IASTStatement) { return rwInStatement((IASTStatement) parent, node, indirection); + } else if (parent instanceof IASTDeclarator) { + return rwInDeclarator((IASTDeclarator) parent, indirection); } else if (parent instanceof IASTEqualsInitializer) { return rwInEqualsInitializer((IASTEqualsInitializer) parent, indirection); } else if (parent instanceof IASTArrayModifier) { @@ -76,6 +75,12 @@ public abstract class VariableReadWriteFlags { return READ | WRITE; // fallback } + protected int rwInDeclarator(IASTDeclarator parent, int indirection) { + if (parent.getInitializer() != null) + return WRITE; + return 0; + } + protected int rwInEqualsInitializer(IASTEqualsInitializer parent, int indirection) { IASTNode grand= parent.getParent(); if (grand instanceof IASTDeclarator) { @@ -112,11 +117,7 @@ public abstract class VariableReadWriteFlags { return rwInBinaryExpression(node, (IASTBinaryExpression) expr, indirection); } if (expr instanceof IASTFieldReference) { - if (node.getPropertyInParent() != IASTFieldReference.FIELD_OWNER || - !((IASTFieldReference) expr).isPointerDereference()) { - return rwAnyNode(expr, indirection); - } - return READ; + return rwInFieldReference(node, (IASTFieldReference) expr, indirection); } if (expr instanceof IASTCastExpression) { // must be ahead of unary return rwAnyNode(expr, indirection); @@ -126,7 +127,7 @@ public abstract class VariableReadWriteFlags { } if (expr instanceof IASTArraySubscriptExpression) { if (indirection > 0 && node.getPropertyInParent() == IASTArraySubscriptExpression.ARRAY) { - return rwAnyNode(expr, indirection-1); + return rwAnyNode(expr, indirection - 1); } return READ; } @@ -146,7 +147,7 @@ public abstract class VariableReadWriteFlags { } if (expr instanceof IASTFunctionCallExpression) { if (node.getPropertyInParent() == IASTFunctionCallExpression.FUNCTION_NAME) { - return rwFunctionName((IASTExpression) node); + return rwInFunctionName((IASTExpression) node); } return rwArgumentForFunctionCall((IASTFunctionCallExpression) expr, node, indirection); } @@ -160,7 +161,20 @@ public abstract class VariableReadWriteFlags { return READ | WRITE; // fall back } - protected int rwFunctionName(IASTExpression node) { + protected int rwInFieldReference(IASTNode node, IASTFieldReference expr, int indirection) { + if (node.getPropertyInParent() == IASTFieldReference.FIELD_NAME) { + if (expr.getPropertyInParent() != IASTFunctionCallExpression.FUNCTION_NAME) + return rwAnyNode(expr, indirection); + } else { // IASTFieldReference.FIELD_OWNER + if (expr.isPointerDereference()) + --indirection; + if (indirection >= 0) + return rwAnyNode(expr, indirection); + } + return READ; + } + + protected int rwInFunctionName(IASTExpression node) { return READ; } @@ -206,7 +220,7 @@ public abstract class VariableReadWriteFlags { while (parent instanceof IASTCompoundStatement) { IASTCompoundStatement compound= (IASTCompoundStatement) parent; IASTStatement[] statements= compound.getStatements(); - if (statements[statements.length-1] != stmt) { + if (statements[statements.length - 1] != stmt) { return 0; } stmt= compound; 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 9e864e324df..d2b13592b99 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 @@ -870,6 +870,42 @@ public class ClassTypeHelper { return null; } + /** + * Returns true if and only if the given class has a trivial default constructor. + * A default constructor is trivial if: + *
    + *
  • it is implicitly defined by the compiler, and
  • + *
  • every direct base class has trivial default constructor, and
  • + *
  • for every nonstatic data member that has class type or array of class type, that type + * has trivial default constructor.
  • + *
+ * Similar to std::tr1::has_trivial_default_constructor. + * + * @param classTarget the class to check + * @return true if the class has a trivial default constructor + */ + public static boolean hasTrivialDefaultConstructor(ICPPClassType classTarget) { + for (ICPPConstructor ctor : classTarget.getConstructors()) { + if (!ctor.isImplicit() && ctor.getParameters().length == 0) + return false; + } + for (ICPPClassType baseClass : getAllBases(classTarget)) { + if (!classTarget.isSameType(baseClass) && !hasTrivialDefaultConstructor(baseClass)) + return false; + } + for (ICPPField field : classTarget.getDeclaredFields()) { + if (!field.isStatic()) { + IType type = field.getType(); + type = SemanticUtil.getNestedType(type, TDEF | CVTYPE | ARRAY); + if (type instanceof ICPPClassType && !classTarget.isSameType(type) && + !hasTrivialDefaultConstructor((ICPPClassType) type)) { + return false; + } + } + } + return true; + } + /** * Returns true if and only if the given class has a trivial destructor. * A destructor is trivial if: diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVariableReadWriteFlags.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVariableReadWriteFlags.java index 40a7d9b50d9..cb3e0dad436 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVariableReadWriteFlags.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVariableReadWriteFlags.java @@ -13,6 +13,7 @@ package org.eclipse.cdt.internal.core.dom.parser.cpp.semantics; import org.eclipse.cdt.core.dom.ast.IASTDeclarator; import org.eclipse.cdt.core.dom.ast.IASTExpression; +import org.eclipse.cdt.core.dom.ast.IASTIdExpression; import org.eclipse.cdt.core.dom.ast.IASTImplicitName; import org.eclipse.cdt.core.dom.ast.IASTImplicitNameOwner; import org.eclipse.cdt.core.dom.ast.IASTName; @@ -25,11 +26,14 @@ import org.eclipse.cdt.core.dom.ast.IType; import org.eclipse.cdt.core.dom.ast.IVariable; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTConstructorInitializer; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTUnaryExpression; +import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassType; import org.eclipse.cdt.core.dom.ast.cpp.ICPPConstructor; import org.eclipse.cdt.core.dom.ast.cpp.ICPPFunctionType; import org.eclipse.cdt.core.dom.ast.cpp.ICPPReferenceType; import org.eclipse.cdt.internal.core.dom.parser.ITypeContainer; import org.eclipse.cdt.internal.core.dom.parser.VariableReadWriteFlags; +import org.eclipse.cdt.internal.core.dom.parser.cpp.ClassTypeHelper; +import org.eclipse.cdt.internal.core.dom.parser.cpp.ICPPUnknownType; /** * Helper class to determine whether a variable is accessed for reading and/or writing. @@ -52,6 +56,17 @@ public final class CPPVariableReadWriteFlags extends VariableReadWriteFlags { return super.rwAnyNode(node, indirection); } + @Override + protected int rwInDeclarator(IASTDeclarator parent, int indirection) { + IType type = CPPVisitor.createType(parent); + if (type instanceof ICPPUnknownType || + type instanceof ICPPClassType && + !ClassTypeHelper.hasTrivialDefaultConstructor((ICPPClassType) type)) { + return WRITE; + } + return super.rwInDeclarator(parent, indirection); + } + private int rwInCtorInitializer(IASTNode node, int indirection, ICPPASTConstructorInitializer parent) { IASTNode grand= parent.getParent(); if (grand instanceof IASTDeclarator) { @@ -94,10 +109,12 @@ public final class CPPVariableReadWriteFlags extends VariableReadWriteFlags { } @Override - protected int rwFunctionName(IASTExpression node) { - IType type= node.getExpressionType(); - if (type instanceof ICPPFunctionType && !((ICPPFunctionType) type).isConst()) - return READ | WRITE; + protected int rwInFunctionName(IASTExpression node) { + if (!(node instanceof IASTIdExpression)) { + IType type= node.getExpressionType(); + if (type instanceof ICPPFunctionType && !((ICPPFunctionType) type).isConst()) + return READ | WRITE; + } return READ; } diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java index 847c1575454..d03f38e6e06 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java @@ -881,7 +881,6 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase { // return extracted(b, &a) + a.const_method(); //} public void _testOutputParameterWithMethodCall() throws Exception { - // Currently fails due to http://bugs.eclipse.org/bugs/show_bug.cgi?id=370887 getPreferenceStore().setValue(PreferenceConstants.FUNCTION_PASS_OUTPUT_PARAMETERS_BY_POINTER, true); assertRefactoringSuccess(); } diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/MarkOccurrenceTest.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/MarkOccurrenceTest.java index fd6cd7e0b1d..1e96b57d50b 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/MarkOccurrenceTest.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/MarkOccurrenceTest.java @@ -357,7 +357,7 @@ public class MarkOccurrenceTest extends BaseUITestCase { fEditor.selectAndReveal(fMatch.getOffset(), fMatch.getLength()); - assertOccurrences(2, 1); + assertOccurrences(2, 0); assertOccurrencesInWidget(); } From 947882ff2fa4b2b4c0a277f948ab445e8d77b25b Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Wed, 8 Feb 2012 19:59:04 -0800 Subject: [PATCH 17/43] Cosmetics. --- .../org/eclipse/cdt/core/dom/ast/IASTCopyLocation.java | 6 ++---- .../org/eclipse/cdt/core/dom/ast/IASTFileLocation.java | 3 +-- .../org/eclipse/cdt/core/dom/ast/IASTMacroExpansion.java | 6 ++---- .../cdt/core/dom/ast/IASTMacroExpansionLocation.java | 3 +-- 4 files changed, 6 insertions(+), 12 deletions(-) diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTCopyLocation.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTCopyLocation.java index 99255d5baba..4671066b93f 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTCopyLocation.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTCopyLocation.java @@ -7,17 +7,15 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Institute for Software (IFS)- initial API and implementation + * Institute for Software (IFS)- initial API and implementation ******************************************************************************/ package org.eclipse.cdt.core.dom.ast; /** * @author Emanuel Graf IFS * @since 5.3 - * */ public interface IASTCopyLocation extends IASTNodeLocation { - - public IASTNode getOriginalNode(); + public IASTNode getOriginalNode(); } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTFileLocation.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTFileLocation.java index 9e7ab27a51c..4ad690da89d 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTFileLocation.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTFileLocation.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Doug Schaefer (IBM) - Initial API and implementation + * Doug Schaefer (IBM) - Initial API and implementation *******************************************************************************/ package org.eclipse.cdt.core.dom.ast; @@ -17,7 +17,6 @@ package org.eclipse.cdt.core.dom.ast; * @noimplement This interface is not intended to be implemented by clients. */ public interface IASTFileLocation extends IASTNodeLocation { - /** * The name of the file. * diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTMacroExpansion.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTMacroExpansion.java index afbf2d4b8be..5a0728f405e 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTMacroExpansion.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTMacroExpansion.java @@ -6,8 +6,8 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * IBM - Initial API and implementation - * Markus Schorn (Wind River Systems) + * IBM - Initial API and implementation + * Markus Schorn (Wind River Systems) *******************************************************************************/ package org.eclipse.cdt.core.dom.ast; @@ -16,10 +16,8 @@ package org.eclipse.cdt.core.dom.ast; */ @Deprecated public interface IASTMacroExpansion extends IASTNodeLocation { - /** * The macro definition used for the expansion - * */ public IASTPreprocessorMacroDefinition getMacroDefinition(); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTMacroExpansionLocation.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTMacroExpansionLocation.java index 4edf83d7dcf..1f26360063c 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTMacroExpansionLocation.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTMacroExpansionLocation.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Markus Schorn - initial API and implementation + * Markus Schorn - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.core.dom.ast; @@ -18,7 +18,6 @@ package org.eclipse.cdt.core.dom.ast; * @noimplement This interface is not intended to be implemented by clients. */ public interface IASTMacroExpansionLocation extends IASTNodeLocation { - /** * Returns the expansion node enclosing this location. This will be the outermost * macro expansion that can actually be found in the code. From e128056245491de047d14349f985b727bea1a0f5 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Wed, 8 Feb 2012 20:58:00 -0800 Subject: [PATCH 18/43] Fixed ExtractFunctionRefactoringTest.testOutputParameterWithMethodCall test. --- .../cdt/codan/core/cxx/CxxAstUtils.java | 9 ++++--- .../replace/WhitespaceHandlingTest.java | 5 ++-- .../cdt/core/dom/ast/IASTNodeLocation.java | 5 ++-- .../cdt/internal/core/dom/parser/ASTNode.java | 26 +++++++++---------- .../dom/parser/c/CASTArrayDeclarator.java | 2 +- .../core/dom/parser/c/CASTCaseStatement.java | 2 +- .../parser/c/CASTDesignatedInitializer.java | 2 +- .../cpp/CPPASTBinaryTypeIdExpression.java | 4 +-- .../dom/parser/cpp/CPPASTIdExpression.java | 2 +- .../cpp/CPPASTRangeBasedForStatement.java | 3 ++- .../core/dom/parser/cpp/CPPNodeFactory.java | 2 -- .../core/dom/rewrite/ASTLiteralNode.java | 2 +- .../dom/rewrite/DeclarationGeneratorImpl.java | 7 ++--- .../parser/scanner/ASTPreprocessorName.java | 4 +-- .../ExtractFunctionRefactoringTest.java | 2 +- ...pression.java => ExpressionExtractor.java} | 7 ++++- .../ExtractFunctionRefactoring.java | 21 +++++++-------- ...tionHelper.java => FunctionExtractor.java} | 10 ++++--- ...Statement.java => StatementExtractor.java} | 7 ++++- .../ui/refactoring/utils/NamespaceHelper.java | 2 +- 20 files changed, 69 insertions(+), 55 deletions(-) rename core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/{ExtractExpression.java => ExpressionExtractor.java} (98%) rename core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/{ExtractedFunctionConstructionHelper.java => FunctionExtractor.java} (96%) rename core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/{ExtractStatement.java => StatementExtractor.java} (95%) 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 afe58718799..32b4897795b 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 @@ -32,6 +32,7 @@ import org.eclipse.cdt.core.dom.ast.IASTFunctionDefinition; import org.eclipse.cdt.core.dom.ast.IASTIdExpression; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNode; +import org.eclipse.cdt.core.dom.ast.IASTNode.CopyStyle; import org.eclipse.cdt.core.dom.ast.IASTNodeSelector; import org.eclipse.cdt.core.dom.ast.IASTParameterDeclaration; import org.eclipse.cdt.core.dom.ast.IASTPreprocessorMacroExpansion; @@ -170,7 +171,7 @@ public final class CxxAstUtils { simpleDeclaration.addDeclarator(declarator); return simpleDeclaration; } else { // Fallback - return a `void` declaration - IASTDeclarator declarator = factory.newDeclarator(astName.copy()); + IASTDeclarator declarator = factory.newDeclarator(astName.copy(CopyStyle.withLocations)); IASTSimpleDeclSpecifier declspec = factory.newSimpleDeclSpecifier(); declspec.setType(Kind.eInt); IASTSimpleDeclaration simpleDeclaration = factory.newSimpleDeclaration(declspec); @@ -273,9 +274,9 @@ public final class CxxAstUtils { if (child instanceof IASTParameterDeclaration) { if (nthParam == targetParameterNum) { IASTParameterDeclaration pd = (IASTParameterDeclaration) child; - IASTDeclSpecifier declspec = pd.getDeclSpecifier().copy(); - IASTDeclarator declarator = pd.getDeclarator().copy(); - setNameInNestedDeclarator(declarator, astName.copy()); + IASTDeclSpecifier declspec = pd.getDeclSpecifier().copy(CopyStyle.withLocations); + IASTDeclarator declarator = pd.getDeclarator().copy(CopyStyle.withLocations); + setNameInNestedDeclarator(declarator, astName.copy(CopyStyle.withLocations)); IASTSimpleDeclaration declaration = factory.newSimpleDeclaration(declspec); declaration.addDeclarator(declarator); return declaration; diff --git a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/rewrite/changegenerator/replace/WhitespaceHandlingTest.java b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/rewrite/changegenerator/replace/WhitespaceHandlingTest.java index c748adcc8db..52703d639ed 100644 --- a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/rewrite/changegenerator/replace/WhitespaceHandlingTest.java +++ b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/rewrite/changegenerator/replace/WhitespaceHandlingTest.java @@ -13,8 +13,9 @@ package org.eclipse.cdt.core.parser.tests.rewrite.changegenerator.replace; import junit.framework.Test; -import org.eclipse.cdt.core.dom.ast.IASTStatement; import org.eclipse.cdt.core.dom.ast.ASTVisitor; +import org.eclipse.cdt.core.dom.ast.IASTNode.CopyStyle; +import org.eclipse.cdt.core.dom.ast.IASTStatement; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTForStatement; import org.eclipse.cdt.core.parser.tests.rewrite.changegenerator.ChangeGeneratorTest; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPNodeFactory; @@ -60,7 +61,7 @@ public class WhitespaceHandlingTest extends ChangeGeneratorTest { ICPPASTForStatement forStatement = (ICPPASTForStatement) statement; CPPNodeFactory nf = CPPNodeFactory.getDefault(); - ICPPASTForStatement newFor = forStatement.copy(); + ICPPASTForStatement newFor = forStatement.copy(CopyStyle.withLocations); newFor.setBody(nf.newNullStatement()); ASTModification modification = new ASTModification(ASTModification.ModificationKind.REPLACE, forStatement, newFor, null); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTNodeLocation.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTNodeLocation.java index 5cd0677d9dc..db6bbd5743b 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTNodeLocation.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTNodeLocation.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Doug Schaefer (IBM) - Initial API and implementation + * Doug Schaefer (IBM) - Initial API and implementation *******************************************************************************/ package org.eclipse.cdt.core.dom.ast; @@ -18,6 +18,8 @@ package org.eclipse.cdt.core.dom.ast; * @noimplement This interface is not intended to be implemented by clients. */ public interface IASTNodeLocation { + /** @since 5.4 */ + public static final IASTNodeLocation[] EMPTY_ARRAY = {}; /** * This is the offset within either the file or a macro-expansion. @@ -33,5 +35,4 @@ public interface IASTNodeLocation { * Return a file location that best maps into this location. */ public IASTFileLocation asFileLocation(); - } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTNode.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTNode.java index 0cf76a44f6c..5aa930983af 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTNode.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTNode.java @@ -8,6 +8,7 @@ * Contributors: * John Camelon - Initial API and implementation * Markus Schorn (Wind River Systems) + * Sergey Prigoin (Google) *******************************************************************************/ package org.eclipse.cdt.internal.core.dom.parser; @@ -36,7 +37,6 @@ import org.eclipse.cdt.internal.core.parser.scanner.Token; */ public abstract class ASTNode implements IASTNode { protected static final ICPPFunction UNINITIALIZED_FUNCTION = new CPPFunction(null); - private static final IASTNodeLocation[] EMPTY_LOCATION_ARRAY = {}; private IASTNode parent; private ASTNodeProperty property; @@ -139,18 +139,18 @@ public abstract class ASTNode implements IASTNode { @Override public IASTNodeLocation[] getNodeLocations() { - if (locations != null) - return locations; - if (length == 0) { - locations= EMPTY_LOCATION_ARRAY; - } else { - final IASTTranslationUnit tu= getTranslationUnit(); - if (tu != null) { - ILocationResolver l= (ILocationResolver) tu.getAdapter(ILocationResolver.class); - if (l != null) { - locations= l.getLocations(getOffset(), length); - } - } + if (locations == null) { + if (length != 0) { + final IASTTranslationUnit tu= getTranslationUnit(); + if (tu != null) { + ILocationResolver l= (ILocationResolver) tu.getAdapter(ILocationResolver.class); + if (l != null) { + locations= l.getLocations(getOffset(), length); + } + } + } + if (locations == null) + locations= IASTNodeLocation.EMPTY_ARRAY; } return locations; } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTArrayDeclarator.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTArrayDeclarator.java index 6c45aeb7425..4914bd8e863 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTArrayDeclarator.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTArrayDeclarator.java @@ -46,7 +46,7 @@ public class CASTArrayDeclarator extends CASTDeclarator implements IASTArrayDecl CASTArrayDeclarator copy = new CASTArrayDeclarator(); copyBaseDeclarator(copy, style); for (IASTArrayModifier modifier : getArrayModifiers()) - copy.addArrayModifier(modifier == null ? null : modifier.copy()); + copy.addArrayModifier(modifier == null ? null : modifier.copy(style)); if (style == CopyStyle.withLocations) { copy.setCopyLocation(this); } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTCaseStatement.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTCaseStatement.java index b22164b200c..c18db597193 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTCaseStatement.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTCaseStatement.java @@ -40,7 +40,7 @@ public class CASTCaseStatement extends ASTNode implements IASTCaseStatement, IAS @Override public CASTCaseStatement copy(CopyStyle style) { - CASTCaseStatement copy = new CASTCaseStatement(expression == null ? null : expression.copy()); + CASTCaseStatement copy = new CASTCaseStatement(expression == null ? null : expression.copy(style)); copy.setOffsetAndLength(this); if (style == CopyStyle.withLocations) { copy.setCopyLocation(this); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTDesignatedInitializer.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTDesignatedInitializer.java index 98426ffa7e6..7fa93f34f88 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTDesignatedInitializer.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTDesignatedInitializer.java @@ -100,7 +100,7 @@ public class CASTDesignatedInitializer extends ASTNode implements ICASTDesignate return (IASTInitializer) rhs; } if (rhs instanceof IASTExpression) { - CASTEqualsInitializer init = new CASTEqualsInitializer(((IASTExpression)rhs).copy()); + CASTEqualsInitializer init = new CASTEqualsInitializer(((IASTExpression) rhs).copy()); init.setParent(this); init.setPropertyInParent(OPERAND); return init; diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTBinaryTypeIdExpression.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTBinaryTypeIdExpression.java index ba3230b8fbd..dbc5686e5e3 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTBinaryTypeIdExpression.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTBinaryTypeIdExpression.java @@ -44,8 +44,8 @@ public class CPPASTBinaryTypeIdExpression extends ASTNode implements IASTBinaryT @Override public CPPASTBinaryTypeIdExpression copy(CopyStyle style) { CPPASTBinaryTypeIdExpression copy = new CPPASTBinaryTypeIdExpression(fOperator, - fOperand1 == null ? null : fOperand1.copy(), - fOperand2 == null ? null : fOperand2.copy()); + fOperand1 == null ? null : fOperand1.copy(style), + fOperand2 == null ? null : fOperand2.copy(style)); copy.setOffsetAndLength(this); if (style == CopyStyle.withLocations) { copy.setCopyLocation(this); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTIdExpression.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTIdExpression.java index 0508e3df4a7..9cec4d5e1c3 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTIdExpression.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTIdExpression.java @@ -69,7 +69,7 @@ public class CPPASTIdExpression extends ASTNode implements IASTIdExpression, ICP @Override public CPPASTIdExpression copy(CopyStyle style) { - CPPASTIdExpression copy = new CPPASTIdExpression(name == null ? null : name.copy()); + CPPASTIdExpression copy = new CPPASTIdExpression(name == null ? null : name.copy(style)); copy.setOffsetAndLength(this); if (style == CopyStyle.withLocations) { copy.setCopyLocation(this); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTRangeBasedForStatement.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTRangeBasedForStatement.java index f7e353d70b2..0a4dc3aacd4 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTRangeBasedForStatement.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPASTRangeBasedForStatement.java @@ -152,7 +152,8 @@ public class CPPASTRangeBasedForStatement extends ASTNode implements ICPPASTRang CPPASTName name = new CPPASTName(CPPVisitor.BEGIN); name.setOffset(position.getOffset()); CPPASTIdExpression fname = new CPPASTIdExpression(name); - IASTExpression expr= new CPPASTFunctionCallExpression(fname, new IASTInitializerClause[] {forInit.copy()}); + IASTExpression expr= new CPPASTFunctionCallExpression(fname, + new IASTInitializerClause[] { forInit.copy() }); expr.setParent(this); expr.setPropertyInParent(ICPPASTRangeBasedForStatement.INITIALIZER); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPNodeFactory.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPNodeFactory.java index 5e987c39a55..e7a8561d509 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPNodeFactory.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPNodeFactory.java @@ -113,12 +113,10 @@ import org.eclipse.cdt.core.parser.IScanner; import org.eclipse.cdt.internal.core.dom.parser.NodeFactory; import org.eclipse.cdt.internal.core.parser.scanner.CPreprocessor; - /** * Abstract factory implementation that creates C++ AST nodes. */ public class CPPNodeFactory extends NodeFactory implements ICPPNodeFactory { - private static final CPPNodeFactory DEFAULT_INSTANCE = new CPPNodeFactory(); public static CPPNodeFactory getDefault() { diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/ASTLiteralNode.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/ASTLiteralNode.java index 642cdb1d414..f4e3bcbb436 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/ASTLiteralNode.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/ASTLiteralNode.java @@ -61,7 +61,7 @@ public class ASTLiteralNode implements IASTNode { @Override public IASTNodeLocation[] getNodeLocations() { - return null; + return IASTNodeLocation.EMPTY_ARRAY; } @Override diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/DeclarationGeneratorImpl.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/DeclarationGeneratorImpl.java index 4718e1e11ac..49d25e0451a 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/DeclarationGeneratorImpl.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/DeclarationGeneratorImpl.java @@ -23,6 +23,7 @@ import org.eclipse.cdt.core.dom.ast.IASTDeclarator; import org.eclipse.cdt.core.dom.ast.IASTExpression; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNamedTypeSpecifier; +import org.eclipse.cdt.core.dom.ast.IASTNode.CopyStyle; import org.eclipse.cdt.core.dom.ast.IASTParameterDeclaration; import org.eclipse.cdt.core.dom.ast.IASTPointer; import org.eclipse.cdt.core.dom.ast.IASTPointerOperator; @@ -164,7 +165,7 @@ public class DeclarationGeneratorImpl extends DeclarationGenerator { arrayType = (IArrayType) type; IASTExpression arraySizeExpression = arrayType.getArraySizeExpression(); arrayDeclarator.addArrayModifier(factory.newArrayModifier(arraySizeExpression == null - ? null : arraySizeExpression.copy())); + ? null : arraySizeExpression.copy(CopyStyle.withLocations))); type = arrayType.getType(); } returnedDeclarator = arrayDeclarator; @@ -291,7 +292,7 @@ public class DeclarationGeneratorImpl extends DeclarationGenerator { int nbQualifiedNames = fullQualifiedName.getNames().length; if (nbQualifiedNames > 1) { for (int i = 0; i < nbQualifiedNames - 1; i++) { - newQualifiedName.addName(fullQualifiedName.getNames()[i].copy()); + newQualifiedName.addName(fullQualifiedName.getNames()[i].copy(CopyStyle.withLocations)); } } newQualifiedName.addName(tempId); @@ -309,7 +310,7 @@ public class DeclarationGeneratorImpl extends DeclarationGenerator { private ICPPASTTemplateId getTemplateId(ICPPTemplateInstance type, IASTName templateName) { ICPPNodeFactory cppFactory = (ICPPNodeFactory) factory; - ICPPASTTemplateId tempId = cppFactory.newTemplateId(templateName.copy()); + ICPPASTTemplateId tempId = cppFactory.newTemplateId(templateName.copy(CopyStyle.withLocations)); for (ICPPTemplateArgument arg : type.getTemplateArguments()) { IASTDeclSpecifier argDeclSpec = createDeclSpecFromType(arg.isTypeValue() ? arg.getTypeValue() : arg.getTypeOfNonTypeValue()); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/ASTPreprocessorName.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/ASTPreprocessorName.java index 704cac07265..79b03c72868 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/ASTPreprocessorName.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/ASTPreprocessorName.java @@ -164,9 +164,9 @@ class ASTBuiltinName extends ASTPreprocessorDefinition { @Override public IASTNodeLocation[] getNodeLocations() { if (fFileLocation == null) { - return new IASTNodeLocation[0]; + return IASTNodeLocation.EMPTY_ARRAY; } - return new IASTNodeLocation[]{fFileLocation}; + return new IASTNodeLocation[] { fFileLocation }; } @Override diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java index d03f38e6e06..0654b3fc02c 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/extractfunction/ExtractFunctionRefactoringTest.java @@ -880,7 +880,7 @@ public class ExtractFunctionRefactoringTest extends RefactoringTestBase { // A a, b; // return extracted(b, &a) + a.const_method(); //} - public void _testOutputParameterWithMethodCall() throws Exception { + public void testOutputParameterWithMethodCall() throws Exception { getPreferenceStore().setValue(PreferenceConstants.FUNCTION_PASS_OUTPUT_PARAMETERS_BY_POINTER, true); assertRefactoringSuccess(); } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractExpression.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExpressionExtractor.java similarity index 98% rename from core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractExpression.java rename to core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExpressionExtractor.java index 9409b833d72..3be0b99700a 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractExpression.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExpressionExtractor.java @@ -57,7 +57,12 @@ import org.eclipse.cdt.internal.ui.refactoring.NameInformation; * * @author Mirko Stocker */ -public class ExtractExpression extends ExtractedFunctionConstructionHelper { +public class ExpressionExtractor extends FunctionExtractor { + @Override + public boolean canChooseReturnValue() { + return false; + } + @Override public void constructMethodBody(IASTCompoundStatement compound, List nodes, List parameters, ASTRewrite rewrite, TextEditGroup group) { diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractFunctionRefactoring.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractFunctionRefactoring.java index cb72987ec55..50b6dca145e 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractFunctionRefactoring.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractFunctionRefactoring.java @@ -139,7 +139,7 @@ public class ExtractFunctionRefactoring extends CRefactoring { HashMap nameTrail; - private ExtractedFunctionConstructionHelper functionConstructionHelper; + private FunctionExtractor extractor; private INodeFactory nodeFactory; DefaultCodeFormatterOptions formattingOptions; @@ -204,7 +204,9 @@ public class ExtractFunctionRefactoring extends CRefactoring { if (initStatus.hasFatalError()) return initStatus; - if (info.getMandatoryReturnVariable() == null) { + extractor = FunctionExtractor.createFor(container.getNodesToWrite()); + + if (extractor.canChooseReturnValue() && info.getMandatoryReturnVariable() == null) { chooseReturnVariable(); } @@ -214,9 +216,6 @@ public class ExtractFunctionRefactoring extends CRefactoring { PreferenceConstants.getPreferenceScopes(project.getProject())); info.sortParameters(outFirst); - functionConstructionHelper = - ExtractedFunctionConstructionHelper.createFor(container.getNodesToWrite()); - boolean isExtractExpression = container.getNodesToWrite().get(0) instanceof IASTExpression; info.setExtractExpression(isExtractExpression); @@ -639,7 +638,7 @@ public class ExtractFunctionRefactoring extends CRefactoring { func.setDeclSpecifier(returnType); IASTStandardFunctionDeclarator createdFunctionDeclarator = - functionConstructionHelper.createFunctionDeclarator(qname, + extractor.createFunctionDeclarator(qname, info.getDeclarator(), info.getReturnVariable(), container.getNodesToWrite(), info.getParameters(), nodeFactory); func.setDeclarator(createdFunctionDeclarator); @@ -664,7 +663,7 @@ public class ExtractFunctionRefactoring extends CRefactoring { subRewrite = rewrite.insertBefore(parent, insertPoint, func, group); } - functionConstructionHelper.constructMethodBody(compound, container.getNodesToWrite(), + extractor.constructMethodBody(compound, container.getNodesToWrite(), info.getParameters(), subRewrite, group); // Set return value @@ -689,7 +688,7 @@ public class ExtractFunctionRefactoring extends CRefactoring { private IASTDeclSpecifier getReturnType() { IASTNode firstNodeToWrite = container.getNodesToWrite().get(0); NameInformation returnVariable = info.getReturnVariable(); - return functionConstructionHelper.determineReturnType(firstNodeToWrite, + return extractor.determineReturnType(firstNodeToWrite, returnVariable); } @@ -813,13 +812,13 @@ public class ExtractFunctionRefactoring extends CRefactoring { private IASTNode getReturnAssignment(IASTExpressionStatement stmt, IASTExpression callExpression) { IASTNode node = container.getNodesToWrite().get(0); - return functionConstructionHelper.createReturnAssignment(node, stmt, callExpression); + return extractor.createReturnAssignment(node, stmt, callExpression); } private IASTSimpleDeclaration getDeclaration(IASTName name) { IASTSimpleDeclaration simpleDecl = new CPPASTSimpleDeclaration(); IASTStandardFunctionDeclarator declarator = - functionConstructionHelper.createFunctionDeclarator(name, + extractor.createFunctionDeclarator(name, info.getDeclarator(), info.getReturnVariable(), container.getNodesToWrite(), info.getParameters(), nodeFactory); simpleDecl.addDeclarator(declarator); @@ -834,7 +833,7 @@ public class ExtractFunctionRefactoring extends CRefactoring { } simpleDecl.setParent(ast); IASTStandardFunctionDeclarator declarator = - functionConstructionHelper.createFunctionDeclarator(name, + extractor.createFunctionDeclarator(name, info.getDeclarator(), info.getReturnVariable(), container.getNodesToWrite(), info.getParameters(), nodeFactory); simpleDecl.addDeclarator(declarator); diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractedFunctionConstructionHelper.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/FunctionExtractor.java similarity index 96% rename from core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractedFunctionConstructionHelper.java rename to core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/FunctionExtractor.java index 0ba32f0e614..37ca4c431c8 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractedFunctionConstructionHelper.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/FunctionExtractor.java @@ -47,15 +47,17 @@ import org.eclipse.cdt.internal.ui.refactoring.NameInformation.Indirection; /** * @author Mirko Stocker */ -public abstract class ExtractedFunctionConstructionHelper { +public abstract class FunctionExtractor { - public static ExtractedFunctionConstructionHelper createFor(List list) { + public static FunctionExtractor createFor(List list) { if (list.get(0) instanceof IASTExpression) { - return new ExtractExpression(); + return new ExpressionExtractor(); } - return new ExtractStatement(); + return new StatementExtractor(); } + public abstract boolean canChooseReturnValue(); + public abstract void constructMethodBody(IASTCompoundStatement compound, List nodes, List parameters, ASTRewrite rewrite, TextEditGroup group); diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractStatement.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/StatementExtractor.java similarity index 95% rename from core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractStatement.java rename to core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/StatementExtractor.java index b9af77c0177..b6da4787615 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/ExtractStatement.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/StatementExtractor.java @@ -36,7 +36,12 @@ import org.eclipse.cdt.internal.ui.refactoring.utils.ASTHelper; /** * @author Mirko Stocker */ -public class ExtractStatement extends ExtractedFunctionConstructionHelper { +public class StatementExtractor extends FunctionExtractor { + @Override + public boolean canChooseReturnValue() { + return true; + } + @Override public void constructMethodBody(IASTCompoundStatement compound, List nodes, List parameters, ASTRewrite rewrite, TextEditGroup group) { diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/utils/NamespaceHelper.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/utils/NamespaceHelper.java index f8ce66ae422..ef1ae37ef84 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/utils/NamespaceHelper.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/utils/NamespaceHelper.java @@ -64,7 +64,7 @@ public class NamespaceHelper { @Override public int visit(ICPPASTNamespaceDefinition namespace) { if (checkFileNameAndLocation(translationUnit.getLocation(), offset, namespace)) { - qualifiedName.addName((namespace).getName().copy()); + qualifiedName.addName((namespace).getName().copy(CopyStyle.withLocations)); } return super.visit(namespace); From 2810e3a1fc54f9fd4dcf2dd08452319dc6d63658 Mon Sep 17 00:00:00 2001 From: Michael Lindo Date: Thu, 9 Feb 2012 14:00:08 -0500 Subject: [PATCH 19/43] Bug 370762 - Adding support for Remote Semantic Highlighting in the Remote C/C++ Editor --- .../editor/SemanticHighlightingManager.java | 41 ++++++++++--------- .../SemanticHighlightingReconciler.java | 20 ++++----- 2 files changed, 32 insertions(+), 29 deletions(-) diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/SemanticHighlightingManager.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/SemanticHighlightingManager.java index e9f1b5e77dd..4eef256b4e1 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/SemanticHighlightingManager.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/SemanticHighlightingManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -45,7 +45,7 @@ public class SemanticHighlightingManager implements IPropertyChangeListener { /** * Highlighting style. */ - static class HighlightingStyle { + public static class HighlightingStyle { /** Text attribute */ private TextAttribute fTextAttribute; @@ -94,7 +94,7 @@ public class SemanticHighlightingManager implements IPropertyChangeListener { /** * Highlighted Positions. */ - static class HighlightedPosition extends Position { + public static class HighlightedPosition extends Position { /** Highlighting of the position */ private HighlightingStyle fStyle; @@ -260,30 +260,30 @@ public class SemanticHighlightingManager implements IPropertyChangeListener { } /** Semantic highlighting presenter */ - private SemanticHighlightingPresenter fPresenter; + protected SemanticHighlightingPresenter fPresenter; /** Semantic highlighting reconciler */ private SemanticHighlightingReconciler fReconciler; /** Semantic highlightings */ - private SemanticHighlighting[] fSemanticHighlightings; + protected SemanticHighlighting[] fSemanticHighlightings; /** Highlightings */ - private HighlightingStyle[] fHighlightings; + protected HighlightingStyle[] fHighlightings; /** The editor */ private CEditor fEditor; /** The source viewer */ - private CSourceViewer fSourceViewer; + protected CSourceViewer fSourceViewer; /** The color manager */ - private IColorManager fColorManager; + protected IColorManager fColorManager; /** The preference store */ - private IPreferenceStore fPreferenceStore; + protected IPreferenceStore fPreferenceStore; /** The source viewer configuration */ - private CSourceViewerConfiguration fConfiguration; + protected CSourceViewerConfiguration fConfiguration; /** The presentation reconciler */ - private CPresentationReconciler fPresentationReconciler; + protected CPresentationReconciler fPresentationReconciler; /** The hard-coded ranges */ - private HighlightedRange[][] fHardcodedRanges; + protected HighlightedRange[][] fHardcodedRanges; /** * Install the semantic highlighting on the given editor infrastructure @@ -347,7 +347,7 @@ public class SemanticHighlightingManager implements IPropertyChangeListener { * * @return the hard-coded positions */ - private HighlightedPosition[] createHardcodedPositions() { + protected HighlightedPosition[] createHardcodedPositions() { List positions= new ArrayList(); for (int i= 0; i < fHardcodedRanges.length; i++) { HighlightedRange range= null; @@ -421,14 +421,14 @@ public class SemanticHighlightingManager implements IPropertyChangeListener { /** * @return true iff semantic highlighting is enabled in the preferences */ - private boolean isEnabled() { + protected boolean isEnabled() { return SemanticHighlightings.isEnabled(fPreferenceStore); } /** * Initialize semantic highlightings. */ - private void initializeHighlightings() { + protected void initializeHighlightings() { fSemanticHighlightings= SemanticHighlightings.getSemanticHighlightings(); fHighlightings= new HighlightingStyle[fSemanticHighlightings.length]; @@ -461,7 +461,7 @@ public class SemanticHighlightingManager implements IPropertyChangeListener { /** * Dispose the semantic highlightings. */ - private void disposeHighlightings() { + protected void disposeHighlightings() { for (int i= 0, n= fSemanticHighlightings.length; i < n; i++) removeColor(SemanticHighlightings.getColorPreferenceKey(fSemanticHighlightings[i])); @@ -481,10 +481,11 @@ public class SemanticHighlightingManager implements IPropertyChangeListener { * Handle the given property change event * * @param event The event + * @return */ - private void handlePropertyChangeEvent(PropertyChangeEvent event) { + protected boolean handlePropertyChangeEvent(PropertyChangeEvent event) { if (fPreferenceStore == null) - return; // Uninstalled during event notification + return false; // Uninstalled during event notification if (fConfiguration != null) fConfiguration.handlePropertyChangeEvent(event); @@ -497,7 +498,7 @@ public class SemanticHighlightingManager implements IPropertyChangeListener { } if (!isEnabled()) - return; + return false; boolean refreshNeeded= false; @@ -555,6 +556,8 @@ public class SemanticHighlightingManager implements IPropertyChangeListener { if (refreshNeeded && fReconciler != null) fReconciler.refresh(); + + return refreshNeeded; } private void adaptToEnablementChange(HighlightingStyle highlighting, PropertyChangeEvent event) { diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/SemanticHighlightingReconciler.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/SemanticHighlightingReconciler.java index d71341b1e32..044615618de 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/SemanticHighlightingReconciler.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/SemanticHighlightingReconciler.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -287,18 +287,18 @@ public class SemanticHighlightingReconciler implements ICReconcilingListener { /** The C editor this semantic highlighting reconciler is installed on */ private CEditor fEditor; /** The semantic highlighting presenter */ - private SemanticHighlightingPresenter fPresenter; + protected SemanticHighlightingPresenter fPresenter; /** Semantic highlightings */ - private SemanticHighlighting[] fSemanticHighlightings; + protected SemanticHighlighting[] fSemanticHighlightings; /** Highlightings */ private HighlightingStyle[] fHighlightings; /** Background job's added highlighted positions */ - private List fAddedPositions= new ArrayList(); + protected List fAddedPositions= new ArrayList(); /** Background job's removed highlighted positions */ - private List fRemovedPositions= new ArrayList(); + protected List fRemovedPositions= new ArrayList(); /** Number of removed positions */ - private int fNOfRemovedPositions; + protected int fNOfRemovedPositions; /** Background job */ private Job fJob; @@ -313,9 +313,9 @@ public class SemanticHighlightingReconciler implements ICReconcilingListener { private boolean fIsReconciling= false; /** The semantic highlighting presenter - cache for background thread, only valid during {@link #reconciled(IASTTranslationUnit, boolean, IProgressMonitor)} */ - private SemanticHighlightingPresenter fJobPresenter; + protected SemanticHighlightingPresenter fJobPresenter; /** Semantic highlightings - cache for background thread, only valid during {@link #reconciled(IASTTranslationUnit, boolean, IProgressMonitor)} */ - private SemanticHighlighting[] fJobSemanticHighlightings; + protected SemanticHighlighting[] fJobSemanticHighlightings; /** Highlightings - cache for background thread, only valid during {@link #reconciled(IASTTranslationUnit, boolean, IProgressMonitor)} */ private HighlightingStyle[] fJobHighlightings; @@ -389,7 +389,7 @@ public class SemanticHighlightingReconciler implements ICReconcilingListener { /** * Start reconciling positions. */ - private void startReconcilingPositions() { + protected void startReconcilingPositions() { fJobPresenter.addAllPositions(fRemovedPositions); fNOfRemovedPositions= fRemovedPositions.size(); } @@ -452,7 +452,7 @@ public class SemanticHighlightingReconciler implements ICReconcilingListener { /** * Stop reconciling positions. */ - private void stopReconcilingPositions() { + protected void stopReconcilingPositions() { fRemovedPositions.clear(); fNOfRemovedPositions= 0; fAddedPositions.clear(); From 7f07eb597c9255655efd9895093ac7fb8ac42127 Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Thu, 9 Feb 2012 15:48:17 -0500 Subject: [PATCH 20/43] Bug 346789: fix startup sequence for remote JUnits tests --- .../tests/dsf/gdb/framework/BaseTestCase.java | 64 ++++++++++++------- 1 file changed, 42 insertions(+), 22 deletions(-) diff --git a/dsf-gdb/org.eclipse.cdt.tests.dsf.gdb/src/org/eclipse/cdt/tests/dsf/gdb/framework/BaseTestCase.java b/dsf-gdb/org.eclipse.cdt.tests.dsf.gdb/src/org/eclipse/cdt/tests/dsf/gdb/framework/BaseTestCase.java index f8c3b32ba14..ac625339ebb 100644 --- a/dsf-gdb/org.eclipse.cdt.tests.dsf.gdb/src/org/eclipse/cdt/tests/dsf/gdb/framework/BaseTestCase.java +++ b/dsf-gdb/org.eclipse.cdt.tests.dsf.gdb/src/org/eclipse/cdt/tests/dsf/gdb/framework/BaseTestCase.java @@ -18,10 +18,12 @@ import java.util.Map; import org.eclipse.cdt.debug.core.ICDTLaunchConfigurationConstants; import org.eclipse.cdt.dsf.datamodel.IDMEvent; -import org.eclipse.cdt.dsf.debug.service.IBreakpointsExtension.IBreakpointHitDMEvent; +import org.eclipse.cdt.dsf.debug.service.IRunControl.ISuspendedDMEvent; import org.eclipse.cdt.dsf.gdb.IGDBLaunchConfigurationConstants; import org.eclipse.cdt.dsf.gdb.launching.GdbLaunch; +import org.eclipse.cdt.dsf.mi.service.command.events.IMIDMEvent; import org.eclipse.cdt.dsf.mi.service.command.events.MIStoppedEvent; +import org.eclipse.cdt.dsf.mi.service.command.output.MIFrame; import org.eclipse.cdt.dsf.service.DsfServiceEventHandler; import org.eclipse.cdt.dsf.service.DsfSession; import org.eclipse.cdt.dsf.service.DsfSession.SessionStartedListener; @@ -115,28 +117,46 @@ public class BaseTestCase { @DsfServiceEventHandler public void eventDispatched(IDMEvent event) { - if (event instanceof MIStoppedEvent) { - // We get this low-level event first. Record the MI event; various - // tests use it for context - synchronized(this) { - fInitialStoppedEvent = (MIStoppedEvent)event; - } - } - else if (event instanceof IBreakpointHitDMEvent) { - // We need to wait for a breakpoint event, not just a suspended event, - // this is because for remote tests, there is a suspended event when - // we connect, and then, there is the breakpoint event at main() - - // We get this higher level event shortly thereafter. We don't want - // to consider the session suspended until we get it. Set the event - // semaphore that will allow the test to proceed - synchronized (fTargetSuspendedSem) { - fTargetSuspended = true; - fTargetSuspendedSem.notify(); - } + // Wait for the program to have stopped on main. + // + // We have to jump through hoops to properly handle the remote + // case, because of differences between GDB <= 68 and GDB >= 7.0. + // + // With GDB >= 7.0, when connecting to the remote gdbserver, + // we get a first *stopped event at connection time. This is + // not the ISuspendedDMEvent event we want. We could instead + // listen for an IBreakpointHitDMEvent instead. + // However, with GDB <= 6.8, temporary breakpoints are not + // reported as breakpoint-hit, so we don't get an IBreakpointHitDMEvent + // for GDB <= 6.8. + // + // What I found to be able to know we have stopped at main, in all cases, + // is to look for an ISuspendedDMEvent and then confirming that it indicates + // in its frame that it stopped at "main". This will allow us to skip + // the first *stopped event for GDB >= 7.0 + if (event instanceof ISuspendedDMEvent) { + if (event instanceof IMIDMEvent) { + IMIDMEvent iMIEvent = (IMIDMEvent)event; - // no further need for this listener. Note fLaunch could be null if the test ran into a failure - fSession.removeServiceEventListener(this); + Object miEvent = iMIEvent.getMIEvent(); + if (miEvent instanceof MIStoppedEvent) { + // Store the corresponding MI *stopped event + fInitialStoppedEvent = (MIStoppedEvent)miEvent; + + // Check the content of the frame for "main" + MIFrame frame = fInitialStoppedEvent.getFrame(); + if (frame != null && "main".equals(frame.getFunction())) { + // Set the event semaphore that will allow the test to proceed + synchronized (fTargetSuspendedSem) { + fTargetSuspended = true; + fTargetSuspendedSem.notify(); + } + + // We found our event, no further need for this listener + fSession.removeServiceEventListener(this); + } + } + } } } } From c4d354c7a9627524f67eb54f234cabe57c18a87f Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Thu, 9 Feb 2012 18:32:59 -0800 Subject: [PATCH 21/43] Added toString method. --- .../parser/scanner/IncludeSearchPathElement.java | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/IncludeSearchPathElement.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/IncludeSearchPathElement.java index 3c9acd4c6a2..7cd2ef5e4da 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/IncludeSearchPathElement.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/IncludeSearchPathElement.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Markus Schorn - initial API and implementation + * Markus Schorn - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.internal.core.parser.scanner; @@ -20,7 +20,6 @@ final class IncludeSearchPathElement { public static final String FRAMEWORK_VAR = "__framework__"; //$NON-NLS-1$ public static final String FILE_VAR = "__header__"; //$NON-NLS-1$ - private final String fPath; private final boolean fForQuoteIncludesOnly; private final boolean fIsFrameworkDirectory; @@ -47,7 +46,7 @@ final class IncludeSearchPathElement { return null; } String framework = includeDirective.substring(0, firstSep); - String file= includeDirective.substring(firstSep+1); + String file= includeDirective.substring(firstSep + 1); if (file.length() == 0) return null; @@ -70,7 +69,15 @@ final class IncludeSearchPathElement { private void replace(StringBuilder buf, String find, final String replace) { int idx= buf.indexOf(find); if (idx >= 0) { - buf.replace(idx, idx+find.length(), replace); + buf.replace(idx, idx + find.length(), replace); } } + + /** + * For debugging only. + */ + @Override + public String toString() { + return fPath; + } } \ No newline at end of file From 5b8296109ca2509f3b45d5537a6eed8cf07aa2ea Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Thu, 9 Feb 2012 18:37:27 -0800 Subject: [PATCH 22/43] Let formatter know about the translation unit so that it can resolve includes. --- .../rewrite/changegenerator/ChangeGenerator.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/changegenerator/ChangeGenerator.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/changegenerator/ChangeGenerator.java index 40eb821584b..166f25e155a 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/changegenerator/ChangeGenerator.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/changegenerator/ChangeGenerator.java @@ -52,6 +52,7 @@ import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNamespaceDefinition; import org.eclipse.cdt.core.formatter.CodeFormatter; import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants; import org.eclipse.cdt.core.model.ICProject; +import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.internal.core.dom.rewrite.ASTModification; import org.eclipse.cdt.internal.core.dom.rewrite.ASTModification.ModificationKind; import org.eclipse.cdt.internal.core.dom.rewrite.ASTModificationMap; @@ -63,7 +64,6 @@ import org.eclipse.cdt.internal.core.dom.rewrite.astwriter.ProblemRuntimeExcepti import org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.NodeCommentMap; import org.eclipse.cdt.internal.core.dom.rewrite.util.FileHelper; import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; @@ -124,7 +124,8 @@ public class ChangeGenerator extends ASTVisitor { rootNode.accept(pathProvider); for (IFile currentFile : changes.keySet()) { MultiTextEdit edit = changes.get(currentFile); - edit = formatChangedCode(edit, rootNode.getTranslationUnit().getRawSignature(), currentFile.getProject()); + IASTTranslationUnit ast = rootNode.getTranslationUnit(); + edit = formatChangedCode(edit, ast.getRawSignature(), ast.getOriginatingTranslationUnit()); TextFileChange subchange= ASTRewriteAnalyzer.createCTextFileChange(currentFile); subchange.setEdit(edit); change.add(subchange); @@ -317,11 +318,11 @@ public class ChangeGenerator extends ASTVisitor { * * @param multiEdit The text edit produced by refactoring. * @param code The code being modified. - * @param project The project containing the code. + * @param tu The translation unit containing the code. * @return The text edit containing formatted refactoring changes, or the original text edit * in case of errors. */ - private MultiTextEdit formatChangedCode(MultiTextEdit multiEdit, String code, IProject project) { + private MultiTextEdit formatChangedCode(MultiTextEdit multiEdit, String code, ITranslationUnit tu) { IDocument document = new Document(code); try { // Apply refactoring changes to a temporary document. @@ -364,8 +365,9 @@ public class ChangeGenerator extends ASTVisitor { } // Calculate formatting changes for the regions after the refactoring changes. - ICProject proj = CCorePlugin.getDefault().getCoreModel().create(project); - Map options = proj.getOptions(true); + ICProject project = tu.getCProject(); + Map options = new HashMap(project.getOptions(true)); + options.put(DefaultCodeFormatterConstants.FORMATTER_TRANSLATION_UNIT, tu); // Allow all comments to be indented. options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_NEVER_INDENT_LINE_COMMENTS_ON_FIRST_COLUMN, DefaultCodeFormatterConstants.FALSE); From 143bc1aea02cf3e4bad202c4f519e8801195a55f Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Thu, 9 Feb 2012 18:47:09 -0800 Subject: [PATCH 23/43] Bug 371165 - Invalid formatting of newly created classes. --- .../classwizard/NewClassCodeGenerator.java | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/NewClassCodeGenerator.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/NewClassCodeGenerator.java index d833bea177d..776524cbc25 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/NewClassCodeGenerator.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/NewClassCodeGenerator.java @@ -15,8 +15,10 @@ package org.eclipse.cdt.internal.ui.wizards.classwizard; import java.util.ArrayList; +import java.util.HashMap; import java.util.Iterator; import java.util.List; +import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; @@ -44,6 +46,7 @@ import org.eclipse.cdt.core.browser.IQualifiedTypeName; import org.eclipse.cdt.core.browser.ITypeReference; import org.eclipse.cdt.core.browser.QualifiedTypeName; import org.eclipse.cdt.core.formatter.CodeFormatter; +import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants; import org.eclipse.cdt.core.model.CModelException; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ICContainer; @@ -352,17 +355,19 @@ public class NewClassCodeGenerator { */ private String formatSource(String content, ITranslationUnit tu) throws CModelException { String lineDelimiter= StubUtility.getLineDelimiterUsed(tu); - TextEdit edit= CodeFormatterUtil.format(CodeFormatter.K_TRANSLATION_UNIT, content, 0, lineDelimiter, - tu.getCProject().getOptions(true)); + Map options = new HashMap(tu.getCProject().getOptions(true)); + options.put(DefaultCodeFormatterConstants.FORMATTER_TRANSLATION_UNIT, tu); + TextEdit edit= CodeFormatterUtil.format(CodeFormatter.K_TRANSLATION_UNIT, content, 0, + lineDelimiter, options); if (edit != null) { IDocument doc= new Document(content); try { edit.apply(doc); content= doc.get(); - } catch (MalformedTreeException exc) { - CUIPlugin.log(exc); - } catch (BadLocationException exc) { - CUIPlugin.log(exc); + } catch (MalformedTreeException e) { + CUIPlugin.log(e); + } catch (BadLocationException e) { + CUIPlugin.log(e); } } return content; From ff94f47a9e2d77282bb3545d7d4a0ba07c676ebe Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Thu, 9 Feb 2012 21:17:43 -0800 Subject: [PATCH 24/43] Revert "Let formatter know about the translation unit so that it can resolve includes." This reverts commit 5b8296109ca2509f3b45d5537a6eed8cf07aa2ea. --- .../rewrite/changegenerator/ChangeGenerator.java | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/changegenerator/ChangeGenerator.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/changegenerator/ChangeGenerator.java index 166f25e155a..40eb821584b 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/changegenerator/ChangeGenerator.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/changegenerator/ChangeGenerator.java @@ -52,7 +52,6 @@ import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNamespaceDefinition; import org.eclipse.cdt.core.formatter.CodeFormatter; import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants; import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.internal.core.dom.rewrite.ASTModification; import org.eclipse.cdt.internal.core.dom.rewrite.ASTModification.ModificationKind; import org.eclipse.cdt.internal.core.dom.rewrite.ASTModificationMap; @@ -64,6 +63,7 @@ import org.eclipse.cdt.internal.core.dom.rewrite.astwriter.ProblemRuntimeExcepti import org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.NodeCommentMap; import org.eclipse.cdt.internal.core.dom.rewrite.util.FileHelper; import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; @@ -124,8 +124,7 @@ public class ChangeGenerator extends ASTVisitor { rootNode.accept(pathProvider); for (IFile currentFile : changes.keySet()) { MultiTextEdit edit = changes.get(currentFile); - IASTTranslationUnit ast = rootNode.getTranslationUnit(); - edit = formatChangedCode(edit, ast.getRawSignature(), ast.getOriginatingTranslationUnit()); + edit = formatChangedCode(edit, rootNode.getTranslationUnit().getRawSignature(), currentFile.getProject()); TextFileChange subchange= ASTRewriteAnalyzer.createCTextFileChange(currentFile); subchange.setEdit(edit); change.add(subchange); @@ -318,11 +317,11 @@ public class ChangeGenerator extends ASTVisitor { * * @param multiEdit The text edit produced by refactoring. * @param code The code being modified. - * @param tu The translation unit containing the code. + * @param project The project containing the code. * @return The text edit containing formatted refactoring changes, or the original text edit * in case of errors. */ - private MultiTextEdit formatChangedCode(MultiTextEdit multiEdit, String code, ITranslationUnit tu) { + private MultiTextEdit formatChangedCode(MultiTextEdit multiEdit, String code, IProject project) { IDocument document = new Document(code); try { // Apply refactoring changes to a temporary document. @@ -365,9 +364,8 @@ public class ChangeGenerator extends ASTVisitor { } // Calculate formatting changes for the regions after the refactoring changes. - ICProject project = tu.getCProject(); - Map options = new HashMap(project.getOptions(true)); - options.put(DefaultCodeFormatterConstants.FORMATTER_TRANSLATION_UNIT, tu); + ICProject proj = CCorePlugin.getDefault().getCoreModel().create(project); + Map options = proj.getOptions(true); // Allow all comments to be indented. options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_NEVER_INDENT_LINE_COMMENTS_ON_FIRST_COLUMN, DefaultCodeFormatterConstants.FALSE); From 093697a0167b5b9bb0287baa0dd38547a976f1e5 Mon Sep 17 00:00:00 2001 From: "William R. Swanson" Date: Fri, 10 Feb 2012 13:10:03 -0500 Subject: [PATCH 25/43] Bug 335027: Visualizer View feature. Initial contribution. --- .../eclipse/cdt/internal/core/ICPUInfo.java | 18 + .../eclipse/cdt/internal/core/ICoreInfo.java | 18 + .../.classpath | 8 + .../.project | 34 + .../.settings/org.eclipse.jdt.core.prefs | 70 ++ .../META-INF/MANIFEST.MF | 25 + .../about.html | 24 + .../build.properties | 19 + .../plugin.properties | 12 + .../plugin.xml | 20 + .../pom.xml | 17 + .../resources/messages.properties | 21 + .../ui/MulticoreVisualizerUIPlugin.java | 282 ++++++ .../internal/ui/actions/RefreshAction.java | 66 ++ .../internal/ui/actions/SelectAllAction.java | 66 ++ .../internal/ui/model/VisualizerCPU.java | 133 +++ .../internal/ui/model/VisualizerCore.java | 83 ++ .../ui/model/VisualizerExecutionState.java | 22 + .../internal/ui/model/VisualizerModel.java | 226 +++++ .../internal/ui/model/VisualizerThread.java | 153 +++ .../view/IMulticoreVisualizerConstants.java | 61 ++ .../internal/ui/view/MulticoreVisualizer.java | 879 +++++++++++++++++ .../ui/view/MulticoreVisualizerCPU.java | 119 +++ .../ui/view/MulticoreVisualizerCanvas.java | 896 ++++++++++++++++++ .../ui/view/MulticoreVisualizerCore.java | 165 ++++ .../MulticoreVisualizerEventListener.java | 194 ++++ .../MulticoreVisualizerGraphicObject.java | 45 + .../ui/view/MulticoreVisualizerMarquee.java | 69 ++ .../MulticoreVisualizerSelectionFinder.java | 165 ++++ .../ui/view/MulticoreVisualizerThread.java | 190 ++++ .../internal/utils/DSFDebugModel.java | 340 +++++++ .../internal/utils/DSFDebugModelListener.java | 68 ++ .../internal/utils/DSFSessionState.java | 173 ++++ .../internal/utils/DebugViewTreeWalker.java | 135 +++ .../internal/utils/DebugViewUtils.java | 79 ++ .../cdt/dsf/gdb/internal/CoreList.java | 115 +++ .../gdb/launching/ServicesLaunchSequence.java | 11 +- .../cdt/dsf/gdb/service/GDBHardware.java | 357 +++++++ .../gdb/service/GdbDebugServicesFactory.java | 14 +- .../cdt/dsf/gdb/service/IGDBHardware.java | 112 +++ .../service/command/GDBControlDMContext.java | 6 +- .../.project | 17 + .../build.properties | 16 + .../eclipse_update_120.jpg | Bin 0 -> 21695 bytes .../epl-v10.html | 328 +++++++ .../feature.properties | 166 ++++ .../feature.xml | 27 + .../license.html | 108 +++ .../pom.xml | 18 + .../.project | 17 + .../ABOUT.txt | 359 +++++++ .../build.properties | 17 + .../eclipse_update_120.jpg | Bin 0 -> 21695 bytes .../epl-v10.html | 328 +++++++ .../feature.properties | 166 ++++ .../feature.xml | 34 + .../license.html | 108 +++ .../pom.xml | 18 + .../.classpath | 8 + .../org.eclipse.cdt.visualizer.core/.project | 28 + .../.settings/org.eclipse.jdt.core.prefs | 8 + .../org.eclipse.cdt.visualizer.core/ABOUT.txt | 17 + .../META-INF/MANIFEST.MF | 15 + .../about.html | 24 + .../build.properties | 17 + .../plugin.properties | 17 + .../org.eclipse.cdt.visualizer.core/pom.xml | 17 + .../resources/messages.properties | 14 + .../cdt/visualizer/core/Extension.java | 92 ++ .../cdt/visualizer/core/ExtensionElement.java | 160 ++++ .../cdt/visualizer/core/ResourceManager.java | 195 ++++ .../core/plugin/CDTVisualizerCorePlugin.java | 126 +++ .../org.eclipse.cdt.visualizer.ui/.classpath | 8 + .../org.eclipse.cdt.visualizer.ui/.project | 28 + .../.settings/org.eclipse.jdt.core.prefs | 8 + .../org.eclipse.cdt.visualizer.ui/ABOUT.txt | 17 + .../META-INF/MANIFEST.MF | 20 + .../org.eclipse.cdt.visualizer.ui/about.html | 24 + .../build.properties | 23 + .../icons/full/view16/visualizer_view.png | Bin 0 -> 2921 bytes .../plugin.properties | 19 + .../org.eclipse.cdt.visualizer.ui/plugin.xml | 41 + .../org.eclipse.cdt.visualizer.ui/pom.xml | 17 + .../resources/messages.properties | 17 + ....eclipse.cdt.visualizer.ui.visualizer.exsd | 123 +++ .../cdt/visualizer/ui/IVisualizer.java | 171 ++++ .../cdt/visualizer/ui/IVisualizerViewer.java | 111 +++ .../eclipse/cdt/visualizer/ui/Visualizer.java | 275 ++++++ .../cdt/visualizer/ui/VisualizerAction.java | 79 ++ .../cdt/visualizer/ui/VisualizerView.java | 415 ++++++++ .../cdt/visualizer/ui/VisualizerViewer.java | 540 +++++++++++ .../visualizer/ui/canvas/BufferedCanvas.java | 201 ++++ .../visualizer/ui/canvas/GraphicCanvas.java | 167 ++++ .../ui/canvas/GraphicCanvasVisualizer.java | 123 +++ .../visualizer/ui/canvas/GraphicObject.java | 278 ++++++ .../visualizer/ui/canvas/IGraphicObject.java | 49 + .../ui/events/IVisualizerViewerListener.java | 31 + .../ui/events/VisualizerViewerEvent.java | 79 ++ .../ui/plugin/CDTVisualizerUIPlugin.java | 159 ++++ .../cdt/visualizer/ui/test/TestCanvas.java | 106 +++ .../ui/test/TestCanvasVisualizer.java | 114 +++ .../cdt/visualizer/ui/util/Colors.java | 127 +++ .../eclipse/cdt/visualizer/ui/util/Event.java | 107 +++ .../cdt/visualizer/ui/util/GUIUtils.java | 127 +++ .../cdt/visualizer/ui/util/ListenerList.java | 148 +++ .../cdt/visualizer/ui/util/MouseMonitor.java | 383 ++++++++ .../ui/util/RunnableWithResult.java | 159 ++++ .../visualizer/ui/util/SelectionManager.java | 166 ++++ .../ui/util/SelectionProviderAdapter.java | 97 ++ .../visualizer/ui/util/SelectionUtils.java | 280 ++++++ .../eclipse/cdt/visualizer/ui/util/Timer.java | 100 ++ .../eclipse/cdt/visualizer/ui/util/Todo.java | 99 ++ .../visualizer/ui/util/UIResourceManager.java | 375 ++++++++ .../ui/util/WorkbenchSelectionAdapter.java | 220 +++++ 114 files changed, 13601 insertions(+), 5 deletions(-) create mode 100644 core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/ICPUInfo.java create mode 100644 core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/ICoreInfo.java create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/.classpath create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/.project create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/.settings/org.eclipse.jdt.core.prefs create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/META-INF/MANIFEST.MF create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/about.html create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/build.properties create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/plugin.properties create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/plugin.xml create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/pom.xml create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/resources/messages.properties create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/MulticoreVisualizerUIPlugin.java create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/actions/RefreshAction.java create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/actions/SelectAllAction.java create mode 100755 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerCPU.java create mode 100755 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerCore.java create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerExecutionState.java create mode 100755 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerModel.java create mode 100755 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerThread.java create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/IMulticoreVisualizerConstants.java create mode 100755 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizer.java create mode 100755 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerCPU.java create mode 100755 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerCanvas.java create mode 100755 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerCore.java create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerEventListener.java create mode 100755 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerGraphicObject.java create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerMarquee.java create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerSelectionFinder.java create mode 100755 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerThread.java create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFDebugModel.java create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFDebugModelListener.java create mode 100755 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFSessionState.java create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DebugViewTreeWalker.java create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DebugViewUtils.java create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/internal/CoreList.java create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/GDBHardware.java create mode 100644 dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/IGDBHardware.java create mode 100644 dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/.project create mode 100755 dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/build.properties create mode 100644 dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/eclipse_update_120.jpg create mode 100644 dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/epl-v10.html create mode 100644 dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/feature.properties create mode 100755 dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/feature.xml create mode 100644 dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/license.html create mode 100644 dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/pom.xml create mode 100755 visualizer/org.eclipse.cdt.visualizer-feature/.project create mode 100644 visualizer/org.eclipse.cdt.visualizer-feature/ABOUT.txt create mode 100755 visualizer/org.eclipse.cdt.visualizer-feature/build.properties create mode 100644 visualizer/org.eclipse.cdt.visualizer-feature/eclipse_update_120.jpg create mode 100644 visualizer/org.eclipse.cdt.visualizer-feature/epl-v10.html create mode 100644 visualizer/org.eclipse.cdt.visualizer-feature/feature.properties create mode 100755 visualizer/org.eclipse.cdt.visualizer-feature/feature.xml create mode 100644 visualizer/org.eclipse.cdt.visualizer-feature/license.html create mode 100644 visualizer/org.eclipse.cdt.visualizer-feature/pom.xml create mode 100755 visualizer/org.eclipse.cdt.visualizer.core/.classpath create mode 100755 visualizer/org.eclipse.cdt.visualizer.core/.project create mode 100755 visualizer/org.eclipse.cdt.visualizer.core/.settings/org.eclipse.jdt.core.prefs create mode 100755 visualizer/org.eclipse.cdt.visualizer.core/ABOUT.txt create mode 100755 visualizer/org.eclipse.cdt.visualizer.core/META-INF/MANIFEST.MF create mode 100644 visualizer/org.eclipse.cdt.visualizer.core/about.html create mode 100755 visualizer/org.eclipse.cdt.visualizer.core/build.properties create mode 100644 visualizer/org.eclipse.cdt.visualizer.core/plugin.properties create mode 100644 visualizer/org.eclipse.cdt.visualizer.core/pom.xml create mode 100644 visualizer/org.eclipse.cdt.visualizer.core/resources/messages.properties create mode 100644 visualizer/org.eclipse.cdt.visualizer.core/src/org/eclipse/cdt/visualizer/core/Extension.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.core/src/org/eclipse/cdt/visualizer/core/ExtensionElement.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.core/src/org/eclipse/cdt/visualizer/core/ResourceManager.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.core/src/org/eclipse/cdt/visualizer/core/plugin/CDTVisualizerCorePlugin.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/.classpath create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/.project create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/.settings/org.eclipse.jdt.core.prefs create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/ABOUT.txt create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/META-INF/MANIFEST.MF create mode 100644 visualizer/org.eclipse.cdt.visualizer.ui/about.html create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/build.properties create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/icons/full/view16/visualizer_view.png create mode 100644 visualizer/org.eclipse.cdt.visualizer.ui/plugin.properties create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/plugin.xml create mode 100644 visualizer/org.eclipse.cdt.visualizer.ui/pom.xml create mode 100644 visualizer/org.eclipse.cdt.visualizer.ui/resources/messages.properties create mode 100644 visualizer/org.eclipse.cdt.visualizer.ui/schema/org.eclipse.cdt.visualizer.ui.visualizer.exsd create mode 100644 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/IVisualizer.java create mode 100644 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/IVisualizerViewer.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/Visualizer.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/VisualizerAction.java create mode 100644 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/VisualizerView.java create mode 100644 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/VisualizerViewer.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/BufferedCanvas.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/GraphicCanvas.java create mode 100644 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/GraphicCanvasVisualizer.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/GraphicObject.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/IGraphicObject.java create mode 100644 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/events/IVisualizerViewerListener.java create mode 100644 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/events/VisualizerViewerEvent.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/plugin/CDTVisualizerUIPlugin.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/test/TestCanvas.java create mode 100644 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/test/TestCanvasVisualizer.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/Colors.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/Event.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/GUIUtils.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/ListenerList.java create mode 100644 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/MouseMonitor.java create mode 100644 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/RunnableWithResult.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/SelectionManager.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/SelectionProviderAdapter.java create mode 100644 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/SelectionUtils.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/Timer.java create mode 100644 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/Todo.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/UIResourceManager.java create mode 100755 visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/WorkbenchSelectionAdapter.java diff --git a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/ICPUInfo.java b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/ICPUInfo.java new file mode 100644 index 00000000000..4761799ef82 --- /dev/null +++ b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/ICPUInfo.java @@ -0,0 +1,18 @@ +/******************************************************************************* + * Copyright (c) 2012 Ericsson and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Marc Khouzam (Ericsson) - Initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.internal.core; + +/** + */ +public interface ICPUInfo { + public String getId(); + public String getNumOfCores(); +} diff --git a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/ICoreInfo.java b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/ICoreInfo.java new file mode 100644 index 00000000000..3eba56f8783 --- /dev/null +++ b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/core/ICoreInfo.java @@ -0,0 +1,18 @@ +/******************************************************************************* + * Copyright (c) 2012 Ericsson and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Marc Khouzam (Ericsson) - Initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.internal.core; + +/** + */ +public interface ICoreInfo { + public String getId(); + public String getPhysicalId(); +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/.classpath b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/.classpath new file mode 100644 index 00000000000..31db9a91174 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/.classpath @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/.project b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/.project new file mode 100644 index 00000000000..8b3f7a66576 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/.project @@ -0,0 +1,34 @@ + + + org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.pde.api.tools.apiAnalysisBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + org.eclipse.pde.api.tools.apiAnalysisNature + + diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/.settings/org.eclipse.jdt.core.prefs b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000000..669b0a3caf2 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,70 @@ +#Tue Jun 24 11:04:03 PDT 2008 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=warning +org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning +org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled +org.eclipse.jdt.core.compiler.problem.fieldHiding=warning +org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore +org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=warning +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning +org.eclipse.jdt.core.compiler.problem.nullReference=error +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning +org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning +org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning +org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore +org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.compiler.problem.unusedImport=error +org.eclipse.jdt.core.compiler.problem.unusedLabel=warning +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/META-INF/MANIFEST.MF b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/META-INF/MANIFEST.MF new file mode 100644 index 00000000000..eef9f222bf8 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/META-INF/MANIFEST.MF @@ -0,0 +1,25 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: %pluginName +Bundle-Vendor: %providerName +Bundle-SymbolicName: org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui;singleton:=true +Bundle-Version: 1.0.0.qualifier +Bundle-Activator: org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.MulticoreVisualizerUIPlugin +Bundle-Localization: plugin +Require-Bundle: org.eclipse.ui, + org.eclipse.core.runtime, + org.eclipse.cdt.dsf, + org.eclipse.cdt.dsf.ui, + org.eclipse.cdt.dsf.gdb, + org.eclipse.cdt.ui, + org.eclipse.cdt.visualizer.core, + org.eclipse.cdt.visualizer.ui, + org.eclipse.debug.ui +Bundle-ActivationPolicy: lazy +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Import-Package: com.ibm.icu.text +Export-Package: org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui, + org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.actions, + org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model, + org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.view, + org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.utils diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/about.html b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/about.html new file mode 100644 index 00000000000..cb740ae8bc8 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/about.html @@ -0,0 +1,24 @@ + + + + +About +

About This Content

+ +

June 5, 2007

+

License

+ +

The Eclipse Foundation makes available all content in this plug-in ("Content"). Unless otherwise +indicated below, the Content is provided to you under the terms and conditions of the +Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available +at http://www.eclipse.org/legal/epl-v10.html. +For purposes of the EPL, "Program" will mean the Content.

+ +

If you did not receive this Content directly from the Eclipse Foundation, the Content is +being redistributed by another party ("Redistributor") and different terms and conditions may +apply to your use of any object code in the Content. Check the Redistributor's license that was +provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise +indicated below, the terms and conditions of the EPL still apply to any source code in the Content +and such source code may be obtained at http://www.eclipse.org.

+ + \ No newline at end of file diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/build.properties b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/build.properties new file mode 100644 index 00000000000..6b63ac40a03 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/build.properties @@ -0,0 +1,19 @@ +############################################################################### +# Copyright (c) 2012 Ericsson and others. +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# Marc Khouzam (Ericsson) - initial API and implementation +############################################################################### +source.. = src/,\ + resources/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + plugin.xml,\ + about.html,\ + plugin.properties +src.includes = about.html diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/plugin.properties b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/plugin.properties new file mode 100644 index 00000000000..7216b261257 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/plugin.properties @@ -0,0 +1,12 @@ +############################################################################### +# Copyright (c) 2012 Ericsson and others. +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# Marc Khouzam (Ericsson) - initial API and implementation +############################################################################### +pluginName=Multicore Visualizer for DSF-GDB Integration +providerName=Eclipse CDT diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/plugin.xml b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/plugin.xml new file mode 100644 index 00000000000..46a0aac6dde --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/plugin.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/pom.xml b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/pom.xml new file mode 100644 index 00000000000..d3a9fcbd007 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/pom.xml @@ -0,0 +1,17 @@ + + + 4.0.0 + + + org.eclipse.cdt + cdt-parent + 8.1.0-SNAPSHOT + ../../pom.xml + + + 1.0.0-SNAPSHOT + org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui + eclipse-plugin + diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/resources/messages.properties b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/resources/messages.properties new file mode 100644 index 00000000000..0103a53551c --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/resources/messages.properties @@ -0,0 +1,21 @@ +# ============================================================================= +# Copyright (c) 2012 Tilera 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 +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# William R. Swanson (Tilera Corporation) +# ============================================================================= + +# ----------------------------------------------------------------------------- +# Application string resources +# ----------------------------------------------------------------------------- + +# MulticoreVisualizer actions +MulticoreVisualizer.actions.SelectAll.text=Select &All@Ctrl+A +MulticoreVisualizer.actions.SelectAll.description=Select all thread(s) + +MulticoreVisualizer.actions.Refresh.text=Refresh@F5 +MulticoreVisualizer.actions.Refresh.description=Refresh the visualizer display diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/MulticoreVisualizerUIPlugin.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/MulticoreVisualizerUIPlugin.java new file mode 100644 index 00000000000..f780d4e4051 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/MulticoreVisualizerUIPlugin.java @@ -0,0 +1,282 @@ +/******************************************************************************* + * Copyright (c) 2012 Ericsson and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Marc Khouzam (Ericsson) - initial API and implementation + * William R. Swanson (Tilera Corporation) - added resource support + *******************************************************************************/ +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui; + +import org.eclipse.cdt.dsf.gdb.launching.LaunchMessages; +import org.eclipse.cdt.visualizer.ui.plugin.CDTVisualizerUIPlugin; +import org.eclipse.cdt.visualizer.ui.util.UIResourceManager; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.dialogs.ErrorDialog; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.plugin.AbstractUIPlugin; +import org.osgi.framework.BundleContext; + +/** + * The activator class controls the plug-in life cycle + */ +public class MulticoreVisualizerUIPlugin extends AbstractUIPlugin +{ + // --- constants --- + + // The plug-in ID + public static final String PLUGIN_ID = "org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui"; //$NON-NLS-1$ + + + // --- static members --- + + /** Singleton instance */ + private static MulticoreVisualizerUIPlugin plugin; + + /** Bundle context */ + private static BundleContext fgBundleContext; + + /** Resource manager */ + protected static UIResourceManager s_resources = null; + + /** + * Returns the shared instance + */ + public static MulticoreVisualizerUIPlugin getDefault() { + return plugin; + } + + /** + * Returns the bundle context for this plugin. + */ + public static BundleContext getBundleContext() { + return fgBundleContext; + } + + + // --- constructors/destructors --- + + /** + * The constructor + */ + public MulticoreVisualizerUIPlugin() { + } + + + // --- plugin startup/shutdown methods --- + + /* + * (non-Javadoc) + * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) + */ + @Override + public void start(BundleContext context) throws Exception { + fgBundleContext = context; + super.start(context); + plugin = this; + + // initialize resource management (strings, images, fonts, colors, etc.) + getPluginResources(); + } + + /* + * (non-Javadoc) + * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) + */ + @Override + public void stop(BundleContext context) throws Exception { + // clean up resource management + cleanupPluginResources(); + + plugin = null; + super.stop(context); + fgBundleContext = null; + } + + + // --- logging --- + + /** + * Logs the specified status with this plug-in's log. + * + * @param status + * status to log + */ + public static void log(IStatus status) { + getDefault().getLog().log(status); + } + /** + * Logs an internal error with the specified message. + * + * @param message + * the error message to log + */ + public static void logErrorMessage(String message) { + log(new Status(IStatus.ERROR, getUniqueIdentifier(), IStatus.ERROR, message, null)); + } + + /** + * Logs an internal error with the specified throwable + * + * @param e + * the exception to be logged + */ + public static void log(Throwable e) { + log(new Status(IStatus.ERROR, getUniqueIdentifier(), IStatus.ERROR, e.getMessage(), e)); + } + + + // --- accessors --- + + /** + * Convenience method which returns the unique identifier of this plugin. + */ + public static String getUniqueIdentifier() { + if (getDefault() == null) { + // If the default instance is not yet initialized, + // return a static identifier. This identifier must + // match the plugin id defined in plugin.xml + return PLUGIN_ID; + } + return getDefault().getBundle().getSymbolicName(); + } + + + // --- UI plugin support --- + + /** + * copied from org.eclipse.cdt.launch.internal.ui.LaunchUIPlugin + */ + private static Shell debugDialogShell; + + /** + * Returns shell (workbench or dialog) for this plugin. + */ + public static Shell getShell() { + if (getActiveWorkbenchShell() != null) { + return getActiveWorkbenchShell(); + } + if (debugDialogShell != null) { + if (!debugDialogShell.isDisposed()) + return debugDialogShell; + debugDialogShell = null; + } + IWorkbenchWindow[] windows = getDefault().getWorkbench().getWorkbenchWindows(); + return windows[0].getShell(); + } + + public static void setDialogShell(Shell shell) { + debugDialogShell = shell; + } + + /** + * Returns the active workbench window + * + * @return the active workbench window + */ + public static IWorkbenchWindow getActiveWorkbenchWindow() { + return getDefault().getWorkbench().getActiveWorkbenchWindow(); + } + + public static IWorkbenchPage getActivePage() { + IWorkbenchWindow w = getActiveWorkbenchWindow(); + if (w != null) { + return w.getActivePage(); + } + return null; + } + + /** + * Returns the active workbench shell or null if none + * + * @return the active workbench shell or null if none + */ + public static Shell getActiveWorkbenchShell() { + IWorkbenchWindow window = getActiveWorkbenchWindow(); + if (window != null) { + return window.getShell(); + } + return null; + } + + /** + * Displays an error dialog. + */ + public static void errorDialog(String message, IStatus status) { + log(status); + Shell shell = getActiveWorkbenchShell(); + if (shell != null) { + ErrorDialog.openError(shell, LaunchMessages.getString("LaunchUIPlugin.Error"), message, status); //$NON-NLS-1$ + } + } + + /** + * Displays an error dialog. + */ + public static void errorDialog(String message, Throwable t) { + log(t); + Shell shell = getActiveWorkbenchShell(); + if (shell != null) { + IStatus status = new Status(IStatus.ERROR, getUniqueIdentifier(), 1, t.getMessage(), null); + ErrorDialog.openError(shell, LaunchMessages.getString("LaunchUIPlugin.Error"), message, status); //$NON-NLS-1$ + } + } + + // --- resource management --- + + /** Returns resource manager for this plugin */ + public UIResourceManager getPluginResources() { + if (s_resources == null) { + s_resources = new UIResourceManager(this); + s_resources.setParentManager(CDTVisualizerUIPlugin.getResources()); + } + + return s_resources; + } + + /** Releases resource manager for this plugin. */ + public void cleanupPluginResources() { + s_resources.dispose(); + } + + /** Convenience method for getting plugin resource manager */ + public static UIResourceManager getResources() { + return getDefault().getPluginResources(); + } + + /** Convenience method for looking up string resources */ + public static String getString(String key) { + return getDefault().getPluginResources().getString(key); + } + /** Convenience method for looking up string resources */ + public static String getString(String key, Object... arguments) { + return getDefault().getPluginResources().getString(key, arguments); + } + + /** Convenience method for looking up image resources */ + public static Image getImage(String key) { + return getDefault().getPluginResources().getImage(key); + } + /** Convenience method for looking up image resources */ + public static ImageDescriptor getImageDescriptor(String key) { + return getDefault().getPluginResources().getImageDescriptor(key); + } + + /** Convenience method for looking up font resources */ + public static Font getFont(String fontName, int height) { + return getDefault().getPluginResources().getFont(fontName, height); + } + /** Convenience method for looking up font resources */ + public static Font getFont(String fontName, int height, int style) { + return getDefault().getPluginResources().getFont(fontName, height, style); + } +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/actions/RefreshAction.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/actions/RefreshAction.java new file mode 100644 index 00000000000..d60327715f9 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/actions/RefreshAction.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.actions; + +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.MulticoreVisualizerUIPlugin; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.view.MulticoreVisualizer; +import org.eclipse.cdt.visualizer.ui.VisualizerAction; +import org.eclipse.swt.SWT; + +/** Select All action for Visualizer context menu. */ +public class RefreshAction extends VisualizerAction +{ + // --- members --- + + /** Visualizer instance we're associated with. */ + MulticoreVisualizer m_visualizer = null; + + + // --- constructors/destructors --- + + /** Constructor. */ + public RefreshAction() + { + setText(MulticoreVisualizerUIPlugin.getString( + "MulticoreVisualizer.actions.Refresh.text")); //$NON-NLS-1$ + setDescription(MulticoreVisualizerUIPlugin.getString( + "MulticoreVisualizer.actions.Refresh.description")); //$NON-NLS-1$ + setAccelerator(SWT.F5); + } + + /** Dispose method. */ + @Override + public void dispose() + { + m_visualizer = null; + super.dispose(); + } + + + // --- init methods --- + + /** Initializes this action for the specified view. */ + public void init(MulticoreVisualizer visualizer) + { + m_visualizer = visualizer; + } + + + // --- methods --- + + /** Invoked when action is triggered. */ + @Override + public void run() { + if (m_visualizer != null) + m_visualizer.refresh(); + } +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/actions/SelectAllAction.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/actions/SelectAllAction.java new file mode 100644 index 00000000000..80123a9f526 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/actions/SelectAllAction.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.actions; + +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.MulticoreVisualizerUIPlugin; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.view.MulticoreVisualizer; +import org.eclipse.cdt.visualizer.ui.VisualizerAction; +import org.eclipse.swt.SWT; + +/** Select All action for Visualizer context menu. */ +public class SelectAllAction extends VisualizerAction +{ + // --- members --- + + /** Visualizer instance we're associated with. */ + MulticoreVisualizer m_visualizer = null; + + + // --- constructors/destructors --- + + /** Constructor. */ + public SelectAllAction() + { + setText(MulticoreVisualizerUIPlugin.getString( + "MulticoreVisualizer.actions.SelectAll.text")); //$NON-NLS-1$ + setDescription(MulticoreVisualizerUIPlugin.getString( + "MulticoreVisualizer.actions.SelectAll.description")); //$NON-NLS-1$ + setAccelerator(SWT.CTRL + 'A'); + } + + /** Dispose method. */ + @Override + public void dispose() + { + m_visualizer = null; + super.dispose(); + } + + + // --- init methods --- + + /** Initializes this action for the specified view. */ + public void init(MulticoreVisualizer visualizer) + { + m_visualizer = visualizer; + } + + + // --- methods --- + + /** Invoked when action is triggered. */ + @Override + public void run() { + if (m_visualizer != null) + m_visualizer.selectAll(); + } +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerCPU.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerCPU.java new file mode 100755 index 00000000000..1f92161f1fd --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerCPU.java @@ -0,0 +1,133 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Hashtable; +import java.util.List; + +//---------------------------------------------------------------------------- +// VisualizerCPU +//---------------------------------------------------------------------------- + +/** Represents single CPU. */ +public class VisualizerCPU + implements Comparable +{ + // --- members --- + + /** ID of this core. */ + public int m_id; + + /** List of cores */ + protected ArrayList m_cores; + + /** Lookup table for cores. */ + protected Hashtable m_coreMap; + + + // --- constructors/destructors --- + + /** Constructor */ + public VisualizerCPU(int id) { + m_id = id; + m_cores = new ArrayList(); + m_coreMap = new Hashtable(); + } + + /** Dispose method */ + public void dispose() { + if (m_cores != null) { + for (VisualizerCore core : m_cores) { + core.dispose(); + } + m_coreMap.clear(); + m_coreMap = null; + m_cores.clear(); + m_cores = null; + } + } + + + // --- Object methods --- + + /** Returns string representation. */ + @Override + public String toString() { + return "CPU:" + m_id; //$NON-NLS-1$ + } + + + // --- accessors --- + + /** Gets ID of this CPU. */ + public int getID() { + return m_id; + } + + + // --- methods --- + + /** Gets number of cores. */ + public int getCoreCount() { + return m_cores.size(); + } + + /** Gets cores. */ + public List getCores() { + return m_cores; + } + + /** Gets core with specified ID. */ + public VisualizerCore getCore(int id) { + return m_coreMap.get(id); + } + + /** Adds core. */ + public VisualizerCore addCore(VisualizerCore core) { + m_cores.add(core); + m_coreMap.put(core.getID(), core); + return core; + } + + /** Removes core. */ + public void removeCore(VisualizerCore core) { + m_cores.remove(core); + m_coreMap.remove(core.getID()); + } + + + /** Sorts cores, cpus, etc. by IDs. */ + public void sort() { + Collections.sort(m_cores); + } + + + // --- Comparable implementation --- + + /** Compares this item to the specified item. */ + @Override + public int compareTo(VisualizerCPU o) { + int result = 0; + if (o != null) { + if (m_id < o.m_id) { + result = -1; + } + else if (m_id > o.m_id) { + result = 1; + } + } + return result; + } + +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerCore.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerCore.java new file mode 100755 index 00000000000..87bc1c55e96 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerCore.java @@ -0,0 +1,83 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model; + +/** Represents single core of a CPU. */ +public class VisualizerCore + implements Comparable +{ + // --- members --- + + /** CPU this core is part of. */ + public VisualizerCPU m_cpu = null; + + /** Linux CPU ID of this core. */ + public int m_id = 0; + + + // --- constructors/destructors --- + + /** Constructor */ + public VisualizerCore(VisualizerCPU cpu, int id) { + m_cpu = cpu; + m_id = id; + } + + /** Dispose method */ + public void dispose() { + } + + + // --- Object methods --- + + /** Returns string representation. */ + @Override + public String toString() { + return m_cpu + ",Core:" + m_id; //$NON-NLS-1$ + } + + + // --- accessors --- + + /** Gets CPU this core is part of. */ + public VisualizerCPU getCPU() { + return m_cpu; + } + + /** Gets Linux CPU ID of this core. */ + public int getID() { + return m_id; + } + + + // --- methods --- + + + + // --- Comparable implementation --- + + /** Compares this item to the specified item. */ + @Override + public int compareTo(VisualizerCore o) { + int result = 0; + if (o != null) { + if (m_id < o.m_id) { + result = -1; + } + else if (m_id > o.m_id) { + result = 1; + } + } + return result; + } + +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerExecutionState.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerExecutionState.java new file mode 100644 index 00000000000..965a2e84ffe --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerExecutionState.java @@ -0,0 +1,22 @@ +/******************************************************************************* + * Copyright (c) 2012 Ericsson and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Marc Khouzam (Ericsson) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model; + +/** + * Execution state for the different multicore visualizer objects. + */ +public enum VisualizerExecutionState { + RUNNING, + SUSPENDED, + CRASHED, + EXITED +}; diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerModel.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerModel.java new file mode 100755 index 00000000000..d62a71435d7 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerModel.java @@ -0,0 +1,226 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.cdt.visualizer.ui.util.Todo; + +/** + * Class representing the state of the data to display in the MulticoreVisualizer. + */ +public class VisualizerModel +{ + // --- members --- + + /** List of cpus (and cores) */ + protected ArrayList m_cpus; + + /** Lookup table for CPUs */ + protected Hashtable m_cpuMap; + + /** List of threads */ + protected ArrayList m_threads; + + /** Completion state tracker. */ + protected Todo m_todo; + + // Setting to remove exited threads, or keep them shown. + // If we are to support this, we should have a preference + // and a way to for the user to clean up old threads, + // or maybe a timeout to remove them. + private boolean m_keepExitedThreads = false; + + // --- constructors/destructors --- + + /** Constructor */ + public VisualizerModel() { + m_cpus = new ArrayList(); + m_cpuMap = new Hashtable(); + m_threads = new ArrayList(); + m_todo = new Todo(); + } + + /** Dispose method */ + public void dispose() { + if (m_cpus != null) { + for (VisualizerCPU cpu : m_cpus) { + cpu.dispose(); + } + m_cpuMap.clear(); + m_cpuMap = null; + m_cpus.clear(); + m_cpus = null; + } + if (m_threads != null) { + for (VisualizerThread thread : m_threads) { + thread.dispose(); + } + m_threads.clear(); + m_threads = null; + } + if (m_todo != null) { + m_todo.dispose(); + m_todo = null; + } + } + + + // --- accessors --- + + /** Gets completion state tracker. */ + public Todo getTodo() { + return m_todo; + } + + // --- methods --- + + /** Sorts cores, cpus, etc. by IDs. */ + public void sort() { + Collections.sort(m_cpus); + for (VisualizerCPU cpu : m_cpus) cpu.sort(); + Collections.sort(m_threads); + } + + + // --- core/cpu management --- + + /** Gets number of CPUs. */ + public int getCPUCount() { + return m_cpus.size(); + } + + /** Gets CPU with specified ID. */ + public VisualizerCPU getCPU(int id) { + return m_cpuMap.get(id); + } + + /** Gets Core with specified ID. */ + public VisualizerCore getCore(int id) { + VisualizerCore result = null; + for (VisualizerCPU cpu: m_cpus) { + result = cpu.getCore(id); + if (result != null) break; + } + return result; + } + + /** Gets CPU set. */ + public List getCPUs() { + return m_cpus; + } + + /** Adds CPU. */ + public VisualizerCPU addCPU(VisualizerCPU cpu) { + m_cpus.add(cpu); + m_cpuMap.put(cpu.getID(), cpu); + return cpu; + } + + /** Removes CPU. */ + public void removeCPU(VisualizerCPU cpu) { + m_cpus.remove(cpu); + m_cpuMap.remove(cpu.getID()); + } + + + /** Gets maximum number of cores per CPU. */ + public int getCoresPerCPU() { + int maxCores = 1; + for (VisualizerCPU cpu : m_cpus) { + int cores = cpu.getCoreCount(); + if (cores > maxCores) maxCores = cores; + } + return maxCores; + } + + + // --- thread management --- + + /** Gets threads. */ + public List getThreads() { + return m_threads; + } + + /** + * Finds thread(s) by process ID. + * If no threads are found, returns null rather + * than an empty list. + */ + public List getThreadsForProcess(int processId) { + List result = null; + for (VisualizerThread thread : m_threads) { + if (thread.getPID() == processId) { + if (result == null) result = new ArrayList(); + result.add(thread); + } + } + return result; + } + + /** + * Find a thread by GDB threadId. + * Since thread ids are unique across a GDB session, + * we can uniquely find a thread based on its id. + */ + public VisualizerThread getThread(int threadId) { + VisualizerThread result = null; + for (VisualizerThread thread : m_threads) { + if (thread.getGDBTID() == threadId) { + result = thread; + break; + } + } + return result; + } + + /** Adds thread. */ + public VisualizerThread addThread(VisualizerThread thread) { + m_threads.add(thread); + return thread; + } + + /** Removes thread. */ + public void removeThread(VisualizerThread thread) { + m_threads.remove(thread); + } + + /** + * Removes thread by GDB threadId. + */ + public void removeThread(int threadId) { + Iterator itr = m_threads.iterator(); + while (itr.hasNext()) { + VisualizerThread thread = itr.next(); + if (thread.getGDBTID() == threadId) { + itr.remove(); + break; + } + } + } + + /** + * Mark the specified thread as having exited. + */ + public void markThreadExited(int threadId) { + if (m_keepExitedThreads) { + VisualizerThread thread = getThread(threadId); + thread.setState(VisualizerExecutionState.EXITED); + } else { + removeThread(threadId); + } + } +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerThread.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerThread.java new file mode 100755 index 00000000000..9c19d57bc5b --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/model/VisualizerThread.java @@ -0,0 +1,153 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + * Marc Khouzam (Ericsson) - Added knowledge about execution + * state and os/gdb thread ids + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model; + +/** Represents single thread. */ +public class VisualizerThread + implements Comparable +{ + // --- members --- + + /** Current core this thread is on. */ + protected VisualizerCore m_core; + + /** Process ID (pid). */ + protected int m_pid; + + /** OS Thread ID (tid). */ + protected int m_tid; + + /** Thread ID as chosen by GDB. */ + protected int m_gdbtid; + + /** Thread execution state. */ + protected VisualizerExecutionState m_threadState; + + + // --- constructors/destructors --- + + /** Constructor. */ + public VisualizerThread(VisualizerCore core, int pid, int tid, int gdbtid, VisualizerExecutionState state) { + m_core = core; + m_pid = pid; + m_tid = tid; + m_gdbtid = gdbtid; + m_threadState = state; + } + + /** Dispose method */ + public void dispose() { + m_core = null; + } + + + // --- Object methods --- + + /** Equality comparison. */ + @Override + public boolean equals(Object obj) { + boolean result = false; + if (obj instanceof VisualizerThread) { + VisualizerThread v = (VisualizerThread) obj; + result = ( + v.m_pid == m_pid && + v.m_tid == m_tid && + v.m_gdbtid == m_gdbtid + ); + } + return result; + } + + /** Returns string representation. */ + @Override + public String toString() { + StringBuffer output = new StringBuffer(); + output.append(m_core).append(",Proc:").append(m_pid) //$NON-NLS-1$ + .append(",Thread:(").append(m_tid).append(",").append(m_gdbtid).append(")"); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + return output.toString(); + } + + + // --- accessors --- + + /** Gets core. */ + public VisualizerCore getCore() { + return m_core; + } + + public void setCore(VisualizerCore core) { + m_core = core; + } + + /** Returns true if this is the "process" thread, i.e. + * its PID and OS TID are the same. + */ + public boolean isProcessThread() + { + return m_pid == m_tid; + } + + /** Gets process id (pid). */ + public int getPID() { + return m_pid; + } + + /** Gets thread id (tid). */ + public int getTID() { + return m_tid; + } + + /** Gets gdb thread id. */ + public int getGDBTID() { + return m_gdbtid; + } + + /** Gets thread execution state. */ + public VisualizerExecutionState getState() { + return m_threadState; + } + + /** Sets thread execution state. */ + public void setState(VisualizerExecutionState state) { + m_threadState = state; + } + + + // --- methods --- + + + + // --- Comparable implementation --- + + /** Compares this item to the specified item. */ + @Override + public int compareTo(VisualizerThread o) { + int result = 0; + if (o != null) { + if (m_pid < o.m_pid) { + result = -1; + } + else if (m_pid > o.m_pid) { + result = 1; + } + else if (m_tid < o.m_tid) { + result = -1; + } + else if (m_tid > o.m_tid) { + result = 1; + } + } + return result; + } +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/IMulticoreVisualizerConstants.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/IMulticoreVisualizerConstants.java new file mode 100644 index 00000000000..5b3a280cacc --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/IMulticoreVisualizerConstants.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (c) 2012 Ericsson and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Marc Khouzam (Ericsson) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.view; + +import org.eclipse.cdt.visualizer.ui.util.Colors; +import org.eclipse.swt.graphics.Color; + + +/** + * Constants to be used in the Multicore Visualizer. + */ +public class IMulticoreVisualizerConstants +{ + // General canvas colors + public static final Color COLOR_SELECTED = Colors.CYAN; + + // Colors for drawing threads + + /** Color to be used to draw a running thread */ + public static final Color COLOR_RUNNING_THREAD = Colors.GREEN; + /** Color to be used to draw a suspended thread */ + public static final Color COLOR_SUSPENDED_THREAD = Colors.YELLOW; + /** Color to be used to draw a crashed thread */ + public static final Color COLOR_CRASHED_THREAD = Colors.RED; + /** Color to be used to draw an exited thread (if they are being shown) */ + public static final Color COLOR_EXITED_THREAD = Colors.GRAY; + + /** Color to be used to draw an highlight for the process thread */ + public static final Color COLOR_PROCESS_THREAD = Colors.WHITE; + + // Colors for drawing cores + + /** Color to be used to draw a running core */ + public static final Color COLOR_RUNNING_CORE_FG = Colors.GREEN; + public static final Color COLOR_RUNNING_CORE_BG = Colors.DARK_GREEN; + /** Color to be used to draw a suspended core */ + public static final Color COLOR_SUSPENDED_CORE_FG = Colors.YELLOW; + public static final Color COLOR_SUSPENDED_CORE_BG = Colors.DARK_YELLOW; + /** Color to be used to draw a crashed core */ + public static final Color COLOR_CRASHED_CORE_FG = Colors.RED; + public static final Color COLOR_CRASHED_CORE_BG = Colors.DARK_RED; + + // Colors for text + + /** Color to be used to draw a the text for a thread */ + public static final Color COLOR_THREAD_TEXT_FG = Colors.WHITE; + public static final Color COLOR_THREAD_TEXT_BG = Colors.BLACK; + + /** Color to be used to draw a the text for a core */ + public static final Color COLOR_CORE_TEXT_FG = Colors.WHITE; + public static final Color COLOR_CORE_TEXT_BG = Colors.BLACK; +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizer.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizer.java new file mode 100755 index 00000000000..8dc1a78028d --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizer.java @@ -0,0 +1,879 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.view; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.eclipse.cdt.dsf.concurrent.ConfinedToDsfExecutor; +import org.eclipse.cdt.dsf.concurrent.DsfRunnable; +import org.eclipse.cdt.dsf.datamodel.DMContexts; +import org.eclipse.cdt.dsf.datamodel.IDMContext; +import org.eclipse.cdt.dsf.debug.service.IProcesses.IThreadDMData; +import org.eclipse.cdt.dsf.gdb.launching.GDBProcess; +import org.eclipse.cdt.dsf.gdb.launching.GdbLaunch; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.actions.RefreshAction; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.actions.SelectAllAction; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerCPU; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerCore; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerExecutionState; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerModel; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerThread; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.utils.DSFDebugModel; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.utils.DSFDebugModelListener; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.utils.DSFSessionState; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.utils.DebugViewUtils; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardware.ICPUDMContext; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardware.ICoreDMContext; +import org.eclipse.cdt.dsf.mi.service.IMIExecutionDMContext; +import org.eclipse.cdt.dsf.mi.service.IMIProcessDMContext; +import org.eclipse.cdt.dsf.ui.viewmodel.datamodel.IDMVMContext; +import org.eclipse.cdt.visualizer.ui.canvas.GraphicCanvas; +import org.eclipse.cdt.visualizer.ui.canvas.GraphicCanvasVisualizer; +import org.eclipse.cdt.visualizer.ui.plugin.CDTVisualizerUIPlugin; +import org.eclipse.cdt.visualizer.ui.util.Colors; +import org.eclipse.cdt.visualizer.ui.util.GUIUtils; +import org.eclipse.cdt.visualizer.ui.util.SelectionUtils; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.debug.core.ILaunch; +import org.eclipse.debug.internal.ui.commands.actions.DropToFrameCommandAction; +import org.eclipse.debug.internal.ui.commands.actions.ResumeCommandAction; +import org.eclipse.debug.internal.ui.commands.actions.StepIntoCommandAction; +import org.eclipse.debug.internal.ui.commands.actions.StepOverCommandAction; +import org.eclipse.debug.internal.ui.commands.actions.StepReturnCommandAction; +import org.eclipse.debug.internal.ui.commands.actions.SuspendCommandAction; +import org.eclipse.debug.internal.ui.commands.actions.TerminateCommandAction; +import org.eclipse.debug.internal.ui.views.launch.LaunchView; +import org.eclipse.debug.ui.DebugUITools; +import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.action.IToolBarManager; +import org.eclipse.jface.action.Separator; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.widgets.Composite; + +/** + * The Multicore Visualizer is a generic visualizer that displays + * CPUs, cores, threads graphically. + * + * This visualizer uses the CDT Visualizer framework. + */ +@SuppressWarnings("restriction") +public class MulticoreVisualizer extends GraphicCanvasVisualizer + implements DSFDebugModelListener +{ + // --- constants --- + + /** Eclipse ID for this view */ + public static final String ECLIPSE_ID = "org.eclipse.cdt.dsf.gdb.multicorevisualizer.visualizer"; //$NON-NLS-1$ + + + // --- members --- + + /** + * The data model drawn by this visualizer. + */ + protected VisualizerModel fDataModel; + + /** Downcast reference to canvas. */ + protected MulticoreVisualizerCanvas m_canvas; + + /** DSF debug context session object. */ + protected DSFSessionState m_sessionState; + + /** Event listener class for DSF events */ + protected MulticoreVisualizerEventListener fEventListener; + + + // --- UI members --- + + /** Whether actions have been initialized. */ + boolean m_actionsInitialized = false; + + /** Toolbar / menu action */ + Separator m_separatorAction = null; + + /** Toolbar / menu action */ + ResumeCommandAction m_resumeAction = null; + + /** Toolbar / menu action */ + SuspendCommandAction m_suspendAction = null; + + /** Toolbar / menu action */ + TerminateCommandAction m_terminateAction = null; + + /** Toolbar / menu action */ + StepReturnCommandAction m_stepReturnAction = null; + + /** Toolbar / menu action */ + StepOverCommandAction m_stepOverAction = null; + + /** Toolbar / menu action */ + StepIntoCommandAction m_stepIntoAction = null; + + /** Toolbar / menu action */ + DropToFrameCommandAction m_dropToFrameAction = null; + + /** Toolbar / menu action */ + SelectAllAction m_selectAllAction = null; + + /** Toolbar / menu action */ + RefreshAction m_refreshAction = null; + + + // --- constructors/destructors --- + + /** Constructor. */ + public MulticoreVisualizer() + { + } + + /** Dispose method. */ + @Override + public void dispose() + { + super.dispose(); + disposeActions(); + } + + + // --- init methods --- + + /** Invoked when visualizer is created, to permit any initialization. */ + @Override + public void initializeVisualizer() { + fEventListener = new MulticoreVisualizerEventListener(this); + } + + /** Invoked when visualizer is disposed, to permit any cleanup. */ + @Override + public void disposeVisualizer() + { + // handle any other cleanup + dispose(); + } + + + // --- accessors --- + + /** Returns non-localized unique name for this visualizer. */ + @Override + public String getName() { + return "multicore"; //$NON-NLS-1$ + } + + /** Returns localized name to display for this visualizer. */ + @Override + public String getDisplayName() { + // TODO: use a string resource here. + return "Multicore Visualizer"; //$NON-NLS-1$ + } + + /** Returns localized tooltip text to display for this visualizer. */ + @Override + public String getDescription() { + // TODO: use a string resource here. + return "Displays current state of selected debug target."; //$NON-NLS-1$ + } + + + // --- canvas management --- + + /** Creates and returns visualizer canvas control. */ + @Override + public GraphicCanvas createCanvas(Composite parent) + { + m_canvas = new MulticoreVisualizerCanvas(parent); + m_canvas.addSelectionChangedListener(this); + return m_canvas; + } + + /** Invoked when canvas control should be disposed. */ + @Override + public void disposeCanvas() + { + if (m_canvas != null) { + m_canvas.removeSelectionChangedListener(this); + m_canvas.dispose(); + m_canvas = null; + } + } + + /** Invoked after visualizer control creation, */ + @Override + protected void initializeCanvas(GraphicCanvas canvas) + { + // Any workbench views left open at application shutdown may be instanced + // before our plugins are fully loaded, so make sure resource manager is initialized. + // Note: this also associates the resource manager with the Colors class; + // until this is done, the Colors constants are null. + CDTVisualizerUIPlugin.getResources(); + + m_canvas.setBackground(Colors.BLACK); + m_canvas.setForeground(Colors.GREEN); + } + + /** Returns downcast reference to grid view canvas. */ + public MulticoreVisualizerCanvas getMulticoreVisualizerCanvas() + { + return (MulticoreVisualizerCanvas) getCanvas(); + } + + /** Return the data model backing this multicore visualizer */ + public VisualizerModel getModel() { + return fDataModel; + } + + + // --- action management --- + + /** Creates actions for menus/toolbar. */ + protected void createActions() + { + if (m_actionsInitialized) return; // already done + + LaunchView debugView = DebugViewUtils.getDebugView(); + + m_separatorAction = new Separator(); + + m_resumeAction = new ResumeCommandAction(); + if (debugView != null) m_resumeAction.init(debugView); + + m_suspendAction = new SuspendCommandAction(); + if (debugView != null) m_suspendAction.init(debugView); + + m_terminateAction = new TerminateCommandAction(); + if (debugView != null) m_terminateAction.init(debugView); + + + m_stepReturnAction = new StepReturnCommandAction(); + if (debugView != null) m_stepReturnAction.init(debugView); + + m_stepOverAction = new StepOverCommandAction(); + if (debugView != null) m_stepOverAction.init(debugView); + + m_stepIntoAction = new StepIntoCommandAction(); + if (debugView != null) m_stepIntoAction.init(debugView); + + m_dropToFrameAction = new DropToFrameCommandAction(); + if (debugView != null) m_dropToFrameAction.init(debugView); + + m_selectAllAction = new SelectAllAction(); + m_selectAllAction.init(this); + + m_refreshAction = new RefreshAction(); + m_refreshAction.init(this); + + // Note: debug view may not be initialized at startup, + // so we'll pretend the actions are not yet updated, + // and reinitialize them later. + m_actionsInitialized = (debugView != null); + } + + /** Updates actions displayed on menu/toolbars. */ + protected void updateActions() + { + if (! m_actionsInitialized) return; + + // TODO: do we need any special enabling code here? + // Seems like we can rely on the enabling done by the DebugView itself, + // since we've associated these actions with it. + + boolean enabled = hasSelection(); + + m_resumeAction.setEnabled(enabled); + m_suspendAction.setEnabled(enabled); + m_terminateAction.setEnabled(enabled); + + m_stepReturnAction.setEnabled(enabled); + m_stepOverAction.setEnabled(enabled); + m_stepIntoAction.setEnabled(enabled); + m_dropToFrameAction.setEnabled(enabled); + + } + + /** Updates actions specific to context menu. */ + protected void updateContextMenuActions(Point location) + { + } + + /** Cleans up actions. */ + protected void disposeActions() { + if (m_resumeAction != null) { + m_resumeAction.dispose(); + m_resumeAction = null; + } + + if (m_suspendAction != null) { + m_suspendAction.dispose(); + m_suspendAction = null; + } + + if (m_terminateAction != null) { + m_terminateAction.dispose(); + m_terminateAction = null; + } + + if (m_stepReturnAction != null) { + m_stepReturnAction.dispose(); + m_stepReturnAction = null; + } + + if (m_stepOverAction != null) { + m_stepOverAction.dispose(); + m_stepOverAction = null; + } + + if (m_stepIntoAction != null) { + m_stepIntoAction.dispose(); + m_stepIntoAction = null; + } + + if (m_dropToFrameAction != null) { + m_dropToFrameAction.dispose(); + m_dropToFrameAction = null; + } + + if (m_selectAllAction != null) { + m_selectAllAction.dispose(); + m_selectAllAction = null; + } + + if (m_refreshAction != null) { + m_refreshAction.dispose(); + m_refreshAction = null; + } + + m_actionsInitialized = false; + } + + + // --- menu/toolbar management --- + + /** Invoked when visualizer is selected, to populate the toolbar. */ + @Override + public void populateToolBar(IToolBarManager toolBarManager) + { + // initialize menu/toolbar actions, if needed + createActions(); + + toolBarManager.add(m_resumeAction); + toolBarManager.add(m_suspendAction); + toolBarManager.add(m_terminateAction); + + toolBarManager.add(m_separatorAction); + + toolBarManager.add(m_stepReturnAction); + toolBarManager.add(m_stepOverAction); + toolBarManager.add(m_stepIntoAction); + toolBarManager.add(m_dropToFrameAction); + + updateActions(); + } + + /** Invoked when visualizer is selected, to populate the toolbar's menu. */ + @Override + public void populateMenu(IMenuManager menuManager) + { + // initialize menu/toolbar actions, if needed + createActions(); + + // TODO: Anything we want to hide on the toolbar menu? + + updateActions(); + } + + /** Invoked when visualizer view's context menu is invoked, to populate it. */ + @Override + public void populateContextMenu(IMenuManager menuManager) + { + // initialize menu/toolbar actions, if needed + createActions(); + + menuManager.add(m_resumeAction); + menuManager.add(m_suspendAction); + menuManager.add(m_terminateAction); + + menuManager.add(m_separatorAction); + + menuManager.add(m_stepReturnAction); + menuManager.add(m_stepOverAction); + menuManager.add(m_stepIntoAction); + menuManager.add(m_dropToFrameAction); + + menuManager.add(m_separatorAction); + + menuManager.add(m_selectAllAction); + menuManager.add(m_refreshAction); + + updateActions(); + Point location = m_viewer.getContextMenuLocation(); + updateContextMenuActions(location); + } + + + // --- visualizer selection management --- + + /** Invoked when visualizer has been selected. */ + @Override + public void visualizerSelected() { + updateActions(); + }; + + /** Invoked when another visualizer has been selected, hiding this one. */ + @Override + public void visualizerDeselected() { + }; + + + // --- workbench selection management --- + + /** + * Tests whether if the IVisualizer can display the selection + * (or something reachable from it). + */ + @Override + public int handlesSelection(ISelection selection) + { + // By default, we don't support anything. + int result = 0; + + Object sel = SelectionUtils.getSelectedObject(selection); + if (sel instanceof GdbLaunch || + sel instanceof GDBProcess || + sel instanceof IDMVMContext) + { + result = 1; + } + else { + result = 0; + } + + return result; + } + + /** + * Invoked by VisualizerViewer when workbench selection changes. + */ + @Override + public void workbenchSelectionChanged(ISelection selection) + { + refresh(); + } + + /** Refreshes visualizer content from model. */ + public void refresh() + { + // See if we need to update our debug info from + // the workbench selection. This will be done asynchronously. + boolean changed = updateDebugContext(); + + // Even if debug info doesn't change, we still want to + // check whether the canvas selection needs to change + // to reflect the current workbench selection. + if (!changed) updateCanvasSelection(); + } + + + // --- ISelectionChangedListener implementation --- + + /** + * Invoked when visualizer control's selection changes. + * Sets control selection as its own selection, + * and raises selection changed event for any listeners. + */ + @Override + public void selectionChanged(SelectionChangedEvent event) { + super.selectionChanged(event); + + // Force Debug View's selection to reflect visualizer selection, + // since debug view doesn't update itself from the workbench selection. + // NOTE: This can be overridden by the model selection policy, if there is one. + ISelection debugViewSelection = visualizerToDebugViewSelection(getSelection()); + DebugViewUtils.setDebugViewSelection(debugViewSelection); + + // update actions to reflect change of selection + updateActions(); + } + + + // --- Selection conversion methods --- + + /** Gets debug view selection from visualizer selection. */ + protected ISelection visualizerToDebugViewSelection(ISelection visualizerSelection) + { + MulticoreVisualizerSelectionFinder selectionFinder = + new MulticoreVisualizerSelectionFinder(); + ISelection workbenchSelection = + selectionFinder.findSelection(visualizerSelection); + return workbenchSelection; + } + + /** Gets visualizer selection from debug view selection. */ + protected ISelection workbenchToVisualizerSelection(ISelection workbenchSelection) + { + ISelection visualizerSelection = null; + + List items = SelectionUtils.getSelectedObjects(workbenchSelection); + + // Use the current canvas model to match Debug View items + // with corresponding threads, if any. + VisualizerModel model = m_canvas.getModel(); + if (model != null) { + + Set selected = new HashSet(); + + for (Object item : items) { + + // Currently, we ignore selections other than DSF context objects. + // TODO: any other cases where we could map selections to canvas? + if (item instanceof IDMVMContext) + { + IDMContext context = ((IDMVMContext) item).getDMContext(); + + IMIProcessDMContext processContext = + DMContexts.getAncestorOfType(context, IMIProcessDMContext.class); + int pid = Integer.parseInt(processContext.getProcId()); + + IMIExecutionDMContext execContext = + DMContexts.getAncestorOfType(context, IMIExecutionDMContext.class); + int tid = (execContext == null) ? 0 : execContext.getThreadId(); + + if (tid == 0) { // process + List threads = model.getThreadsForProcess(pid); + if (threads != null) { + selected.addAll(threads); + } + } + else { // thread + VisualizerThread thread = model.getThread(tid); + if (thread != null) { + selected.add(thread); + } + } + } + } + + visualizerSelection = SelectionUtils.toSelection(selected); + } + + return visualizerSelection; + } + + + // --- DSF Context Management --- + + /** Updates debug context being displayed by canvas. + * Returns true if canvas context actually changes, false if not. + */ + public boolean updateDebugContext() + { + String sessionId = null; + IAdaptable debugContext = DebugUITools.getDebugContext(); + if (debugContext instanceof IDMVMContext) { + sessionId = ((IDMVMContext)debugContext).getDMContext().getSessionId(); + } else if (debugContext instanceof GdbLaunch) { + GdbLaunch gdbLaunch = (GdbLaunch)debugContext; + if (gdbLaunch.isTerminated() == false) { + sessionId = gdbLaunch.getSession().getId(); + } + } else if (debugContext instanceof GDBProcess) { + ILaunch launch = ((GDBProcess)debugContext).getLaunch(); + if (launch.isTerminated() == false && + launch instanceof GdbLaunch) { + sessionId = ((GdbLaunch)launch).getSession().getId(); + } + } + + return setDebugSession(sessionId); + } + + /** Sets debug context being displayed by canvas. + * Returns true if canvas context actually changes, false if not. + */ + public boolean setDebugSession(String sessionId) { + boolean changed = true; + + if (m_sessionState != null && + ! m_sessionState.getSessionID().equals(sessionId)) + { + m_sessionState.removeServiceEventListener(fEventListener); + m_sessionState.dispose(); + m_sessionState = null; + changed = true; + } + + if (m_sessionState == null && + sessionId != null) + { + m_sessionState = new DSFSessionState(sessionId); + m_sessionState.addServiceEventListener(fEventListener); + changed = true; + } + + if (changed) update(); + + return changed; + } + + + // --- Update methods --- + + /** Updates visualizer canvas state. */ + public void update() { + // Create new VisualizerModel and hand it to canvas, + // TODO: cache the VisualizerModel somehow and update it, + // rather than creating it from scratch each time. + if (m_sessionState == null) { + // no state to display, we can immediately clear the canvas + setCanvasModel(null); + return; + } + m_sessionState.execute(new DsfRunnable() { @Override public void run() { + // get model asynchronously, and update canvas + // in getVisualizerModelDone(). + getVisualizerModel(); + }}); + } + + /** Sets canvas model. (Also updates canvas selection.) */ + protected void setCanvasModel(VisualizerModel model) { + final VisualizerModel model_f = model; + GUIUtils.exec(new Runnable() { @Override public void run() { + m_canvas.setModel(model_f); + + // Update the canvas's selection from the current workbench selection. + updateCanvasSelectionInternal(); + }}); + } + + /** Updates canvas selection from current workbench selection. */ + protected void updateCanvasSelection() { + GUIUtils.exec(new Runnable() { @Override public void run() { + // Update the canvas's selection from the current workbench selection. + updateCanvasSelectionInternal(); + }}); + } + + /** Updates canvas selection from current workbench selection. + * Note: this method assumes it is called on the UI thread. */ + protected void updateCanvasSelectionInternal() + { + updateCanvasSelectionInternal(SelectionUtils.getWorkbenchSelection()); + } + + /** Updates canvas selection from current workbench selection. + * Note: this method assumes it is called on the UI thread. */ + protected void updateCanvasSelectionInternal(ISelection selection) + { + ISelection canvasSelection = workbenchToVisualizerSelection(selection); + + // canvas does not raise a selection changed event in this case + // to avoid circular selection update events + if (canvasSelection != null) + m_canvas.setSelection(canvasSelection, false); + } + + + /** Selects all thread(s) displayed in the canvas. */ + public void selectAll() + { + m_canvas.selectAll(); + } + + // --- Visualizer model update methods --- + + /** Starts visualizer model request. + * Calls getVisualizerModelDone() with the constructed model. + */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + public void getVisualizerModel() { + fDataModel = new VisualizerModel(); + DSFDebugModel.getCPUs(m_sessionState, this, fDataModel); + } + + /** Invoked when getModel() request completes. */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + public void getVisualizerModelDone(VisualizerModel model) { + model.sort(); + setCanvasModel(model); + } + + + // --- DSFDebugModelListener implementation --- + + /** Invoked when DSFDebugModel.getCPUs() completes. */ + @Override + @ConfinedToDsfExecutor("getSession().getExecutor()") + public void getCPUsDone(ICPUDMContext[] cpuContexts, Object arg) + { + VisualizerModel model = (VisualizerModel) arg; + + if (cpuContexts == null || cpuContexts.length == 0) { + // Whoops, no CPU data. + // We'll fake a CPU and use it to contain any cores we find. + + model.addCPU(new VisualizerCPU(0)); + + // keep track of CPUs left to visit + model.getTodo().add(1); + + // Collect core data. + DSFDebugModel.getCores(m_sessionState, this, model); + } else { + // keep track of CPUs left to visit + int count = cpuContexts.length; + model.getTodo().add(count); + + for (ICPUDMContext cpuContext : cpuContexts) { + int cpuID = Integer.parseInt(cpuContext.getId()); + model.addCPU(new VisualizerCPU(cpuID)); + + // Collect core data. + DSFDebugModel.getCores(m_sessionState, cpuContext, this, model); + } + + } + } + + + /** Invoked when getCores() request completes. */ + @Override + @ConfinedToDsfExecutor("getSession().getExecutor()") + public void getCoresDone(ICPUDMContext cpuContext, + ICoreDMContext[] coreContexts, + Object arg) + { + VisualizerModel model = (VisualizerModel) arg; + + if (coreContexts == null || coreContexts.length == 0) { + // no cores for this cpu context + // That's fine. + } else { + int cpuID = Integer.parseInt(cpuContext.getId()); + VisualizerCPU cpu = model.getCPU(cpuID); + + // keep track of Cores left to visit + int count = coreContexts.length; + model.getTodo().add(count); + + for (ICoreDMContext coreContext : coreContexts) { + int coreID = Integer.parseInt(coreContext.getId()); + cpu.addCore(new VisualizerCore(cpu, coreID)); + + // Collect thread data + DSFDebugModel.getThreads(m_sessionState, cpuContext, coreContext, this, model); + } + } + + // keep track of CPUs visited + // note: do this _after_ incrementing for cores + done(1, model); + } + + + /** Invoked when getThreads() request completes. */ + @Override + @ConfinedToDsfExecutor("getSession().getExecutor()") + public void getThreadsDone(ICPUDMContext cpuContext, + ICoreDMContext coreContext, + IDMContext[] threadContexts, + Object arg) + { + VisualizerModel model = (VisualizerModel) arg; + + if (threadContexts == null || threadContexts.length == 0) { + // no threads for this core + // That's fine. + } else { + // keep track of threads left to visit + int count = threadContexts.length; + model.getTodo().add(count); + + for (IDMContext threadContext : threadContexts) { + IMIExecutionDMContext execContext = + DMContexts.getAncestorOfType(threadContext, IMIExecutionDMContext.class); + + // Don't add the thread to the model just yet, let's wait until we have its data and execution state. + // Collect thread data + DSFDebugModel.getThreadData(m_sessionState, cpuContext, coreContext, execContext, this, model); + } + + } + + // keep track of cores visited + // note: do this _after_ incrementing for threads + done(1, model); + } + + /** Invoked when getThreads() request completes. */ + @Override + @ConfinedToDsfExecutor("getSession().getExecutor()") + public void getThreadDataDone(ICPUDMContext cpuContext, + ICoreDMContext coreContext, + IMIExecutionDMContext execContext, + IThreadDMData threadData, + Object arg) + { + + // Don't add the thread to the model just yet, let's wait until we have its execution state. + DSFDebugModel.getThreadExecutionState(m_sessionState, cpuContext, coreContext, execContext, threadData, this, arg); + } + + + /** Invoked when getThreadExecutionState() request completes. */ + @Override + @ConfinedToDsfExecutor("getSession().getExecutor()") + public void getThreadExecutionStateDone(ICPUDMContext cpuContext, + ICoreDMContext coreContext, + IMIExecutionDMContext execContext, + IThreadDMData threadData, + VisualizerExecutionState state, + Object arg) + { + VisualizerModel model = (VisualizerModel) arg; + int cpuID = Integer.parseInt(cpuContext.getId()); + VisualizerCPU cpu = model.getCPU(cpuID); + int coreID = Integer.parseInt(coreContext.getId()); + VisualizerCore core = cpu.getCore(coreID); + + if (state == null) { + // Unable to obtain execution state. Assume running + state = VisualizerExecutionState.RUNNING; + } + + IMIProcessDMContext processContext = + DMContexts.getAncestorOfType(execContext, IMIProcessDMContext.class); + int pid = Integer.parseInt(processContext.getProcId()); + int tid = execContext.getThreadId(); + String osTIDValue = threadData.getId(); + + // If we can't get the real Linux OS tid, fallback to using the gdb thread id + int osTid = (osTIDValue == null) ? tid : Integer.parseInt(osTIDValue); + + model.addThread(new VisualizerThread(core, pid, osTid, tid, state)); + + // keep track of threads visited + done(1, model); + } + + /** Update "done" count for current visualizer model. */ + protected void done(int n, VisualizerModel model) { + model.getTodo().done(n); + if (model.getTodo().isDone()) { + getVisualizerModelDone(model); + } + } +} + diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerCPU.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerCPU.java new file mode 100755 index 00000000000..fc0cf24f29d --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerCPU.java @@ -0,0 +1,119 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.view; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.cdt.visualizer.ui.util.Colors; +import org.eclipse.cdt.visualizer.ui.util.GUIUtils; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.GC; + +/** + * Graphic object for MulticoreVisualizer. + */ +public class MulticoreVisualizerCPU extends MulticoreVisualizerGraphicObject +{ + // --- members --- + + /** CPU ID. */ + protected int m_id; + + /** Child cores. */ + protected ArrayList m_cores; + + + // --- constructors/destructors --- + + /** Constructor */ + public MulticoreVisualizerCPU(int id) + { + m_id = id; + m_cores = new ArrayList(); + } + + /** Dispose method */ + @Override + public void dispose() { + super.dispose(); + } + + + // --- accessors --- + + /** Gets CPU ID. */ + public int getID() { + return m_id; + } + + + // --- methods --- + + /** Adds child core. */ + public void addCore(MulticoreVisualizerCore core) + { + m_cores.add(core); + } + + /** Removes child core. */ + public void removeCore(MulticoreVisualizerCore core) + { + m_cores.remove(core); + } + + /** Gets list of child cores. */ + public List getCores() + { + return m_cores; + } + + + // --- paint methods --- + + /** Invoked to allow element to paint itself on the viewer canvas */ + @Override + public void paintContent(GC gc) { + Color fg, bg; + fg = Colors.getColor(0,255,0); + bg = Colors.getColor(0,64,0); + gc.setForeground(fg); + gc.setBackground(bg); + + gc.fillRectangle(m_bounds); + gc.drawRectangle(m_bounds); + } + + /** Returns true if object has decorations to paint. */ + @Override + public boolean hasDecorations() { + return true; + } + + /** Invoked to allow element to paint decorations on top of anything drawn on it */ + @Override + public void paintDecorations(GC gc) { + if (m_bounds.height > 20) { + Color fg, bg; + fg = Colors.getColor(0,255,0); + bg = Colors.getColor(0,64,0); + gc.setForeground(fg); + gc.setBackground(bg); + + int text_indent = 6; + int tx = m_bounds.x + m_bounds.width - text_indent; + int ty = m_bounds.y + m_bounds.height - text_indent; + GUIUtils.drawTextAligned(gc, Integer.toString(m_id), tx, ty, false, false); + } + } + +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerCanvas.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerCanvas.java new file mode 100755 index 00000000000..993e2270b65 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerCanvas.java @@ -0,0 +1,896 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.view; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.List; + +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.MulticoreVisualizerUIPlugin; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerCPU; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerCore; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerModel; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerThread; +import org.eclipse.cdt.visualizer.ui.canvas.GraphicCanvas; +import org.eclipse.cdt.visualizer.ui.plugin.CDTVisualizerUIPlugin; +import org.eclipse.cdt.visualizer.ui.util.GUIUtils; +import org.eclipse.cdt.visualizer.ui.util.MouseMonitor; +import org.eclipse.cdt.visualizer.ui.util.SelectionManager; +import org.eclipse.cdt.visualizer.ui.util.SelectionUtils; +import org.eclipse.cdt.visualizer.ui.util.Timer; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.widgets.Composite; + + +/** + * MulticoreVisualizer's display canvas. + */ +public class MulticoreVisualizerCanvas extends GraphicCanvas + implements ISelectionProvider +{ + // --- constants --- + + /** Canvas update interval in milliseconds. */ + protected static final int CANVAS_UPDATE_INTERVAL = 100; + + /** Spacing to allow between threads, when many are displayed on same tile. */ + protected static final int THREAD_SPACING = 8; + + + // --- members --- + + /** Update timer */ + protected Timer m_updateTimer = null; + + /** Whether we need to recache graphic objects. */ + protected boolean m_recache = true; + + /** + * Whether we need to recache objects that depend on target state. + */ + protected boolean m_recacheState = true; + + /** + * Whether view size has changed, requiring us to recalculate object sizes. + */ + protected boolean m_recacheSizes = true; + + /** Whether we need to repaint the canvas */ + protected boolean m_update = true; + + + // --- UI members --- + + /** Text font */ + protected Font m_textFont = null; + + /** Externally visible selection manager. */ + protected SelectionManager m_selectionManager; + + /** Mouse-drag marquee graphic element */ + protected MulticoreVisualizerMarquee m_marquee = null; + + /** Last mouse down/up point, for shift-click selections. */ + protected Point m_lastSelectionClick = new Point(0,0); + + /** Mouse click/drag monitor */ + protected MouseMonitor m_mouseMonitor = null; + + + // --- cached repaint state --- + + /** Current visualizer model we're displaying. */ + protected VisualizerModel m_model = null; + + /** Number of CPUs to display. */ + protected int m_cpu_count = 15; + + /** Number of Cores per CPU to display. */ + protected int m_cores_per_cpu = 3; + + /** List of CPUs we're displaying. */ + protected ArrayList m_cpus = null; + /** Mapping from model to view objects. */ + protected Hashtable m_cpuMap = null; + + /** List of CPU cores we're displaying. */ + protected ArrayList m_cores = null; + /** Mapping from model to view objects. */ + protected Hashtable m_coreMap = null; + + /** Graphic objects representing threads */ + protected ArrayList m_threads = null; + /** Mapping from model to view objects. */ + protected Hashtable m_threadMap = null; + + /** Selected PIDs. */ + protected HashSet m_selectedPIDs = null; + + + // --- constructors/destructors --- + + /** Constructor. */ + public MulticoreVisualizerCanvas(Composite parent) { + super(parent); + initMulticoreVisualizerCanvas(parent); + } + + /** Dispose method. */ + @Override + public void dispose() { + cleanupMulticoreVisualizerCanvas(); + super.dispose(); + } + + + // --- init methods --- + + /** Initializes control */ + protected void initMulticoreVisualizerCanvas(Composite parent) { + // perform any initialization here + + // text font + m_textFont = CDTVisualizerUIPlugin.getResources().getFont("Luxi Sans", 8); //$NON-NLS-1$ + setFont(m_textFont); + + // initialize cached state storage + m_cpus = new ArrayList(); + m_cpuMap = new Hashtable(); + + m_cores = new ArrayList(); + m_coreMap = new Hashtable(); + + m_threads = new ArrayList(); + m_threadMap = new Hashtable(); + + m_selectedPIDs = new HashSet(); + + // mouse-drag monitor + m_mouseMonitor = new MouseMonitor(this) { + /** Invoked for a selection click at the specified point. */ + @Override + public void select(int x, int y, int keys) { + MulticoreVisualizerCanvas.this.select(x, y, keys); + } + + /** Invoked for a double click at the specified point. */ + @Override + public void mouseDoubleClick(int button, int x, int y, int keys) { + MulticoreVisualizerCanvas.this.select(x, y, keys); + } + + /** Invoked for a menu mouse down at the specified point. */ + @Override + public void mouseDown(int button, int x, int y, int keys) { + if (button == RIGHT_BUTTON) { + if (! hasSelection()) { + // If there isn't a selection currently, try to + // select item(s) under the mouse before popping up the context menu. + MulticoreVisualizerCanvas.this.select(x, y, keys); + } + } + } + + /** Invoked when mouse is dragged. */ + @Override + public void drag(int button, int x, int y, int keys, int dragState) { + if (button == LEFT_BUTTON) { + MulticoreVisualizerCanvas.this.drag(x, y, keys, dragState); + } + } + }; + + // selection marquee + m_marquee = new MulticoreVisualizerMarquee(); + + // selection manager + m_selectionManager = new SelectionManager(this, "MulticoreVisualizerCanvas selection manager"); //$NON-NLS-1$ + + // add update timer + m_updateTimer = new Timer(CANVAS_UPDATE_INTERVAL) { + @Override + public void run() { + update(); + } + }; + m_updateTimer.setRepeating(false); // one-shot timer + m_updateTimer.start(); + } + + /** Cleans up control */ + protected void cleanupMulticoreVisualizerCanvas() { + if (m_updateTimer != null) { + m_updateTimer.dispose(); + m_updateTimer = null; + } + if (m_marquee != null) { + m_marquee.dispose(); + m_marquee = null; + } + if (m_mouseMonitor != null) { + m_mouseMonitor.dispose(); + m_mouseMonitor = null; + } + if (m_selectionManager != null) { + m_selectionManager.dispose(); + m_selectionManager = null; + } + if (m_cpus != null) { + m_cpus.clear(); + m_cpus = null; + } + if (m_cpuMap != null) { + m_cpuMap.clear(); + m_cpuMap = null; + } + if (m_cores != null) { + m_cores.clear(); + m_cores = null; + } + if (m_coreMap != null) { + m_coreMap.clear(); + m_coreMap = null; + } + if (m_threads != null) { + m_threads.clear(); + m_threads = null; + } + if (m_threadMap != null) { + m_threadMap.clear(); + m_threadMap = null; + } + if (m_selectedPIDs != null) { + m_selectedPIDs.clear(); + m_selectedPIDs = null; + } + } + + + // --- accessors --- + + /** Gets currently displayed model. */ + public VisualizerModel getModel() + { + return m_model; + } + + /** Sets model to display, and requests canvas update. */ + public void setModel(VisualizerModel model) + { + m_model = model; + requestRecache(); + requestUpdate(); + } + + + + // --- resize methods --- + + /** Invoked when control is resized. */ + @Override + public void resized(Rectangle bounds) { + requestRecache(false, true); + // note: resize itself will trigger an update, so we don't have to request one + } + + + // --- update methods --- + + /** + * Requests an update on next timer tick. + * NOTE: use this method instead of normal update(), + * multiple update requests on same tick are batched. + */ + public void requestUpdate() { + GUIUtils.exec(new Runnable() { @Override public void run() { + m_updateTimer.start(); + }}); + } + + + // --- paint methods --- + + /** Requests that next paint call should recache state and/or size information */ + // synchronized so we don't change recache flags while doing a recache + public synchronized void requestRecache() { + requestRecache(true, true); + } + + /** Requests that next paint call should recache state and/or size information */ + // synchronized so we don't change recache flags while doing a recache + public synchronized void requestRecache(boolean state, boolean sizes) { + m_recache = true; + // NOTE: we intentionally OR these flags with any pending request(s) + m_recacheState |= state; + m_recacheSizes |= sizes; + } + + /** Fits n square items into a rectangle of the specified size. + * Returns largest edge of one of the square items that allows + * them all to pack neatly in rows/columns in the specified area. */ + public int fitSquareItems(int nitems, int width, int height) { + int max_edge = 0; + if (width > height) { + for (int items_per_row = nitems; items_per_row > 0; --items_per_row) { + int rows = (int) Math.ceil(1.0 * nitems / items_per_row); + int w = width / items_per_row; + int h = height / rows; + int edge = (w < h) ? w : h; + if (edge * rows > height || edge * items_per_row > width) continue; + if (edge > max_edge) max_edge = edge; + } + } + else { + for (int items_per_col = nitems; items_per_col > 0; --items_per_col) { + int cols = (int) Math.ceil(1.0 * nitems / items_per_col); + int w = width / cols; + int h = height / items_per_col; + int edge = (w < h) ? w : h; + if (edge * cols > width || edge * items_per_col > height) continue; + if (edge > max_edge) max_edge = edge; + } + } + return max_edge; + } + + /** Recache persistent objects (tiles, etc.) for new monitor */ + // synchronized so we don't change recache flags while doing a recache + public synchronized void recache() { + if (! m_recache) return; // nothing to do, free the lock quickly + + if (m_recacheState) { + + // clear all grid view objects + clear(); + + // clear cached state + m_cpus.clear(); + m_cores.clear(); + m_threads.clear(); + + // For debugging purposes only, allows us to force a CPU count. + //int cpu_count = 0; + //int force_cpu_count = 2; + + if (m_model != null) { + for (VisualizerCPU cpu : m_model.getCPUs()) { + //if (force_cpu_count >= cpu_count) break; + //cpu_count++; + MulticoreVisualizerCPU mcpu = new MulticoreVisualizerCPU(cpu.getID()); + m_cpus.add(mcpu); + m_cpuMap.put(cpu, mcpu); + for (VisualizerCore core : cpu.getCores()) { + MulticoreVisualizerCore mcore = new MulticoreVisualizerCore(mcpu, core.getID()); + m_cores.add(mcore); + m_coreMap.put(core, mcore); + } + } + } + /* + while (cpu_count < force_cpu_count) { + MulticoreVisualizerCPU mcpu = new MulticoreVisualizerCPU(cpu_count); + m_cpus.add(mcpu); + cpu_count++; + } + */ + + // we've recached state, which implies recacheing sizes too + m_recacheState = false; + m_recacheSizes = true; + } + + if (m_recacheSizes) { + // update cached size information + + // General margin/spacing constants. + int cpu_margin = 8; // margin around edges of CPU grid + int cpu_separation = 6; // spacing between CPUS + + int core_margin = 4; // margin around cores in a CPU + int core_separation = 2; // spacing between cores + + // Get overall area we have for laying out content. + Rectangle bounds = getClientArea(); + GUIUtils.inset(bounds, cpu_margin); + + // Figure out area to allocate to each CPU box. + int ncpus = m_cpus.size(); + int width = bounds.width + cpu_separation; + int height = bounds.height + cpu_separation; + int cpu_edge = fitSquareItems(ncpus, width, height); + int cpu_size = cpu_edge - cpu_separation; + if (cpu_size < 0) cpu_size = 0; + + // Calculate area on each CPU for placing cores. + int ncores = m_cores.size(); + int cpu_width = cpu_size - core_margin * 2 + core_separation; + int cpu_height = cpu_size - core_margin * 2 + core_separation; + int core_edge = fitSquareItems(ncores, cpu_width, cpu_height); + int core_size = core_edge - core_separation; + if (core_size < 0) core_size = 0; + + int x = bounds.x, y = bounds.y; + for (MulticoreVisualizerCPU cpu : m_cpus) { + cpu.setBounds(x, y, cpu_size-1, cpu_size-1); + + int left = x + core_margin; + int cx = left, cy = y + core_margin; + for (MulticoreVisualizerCore core : cpu.getCores()) + { + core.setBounds(cx, cy, core_size, core_size); + + cx += core_size + core_separation; + if (cx + core_size > x + cpu_size) { + cx = left; + cy += core_size + core_separation; + } + } + + x += cpu_size + cpu_separation; + if (x + cpu_size > bounds.x + width) { + x = bounds.x; + y += cpu_size + cpu_separation; + } + } + + m_recacheSizes = false; + } + } + + /** Invoked when canvas repaint event is raised. + * Default implementation clears canvas to background color. + */ + @Override + public void paintCanvas(GC gc) { + // NOTE: We have a little setup to do first, + // so we delay clearing/redrawing the canvas until needed, + // to minimize any potential visual flickering. + + // recache/resize tiles & shims if needed + recache(); + + // do any "per frame" updating/replacement of graphic objects + + // recalculate process/thread graphic objects on the fly + // TODO: can we cache/pool these and just move them around? + for (MulticoreVisualizerCore core : m_cores) { + core.removeAllThreads(); + } + m_threads.clear(); + m_threadMap.clear(); + + // update based on current processes/threads + if (m_model != null) { + + // NOTE: we assume that we've already created and sized the graphic + // objects for cpus/cores in recache() above, + // so we can use these to determine the size/location of more dynamic elements + // like processes and threads + + for (VisualizerThread thread : m_model.getThreads()) { + VisualizerCore core = thread.getCore(); + MulticoreVisualizerCore mcore = m_coreMap.get(core); + if (mcore != null) { + MulticoreVisualizerThread mthread = + new MulticoreVisualizerThread(mcore, thread); + mcore.addThread(mthread); + m_threads.add(mthread); + m_threadMap.put(thread, mthread); + } + } + + // now set sizes of processes/threads for each tile + for (MulticoreVisualizerCore core : m_cores) { + Rectangle bounds = core.getBounds(); + + // how we lay out threads depends on how many there are + List threads = core.getThreads(); + int threadspotsize = MulticoreVisualizerThread.THREAD_SPOT_SIZE; + int threadheight = threadspotsize + THREAD_SPACING; + int count = threads.size(); + int tileheight = bounds.height - 4; + int tx = bounds.x + 2; + int ty = bounds.y + 2; + int dty = (count < 1) ? 0 : tileheight / count; + if (dty > threadheight) dty = threadheight; + if (count > 0 && dty * count <= tileheight) { + ty = bounds.y + 2 + (tileheight - (dty * count)) / 2; + if (ty < bounds.y + 2) ty = bounds.y + 2; + } + else if (count > 0) { + dty = tileheight / count; + if (dty > threadheight) dty = threadheight; + } + int t = 0; + for (MulticoreVisualizerThread threadobj : threads) { + int y = ty + dty * (t++); + threadobj.setBounds(tx, y, threadspotsize, threadspotsize); + } + } + } + + // restore canvas object highlighting from model object selection + restoreSelection(); + + // FIXME: enable secondary highlight for threads that are + // part of a selected process. + m_selectedPIDs.clear(); + for (MulticoreVisualizerThread mthread : m_threads) { + if (mthread.isSelected()) { + m_selectedPIDs.add(mthread.getPID()); + } + } + for (MulticoreVisualizerThread mthread : m_threads) { + mthread.setProcessSelected(m_selectedPIDs.contains(mthread.getPID())); + } + + // NOW we can clear the background + clearCanvas(gc); + + // Make sure color/font resources are properly initialized. + MulticoreVisualizerUIPlugin.getResources(); + + // paint cpus + for (MulticoreVisualizerCPU cpu : m_cpus) { + cpu.paintContent(gc); + } + + // paint cores + for (MulticoreVisualizerCore core : m_cores) { + core.paintContent(gc); + } + + // paint cpus IDs on top of cores + for (MulticoreVisualizerCPU cpu : m_cpus) { + cpu.paintDecorations(gc); + } + + // paint threads on top of cores + for (MulticoreVisualizerThread thread : m_threads) { + thread.paintContent(gc); + } + + // paint drag-selection marquee last, so it's on top. + m_marquee.paintContent(gc); + } + + + // --- mouse event handlers --- + + /** Invoked when mouse is dragged. */ + public void drag(int x, int y, int keys, int dragState) + { + Rectangle region = m_mouseMonitor.getDragRegion(); + switch (dragState) { + case MouseMonitor.MOUSE_DRAG_BEGIN: + m_marquee.setBounds(region); + m_marquee.setVisible(true); + update(); + break; + case MouseMonitor.MOUSE_DRAG: + m_marquee.setBounds(region); + update(); + break; + case MouseMonitor.MOUSE_DRAG_END: + default: + m_marquee.setBounds(region); + m_marquee.setVisible(false); + + boolean addToSelection = MouseMonitor.isShiftDown(keys); + boolean toggleSelection = MouseMonitor.isControlDown(keys); + + selectRegion(m_marquee.getBounds(), addToSelection, toggleSelection); + + // remember last mouse-up point for shift-click selection + m_lastSelectionClick.x = x; + m_lastSelectionClick.y = y; + + update(); + break; + } + } + + /** Invoked for a selection click at the specified point. */ + public void select(int x, int y, int keys) + { + boolean addToSelection = MouseMonitor.isShiftDown(keys); + boolean toggleSelection = MouseMonitor.isControlDown(keys); + + selectPoint(x,y, addToSelection, toggleSelection); + } + + + // --- selection methods --- + + /** + * Selects item(s), if any, in specified region + * + * If addToSelection is true, appends item(s) to current selection + * without changing selection state of other items. + * + * If toggleSelection is true, toggles selection of item(s) + * without changing selection state of other items. + * + * If both are true, deselects item(s) + * without changing selection state of other items. + * + * Otherwise, selects item(s) and deselects other items. + */ + public void selectRegion(Rectangle region, + boolean addToSelection, boolean toggleSelection) + { + // currently, we select/deselect threads, not processes or tiles + if (m_threads != null) { + + boolean changed = false; + + for (MulticoreVisualizerThread tobj : m_threads) { + boolean within = tobj.isWithin(region); + + if (addToSelection && toggleSelection) { + if (within) { + tobj.setSelected(false); + changed = true; + } + } + else if (addToSelection) { + if (within) { + tobj.setSelected(true); + changed = true; + } + } + else if (toggleSelection) { + if (within) { + tobj.setSelected(! tobj.isSelected()); + changed = true; + } + } + else { + tobj.setSelected(within); + changed = true; + } + } + + if (changed) + selectionChanged(); + } + } + + /** + * Selects item(s), if any, at specified point. + * + * If addToSelection is true, appends item(s) to current selection + * without changing selection state of other items. + * + * If toggleSelection is true, toggles selection of item(s) + * without changing selection state of other items. + * + * If both are true, deselects item(s) + * without changing selection state of other items. + * + * Otherwise, selects item(s) and deselects other items. + */ + public void selectPoint(int x, int y, + boolean addToSelection, boolean toggleSelection) + { + // Currently we only allow selection of threads. + if (m_threads != null) { + + List threads = new ArrayList(); + + // first see if selection click landed on a thread dot. + for (MulticoreVisualizerThread tobj : m_threads) { + if (tobj.contains(x,y)) { + threads.add(tobj); + break; + } + } + + // if not, see if it landed on a core; if so, select its threads + if (threads.isEmpty()) { + for (MulticoreVisualizerCore tobj : m_cores) { + if (tobj.contains(x,y)) { + List corethreads = tobj.getThreads(); + threads.addAll(corethreads); + break; + } + } + } + + // in addToSelection case, include any threads in region + // bracketed by last selection click and current click + // (with some extra slop added so we pick up threads that + // overlap the edge of this region) + if (addToSelection) { + int spotSize = MulticoreVisualizerThread.THREAD_SPOT_SIZE * 3; + Rectangle r1 = new Rectangle(m_lastSelectionClick.x - spotSize/2, + m_lastSelectionClick.y - spotSize/2, + spotSize, spotSize); + Rectangle r2 = new Rectangle(x - spotSize/2, y - spotSize/2, spotSize, spotSize); + Rectangle region = r1.union(r2); + + for (MulticoreVisualizerThread tobj : m_threads) { + if (tobj.isWithin(region)) { + threads.add(tobj); + } + } + } + + boolean changed = false; + + for (MulticoreVisualizerThread tobj : m_threads) { + boolean within = threads.contains(tobj); + + if (addToSelection && toggleSelection) { + if (within) { + tobj.setSelected(false); + changed = true; + } + } + else if (addToSelection) { + if (within) { + tobj.setSelected(true); + changed = true; + } + } + else if (toggleSelection) { + if (within) { + tobj.setSelected(! tobj.isSelected()); + changed = true; + } + } + else { + tobj.setSelected(within); + changed = true; + } + } + + if (changed) + selectionChanged(); + } + + // remember last mouse-up point for shift-click selection + m_lastSelectionClick.x = x; + m_lastSelectionClick.y = y; + } + + + // --- selection management methods --- + + /** Selects all items in the canvas. */ + public void selectAll() + { + // currently, we select/deselect threads, not processes or tiles + if (m_threads != null) { + + for (MulticoreVisualizerThread tobj : m_threads) { + tobj.setSelected(true); + } + + selectionChanged(); + } + } + + /** Clears selection. */ + public void clearSelection() { + // currently, we select/deselect threads, not processes or tiles + if (m_threads != null) { + + for (MulticoreVisualizerThread tobj : m_threads) { + tobj.setSelected(false); + } + + selectionChanged(); + } + } + + /** Things to do whenever the selection changes. */ + protected void selectionChanged() { + selectionChanged(true); + } + + /** Things to do whenever the selection changes. */ + protected void selectionChanged(boolean raiseEvent) { + // Note: we save selection (and raise event) now, + // and let canvas "catch up" on its next update tick. + updateSelection(raiseEvent); + requestUpdate(); + } + + /** Saves current canvas selection as list of model objects. */ + protected void updateSelection(boolean raiseEvent) { + // get model objects (if any) corresponding to canvas selection + HashSet selectedThreads = new HashSet(); + if (m_threads != null) { + for (MulticoreVisualizerThread tobj : m_threads) { + if (tobj.isSelected()) { + selectedThreads.add(tobj.getThread()); + } + } + } + + // update model object selection + ISelection selection = SelectionUtils.toSelection(selectedThreads); + setSelection(selection, raiseEvent); + } + + /** Restores current selection from saved list of model objects. */ + protected void restoreSelection() { + ISelection selection = getSelection(); + List selectedThreads = SelectionUtils.getSelectedObjects(selection); + if (m_threads != null) { + for (MulticoreVisualizerThread tobj : m_threads) { + tobj.setSelected(selectedThreads.contains(tobj.getThread())); + } + } + } + + + // --- ISelectionProvider implementation --- + + // Delegate to selection manager. + + /** Adds external listener for selection change events. */ + @Override + public void addSelectionChangedListener(ISelectionChangedListener listener) { + m_selectionManager.addSelectionChangedListener(listener); + } + + /** Removes external listener for selection change events. */ + @Override + public void removeSelectionChangedListener(ISelectionChangedListener listener) { + m_selectionManager.removeSelectionChangedListener(listener); + } + + /** Raises selection changed event. */ + public void raiseSelectionChangedEvent() { + m_selectionManager.raiseSelectionChangedEvent(); + } + + /** Returns true if we have a selection. */ + public boolean hasSelection() + { + return m_selectionManager.hasSelection(); + } + + /** Gets current externally-visible selection. */ + @Override + public ISelection getSelection() + { + return m_selectionManager.getSelection(); + } + + /** Sets externally-visible selection. */ + @Override + public void setSelection(ISelection selection) + { + m_selectionManager.setSelection(selection); + } + + /** Sets externally-visible selection. */ + public void setSelection(ISelection selection, boolean raiseEvent) + { + m_selectionManager.setSelection(selection, raiseEvent); + } + + /** Sets whether selection events are enabled. */ + public void setSelectionEventsEnabled(boolean enabled) { + m_selectionManager.setSelectionEventsEnabled(enabled); + } +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerCore.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerCore.java new file mode 100755 index 00000000000..2772a058ea7 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerCore.java @@ -0,0 +1,165 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.view; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerExecutionState; +import org.eclipse.cdt.visualizer.ui.util.Colors; +import org.eclipse.cdt.visualizer.ui.util.GUIUtils; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.GC; + +/** + * MulticoreVisualizer CPU core object. + */ +public class MulticoreVisualizerCore extends MulticoreVisualizerGraphicObject +{ + // --- members --- + + /** Parent CPU. */ + protected MulticoreVisualizerCPU m_cpu = null; + + /** Core ID. */ + protected int m_id; + + /** List of threads currently on this core. */ + protected ArrayList m_threads; + + // --- constructors/destructors --- + + /** Constructor */ + public MulticoreVisualizerCore(MulticoreVisualizerCPU cpu, int id) { + m_cpu = cpu; + if (m_cpu != null) m_cpu.addCore(this); + m_id = id; + m_threads = new ArrayList(); + } + + /** Dispose method */ + @Override + public void dispose() { + super.dispose(); + if (m_threads != null) { + m_threads.clear(); + m_threads = null; + } + } + + + // --- accessors --- + + /** Gets parent CPU. */ + public MulticoreVisualizerCPU getCPU() { + return m_cpu; + } + + /** Gets Core ID. */ + public int getID() { + return m_id; + } + + + // --- methods --- + + /** Adds child thread. */ + public void addThread(MulticoreVisualizerThread thread) + { + m_threads.add(thread); + } + + /** Removes child thread. */ + public void removeThread(MulticoreVisualizerThread thread) + { + m_threads.remove(thread); + } + + /** Removes all child threads. */ + public void removeAllThreads() + { + m_threads.clear(); + } + + /** Gets list of child threads. */ + public List getThreads() + { + return m_threads; + } + + /** + * A core state is based on its thread states. + * If any thread is CRASHED, the core is CRASHED. + * If no thread is CRASHED and any thread is SUSPENDED, the core is SUSPENDED. + * If no thread is CRASHED and no thread is SUSPENDED, the core is RUNNING. + */ + protected VisualizerExecutionState getCoreState() { + VisualizerExecutionState state = VisualizerExecutionState.RUNNING; + + for (MulticoreVisualizerThread thread : m_threads) { + switch (thread.getState()) { + case CRASHED: + // As soon as we have a crashed thread, we mark + // the core as crashed. + return VisualizerExecutionState.CRASHED; + case SUSPENDED: + // As soon as we have a suspended thread, we + // consider the core as suspended. However, + // we keep looping through the threads + // looking for a crashed one. + state = VisualizerExecutionState.SUSPENDED; + break; + } + } + + return state; + } + + /** Returns core color for current state. */ + protected Color getCoreStateColor(boolean foreground) { + VisualizerExecutionState state = getCoreState(); + + switch (state) { + case RUNNING: + if (foreground) return IMulticoreVisualizerConstants.COLOR_RUNNING_CORE_FG; + return IMulticoreVisualizerConstants.COLOR_RUNNING_CORE_BG; + case SUSPENDED: + if (foreground) return IMulticoreVisualizerConstants.COLOR_SUSPENDED_CORE_FG; + return IMulticoreVisualizerConstants.COLOR_SUSPENDED_CORE_BG; + case CRASHED: + if (foreground) return IMulticoreVisualizerConstants.COLOR_CRASHED_CORE_FG; + return IMulticoreVisualizerConstants.COLOR_CRASHED_CORE_BG; + } + + assert false; + return Colors.BLACK; + } + + // --- paint methods --- + + /** Invoked to allow element to paint itself on the viewer canvas */ + @Override + public void paintContent(GC gc) { + gc.setForeground(getCoreStateColor(true)); + gc.setBackground(getCoreStateColor(false)); + + gc.fillRectangle(m_bounds); + gc.drawRectangle(m_bounds); + + if (m_bounds.height > 16) { + int text_indent = 3; + int tx = m_bounds.x + m_bounds.width - text_indent; + int ty = m_bounds.y + text_indent; + GUIUtils.drawTextAligned(gc, Integer.toString(m_id), tx, ty, false, true); + } + } +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerEventListener.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerEventListener.java new file mode 100644 index 00000000000..cacb15f641b --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerEventListener.java @@ -0,0 +1,194 @@ +/******************************************************************************* + * Copyright (c) 2012 Ericsson and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Marc Khouzam (Ericsson) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.view; + +import org.eclipse.cdt.dsf.concurrent.ImmediateDataRequestMonitor; +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.IProcesses.IThreadDMContext; +import org.eclipse.cdt.dsf.debug.service.IProcesses.IThreadDMData; +import org.eclipse.cdt.dsf.debug.service.IRunControl.IContainerDMContext; +import org.eclipse.cdt.dsf.debug.service.IRunControl.IExitedDMEvent; +import org.eclipse.cdt.dsf.debug.service.IRunControl.IResumedDMEvent; +import org.eclipse.cdt.dsf.debug.service.IRunControl.IStartedDMEvent; +import org.eclipse.cdt.dsf.debug.service.IRunControl.ISuspendedDMEvent; +import org.eclipse.cdt.dsf.debug.service.IRunControl.StateChangeReason; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.MulticoreVisualizerUIPlugin; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerCore; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerExecutionState; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerThread; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.utils.DSFDebugModel; +import org.eclipse.cdt.dsf.gdb.service.IGDBProcesses.IGdbThreadDMData; +import org.eclipse.cdt.dsf.mi.service.IMIExecutionDMContext; +import org.eclipse.cdt.dsf.mi.service.IMIProcessDMContext; +import org.eclipse.cdt.dsf.mi.service.command.events.IMIDMEvent; +import org.eclipse.cdt.dsf.mi.service.command.events.MISignalEvent; +import org.eclipse.cdt.dsf.service.DsfServiceEventHandler; +import org.eclipse.cdt.dsf.service.DsfServicesTracker; + + +/** + * DSF event listener class for the Multicore Visualizer. + * This class will handle different relevant DSF events + * and update the Multicore Visualizer accordingly. + */ +public class MulticoreVisualizerEventListener { + + // --- members --- + + /** Visualizer we're managing events for. */ + protected MulticoreVisualizer fVisualizer; + + + // --- constructors/destructors --- + + /** Constructor */ + public MulticoreVisualizerEventListener(MulticoreVisualizer visualizer) { + fVisualizer = visualizer; + } + + + // --- event handlers --- + + /** Invoked when a thread or process is suspended. */ + @DsfServiceEventHandler + public void handleEvent(ISuspendedDMEvent event) { + IDMContext context = event.getDMContext(); + if (context instanceof IContainerDMContext) { + // We don't deal with processes + } else if (context instanceof IMIExecutionDMContext) { + // Thread suspended + int tid = ((IMIExecutionDMContext)context).getThreadId(); + + VisualizerThread thread = fVisualizer.getModel().getThread(tid); + + if (thread != null) { + assert thread.getState() == VisualizerExecutionState.RUNNING; + + VisualizerExecutionState newState = VisualizerExecutionState.SUSPENDED; + + if (event.getReason() == StateChangeReason.SIGNAL) { + if (event instanceof IMIDMEvent) { + Object miEvent = ((IMIDMEvent)event).getMIEvent(); + if (miEvent instanceof MISignalEvent) { + String signalName = ((MISignalEvent)miEvent).getName(); + if (DSFDebugModel.isCrashSignal(signalName)) { + newState = VisualizerExecutionState.CRASHED; + } + + } + } + } + + thread.setState(newState); + fVisualizer.getMulticoreVisualizerCanvas().requestUpdate(); + } + } + } + + /** Invoked when a thread or process is resumed. */ + @DsfServiceEventHandler + public void handleEvent(IResumedDMEvent event) { + IDMContext context = event.getDMContext(); + if (context instanceof IContainerDMContext) { + // We don't deal with processes + } else if (context instanceof IMIExecutionDMContext) { + // Thread resumed + int tid = ((IMIExecutionDMContext)context).getThreadId(); + + VisualizerThread thread = fVisualizer.getModel().getThread(tid); + + if (thread != null) { + assert thread.getState() == VisualizerExecutionState.SUSPENDED || + thread.getState() == VisualizerExecutionState.CRASHED; + + thread.setState(VisualizerExecutionState.RUNNING); + fVisualizer.getMulticoreVisualizerCanvas().requestUpdate(); + } + } + } + + /** Invoked when a thread or process starts. */ + @DsfServiceEventHandler + public void handleEvent(IStartedDMEvent event) { + IDMContext context = event.getDMContext(); + if (context instanceof IContainerDMContext) { + // We don't deal with processes + } else if (context instanceof IMIExecutionDMContext) { + // New thread added + final IMIExecutionDMContext execDmc = (IMIExecutionDMContext)context; + final IMIProcessDMContext processContext = + DMContexts.getAncestorOfType(execDmc, IMIProcessDMContext.class); + IThreadDMContext threadContext = + DMContexts.getAncestorOfType(execDmc, IThreadDMContext.class); + + DsfServicesTracker tracker = + new DsfServicesTracker(MulticoreVisualizerUIPlugin.getBundleContext(), + execDmc.getSessionId()); + IProcesses procService = tracker.getService(IProcesses.class); + tracker.dispose(); + + procService.getExecutionData(threadContext, + new ImmediateDataRequestMonitor() { + @Override + protected void handleSuccess() { + IThreadDMData data = getData(); + + // Check whether we know about cores + if (data instanceof IGdbThreadDMData) { + String[] cores = ((IGdbThreadDMData)data).getCores(); + if (cores != null) { + assert cores.length == 1; // A thread belongs to a single core + int coreId = Integer.parseInt(cores[0]); + VisualizerCore vCore = fVisualizer.getModel().getCore(coreId); + + int pid = Integer.parseInt(processContext.getProcId()); + int tid = execDmc.getThreadId(); + + int osTid = 0; + try { + osTid = Integer.parseInt(data.getId()); + } catch (NumberFormatException e) { + // I've seen a case at startup where GDB is not ready to + // return the osTID so we get null. + // That is ok, we'll be refreshing right away at startup + } + + fVisualizer.getModel().addThread(new VisualizerThread(vCore, pid, osTid, tid, VisualizerExecutionState.RUNNING)); + + fVisualizer.getMulticoreVisualizerCanvas().requestUpdate(); + } + } + } + } + ); + } + } + + /** Invoked when a thread or process exits. */ + @DsfServiceEventHandler + public void handleEvent(IExitedDMEvent event) { + IDMContext context = event.getDMContext(); + if (context instanceof IContainerDMContext) { + // We don't deal with processes + } else if (context instanceof IMIExecutionDMContext) { + // Thread exited + int tid = ((IMIExecutionDMContext)context).getThreadId(); + + fVisualizer.getModel().markThreadExited(tid); + + fVisualizer.getMulticoreVisualizerCanvas().requestUpdate(); + } + } +} + diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerGraphicObject.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerGraphicObject.java new file mode 100755 index 00000000000..7e3a4cc6b20 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerGraphicObject.java @@ -0,0 +1,45 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.view; + +import org.eclipse.cdt.visualizer.ui.canvas.GraphicObject; +import org.eclipse.swt.graphics.GC; + +/** + * Graphic object for MulticoreVisualizer. + */ +public class MulticoreVisualizerGraphicObject extends GraphicObject +{ + // --- members --- + + // --- constructors/destructors --- + + /** Constructor */ + public MulticoreVisualizerGraphicObject() { + } + + /** Dispose method */ + @Override + public void dispose() { + super.dispose(); + } + + + // --- methods --- + + /** Invoked to allow element to paint itself on the viewer canvas */ + @Override + public void paintContent(GC gc) { + gc.fillRectangle(m_bounds); + gc.drawRectangle(m_bounds); + } +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerMarquee.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerMarquee.java new file mode 100644 index 00000000000..db872dd26a9 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerMarquee.java @@ -0,0 +1,69 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.view; + +import org.eclipse.cdt.visualizer.ui.util.Colors; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.GC; + +/** + * MulticoreVisualizer "marquee" (selection box) object. + */ +public class MulticoreVisualizerMarquee extends MulticoreVisualizerGraphicObject +{ + // --- members --- + + + // --- constructors/destructors --- + + /** Constructor */ + public MulticoreVisualizerMarquee() { + setVisible(false); + } + + /** Dispose method */ + @Override + public void dispose() { + super.dispose(); + } + + + // --- Object methods --- + + /** Returns string representation of element */ + @Override + public String toString() { + return "MarqueeGraphicObject[" + //$NON-NLS-1$ + m_bounds.x + "," + //$NON-NLS-1$ + m_bounds.y + "," + //$NON-NLS-1$ + m_bounds.width + "," + //$NON-NLS-1$ + m_bounds.height + "]"; //$NON-NLS-1$ + } + + + // --- accessors --- + + + // --- methods --- + + /** Invoked to allow element to paint itself on the viewer canvas */ + @Override + public void paintContent(GC gc) { + if (m_visible) { + Color bg = Colors.BLACK; + Color fg = IMulticoreVisualizerConstants.COLOR_SELECTED; + gc.setBackground(bg); + gc.setForeground(fg); + gc.drawRectangle(m_bounds); + } + } +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerSelectionFinder.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerSelectionFinder.java new file mode 100644 index 00000000000..4fcda4411e0 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerSelectionFinder.java @@ -0,0 +1,165 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.view; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.eclipse.cdt.dsf.datamodel.DMContexts; +import org.eclipse.cdt.dsf.datamodel.IDMContext; +import org.eclipse.cdt.dsf.debug.service.IProcesses.IThreadDMContext; +import org.eclipse.cdt.dsf.debug.service.IStack.IFrameDMContext; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerThread; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.utils.DebugViewTreeWalker; +import org.eclipse.cdt.dsf.mi.service.IMIExecutionDMContext; +import org.eclipse.cdt.dsf.mi.service.IMIProcessDMContext; +import org.eclipse.cdt.dsf.ui.viewmodel.datamodel.IDMVMContext; +import org.eclipse.cdt.visualizer.ui.util.SelectionUtils; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.TreePath; + + +/** +* Debug view tree walker that finds elements to select +* based on selection obtained from the multicore visualizer. +*/ +@SuppressWarnings("restriction") // allow access to internal interfaces +public class MulticoreVisualizerSelectionFinder + extends DebugViewTreeWalker +{ + // --- members --- + + /** Selection item(s) we're currently looking for. */ + List m_selection = null; + + /** Result we're found, if any. */ + Set m_result = null; + + + // --- constructors/destructors --- + + /** Constructor */ + public MulticoreVisualizerSelectionFinder() + { + } + + /** Dispose method */ + @Override + public void dispose() { + super.dispose(); + } + + // --- methods --- + + /** Finds and returns Debug View element for specified + * Visualizer selection item. + * (E.g. the IDMVMContext for a VisualizerThread. + * Returns null if no match is found. + */ + public ISelection findSelection(ISelection selection) + { + m_selection = SelectionUtils.getSelectedObjects(selection); + + m_result = new HashSet(); + walk(); + ISelection found = SelectionUtils.toSelection(m_result); + return found; + } + + /** Processes an element of the tree view. + * Returns true if children of this element should be processed, + * and false if they can be skipped. + */ + @Override + public boolean processElement(TreePath path) + { + boolean result = true; + + Object element = getElement(path); + + if (element instanceof IDMVMContext) { + IDMContext context = ((IDMVMContext) element).getDMContext(); + int pid = getPID(context); + int tid = getTID(context); + + if (isThreadContext(context)) + { + for (Object o : m_selection) { + if (o instanceof VisualizerThread) { + VisualizerThread thread = (VisualizerThread) o; + // The Debug view model uses the GDB thread, to we need to use that one from the Visualizer model + if (thread.getPID() == pid && thread.getGDBTID() == tid) + { + m_result.add(element); + } + } + } + } + else if (context instanceof IFrameDMContext) + { + // FIXME: if we have frame[0] under a selected thread, + // select that stack frame instead of the thread + if (isThreadFrameZero(context)) + { + IDMVMContext threadContext = (IDMVMContext) path.getParentPath().getLastSegment(); + if (m_result.contains(threadContext)) + { + m_result.remove(threadContext); + m_result.add(element); + } + } + } + } + + return result; + } + + /** Returns PID for specified debug context. */ + public static int getPID(IDMContext context) + { + IMIProcessDMContext processContext = + DMContexts.getAncestorOfType(context, IMIProcessDMContext.class); + int pid = (processContext == null) ? 0 : + Integer.parseInt(processContext.getProcId()); + return pid; + } + + /** Returns TID for specified debug context. */ + public static int getTID(IDMContext context) + { + IMIExecutionDMContext execContext = + DMContexts.getAncestorOfType(context, IMIExecutionDMContext.class); + int tid = (execContext == null) ? 0 : + execContext.getThreadId(); + return tid; + } + + /** Returns true if specified context represents a thread. */ + public static boolean isThreadContext(IDMContext context) + { + // TODO: is there a more elegant way to express this? + return + context instanceof IMIExecutionDMContext && + context.getParents().length >= 2 && + (context.getParents()[0] instanceof IThreadDMContext || + context.getParents()[1] instanceof IThreadDMContext); + } + + /** Returns true if context represents the topmost (0th) frame under a thread. */ + public static boolean isThreadFrameZero(IDMContext context) + { + // TODO: is there a more elegant way to express this? + String value = context.toString(); + return (value != null && value.endsWith(".frame[0]")); //$NON-NLS-1$ + } +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerThread.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerThread.java new file mode 100755 index 00000000000..c46708020b2 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/ui/view/MulticoreVisualizerThread.java @@ -0,0 +1,190 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.view; + +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerExecutionState; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerThread; +import org.eclipse.cdt.visualizer.ui.util.Colors; +import org.eclipse.cdt.visualizer.ui.util.GUIUtils; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.GC; + +/** + * MulticoreVisualizer Thread object. + */ +public class MulticoreVisualizerThread extends MulticoreVisualizerGraphicObject +{ + // --- constants --- + + /** Thread "pixie" spot width/height */ + public static final int THREAD_SPOT_SIZE = 18; + + /** Minimum containing object size to allow thread to draw itself. */ + public static final int MIN_PARENT_WIDTH = THREAD_SPOT_SIZE + 4; + + + // --- members --- + + /** Parent CPU. */ + protected MulticoreVisualizerCore m_core; + + /** Visualizer model thread. */ + protected VisualizerThread m_thread; + + /** Whether this thread is part of a currently selected process. */ + protected boolean m_processSelected = true; + + + // --- constructors/destructors --- + + /** Constructor */ + public MulticoreVisualizerThread(MulticoreVisualizerCore core, VisualizerThread thread) { + m_core = core; + m_thread = thread; + } + + /** Dispose method */ + @Override + public void dispose() { + super.dispose(); + m_thread = null; + } + + + // --- accessors --- + + /** Gets parent Core. */ + public MulticoreVisualizerCore getCore() { + return m_core; + } + + /** Sets parent Core. */ + public void setCore(MulticoreVisualizerCore core) { + m_core = core; + } + + /** Gets thread model object. */ + public VisualizerThread getThread() + { + return m_thread; + } + + /** Gets Process ID. */ + public int getPID() { + return m_thread.getPID(); + } + + /** Gets Thread ID. */ + public int getTID() { + return m_thread.getTID(); + } + + /** Gets thread state. */ + public VisualizerExecutionState getState() { + return m_thread.getState(); + } + + /** Sets whether thread's process is selected. */ + public void setProcessSelected(boolean processSelected) + { + m_processSelected = processSelected; + } + + /** Gets whether thread's process is selected. */ + public boolean getProcessSelected() + { + return m_processSelected; + } + + + // --- methods --- + + /** Gets thread color based on current state. */ + protected Color getThreadStateColor() { + switch (m_thread.getState()) { + case RUNNING: + return IMulticoreVisualizerConstants.COLOR_RUNNING_THREAD; + case SUSPENDED: + return IMulticoreVisualizerConstants.COLOR_SUSPENDED_THREAD; + case CRASHED: + return IMulticoreVisualizerConstants.COLOR_CRASHED_THREAD; + case EXITED: + return IMulticoreVisualizerConstants.COLOR_EXITED_THREAD; + } + + assert false; + return Colors.BLACK; + } + + // --- paint methods --- + + /** Invoked to allow element to paint itself on the viewer canvas */ + @Override + public void paintContent(GC gc) { + if (m_core.getWidth() >= MIN_PARENT_WIDTH) { + gc.setBackground(getThreadStateColor()); + + int x = m_bounds.x; + int y = m_bounds.y; + int w = THREAD_SPOT_SIZE; + int h = THREAD_SPOT_SIZE; + + // draw an alpha-shaded "pixie" light for each thread + int step1 = 3; + int step2 = 6; + int alpha1 = 128; + int alpha2 = 196; + int alpha3 = 255; + if (! m_processSelected) { + alpha1 -= 64; + alpha2 -= 64; + alpha3 -= 64; + } + gc.setAlpha(alpha1); + gc.fillOval(x, y, w, h); + gc.setAlpha(alpha2); + gc.fillOval(x+step1, y+step1, w-step1*2, h-step1*2); + gc.setAlpha(alpha3); + gc.fillOval(x+step2, y+step2, w-step2*2, h-step2*2); + gc.setAlpha(255); + + // special case: for the "process" thread, draw an enclosing circle + if (m_thread.isProcessThread()) { + // Subtract one from the width and height + // in the case of drawOval because that method + // adds a pixel to each value for some reason + gc.setForeground(IMulticoreVisualizerConstants.COLOR_PROCESS_THREAD); + gc.drawOval(x,y,w-1,h-1); + } + + // draw text annotations + gc.setBackground(IMulticoreVisualizerConstants.COLOR_THREAD_TEXT_BG); + gc.setForeground(IMulticoreVisualizerConstants.COLOR_THREAD_TEXT_FG); + + // if it has an associated debugger, add a marker + // (for now, every thread is debugged.) +// GUIUtils.drawText(gc, "D", x+w, y-8); //$NON-NLS-1$ + + // draw TID + String displayTID = Integer.toString(m_thread.getTID()); + GUIUtils.drawText(gc, displayTID, x + w + 4, y + 2); + + // draw selection marker, if any + if (m_selected) + { + gc.setForeground(IMulticoreVisualizerConstants.COLOR_SELECTED); + gc.drawOval(x-2,y-2,w+3,h+3); + gc.drawOval(x-3,y-3,w+5,h+5); + } + } + } +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFDebugModel.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFDebugModel.java new file mode 100644 index 00000000000..101673d3b91 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFDebugModel.java @@ -0,0 +1,340 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.utils; + +import java.util.ArrayList; + +import org.eclipse.cdt.dsf.concurrent.ConfinedToDsfExecutor; +import org.eclipse.cdt.dsf.concurrent.ImmediateCountingRequestMonitor; +import org.eclipse.cdt.dsf.concurrent.ImmediateDataRequestMonitor; +import org.eclipse.cdt.dsf.concurrent.ImmediateRequestMonitor; +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.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.IExecutionDMData; +import org.eclipse.cdt.dsf.debug.service.IRunControl.IExecutionDMData2; +import org.eclipse.cdt.dsf.debug.service.IRunControl.StateChangeReason; +import org.eclipse.cdt.dsf.debug.service.command.ICommandControlService; +import org.eclipse.cdt.dsf.debug.service.command.ICommandControlService.ICommandControlDMContext; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerExecutionState; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardware; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardware.ICPUDMContext; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardware.ICoreDMContext; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardware.IHardwareTargetDMContext; +import org.eclipse.cdt.dsf.gdb.service.IGDBProcesses.IGdbThreadDMData; +import org.eclipse.cdt.dsf.mi.service.IMIExecutionDMContext; + + +/** Debugger state information accessors. + * + * NOTE: The methods on this class perform asynchronous operations, + * and call back to a method on a provided DSFDebugModelListener instance + * when the operation is completed. + * + * The "arg" argument to each method can be used by the caller to + * pass through information (partial state, etc.) that will be needed + * by the callback method. This argument is ignored by the methods + * on this class, and is allowed to be null. + */ +public class DSFDebugModel { + + // --- static methods --- + + /** Requests list of CPUs. + * Calls back to getCPUsDone() on listener. */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + public static void getCPUs(DSFSessionState sessionState, + final DSFDebugModelListener listener, + final Object arg) + { + ICommandControlService controlService = sessionState.getService(ICommandControlService.class); + IGDBHardware hwService = sessionState.getService(IGDBHardware.class); + if (controlService == null || hwService == null) { + listener.getCPUsDone(null, arg); + return; + } + + IHardwareTargetDMContext contextToUse = DMContexts.getAncestorOfType(controlService.getContext(), + IHardwareTargetDMContext.class); + hwService.getCPUs(contextToUse, + new ImmediateDataRequestMonitor() { + @Override + protected void handleCompleted() { + ICPUDMContext[] cpuContexts = getData(); + if (! isSuccess()) cpuContexts = null; + listener.getCPUsDone(cpuContexts, arg); + } + } + ); + } + + /** Requests list of Cores. + * Calls back to getCoresDone() on listener. */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + public static void getCores(DSFSessionState sessionState, + DSFDebugModelListener listener, + Object arg) + { + getCores(sessionState, null, listener, arg); + } + + /** Requests list of Cores. + * Calls back to getCoresDone() on listener. */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + public static void getCores(DSFSessionState sessionState, + final ICPUDMContext cpuContext, + final DSFDebugModelListener listener, + final Object arg) + { + IGDBHardware hwService = sessionState.getService(IGDBHardware.class); + if (hwService == null) { + listener.getCoresDone(cpuContext, null, arg); + return; + } + + IDMContext targetContextToUse = cpuContext; + if (targetContextToUse == null) { + // if caller doesn't supply a specific cpu context, + // use the hardware context (so we get all available cores) + ICommandControlService controlService = sessionState.getService(ICommandControlService.class); + targetContextToUse = DMContexts.getAncestorOfType(controlService.getContext(), + IHardwareTargetDMContext.class); + } + + hwService.getCores(targetContextToUse, + new ImmediateDataRequestMonitor() { + @Override + protected void handleCompleted() { + ICoreDMContext[] coreContexts = getData(); + + if (!isSuccess() || coreContexts == null || coreContexts.length < 1) { + // Unable to get any core data + listener.getCoresDone(cpuContext, null, arg); + return; + } + + ICPUDMContext cpuContextToUse = cpuContext; + if (cpuContextToUse == null) { + // If we didn't have a CPU context, lets use the ancestor of the first core context + cpuContextToUse = DMContexts.getAncestorOfType(coreContexts[0], ICPUDMContext.class); + } + listener.getCoresDone(cpuContextToUse, coreContexts, arg); + } + } + ); + } + + /** Requests list of Threads. + * Calls back to getThreadsDone() on listener. */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + public static void getThreads(DSFSessionState sessionState, + final ICPUDMContext cpuContext, + final ICoreDMContext coreContext, + final DSFDebugModelListener listener, + final Object arg) + { + // Get control DM context associated with the core + // Process/Thread Info service (GDBProcesses_X_Y_Z) + final IProcesses procService = sessionState.getService(IProcesses.class); + // Debugger control context (GDBControlDMContext) + ICommandControlDMContext controlContext = + DMContexts.getAncestorOfType(coreContext, ICommandControlDMContext.class); + if (procService == null || controlContext == null) { + listener.getThreadsDone(cpuContext, coreContext, null, arg); + return; + } + + // Get debugged processes + procService.getProcessesBeingDebugged(controlContext, + new ImmediateDataRequestMonitor() { + + @Override + protected void handleCompleted() { + IDMContext[] processContexts = getData(); + + if (!isSuccess() || processContexts == null || processContexts.length < 1) { + // Unable to get any process data for this core + // Is this an issue? A core may have no processes/threads, right? + listener.getThreadsDone(cpuContext, coreContext, null, arg); + return; + } + + final ArrayList threadContextsList = new ArrayList(); + + final ImmediateCountingRequestMonitor crm1 = new ImmediateCountingRequestMonitor( + new ImmediateRequestMonitor() { + @Override + protected void handleCompleted() { + IDMContext[] threadContexts = threadContextsList.toArray(new IDMContext[threadContextsList.size()]); + listener.getThreadsDone(cpuContext, coreContext, threadContexts, arg); + } + }); + crm1.setDoneCount(processContexts.length); + + for (IDMContext processContext : processContexts) { + IContainerDMContext containerContext = + DMContexts.getAncestorOfType(processContext, IContainerDMContext.class); + + procService.getProcessesBeingDebugged(containerContext, + new ImmediateDataRequestMonitor(crm1) { + + @Override + protected void handleCompleted() { + IDMContext[] threadContexts = getData(); + + if (!isSuccess() || threadContexts == null || threadContexts.length < 1) { + crm1.done(); + return; + } + + final ImmediateCountingRequestMonitor crm2 = new ImmediateCountingRequestMonitor(crm1); + crm2.setDoneCount(threadContexts.length); + + for (final IDMContext threadContext : threadContexts) { + IThreadDMContext threadContext2 = + DMContexts.getAncestorOfType(threadContext, IThreadDMContext.class); + + procService.getExecutionData(threadContext2, + new ImmediateDataRequestMonitor(crm2) { + + @Override + protected void handleCompleted() { + IThreadDMData data = getData(); + + // Check whether we know about cores + if (data != null && data instanceof IGdbThreadDMData) { + String[] cores = ((IGdbThreadDMData)data).getCores(); + if (cores != null && cores.length == 1) { + if (coreContext.getId().equals(cores[0])) { + // This thread belongs to the proper core + threadContextsList.add(threadContext); + } + } + } + crm2.done(); + } + } + ); + } + } + } + ); + } + } + } + ); + } + + /** Requests data of a thread. + * Calls back to getThreadDataDone() on listener. */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + public static void getThreadData(DSFSessionState sessionState, + final ICPUDMContext cpuContext, + final ICoreDMContext coreContext, + final IMIExecutionDMContext execContext, + final DSFDebugModelListener listener, + final Object arg) + { + IProcesses procService = sessionState.getService(IProcesses.class); + + if (procService == null) { + listener.getThreadDataDone(cpuContext, coreContext, execContext, null, arg); + return; + } + + final IThreadDMContext threadContext = DMContexts.getAncestorOfType(execContext, IThreadDMContext.class); + procService.getExecutionData(threadContext, + new ImmediateDataRequestMonitor() { + @Override + protected void handleCompleted() { + IThreadDMData threadData = isSuccess() ? getData() : null; + listener.getThreadDataDone(cpuContext, coreContext, execContext, threadData, arg); + } + }); + + } + + /** Requests execution state of a thread. + * Calls back to getThreadExecutionStateDone() on listener. */ + @ConfinedToDsfExecutor("getSession().getExecutor()") + public static void getThreadExecutionState(DSFSessionState sessionState, + final ICPUDMContext cpuContext, + final ICoreDMContext coreContext, + final IMIExecutionDMContext execContext, + final IThreadDMData threadData, + final DSFDebugModelListener listener, + final Object arg) + { + IRunControl runControl = sessionState.getService(IRunControl.class); + + if (runControl == null) { + listener.getThreadExecutionStateDone(cpuContext, coreContext, execContext, threadData, null, arg); + return; + } + + if (runControl.isSuspended(execContext) == false) { + // The thread is running + listener.getThreadExecutionStateDone(cpuContext, coreContext, execContext, threadData, + VisualizerExecutionState.RUNNING, arg); + } else { + // For a suspended thread, let's see why it is suspended, + // to find out if the thread is crashed + runControl.getExecutionData(execContext, + new ImmediateDataRequestMonitor() { + @Override + protected void handleCompleted() { + IExecutionDMData executionData = getData(); + + VisualizerExecutionState state = VisualizerExecutionState.SUSPENDED; + + if (isSuccess() && executionData != null) { + if (executionData.getStateChangeReason() == StateChangeReason.SIGNAL) { + if (executionData instanceof IExecutionDMData2) { + String details = ((IExecutionDMData2)executionData).getDetails(); + if (details != null) { + if (isCrashSignal(details)) { + state = VisualizerExecutionState.CRASHED; + } + } + } + } + } + + listener.getThreadExecutionStateDone(cpuContext, coreContext, execContext, threadData, state, arg); + } + }); + } + + } + + /** + * Return true if the string SIGNALINFO describes a signal + * that indicates a crash. + */ + public static boolean isCrashSignal(String signalInfo) { + if (signalInfo.startsWith("SIGHUP") || //$NON-NLS-1$ + signalInfo.startsWith("SIGILL") || //$NON-NLS-1$ + signalInfo.startsWith("SIGABRT") || //$NON-NLS-1$ + signalInfo.startsWith("SIGBUS") || //$NON-NLS-1$ + signalInfo.startsWith("SIGSEGV")) { //$NON-NLS-1$ + // Not sure about the list of events here... + // We are dealing with a crash + return true; + } + + return false; + } +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFDebugModelListener.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFDebugModelListener.java new file mode 100644 index 00000000000..ccc0eed5fb8 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFDebugModelListener.java @@ -0,0 +1,68 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.utils; + + +import org.eclipse.cdt.dsf.datamodel.IDMContext; +import org.eclipse.cdt.dsf.debug.service.IProcesses.IThreadDMData; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerExecutionState; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardware.ICPUDMContext; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardware.ICoreDMContext; +import org.eclipse.cdt.dsf.mi.service.IMIExecutionDMContext; + +/** Interface for classes that interact with DSFDebugModel. + * + * An instance of this interface is passed as + * an argument to a method of DSFDebugModel, and + * the corresponding callback on this interface is + * invoked when the method completes. + * + * The "arg" argument is the value (if any) passed + * through the corresponding "arg" argument of the + * DSFDebugModel method. + * + * TODO: we intend to refactor this API and make this + * a base class rather than an instance. + */ +public interface DSFDebugModelListener { + + /** Invoked when getCPUs() request completes. */ + public void getCPUsDone(ICPUDMContext[] cpuContexts, + Object arg); + + /** Invoked when getCores() request completes. */ + public void getCoresDone(ICPUDMContext cpuContext, + ICoreDMContext[] coreContexts, + Object arg); + + /** Invoked when getThreads() request completes. */ + public void getThreadsDone(ICPUDMContext cpuContext, + ICoreDMContext coreContext, + IDMContext[] threadContexts, + Object arg); + + /** Invoked when getThreadDataState() request completes. */ + public void getThreadDataDone(ICPUDMContext cpuContext, + ICoreDMContext coreContext, + IMIExecutionDMContext threadContext, + IThreadDMData data, + Object arg); + + /** Invoked when getThreadExecutionState() request completes. */ + public void getThreadExecutionStateDone(ICPUDMContext cpuContext, + ICoreDMContext coreContext, + IMIExecutionDMContext threadContext, + IThreadDMData threadData, + VisualizerExecutionState state, + Object arg); + +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFSessionState.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFSessionState.java new file mode 100755 index 00000000000..ea7fc5249eb --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DSFSessionState.java @@ -0,0 +1,173 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.utils; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.RejectedExecutionException; + +import org.eclipse.cdt.dsf.concurrent.ConfinedToDsfExecutor; +import org.eclipse.cdt.dsf.concurrent.DsfRunnable; +import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.MulticoreVisualizerUIPlugin; +import org.eclipse.cdt.dsf.service.DsfServicesTracker; +import org.eclipse.cdt.dsf.service.DsfSession; + +/** + * DSF session state object. + * + * Encapsulates and manages DsfSession we're currently tracking. + */ +public class DSFSessionState +{ + // --- members --- + + /** Current session ID. */ + protected String m_sessionId; + + /** Current set of session event listeners. */ + protected List m_sessionListeners; + + /** Services tracker, used to access services. */ + protected DsfServicesTracker m_servicesTracker; + + // --- constructors/destructors --- + + public DSFSessionState(String sessionId) { + m_sessionId = sessionId; + m_sessionListeners = new ArrayList(); + m_servicesTracker = new DsfServicesTracker(MulticoreVisualizerUIPlugin.getBundleContext(), m_sessionId); + } + + /** Dispose method. */ + public void dispose() + { + if (m_sessionId != null) { + removeAllServiceEventListeners(); + m_sessionId = null; + m_sessionListeners = null; + } + + if (m_servicesTracker != null) { + m_servicesTracker.dispose(); + m_servicesTracker = null; + } + } + + + // --- accessors --- + + /** Returns session ID. */ + public String getSessionID() + { + return m_sessionId; + } + + + // --- listener management --- + + /** Adds a service event listener. */ + public void addServiceEventListener(Object listener) + { + final Object listener_f = listener; + final DsfSession session_f = getDsfSession(); + if (session_f != null) { + try { + session_f.getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + session_f.addServiceEventListener(listener_f, null); + m_sessionListeners.add(listener_f); + } + }); + } catch (RejectedExecutionException e) { + // Session is shut down. + } + } + } + + /** Removes a service event listener. */ + public void removeServiceEventListener(Object listener) + { + final Object listener_f = listener; + final DsfSession session_f = getDsfSession(); + if (session_f != null) { + try { + session_f.getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + if (m_sessionListeners != null) { + session_f.removeServiceEventListener(listener_f); + m_sessionListeners.remove(listener_f); + } + } + }); + } catch (RejectedExecutionException e) { + // Session is shut down. + } + } + } + + /** Removes all service event listeners. */ + public void removeAllServiceEventListeners() + { + final DsfSession session_f = getDsfSession(); + if (session_f != null) { + try { + session_f.getExecutor().execute(new DsfRunnable() { + @Override + public void run() { + if (m_sessionListeners != null) { + for (Object listener : m_sessionListeners) { + session_f.removeServiceEventListener(listener); + } + m_sessionListeners.clear(); + } + } + }); + } catch (RejectedExecutionException e) { + // Session is shut down. + } + } + } + + + // --- methods --- + + /** Gets current DsfSession, if it's still active. */ + protected DsfSession getDsfSession() { + return DsfSession.getSession(m_sessionId); + } + + /** Executes DsfRunnable. */ + public void execute(DsfRunnable runnable) + { + try { + DsfSession session = getDsfSession(); + if (session == null) { + // TODO: log this? + } + else { + session.getExecutor().execute(runnable); + } + } + catch (RejectedExecutionException e) { + // TODO: log or handle this properly. + System.err.println("DSFSessionState.execute(): session rejected execution request."); //$NON-NLS-1$ + } + } + + /** Gets service of the specified type. */ + @ConfinedToDsfExecutor("getDsfSession().getExecutor()") + public V getService(Class serviceClass) { + return (m_servicesTracker == null) ? null : m_servicesTracker.getService(serviceClass); + } +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DebugViewTreeWalker.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DebugViewTreeWalker.java new file mode 100644 index 00000000000..5f7776dc971 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui/src/org/eclipse/cdt/dsf/gdb/multicorevisualizer/internal/utils/DebugViewTreeWalker.java @@ -0,0 +1,135 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.utils; + +import org.eclipse.debug.internal.ui.viewers.model.provisional.TreeModelViewer; +import org.eclipse.jface.viewers.TreePath; +import org.eclipse.swt.widgets.Tree; +import org.eclipse.swt.widgets.TreeItem; + +/** + * Base class that walks Debug View tree elements. + * + * Intended to be subclassed by code that needs to walk the content + * of the Debug View (e.g. to find elements or construct model deltas). + * + * In the simplest case, a derived class should only need to + * implement processElement(), and one should then only need + * to call walk() to walk the tree and get an appropriate delta. + */ +@SuppressWarnings("restriction") // allow access to internal classes +public class DebugViewTreeWalker +{ + // --- members --- + + /** Debug View tree viewer */ + TreeModelViewer m_viewer = null; + + + // --- constructors/destructors --- + + /** Constructor */ + public DebugViewTreeWalker() + { + m_viewer = DebugViewUtils.getDebugViewer(); + } + + /** Dispose method */ + public void dispose() + { + m_viewer = null; + } + + + // --- methods --- + + /** Walks the Debug View's tree, + * calling processElement for each element. + */ + public void walk() + { + walk(getRootPath()); + } + + /** + * Walks the Debug View's tree from the specified element. + * This method should invoke processElement on the element + * itself, and walkChildren() to process the children of the element. + */ + public void walk(TreePath path) + { + if (path == null) return; + boolean processChildren = processElement(path); + if (processChildren) { + walkChildren(path); + } + } + + /** Walks children of the specified element. + * This method should invoke walk() to process + * each child element. + */ + public void walkChildren(TreePath path) + { + if (path == null) return; + int children = m_viewer.getChildCount(path); + if (children > 0) { + for (int i=0; i runnable = + new RunnableWithResult() { + @Override + public IViewPart call() { + IViewPart view = null; + IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); + if (activePage != null) { + view = (viewID_f == null) ? null : activePage.findView(viewID_f); + } + return view; + } + }; + // run on UI thread, wait for result + GUIUtils.execAndWait(runnable); + IViewPart result = runnable.getResult(); + return result; + } + + /** + * Sets debug view selection. + * Specified selection is an IStructuredSelection containing a flat list + * of the model objects (that is, _not_ the tree view nodes) to be selected. + */ + public static boolean setDebugViewSelection(ISelection selection) + { + TreeModelViewer viewer = DebugViewUtils.getDebugViewer(); + if (viewer == null || selection == null) return false; + return viewer.trySelection(selection, true, true); + } +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/internal/CoreList.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/internal/CoreList.java new file mode 100644 index 00000000000..c8a70ec724e --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/internal/CoreList.java @@ -0,0 +1,115 @@ +/******************************************************************************* + * Copyright (c) 2012 Ericsson and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Marc Khouzam (Ericsson) - Initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.dsf.gdb.internal; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.util.Vector; + +import org.eclipse.cdt.internal.core.ICoreInfo; + +/** + */ +public class CoreList { + + private class CoreInfo implements ICoreInfo { + private String fId; + private String fPhysicalId; + + public CoreInfo(String id, String pId) { + fId = id; + fPhysicalId = pId; + } + + @Override + public String getId() { + return fId; + } + + @Override + public String getPhysicalId() { + return fPhysicalId; + } + } + + private ICoreInfo[] fCoreList; + + public CoreList() { + } + + /** + * Returns the list of cores as shown in /proc/cpuinfo + * This method will only parse /proc/cpuinfo once and cache + * the result. To force a re-parse, one must create a new + * CoreList object. + */ + public ICoreInfo[] getCoreList() { + if (fCoreList != null) { + return fCoreList; + } + + File cpuInfo = new File("/proc/cpuinfo"); //$NON-NLS-1$ + + Vector coreInfo = new Vector(); + BufferedReader reader = null; + try { + String physicalId = null; + String coreId = null; + String cpuCores = null; + + Reader r = new InputStreamReader(new FileInputStream(cpuInfo)); + reader = new BufferedReader(r); + String line; + while ((line = reader.readLine()) != null) { + line = line.trim(); + if (line.startsWith("physical id")) { //$NON-NLS-1$ + // Found the physical id of this core, so store it temporarily + physicalId = line.split(":")[1].trim(); //$NON-NLS-1$ + } else if (line.startsWith("core id")) { //$NON-NLS-1$ + // Found core id of this core which come after the entry + // for physical id, so we have both now. + coreId = line.split(":")[1].trim(); //$NON-NLS-1$ + } else if (line.startsWith("cpu cores")) { //$NON-NLS-1$ + // Found CPU core count which comes after the entry + // for core id, so we have all three by now. + cpuCores = line.split(":")[1].trim(); //$NON-NLS-1$ + + int cid = Integer.parseInt(coreId); + int pid = Integer.parseInt(physicalId); + int cores_per_pid = Integer.parseInt(cpuCores); + String absoluteCoreID = Integer.toString(cid + pid * cores_per_pid); + + coreInfo.add(new CoreInfo(absoluteCoreID, physicalId)); + + // Get ready to look for the next core. + physicalId = null; + coreId = null; + cpuCores = null; + } + } + } catch (IOException e) { + } finally { + try { + if (reader != null) { + reader.close(); + } + } catch (IOException e) {/* Don't care */} + reader = null; + } + + fCoreList = coreInfo.toArray(new ICoreInfo[coreInfo.size()]); + return fCoreList; + } +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/launching/ServicesLaunchSequence.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/launching/ServicesLaunchSequence.java index 43e253aadd0..22ffdf57f92 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/launching/ServicesLaunchSequence.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/launching/ServicesLaunchSequence.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2010 Wind River Systems and others. + * Copyright (c) 2006, 2012 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 @@ -10,6 +10,7 @@ * Nokia - created GDBBackend service. Sep. 2008 * IBM Corporation * Ericsson - Support for Tracing Control service + * Marc Khouzam (Ericsson) - Start IGDBHardware service for the multicore visualizer (Bug 335027) *******************************************************************************/ package org.eclipse.cdt.dsf.gdb.launching; @@ -25,9 +26,10 @@ import org.eclipse.cdt.dsf.debug.service.IProcesses; import org.eclipse.cdt.dsf.debug.service.IRegisters; import org.eclipse.cdt.dsf.debug.service.IRunControl; import org.eclipse.cdt.dsf.debug.service.ISourceLookup; -import org.eclipse.cdt.dsf.debug.service.IStack; import org.eclipse.cdt.dsf.debug.service.ISourceLookup.ISourceLookupDMContext; +import org.eclipse.cdt.dsf.debug.service.IStack; import org.eclipse.cdt.dsf.debug.service.command.ICommandControlService; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardware; import org.eclipse.cdt.dsf.gdb.service.IGDBTraceControl; import org.eclipse.cdt.dsf.mi.service.CSourceLookup; import org.eclipse.cdt.dsf.mi.service.IMIBackend; @@ -59,6 +61,11 @@ public class ServicesLaunchSequence extends Sequence { } }, new Step() { @Override + public void execute(RequestMonitor requestMonitor) { + IGDBHardware hwService = fLaunch.getServiceFactory().createService(IGDBHardware.class, fSession, fLaunch.getLaunchConfiguration()); + hwService.initialize(requestMonitor); + }}, + new Step() { @Override public void execute(RequestMonitor requestMonitor) { fProcService = (IMIProcesses)fLaunch.getServiceFactory().createService(IProcesses.class, fSession); fProcService.initialize(requestMonitor); diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/GDBHardware.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/GDBHardware.java new file mode 100644 index 00000000000..06c07c2b0ca --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/GDBHardware.java @@ -0,0 +1,357 @@ +/******************************************************************************* + * Copyright (c) 2012 Ericsson and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Marc Khouzam (Ericsson) - initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.dsf.gdb.service; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.Set; +import java.util.Vector; + +import org.eclipse.cdt.dsf.concurrent.DataRequestMonitor; +import org.eclipse.cdt.dsf.concurrent.ImmediateExecutor; +import org.eclipse.cdt.dsf.concurrent.Immutable; +import org.eclipse.cdt.dsf.concurrent.RequestMonitor; +import org.eclipse.cdt.dsf.datamodel.AbstractDMContext; +import org.eclipse.cdt.dsf.datamodel.IDMContext; +import org.eclipse.cdt.dsf.datamodel.IDMData; +import org.eclipse.cdt.dsf.debug.service.ICachingService; +import org.eclipse.cdt.dsf.gdb.internal.CoreList; +import org.eclipse.cdt.dsf.gdb.internal.GdbPlugin; +import org.eclipse.cdt.dsf.gdb.service.command.IGDBControl; +import org.eclipse.cdt.dsf.mi.service.IMICommandControl; +import org.eclipse.cdt.dsf.mi.service.command.CommandFactory; +import org.eclipse.cdt.dsf.mi.service.command.output.MIListThreadGroupsInfo; +import org.eclipse.cdt.dsf.mi.service.command.output.MIListThreadGroupsInfo.IThreadGroupInfo; +import org.eclipse.cdt.dsf.service.AbstractDsfService; +import org.eclipse.cdt.dsf.service.DsfSession; +import org.eclipse.cdt.internal.core.ICoreInfo; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.Status; +import org.osgi.framework.BundleContext; + +/** + * This class implements the IGDBHardware interface which gives access + * to hardware information about the target. + * + * @since 4.1 + */ +@SuppressWarnings("restriction") +public class GDBHardware extends AbstractDsfService implements IGDBHardware, ICachingService { + + @Immutable + protected static class GDBCPUDMC extends AbstractDMContext + implements ICPUDMContext + { + /** + * String ID that is used to identify the thread in the GDB/MI protocol. + */ + private final String fId; + + /** + */ + protected GDBCPUDMC(String sessionId, IHardwareTargetDMContext targetDmc, String id) { + super(sessionId, targetDmc == null ? new IDMContext[0] : new IDMContext[] { targetDmc }); + fId = id; + } + + public String getId(){ + return fId; + } + + @Override + public String toString() { return baseToString() + ".CPU[" + fId + "]"; } //$NON-NLS-1$ //$NON-NLS-2$ + + @Override + public boolean equals(Object obj) { + return baseEquals(obj) && ((GDBCPUDMC)obj).fId.equals(fId); + } + + @Override + public int hashCode() { return baseHashCode() ^ fId.hashCode(); } + } + + @Immutable + protected static class GDBCoreDMC extends AbstractDMContext + implements ICoreDMContext + { + private final String fId; + + public GDBCoreDMC(String sessionId, ICPUDMContext CPUDmc, String id) { + super(sessionId, CPUDmc == null ? new IDMContext[0] : new IDMContext[] { CPUDmc }); + fId = id; + } + + public String getId(){ return fId; } + + @Override + public String toString() { return baseToString() + ".core[" + fId + "]"; } //$NON-NLS-1$ //$NON-NLS-2$ + + @Override + public boolean equals(Object obj) { + return baseEquals(obj) && + (((GDBCoreDMC)obj).fId == null ? fId == null : ((GDBCoreDMC)obj).fId.equals(fId)); + } + + @Override + public int hashCode() { return baseHashCode() ^ (fId == null ? 0 : fId.hashCode()); } + } + + @Immutable + protected static class GDBCPUDMData implements ICPUDMData { + final int fNumCores; + + public GDBCPUDMData(int num) { + fNumCores = num; + } + + public int getNumCores() { return fNumCores; } + } + + @Immutable + protected static class GDBCoreDMData implements ICoreDMData { + final String fPhysicalId; + + public GDBCoreDMData(String id) { + fPhysicalId = id; + } + + public String getPhysicalId() { return fPhysicalId; } + } + + + private IGDBControl fCommandControl; + private IGDBBackend fBackend; + private CommandFactory fCommandFactory; + + // The list of cores should not change, so we can store + // it once we figured it out. + private ICPUDMContext[] fCPUs; + private ICoreDMContext[] fCores; + + + public GDBHardware(DsfSession session) { + super(session); + } + + /** + * This method initializes this service. + * + * @param requestMonitor + * The request monitor indicating the operation is finished + */ + @Override + public void initialize(final RequestMonitor requestMonitor) { + super.initialize(new RequestMonitor(ImmediateExecutor.getInstance(), requestMonitor) { + @Override + protected void handleSuccess() { + doInitialize(requestMonitor); + } + }); + } + + /** + * This method initializes this service after our superclass's initialize() + * method succeeds. + * + * @param requestMonitor + * The call-back object to notify when this service's + * initialization is done. + */ + private void doInitialize(RequestMonitor requestMonitor) { + + fCommandControl = getServicesTracker().getService(IGDBControl.class); + fBackend = getServicesTracker().getService(IGDBBackend.class); + + fCommandFactory = getServicesTracker().getService(IMICommandControl.class).getCommandFactory(); + + // Register this service. + register(new String[] { IGDBHardware.class.getName(), + GDBHardware.class.getName() }, + new Hashtable()); + + requestMonitor.done(); + } + + + /** + * This method shuts down this service. It unregisters the service, stops + * receiving service events, and calls the superclass shutdown() method to + * finish the shutdown process. + * + * @return void + */ + @Override + public void shutdown(RequestMonitor requestMonitor) { + unregister(); + super.shutdown(requestMonitor); + } + + /** + * @return The bundle context of the plug-in to which this service belongs. + */ + @Override + protected BundleContext getBundleContext() { + return GdbPlugin.getBundleContext(); + } + + public void getCPUs(IHardwareTargetDMContext dmc, DataRequestMonitor rm) { + if (fCPUs != null) { + rm.done(fCPUs); + return; + } + + if (fBackend.getSessionType() == SessionType.REMOTE) { + // Until we can get /proc/cpuinfo from the remote, we can't do anything + fCPUs = new ICPUDMContext[0]; + rm.done(fCPUs); + } else { + // For a local session, let's use /proc/cpuinfo on linux + if (Platform.getOS().equals(Platform.OS_LINUX)) { + Set cpuIds = new HashSet(); + + ICoreInfo[] cores = new CoreList().getCoreList(); + for (ICoreInfo core : cores) { + cpuIds.add(core.getPhysicalId()); + } + + String[] cpuIdsArray = cpuIds.toArray(new String[cpuIds.size()]); + fCPUs = new ICPUDMContext[cpuIdsArray.length]; + for (int i = 0; i < cpuIdsArray.length; i++) { + fCPUs[i] = createCPUContext(dmc, cpuIdsArray[i]); + } + } else { + // No way to know the CPUs on a local Windows session. + fCPUs = new ICPUDMContext[0]; + } + rm.done(fCPUs); + } + } + + public void getCores(IDMContext dmc, final DataRequestMonitor rm) { + if (dmc instanceof ICPUDMContext) { + // Get the cores under this particular CPU + ICPUDMContext cpuDmc = (ICPUDMContext)dmc; + + if (fBackend.getSessionType() == SessionType.REMOTE) { + rm.done(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, NOT_SUPPORTED, "Operation not supported", null)); //$NON-NLS-1$ + } else { + if (Platform.getOS().equals(Platform.OS_LINUX)) { + // Use /proc/cpuinfo to find the cores and match them to the specified CPU + ICoreInfo[] cores = new CoreList().getCoreList(); + + Vector coreDmcs = new Vector(); + for (ICoreInfo core : cores) { + if (core.getPhysicalId().equals(cpuDmc.getId())){ + // This core belongs to the right CPU + coreDmcs.add(new GDBCoreDMC(getSession().getId(), cpuDmc, core.getId())); + } + } + + rm.done(coreDmcs.toArray(new ICoreDMContext[coreDmcs.size()])); + } else { + // No way to know the cores for a specific CPU on a remote Windows session. + rm.done(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, NOT_SUPPORTED, "Operation not supported", null)); //$NON-NLS-1$ + } + } + } else if (dmc instanceof IHardwareTargetDMContext) { + // Get all the cores for this target + + final IHardwareTargetDMContext targetDmc = (IHardwareTargetDMContext)dmc; + + // We already know the list of cores. Just return it. + if (fCores != null) { + rm.done(fCores); + return; + } + + if (fBackend.getSessionType() == SessionType.REMOTE) { + // For a remote session, we can use GDB's -list-thread-groups --available + // command, which shows on which cores a process is running. This does + // not necessarily give the exhaustive list of cores, but that is the best + // we have right now. + // + // In this case, we don't have knowledge about CPUs, so we lump all cores + // into a single CPU. + fCommandControl.queueCommand( + fCommandFactory.createMIListThreadGroups(fCommandControl.getContext(), true), + new DataRequestMonitor(ImmediateExecutor.getInstance(), rm) { + @Override + protected void handleSuccess() { + // First extract the string id for every core GDB reports + Set coreIds = new HashSet(); + IThreadGroupInfo[] groups = getData().getGroupList(); + for (IThreadGroupInfo group : groups) { + coreIds.addAll(Arrays.asList(group.getCores())); + } + + // Now create the context for each distinct core + // + // We don't have CPU info in this case so let's put them all under + // a single CPU + ICPUDMContext cpuDmc = createCPUContext(targetDmc, "0"); //$NON-NLS-1$ + Set coreDmcs = new HashSet(); + for (String id : coreIds) { + coreDmcs.add(new GDBCoreDMC(getSession().getId(), cpuDmc, id)); + } + fCores = coreDmcs.toArray(new ICoreDMContext[coreDmcs.size()]); + + rm.done(fCores); + } + }); + } else { + // For a local session, -list-thread-groups --available does not return + // the cores field. Let's use /proc/cpuinfo on linux instead + if (Platform.getOS().equals(Platform.OS_LINUX)) { + ICoreInfo[] cores = new CoreList().getCoreList(); + fCores = new ICoreDMContext[cores.length]; + for (int i = 0; i < cores.length; i++) { + ICPUDMContext cpuDmc = createCPUContext(targetDmc, cores[i].getPhysicalId()); + fCores[i] = createCoreContext(cpuDmc, cores[i].getId()); + } + } else { + // No way to know the cores on a local Windows session. + fCores = new ICoreDMContext[0]; + } + rm.done(fCores); + } + } else { + rm.done(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE, "Invalid DMC type", null)); //$NON-NLS-1$ + } + } + + public void getExecutionData(IDMContext dmc, DataRequestMonitor rm) { + if (dmc instanceof ICoreDMContext) { + rm.done(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE, "Not done yet", null)); //$NON-NLS-1$ + } else if (dmc instanceof ICPUDMContext) { + rm.done(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE, "Not done yet", null)); //$NON-NLS-1$ + + } else { + rm.done(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE, "Invalid DMC type", null)); //$NON-NLS-1$ + } + } + + @Override + public ICPUDMContext createCPUContext(IHardwareTargetDMContext targetDmc, String CPUId) { + return new GDBCPUDMC(getSession().getId(), targetDmc, CPUId); + } + + @Override + public ICoreDMContext createCoreContext(ICPUDMContext cpuDmc, String coreId) { + return new GDBCoreDMC(getSession().getId(), cpuDmc, coreId); + } + + public void flushCache(IDMContext context) { + fCPUs = null; + fCores = null; + } +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/GdbDebugServicesFactory.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/GdbDebugServicesFactory.java index 5eaccda0f6e..7d6c78fcee7 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/GdbDebugServicesFactory.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/GdbDebugServicesFactory.java @@ -10,6 +10,7 @@ * Nokia - create and use backend service. * Onur Akdemir (TUBITAK BILGEM-ITI) - Multi-process debugging (Bug 237306) * Marc Khouzam (Ericsson) - Support for GDB 7.4 (Bug 367788) + * Marc Khouzam (Ericsson) - Include IGDBHardware service for the multicore visualizer (Bug 335027) *******************************************************************************/ package org.eclipse.cdt.dsf.gdb.service; @@ -95,7 +96,13 @@ public class GdbDebugServicesFactory extends AbstractDsfDebugServicesFactory { return (V)createTraceControlService(session, (ILaunchConfiguration)arg); } } - } + } else if (IGDBHardware.class.isAssignableFrom(clazz)) { + for (Object arg : optionalArguments) { + if (arg instanceof ILaunchConfiguration) { + return (V)createHardwareService(session, (ILaunchConfiguration)arg); + } + } + } return super.createService(clazz, session); } @@ -214,4 +221,9 @@ public class GdbDebugServicesFactory extends AbstractDsfDebugServicesFactory { // in those older GDB versions. Also, gdbserver only supports tracing starting with 7.2 return null; } + + /** @since 4.1 */ + protected IGDBHardware createHardwareService(DsfSession session, ILaunchConfiguration config) { + return new GDBHardware(session); + } } diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/IGDBHardware.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/IGDBHardware.java new file mode 100644 index 00000000000..205d38ebadd --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/IGDBHardware.java @@ -0,0 +1,112 @@ +/******************************************************************************* + * Copyright (c) 2012 Ericsson and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Marc Khouzam (Ericsson) - Initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.dsf.gdb.service; + +import org.eclipse.cdt.dsf.concurrent.DataRequestMonitor; +import org.eclipse.cdt.dsf.datamodel.IDMContext; +import org.eclipse.cdt.dsf.datamodel.IDMData; +import org.eclipse.cdt.dsf.service.IDsfService; + +/** + * EXPERIMENTAL. This class or interface has been added as part + * of a work in progress. There is no guarantee that this API will work or that + * it will remain the same. + * + * The IGDBHardware service provides access to information about the target + * hardware, such as the number of cores. + * + * @since 4.1 + */ +public interface IGDBHardware extends IDsfService { + + /** + * The physical target that has CPUs and Cores. + */ + public interface IHardwareTargetDMContext extends IDMContext {} + + /** + * A physical container of cores. + */ + public interface ICPUDMContext extends IDMContext { + String getId(); + } + + /** + * A logical core. Without SMT (Simultaneous Multi-Threading), + * a logical core is a physical core. However, with SMT, each + * physical core will have two logical cores. + * This context represents each logical core. + */ + public interface ICoreDMContext extends IDMContext { + String getId(); + } + + /** + * Model data interface corresponding to ICPUDMContext. + */ + public interface ICPUDMData extends IDMData { + /** Number of cores contained in this CPU */ + int getNumCores(); + } + + /** + * Model data interface corresponding to ICoreDMContext. + */ + public interface ICoreDMData extends IDMData { + /** + * The physical id of the core. Multiple cores can have + * the same physical id in the case of Simultaneous Multi-Threading. + */ + String getPhysicalId(); + } + + // + // Events, e.g., a core halting, starting, etc + // + + /** + * Returns an array of CPUs, based on the specified context. + * + * @param context The context to which this method applies. + */ + public void getCPUs(IHardwareTargetDMContext context, DataRequestMonitor rm); + + /** + * Returns an array of cores, based on the specified context. + * + * @param context The context to which this method applies. + * For an IHardwareTargetDMContext, all cores will be returned; + * for an ICPUDMContext, the cores on that CPU will be returned. + */ + public void getCores(IDMContext context, DataRequestMonitor rm); + + /** + * Retrieves data for a given ICPUDMContext or ICoreDMContext context. + */ + public void getExecutionData(IDMContext dmc, DataRequestMonitor rm); + + /** + * Create a CPU context. + * + * @param targetDmc The parent context of this context + * @param CPUId The id of the CPU + */ + public ICPUDMContext createCPUContext(IHardwareTargetDMContext targetDmc, String CPUId); + + /** + * Create a core context. + * + * @param cpuDmc The parent CPU context of this context + * @param coreId The id of the core + */ + public ICoreDMContext createCoreContext(ICPUDMContext cpuDmc, String coreId); + +} diff --git a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/command/GDBControlDMContext.java b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/command/GDBControlDMContext.java index d2bd4fe106d..546e1a094d2 100644 --- a/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/command/GDBControlDMContext.java +++ b/dsf-gdb/org.eclipse.cdt.dsf.gdb/src/org/eclipse/cdt/dsf/gdb/service/command/GDBControlDMContext.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2011 Wind River Systems and others. + * Copyright (c) 2007, 2012 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 @@ -8,12 +8,14 @@ * Contributors: * Wind River Systems - initial API and implementation * Onur Akdemir (TUBITAK BILGEM-ITI) - Multi-process debugging (Bug 335324) + * Marc Khouzam (Ericsson) - Include IHardwareTargetDMContext for the multicore visualizer (Bug 335027) *******************************************************************************/ package org.eclipse.cdt.dsf.gdb.service.command; import org.eclipse.cdt.dsf.debug.service.IModules.ISymbolDMContext; import org.eclipse.cdt.dsf.debug.service.ISignals.ISignalsDMContext; import org.eclipse.cdt.dsf.debug.service.ISourceLookup.ISourceLookupDMContext; +import org.eclipse.cdt.dsf.gdb.service.IGDBHardware.IHardwareTargetDMContext; import org.eclipse.cdt.dsf.gdb.service.IGDBTraceControl.ITraceTargetDMContext; import org.eclipse.cdt.dsf.mi.service.command.MIControlDMContext; @@ -22,7 +24,7 @@ import org.eclipse.cdt.dsf.mi.service.command.MIControlDMContext; */ public class GDBControlDMContext extends MIControlDMContext implements ISymbolDMContext, ISourceLookupDMContext, - ISignalsDMContext, ITraceTargetDMContext + ISignalsDMContext, ITraceTargetDMContext, IHardwareTargetDMContext { public GDBControlDMContext(String sessionId, String commandControlId) { diff --git a/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/.project b/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/.project new file mode 100644 index 00000000000..8f8b178a737 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/.project @@ -0,0 +1,17 @@ + + + org.eclipse.cdt.gnu.multicorevisualizer-feature + + + + + + org.eclipse.pde.FeatureBuilder + + + + + + org.eclipse.pde.FeatureNature + + diff --git a/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/build.properties b/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/build.properties new file mode 100755 index 00000000000..1f4c8ef5685 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/build.properties @@ -0,0 +1,16 @@ +############################################################################### +# Copyright (c) 2012 Ericsson and others. +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# Marc Khouzam (Ericsson) +############################################################################### +bin.includes = feature.xml,\ + feature.properties,\ + license.html,\ + epl-v10.html,\ + eclipse_update_120.jpg + \ No newline at end of file diff --git a/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/eclipse_update_120.jpg b/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/eclipse_update_120.jpg new file mode 100644 index 0000000000000000000000000000000000000000..bfdf708ad617e4974cac04cc5c1c8192b09bbeb3 GIT binary patch literal 21695 zcmeHvcU)7=((p+_uhNSGp%(=Nr3wV321I%h5riZ_XrTltiYTH8C`eTiL3$Grle6uPge`61wfz> zKnMH-2t(wlntoUZ0MOS5!~g)G0LUSX01Sj6;2!|t1W0#b0I-Mb{{cHgM85GrK^`dp zjDh{&;{}o4g_%M4W+)aQ`Ia{W{A~pvuts93d%tREoIM6^=!C=Lyq$0!aCH;71=byn z^YsR#4K)C?^2G&J-q>`Y87Oib(yG`r#3&tBpmV+buZH7y1PEApjKiowyHxkU(Hi5-2G-83ief<_Jh+fRXSrN|CA=*)j2XUX~_f zj!rE)&M&}XTx);is8?{CI=Nts$=uL9%3Fptt@w(NMyx4Xvo0Mk%hql-j9GXRQs3b- zvZy5-mvQxJd_(8wrOc8SU8Bq94(F~VWR|-ORQhr>Gf{$CgY0`@~*!7=J4EGX}z^MYhV0my}9>e@je z(%I0OX0mw9@DCCGwFJUHMIiJ7G_c(|82|)Oi{wp>=YxfmePK;|DXQxvrWTTxXk~1? z^ePNXDHa!l9_K|0#ONA>QCtjCAX6X)DN1OqMP^*#<-32yEbpl-hv8E_ysyVYi|YpH z_wmj9%H}+7W~e)u2#VPZAEUWkNBy|qTxz9XGMk&Drkm^Fyow%MPMK>-bpS&Xm4?>n zmzf6^OG&vOu(&oW4*kxUCj|$xJaBDvD){)Bu9LyY#4lB;Z>8x;6}^~2QL_ncF9u9Pl}h7jCzp`Rxd_to{*TD39d(hOkDJ*i zaQgS}TVz;u%v%>46=lT9E%Ob%N{x-L^f9VqzLsoqEnjvduO#q^So|Ync**pr8uF!X zxE_04j3~UKD9p2<&!ElsQ{ltX{I#zi4U@I5is;!e>-gw`3S_M&wAY@v-p5J8s(U-% zc2->TfnQmrUXa$N(#enI2HWcfxoFNQ7sm;X&FBD2mwBX9lz+!(7W#)Kwwa$W{7=x~ z4WTm*3df)DozLSgI^m{&_G$NNv1cDelNL-Vkt8`;qC%=UqVSk=A??N-R~=~w$K)Dx zAKttcbRsA(NW`dN=dpj*X*px0Am%2aqxK{dpLF&!%ge*&saCMuwq)gF2WKff)+Y!+ zpxQ<=@*=-0Y@8i|*czp$>zyxjiO33kG#6Y_oWsHXHD|}8b$vxI-I+gvBcfg)ELJb4 zqN`kul*&ZBKrag^ZJya75C@M3vY`6TJ_kO>Gv2%;_|^9k?5mmE1=7?|qr7WZmhR8` zHe?MQI3>AiBp#a)qubs{=xksuN$>sO8>UnBbwm5}gCz0emy8dS7IrMu_lo+j(x+X} z4sLRdg|PD&s4cYwk#KmviuD=1J@xdnsq)CgWddMY5en^LeRiA;6OlwgQ$Dpx0M-Rf za+eer)Shv|-aXSM-^gJIxVkPiACSJHRH@TrKcN0v9E;@^gXA3%v&#ZRuVsg1N}CwR z*~~#5-$Nx32BpJ1euoNI{X7XkQ%*_rgDiRZFPqAaQEi7Oz8vomt+#r4?WwxfC6ZTz z@)T5?=FQ*>6VOBGsy*3?ymX7?4n;<|2CYpHY0gv9&!%wa#Wf-9*8!>%&7(TZR6_zo zjhCCv4>lF2mqcDt;EK1pq1WQBB1-D4ExJX zZ`tM#xEoY>gb5VbOnKQ`(8TDBq~v>ARjGF!DWFV@!O}huW@xN`PLf9?4g>PX zk@_TpyJPgeZzJ`OA0iDl^NqGQWf7-(;qVogn zx(<69q1a6mH34b?s=D`l(=j)Q{gs!Kn1mt0Xs@-zB&h#y4;5erxC3|q3qGy@20#Pi zfD}mku3aMU_wXz3d;agV-QQmsz7xI)Nld!?xVnNr#Kw@><9yuF-Ujy0C@}RcpD_wg zta`WYrl7axigR}a)4SmW#sU9p`Zylv_AN~m1u%AW`c5aN$-G^$D2%tc>j`f#1^H7w zq`Nc_%?Li^y9uPmFJ+TEdf|LL{)8gKd0`!~?ihC;H!u&4rU|ihgIye$rnU3ITh%_o!(2)KKOJk42g9i0acxteVo&J%1_x%(h76#CO4+Jr{3-7&|#LtpF z6W$${NQfK&StuA0)%NYJfj9v`P7R260oXye{kNn4+tL5B^4rn>?dbn@^nW}0|Cf&b z-Wfo>lTum{~gIA91kfiNC?ymukc{RJJRf6oC2)c1SRbUkTqM5;!kMNht*d16X=#k{#<}|JGRjFye&_ua{e$<^ zU-SNo{=xf`)yy4>SCRfE!#|+^JE{W*xxeo7@1q~l1mQ|xN>SYl1AaehfR74sb3**E zthkh%>G#bEapHCb_y+z1=l9I|I5gJ5|3At63+Io_;An}q!`uBw*?;BzUcj#C;FlRV z!m8}<@5(E;b> zW`|e7y4g8mB%M7lj!Ke0v41V^-p~!sl;E5x`C}F)+VTH=_+820((!L~{Z`lC(!k$h z{%u{q)%CYD@VA(MTi0)O{VfgrE#}|W^;=zkO9Ow4`L}ibR@dLsz~5s2ZC$_B^|v(e zx0wI8)u=Aa*Ek4}B9Y;^_qdsi_Y42APQP&#=qX1phV%| zE`>Z?2jlCC!Q;gZ!OayrFEm^o=jLJO?hgQaZ6@Xd7>T-tgG!c_QjnDumzE%&!1*5j zE%7_k|L{xf+dY;=quoA(u)g_;`c5Sd2lmtKx6_n2dgp%tqkk#2zIwS8oRr@gmwQ{J^a7S_KOTe zaL=wmfGJ}KV78S2_O&nru$eai2@^E{vrYynkRSbag3=t^WCQ>Up0Pc<2Vs!D8~-VS zMuADFH+J{H6rgTw3P<^Po!es}A^wm8RN&?%Gr$3G1N?vpcydh|kOPhZs(>b-3m5>V zz$w56K!MwsZh#ly3tRv$1J{5E;1&=MBmyZw29OIp0*Zk$;18e{cnQ1)FA#JAeZVJR z6qo|$fE8d9JgQC(p@lF(I3PR_LC8UfG(;Yv0?~w=fEYtgLC!)PA?^?#$OXt1NCYGX zk_btKwtZNO~ckn$Viw-;3VQC$4GQY%t%lqo+KAZZjdCB~+V43W%{?2yuu z9w0qPsz{0?wIp>U^(DPVnn0RGT0;7Qw2O3=ckm)k>4eMNM23ePCiP$MnO%%Lm^F}MPWtZP7zFz zK#@oBoT8m#jAD~=AEh9rBBcQ(n$n*#iZX+;lCp(zlyZ}bfl8Q4naY&Pnd&mt9jZrE zFR1#d7OAPJ`KT4Bji|BIm#FVhKc;S?9->~SVWbhGQKzw{@u7*N$)>5H`9QNsOG_(6 zt4eD{i>HmG&84lU9i&~OW1^FwL(-w?g6QtimD07-&C*lS3(~96+t3HlC(u8kZ=s*w zN4ZaEpZY$#eHZuL+gGu#XWudd6N40k0fQUE4Te01W`=P_az-IWO-3|h2xB^9J>v)y zjESE~oe9Nsg(-vS1=A=q8M81mlG&L#g1LbC9rGLuBg;`1a~40Adn{EfpIBk6Laazu zSJo)jV%Bcf4K^+|H8u=e7~3PZcD7aa{p_mj81``XLiR594GuVmCWi}0G)Ec704E8j z7^e}ZFK0663(o2N%=?e+N9_;aU%bEf0Q7*^0pkPb52PP>b6}Z^n@gL^gX=C=J=Zih zE4M1QGj|;KbM6TqCLR?YEKeLyHP0lR1+E5nh2McUz~^`m@apjT@TT&<39 z<}2hI;HTo3=Xcw6_XKj61ykXau9k@_8|7){ex|XNDnC- zazB)Is7IVeTuuC(c)s|M1gpdeiC~E`iCIYjNh`@{$wtYY!!n0m4`&?ilVX(8l?s-s zlvZ^G6RJ#T-pO`d)@fMqegWrcP#CR!-JS_L1y_oPgX} zxg@zBd1iS-`5W?03Zx3h6@nE0P*_)#Rm3Y6D}FsDe$3@q-m!5dVI_=GhSG>KpR%2D zs`4ilxXM|T2P&Tsya+o)8e&+LUlpyIr8=f2s^+ZrP;K`3;p1M%OOCIqE2;;o*J!{r zv^Byt-f1#wnrS9#4r=jfIcnu=&1uVMpVzL@A=S~-iPq^sav@R3T;!atoNl0QgC32Z ziC&`K@CmUKUMDK`q58V|vHJZd1y8!4EHeNMkOr{^1BSweo`%ni$czk)?iqbCmNLFz z+-SmNVr!CTvSNDNG|IHkOvKE`tj?U?+}b?XeAPn3BF5sArKDw`lAg6Vn|F50&cH6sZrL7b zpJYFWQb*lJO`%oMap(z*GA0Hy=Ai5l<1p^1>=^4f;e>EXaGJ)dV-vCS&N|L1&Z{m4 zF4-;wR}0rdHww42ZWZo~?k?^PIBuLDuFd11$2E^no{FCFo^xJ$URmA{?=#-zcxKR< zdgCMFbJb_)oXWX-=hl49eV_O-___PN@fY(C^B)V)3dlT9avpWQ?gHnQf^b-_PPD(&WStacLna=y1SL=l-PCe_`SlU z14&^?tM}3O+mlt3AEj`mM5Jsyz&?1Ns-0SzCX|+tPL_Ty{Y!>#mbsZQW+w?|ZC! zKD|f3AOGO`VZQfV?`Gene$xK%fqerBg9irFK8k)U{3QFSYDi<~&9KRE-w0}C>a+Lf ztaLCZjo=@*%sZd+|k?VC%A#9?tfl> zQw4p2y~}TVSIhpR82U57euQ6g60dqee-QptfbjG38+cpn=jAtg@bVkz)&gWu@B-J5 zKu$qMN|=DIk;p74<#<3W0&w-(W^>`PT&ZevFBxW`)EP+)S@||qh3@TwQVxOLngAp^D$`}rrw%b za@r^nGjj{h;=1976sy*uw$|8Z< zXj?eQ|G2yN^WvV4rIX+FJ2~Y|@5k2^kf*TzVRv&YnmUIo-BY<*?K4ZvTX=re=ARLS*4!L{xi_(-G=`DvXHEr))i2O*Ha@?y zZa6nCdxQD2SwKKyB+U)UQ<1FEq+=N)Rzc=!+nEI5`l=NRoXJcjP}If#^{{sQggjrO zmYCUPvIYhhZ+GnyUe#*xAg<{xRKh9iVok8WZ zd)8-F-nj6%e}aEIwCdARhi0dYSGL~ybm0`FKxC5Q+vSy>6FwjReG}SpZL?K2=vz?_ z<5*;lE=PBoC|Ia3?Yxdyh(x5WY+Pav7NgfPcW-_C!gQXCcI`}|_A@@KSL_W6Bt>}{ zk4X!b@jUT}p_!wRXGh`|#>aaFUI~V-;1A6V=H=y?*_OD>(Y6wR7xYgV2lI9$?zElY zRu)^}I%Yva`j($wfBi;O;nJt`c5{%cxe(d<6ztScpQe0$(t&VwrZ-_1l?*zJW2O{WzL#A?0zpf$wQTVx&XO#J8h&w z?u;1_?deuGSB!){F5gKz&e?DgzloHXC~DAcbUa$Hc=pnElED@lujh+(bnry7} zdV+l2V&_Qf8HDp}uOprScoqkQnFumjQ_~yFwCvjo3LE=ix|!r4e`tqXs?GD{_ zAw6y3+Aj18sH+Asm=JdfObrNM8l z8Wpd-zG1NRs%8S!8h>eqEB8J=+qtZvyMpTJ2i04LZf^7CTLhR_Z1dhfQ&_ioie>qa z42c5q@t~IatmHvcmQ0J$)`;bmCs~SL!B@a$b+)RfYO~OX(4MOxk>|(1?fEs8I<^%{ z?lI9w55!=|`lDw?>eEGThiZ-G9TpeI9J&<~LuO#Sqs?Zla*Y6tOy?~Giq*`GcT;lm zQOHmBZ)j&`449xA%NzV{oKk#OE~L%O(liK4v)vsmZv{ zWBs-6m3YO~6E9IbET+M{V(rrTCaUFFIQX)Q6ELN&(Z!d>Q^}J=1gXtx7YzuYxj9-2 zwJlC}h^@)S0aVTeKyKstyWGtuo;Mux5*+-|_Pxnk5@Yuk-oCB6Gv!a0ZEuh}E_Y1n zMhibHsv#*kEMY3s6x+BltqFSL>Li;5J*Y z%$(fOZnDjboR|kpWavOt8T-Mng&H*Q_Lt0JDg{) zd+}r0*7p7j?z*9p>iRK_rh;ZH*7iEWQHFG7Vru48VlJe#kWNb0@Z8z)>W&f+ZZVjUu{<2nHs&I*VP)VuVkaC z;&ji<*`(_A$-Oy*##c5~8ju9pE?33OQs^cg@EO_Pc+Gmb=wsd1AP=@3weTS%Vm2Rs zGaU(?%*?`bUaZdYHw-rD($2n;b3SxE-92%LUC^a9p~D$p%A}M1($f$T;(yU`-8{MK zz{Tm=ft+)1&BcQA6wuL>cM?=hufjD-1$O+wzL;hynX%A2m)Utq5h;cDW-OySN&v`B zsTcNpwwarn|KT3OB)So)fS5XeXC>!@k+WjXreZGlyMmjabKp_=J3$9h=2irZ!hMhw z55{BNn=P7;*j~;FijqUjT&-HasmjG_Z4x&Ahhq{4{aS?WmH}d(ds==;XDk$nOGOL? ztzMp~c+Svq>(eroK`H^T45}gkFSoOVl||LUm&q5Z=Ztoik~>a#T>QAWl*X$|e_P$a zbavw0wmoV}2vJ)sef8F{0Fg<{@yH@~*X#NTwwc{;f^?p-?r)skY@>O*BgzZ(%q2sf zw+yd4zAm&mwKjK``C{>n3ypU`6WLVW&*Md|_I!7`B6Q|z8NO0uBLJ|ksX*%zhskmJ zQ}bpe^1W9RV$!Uz%n|GZar^f#KvuGCGSkuE#VOxI8vEXlPb|>|@m8*i3(1Mnu*CVT zofbZ0JTW!baTLoeSS2UJBApg}KCaWhXyw}QplrUN_UqJa$rqc0^Y-XGc=!7S64asq zeQ}jlJiV7}YrW}bn{1uT>lBZ=|Cl{~{E$w0w;KPpj!ONpYyDTbJ_PKam5OljcW3tx zIuf;fp_1}QkbraX(S^GQ2NKU{3>y2p^xrGmxH7H4`aXQ)=`vT$sR*XnHr45itqMHl z;wCwzX@Nmsd1k8a_ti0IlAm7lThj6!9A|nu)}&B978|r$=n_YNGFEp@IIXC{%Wf;< zv0#Lk!pH<_n-bItZnkh9kf#fOBv6|>&eYs8dbgsSgaDNCe3e`IRG<>bQhGWos-9_` z=c{n9f21mx$aV9QNs@wko)uQaP;=QPZZ!oP#ht<(sIl|m%O`63>}5p97O;|N(pQg| zBmf9qK8}(0bk0iq(*!`10Qf&+2s%6S;f3wu_&Yc@`Q}I4FZX0hCpaB@%v4XRWQILc zxNKO0RQToot%Grmf71`z?+kOY*=nT?O_y{Yrk$&H!o!pSjLkoz=HLi2S(l ze5r0_R%(^i$wc{~FtyJfFP}zl>k@#_;;J@P4P8&fCjt;LUVk6G@AT<d- zyJ-JB5PIy2cVh78=GuyldzMVivIKzse9cf}hVk2m*jBl_ub)oWT8%`5gRb3L`D4(L z;+`bG%Q2pZq)y@vk4IkhdmQ*&P9Wkzy* zPW#h|=ju(Td;8}!zt(OM0Ijl3)J%+vNyjA*F8eT_;;3b}^_|dd+)DHeOZ@~*Ah{kN z*CDKlE@TOukQXd~s1@#-dr4hgZ820Lx3h#cpsD2BW*BS+GE}Q_w=Dj*IB7Su=XnEZwsK~akcrl|puF%M!vt!Ljaj0C z5*IU4mcQ=w?*y(TdQLtqGzxr%KI;fRYAN*_}umWBIVJ4x2@3ldt2-i@^d%PHBdJmch( z;LzRV%TdQ`=-n2gXRK%{7` zP!bSod)Q^C@I&X=%>AYf@s~}>qqlTa0m3lcIn}$F z$M|;hXyFXkKKH^t#`PG3>7gB_w!5o}c)cF*+b+c10iq@_cZiYz1gy524@F*y&OZXA zWoIS}yEq)Idj)5XBLKZQ5Bb<@cJkPR{Wi{@c!glP_%4L?9OGe{;VY?Q*>Wd8PHumV zXzFt0OqFJ9=3}(Ak6dadJI+{Q*&FPya`a)COz(^I zLy|3Jv%GAw3&;JUx3((ptR7^h<>>UDwbF(&Ni6`|=jZqu0pov}vd zo%O@_54AltQSz$$IOCz4Y0xt<4fhchsf(ngm}1Ax2ozT)4x)MEueZE@ogtUF3bWV* z$Tz#9s##wkC)n5NitegZYwncExnE4WSO~h7lC~+QQ#Tds+HF1sT;E98fZ}#){dw*M z70hN<`32=~+m24wy3|K)RCn#1eEejwF}HA;87Jd&sHZ75TD5<4)31@16;6 z-O1X|kQq0fn{`ov)PA=ttnWX+l9gWZw8SvyL3N?gC#Us9PMUJcgP>6!@upbYFy)q1BZ;U9&k`zzWb1J$pqWzLt!S|#BN zP}D0+BX#tvAHRmJFjhTZdsbPYsNIq=ixOuMIC-k>{r-EAq*1V~z^jrHQ`SrO@5DAL zBk(CUX6IOk^hXo3?Vgk_+f<5-7M<8}kFVFH5|xYPxtY*@vawAd)qa^?L=9J#lq*|f{GH5cK#F8%J)3B3+I}87wt1mNbL4YNZB_M$In%E;kDRFv zyqSM(y_VceQtN$$9zF6pn_1q07u;zrj8ECZ%7`bsx$t{z>exrsWfRbni2I%<-( z@v-vEn-%xA76xtZ^sQ}8-_vKh;%>4u2wDa#-3#U6400d_9`JAguuNu-L z13Yxh$Xn^>2tfFbepR&fto6x9NzfGD9^q(yp3{KBXAi_+!SpeoawaP|Ge^KEKo7H6 zWSkD{q))Jp-i>M%+eXSgE_*!scGM-YCyScN@JMUeV-vnx7>V2 zf)c)pm-;p4xtNB=1rPx(1{d&m4q_+qR$=` zLUoN*%*f~P_@tUzRDG+leUT}CZOe^>p}oz>_+^nvM@L;MDqN%!$V=Z2Q%Vl}%ys`E z>$$n!-nyc`mk-2p9sp+nMWKp-7?(~Y?R)SOX9dgNsIkCZwCS5wN$A-7a_H=3cgVdD zzsji{9h{dVkRVh8APP$bY){6Yp7b?UGgqe6%Dd-eQlKO#CdYE(oOivDqAX9(Jv~%Q zX%}!te=aCA)m5D92FmDR%4DPd+D6)=_GW%PrGiJNtOxFgRezp?tOTFK()sz*CG^=O zoNZVt&1iZpma#8(^nMI8EY??6DJb}3ujOzToII2}Waah}Oqse|oB$;E$`qmI6tKBY zIjIa?#sk9Xc{#UuL<6whIzHQ4nUKa$QO-iimLjbs+|QHMQ^`8Yl}MACoCa-dpX8n{ zQ@A?KDVs51>56fR=Fmgxv7AtS%;xkdw|o8>Lou5U+W=#4*8Zc)BV2r+pg#@G3o9GtQ<)R3{U%Jr_Z@{j+lB9~7H`SkRg=B9{60v#>;?glDd#CO7;O{iFHOs^4G+pJ zT-UbAUduPgJ&kzoEEv)8IkVp0KJ&aK8$*wUS+{tzEJ?>jNnDMbF9tVwN3l3d-J+T_9FPnbtRR@ZCUON_|I?h>(8dut>jUA{Gg7>-y(G zt_5qsQc5HD`H#eUK5BV&jQibd@q$|}(L2|-XI0K7i4p)^wv2Xa7Y_}+6qDGU!s7cP zQ)0M_ff3P){FTWiEy#(_;F8Cna=zwxI95z&60-7`itd(F?$qFFcO|$eF==%w?~4vx zD@GemYUJIrF}OjaPZ~hWcjU1di*V-WC&tsS447>cZ@w_$S(6@V3!TK}FfJ}_LvOAMccEFAf!fyaR8z(FV5*Y^^V2VY)+zcU;x7@>vJ6JE0N`D zckJKtR}ETVxe7P#Hp?NpdmgXEXmmHMz7L*`m5x6A{M;$O8FXX{jA^eSRhB<@UlVG6+&g20xt z1eI{dYN3h=gvqJ%i!;ZwHJ%J~S4>3uzqXET9O;cWI2kUK_&iYV7^_MbUq{+%z{n$& z{)unPJ6#3xQ=Xf)+)-Nd-40XsG*R_}%6UWw{Cu`SBX15YO0R#^ctom`-RX`$G(7J$w-uJO&FZ5O=jrXJQmRC} zzf4Uq`va2!-Q-xK9)@+5Ua6(tGtpz6nN1Aah2ZQ;KA + + + + + + + +Eclipse Public License - Version 1.0 + + + + + + +
+ +

Eclipse Public License - v 1.0 +

+ +

THE ACCOMPANYING PROGRAM IS PROVIDED UNDER +THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, +REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE +OF THIS AGREEMENT.

+ +

1. DEFINITIONS

+ +

"Contribution" means:

+ +

a) +in the case of the initial Contributor, the initial code and documentation +distributed under this Agreement, and
+b) in the case of each subsequent Contributor:

+ +

i) +changes to the Program, and

+ +

ii) +additions to the Program;

+ +

where +such changes and/or additions to the Program originate from and are distributed +by that particular Contributor. A Contribution 'originates' from a Contributor +if it was added to the Program by such Contributor itself or anyone acting on +such Contributor's behalf. Contributions do not include additions to the +Program which: (i) are separate modules of software distributed in conjunction +with the Program under their own license agreement, and (ii) are not derivative +works of the Program.

+ +

"Contributor" means any person or +entity that distributes the Program.

+ +

"Licensed Patents " mean patent +claims licensable by a Contributor which are necessarily infringed by the use +or sale of its Contribution alone or when combined with the Program.

+ +

"Program" means the Contributions +distributed in accordance with this Agreement.

+ +

"Recipient" means anyone who +receives the Program under this Agreement, including all Contributors.

+ +

2. GRANT OF RIGHTS

+ +

a) +Subject to the terms of this Agreement, each Contributor hereby grants Recipient +a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly +display, publicly perform, distribute and sublicense the Contribution of such +Contributor, if any, and such derivative works, in source code and object code +form.

+ +

b) +Subject to the terms of this Agreement, each Contributor hereby grants +Recipient a non-exclusive, worldwide, royalty-free +patent license under Licensed Patents to make, use, sell, offer to sell, import +and otherwise transfer the Contribution of such Contributor, if any, in source +code and object code form. This patent license shall apply to the combination +of the Contribution and the Program if, at the time the Contribution is added +by the Contributor, such addition of the Contribution causes such combination +to be covered by the Licensed Patents. The patent license shall not apply to +any other combinations which include the Contribution. No hardware per se is +licensed hereunder.

+ +

c) +Recipient understands that although each Contributor grants the licenses to its +Contributions set forth herein, no assurances are provided by any Contributor +that the Program does not infringe the patent or other intellectual property +rights of any other entity. Each Contributor disclaims any liability to Recipient +for claims brought by any other entity based on infringement of intellectual +property rights or otherwise. As a condition to exercising the rights and +licenses granted hereunder, each Recipient hereby assumes sole responsibility +to secure any other intellectual property rights needed, if any. For example, +if a third party patent license is required to allow Recipient to distribute +the Program, it is Recipient's responsibility to acquire that license before +distributing the Program.

+ +

d) +Each Contributor represents that to its knowledge it has sufficient copyright +rights in its Contribution, if any, to grant the copyright license set forth in +this Agreement.

+ +

3. REQUIREMENTS

+ +

A Contributor may choose to distribute the +Program in object code form under its own license agreement, provided that: +

+ +

a) +it complies with the terms and conditions of this Agreement; and

+ +

b) +its license agreement:

+ +

i) +effectively disclaims on behalf of all Contributors all warranties and +conditions, express and implied, including warranties or conditions of title +and non-infringement, and implied warranties or conditions of merchantability +and fitness for a particular purpose;

+ +

ii) +effectively excludes on behalf of all Contributors all liability for damages, +including direct, indirect, special, incidental and consequential damages, such +as lost profits;

+ +

iii) +states that any provisions which differ from this Agreement are offered by that +Contributor alone and not by any other party; and

+ +

iv) +states that source code for the Program is available from such Contributor, and +informs licensees how to obtain it in a reasonable manner on or through a +medium customarily used for software exchange.

+ +

When the Program is made available in source +code form:

+ +

a) +it must be made available under this Agreement; and

+ +

b) a +copy of this Agreement must be included with each copy of the Program.

+ +

Contributors may not remove or alter any +copyright notices contained within the Program.

+ +

Each Contributor must identify itself as the +originator of its Contribution, if any, in a manner that reasonably allows +subsequent Recipients to identify the originator of the Contribution.

+ +

4. COMMERCIAL DISTRIBUTION

+ +

Commercial distributors of software may +accept certain responsibilities with respect to end users, business partners +and the like. While this license is intended to facilitate the commercial use +of the Program, the Contributor who includes the Program in a commercial +product offering should do so in a manner which does not create potential +liability for other Contributors. Therefore, if a Contributor includes the +Program in a commercial product offering, such Contributor ("Commercial +Contributor") hereby agrees to defend and indemnify every other +Contributor ("Indemnified Contributor") against any losses, damages and +costs (collectively "Losses") arising from claims, lawsuits and other +legal actions brought by a third party against the Indemnified Contributor to +the extent caused by the acts or omissions of such Commercial Contributor in +connection with its distribution of the Program in a commercial product +offering. The obligations in this section do not apply to any claims or Losses +relating to any actual or alleged intellectual property infringement. In order +to qualify, an Indemnified Contributor must: a) promptly notify the Commercial +Contributor in writing of such claim, and b) allow the Commercial Contributor +to control, and cooperate with the Commercial Contributor in, the defense and +any related settlement negotiations. The Indemnified Contributor may participate +in any such claim at its own expense.

+ +

For example, a Contributor might include the +Program in a commercial product offering, Product X. That Contributor is then a +Commercial Contributor. If that Commercial Contributor then makes performance +claims, or offers warranties related to Product X, those performance claims and +warranties are such Commercial Contributor's responsibility alone. Under this +section, the Commercial Contributor would have to defend claims against the +other Contributors related to those performance claims and warranties, and if a +court requires any other Contributor to pay any damages as a result, the +Commercial Contributor must pay those damages.

+ +

5. NO WARRANTY

+ +

EXCEPT AS EXPRESSLY SET FORTH IN THIS +AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, +WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, +MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely +responsible for determining the appropriateness of using and distributing the +Program and assumes all risks associated with its exercise of rights under this +Agreement , including but not limited to the risks and costs of program errors, +compliance with applicable laws, damage to or loss of data, programs or +equipment, and unavailability or interruption of operations.

+ +

6. DISCLAIMER OF LIABILITY

+ +

EXCEPT AS EXPRESSLY SET FORTH IN THIS +AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY +OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF +THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGES.

+ +

7. GENERAL

+ +

If any provision of this Agreement is invalid +or unenforceable under applicable law, it shall not affect the validity or +enforceability of the remainder of the terms of this Agreement, and without +further action by the parties hereto, such provision shall be reformed to the +minimum extent necessary to make such provision valid and enforceable.

+ +

If Recipient institutes patent litigation +against any entity (including a cross-claim or counterclaim in a lawsuit) +alleging that the Program itself (excluding combinations of the Program with +other software or hardware) infringes such Recipient's patent(s), then such +Recipient's rights granted under Section 2(b) shall terminate as of the date +such litigation is filed.

+ +

All Recipient's rights under this Agreement +shall terminate if it fails to comply with any of the material terms or +conditions of this Agreement and does not cure such failure in a reasonable +period of time after becoming aware of such noncompliance. If all Recipient's +rights under this Agreement terminate, Recipient agrees to cease use and +distribution of the Program as soon as reasonably practicable. However, +Recipient's obligations under this Agreement and any licenses granted by +Recipient relating to the Program shall continue and survive.

+ +

Everyone is permitted to copy and distribute +copies of this Agreement, but in order to avoid inconsistency the Agreement is +copyrighted and may only be modified in the following manner. The Agreement +Steward reserves the right to publish new versions (including revisions) of +this Agreement from time to time. No one other than the Agreement Steward has +the right to modify this Agreement. The Eclipse Foundation is the initial +Agreement Steward. The Eclipse Foundation may assign the responsibility to +serve as the Agreement Steward to a suitable separate entity. Each new version +of the Agreement will be given a distinguishing version number. The Program +(including Contributions) may always be distributed subject to the version of +the Agreement under which it was received. In addition, after a new version of +the Agreement is published, Contributor may elect to distribute the Program +(including its Contributions) under the new version. Except as expressly stated +in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to +the intellectual property of any Contributor under this Agreement, whether +expressly, by implication, estoppel or otherwise. All rights in the Program not +expressly granted under this Agreement are reserved.

+ +

This Agreement is governed by the laws of the +State of New York and the intellectual property laws of the United States of +America. No party to this Agreement will bring a legal action under this +Agreement more than one year after the cause of action arose. Each party waives +its rights to a jury trial in any resulting litigation.

+ +

 

+ +
+ + + + \ No newline at end of file diff --git a/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/feature.properties b/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/feature.properties new file mode 100644 index 00000000000..85e9b92c711 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/feature.properties @@ -0,0 +1,166 @@ +# ============================================================================= +# Copyright (c) 2012 Ericsson and others. +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# Marc Khouzam (Ericsson) +# ============================================================================= + +# ----------------------------------------------------------------------------- +# Feature string resources +# ----------------------------------------------------------------------------- + +# "featureName" property - name of the feature +featureName=CDT Multicore Visualizer + +# "providerName" property - name of the company that provides the feature +providerName=Eclipse CDT + +# "updateSiteName" property - label for the update site +updateSiteName=Eclipse CDT Update Site + +# "description" property - description of the feature +description=Multicore Visualizer which displays the debug session graphically in the Visualizer view. + +# copyright +copyright=\ +Copyright (c) 2012 Ericsson and others.\n\ +All rights reserved. This program and the accompanying materials\n\ +are made available under the terms of the Eclipse Public License v1.0\n\ +which accompanies this distribution, and is available at\n\ +http://www.eclipse.org/legal/epl-v10.html + +# "licenseURL" property - URL of the "Feature License" +# do not translate value - just change to point to a locale-specific HTML page +licenseURL=license.html + +# "license" property - text of the "Feature Update License" +# should be plain text version of license agreement pointed to be "licenseURL" +license=\ +Eclipse Foundation Software User Agreement\n\ +February 1, 2011\n\ +\n\ +Usage Of Content\n\ +\n\ +THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR\n\ +OTHER MATERIALS FOR OPEN SOURCE PROJECTS (COLLECTIVELY "CONTENT").\n\ +USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS\n\ +AGREEMENT AND/OR THE TERMS AND CONDITIONS OF LICENSE AGREEMENTS OR\n\ +NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU\n\ +AGREE THAT YOUR USE OF THE CONTENT IS GOVERNED BY THIS AGREEMENT\n\ +AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS\n\ +OR NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE\n\ +TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND CONDITIONS\n\ +OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED\n\ +BELOW, THEN YOU MAY NOT USE THE CONTENT.\n\ +\n\ +Applicable Licenses\n\ +\n\ +Unless otherwise indicated, all Content made available by the\n\ +Eclipse Foundation is provided to you under the terms and conditions of\n\ +the Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is\n\ +provided with this Content and is also available at http://www.eclipse.org/legal/epl-v10.html.\n\ +For purposes of the EPL, "Program" will mean the Content.\n\ +\n\ +Content includes, but is not limited to, source code, object code,\n\ +documentation and other files maintained in the Eclipse Foundation source code\n\ +repository ("Repository") in software modules ("Modules") and made available\n\ +as downloadable archives ("Downloads").\n\ +\n\ + - Content may be structured and packaged into modules to facilitate delivering,\n\ + extending, and upgrading the Content. Typical modules may include plug-ins ("Plug-ins"),\n\ + plug-in fragments ("Fragments"), and features ("Features").\n\ + - Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java(TM) ARchive)\n\ + in a directory named "plugins".\n\ + - A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material.\n\ + Each Feature may be packaged as a sub-directory in a directory named "features".\n\ + Within a Feature, files named "feature.xml" may contain a list of the names and version\n\ + numbers of the Plug-ins and/or Fragments associated with that Feature.\n\ + - Features may also include other Features ("Included Features"). Within a Feature, files\n\ + named "feature.xml" may contain a list of the names and version numbers of Included Features.\n\ +\n\ +The terms and conditions governing Plug-ins and Fragments should be\n\ +contained in files named "about.html" ("Abouts"). The terms and\n\ +conditions governing Features and Included Features should be contained\n\ +in files named "license.html" ("Feature Licenses"). Abouts and Feature\n\ +Licenses may be located in any directory of a Download or Module\n\ +including, but not limited to the following locations:\n\ +\n\ + - The top-level (root) directory\n\ + - Plug-in and Fragment directories\n\ + - Inside Plug-ins and Fragments packaged as JARs\n\ + - Sub-directories of the directory named "src" of certain Plug-ins\n\ + - Feature directories\n\ +\n\ +Note: if a Feature made available by the Eclipse Foundation is installed using the\n\ +Provisioning Technology (as defined below), you must agree to a license ("Feature \n\ +Update License") during the installation process. If the Feature contains\n\ +Included Features, the Feature Update License should either provide you\n\ +with the terms and conditions governing the Included Features or inform\n\ +you where you can locate them. Feature Update Licenses may be found in\n\ +the "license" property of files named "feature.properties" found within a Feature.\n\ +Such Abouts, Feature Licenses, and Feature Update Licenses contain the\n\ +terms and conditions (or references to such terms and conditions) that\n\ +govern your use of the associated Content in that directory.\n\ +\n\ +THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER\n\ +TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS.\n\ +SOME OF THESE OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):\n\ +\n\ + - Eclipse Distribution License Version 1.0 (available at http://www.eclipse.org/licenses/edl-v1.0.html)\n\ + - Common Public License Version 1.0 (available at http://www.eclipse.org/legal/cpl-v10.html)\n\ + - Apache Software License 1.1 (available at http://www.apache.org/licenses/LICENSE)\n\ + - Apache Software License 2.0 (available at http://www.apache.org/licenses/LICENSE-2.0)\n\ + - Metro Link Public License 1.00 (available at http://www.opengroup.org/openmotif/supporters/metrolink/license.html)\n\ + - Mozilla Public License Version 1.1 (available at http://www.mozilla.org/MPL/MPL-1.1.html)\n\ +\n\ +IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR\n\ +TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License\n\ +is provided, please contact the Eclipse Foundation to determine what terms and conditions\n\ +govern that particular Content.\n\ +\n\ +\n\Use of Provisioning Technology\n\ +\n\ +The Eclipse Foundation makes available provisioning software, examples of which include,\n\ +but are not limited to, p2 and the Eclipse Update Manager ("Provisioning Technology") for\n\ +the purpose of allowing users to install software, documentation, information and/or\n\ +other materials (collectively "Installable Software"). This capability is provided with\n\ +the intent of allowing such users to install, extend and update Eclipse-based products.\n\ +Information about packaging Installable Software is available at\n\ +http://eclipse.org/equinox/p2/repository_packaging.html ("Specification").\n\ +\n\ +You may use Provisioning Technology to allow other parties to install Installable Software.\n\ +You shall be responsible for enabling the applicable license agreements relating to the\n\ +Installable Software to be presented to, and accepted by, the users of the Provisioning Technology\n\ +in accordance with the Specification. By using Provisioning Technology in such a manner and\n\ +making it available in accordance with the Specification, you further acknowledge your\n\ +agreement to, and the acquisition of all necessary rights to permit the following:\n\ +\n\ + 1. A series of actions may occur ("Provisioning Process") in which a user may execute\n\ + the Provisioning Technology on a machine ("Target Machine") with the intent of installing,\n\ + extending or updating the functionality of an Eclipse-based product.\n\ + 2. During the Provisioning Process, the Provisioning Technology may cause third party\n\ + Installable Software or a portion thereof to be accessed and copied to the Target Machine.\n\ + 3. Pursuant to the Specification, you will provide to the user the terms and conditions that\n\ + govern the use of the Installable Software ("Installable Software Agreement") and such\n\ + Installable Software Agreement shall be accessed from the Target Machine in accordance\n\ + with the Specification. Such Installable Software Agreement must inform the user of the\n\ + terms and conditions that govern the Installable Software and must solicit acceptance by\n\ + the end user in the manner prescribed in such Installable Software Agreement. Upon such\n\ + indication of agreement by the user, the provisioning Technology will complete installation\n\ + of the Installable Software.\n\ +\n\ +Cryptography\n\ +\n\ +Content may contain encryption software. The country in which you are\n\ +currently may have restrictions on the import, possession, and use,\n\ +and/or re-export to another country, of encryption software. BEFORE\n\ +using any encryption software, please check the country's laws,\n\ +regulations and policies concerning the import, possession, or use, and\n\ +re-export of encryption software, to see if this is permitted.\n\ +\n\ +Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both.\n +########### end of license property ########################################## diff --git a/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/feature.xml b/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/feature.xml new file mode 100755 index 00000000000..818d399a038 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/feature.xml @@ -0,0 +1,27 @@ + + + + + %description + + + + %copyright + + + + %license + + + + + diff --git a/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/license.html b/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/license.html new file mode 100644 index 00000000000..f19c483b9c8 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/license.html @@ -0,0 +1,108 @@ + + + + + +Eclipse Foundation Software User Agreement + + + +

Eclipse Foundation Software User Agreement

+

February 1, 2011

+ +

Usage Of Content

+ +

THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR OTHER MATERIALS FOR OPEN SOURCE PROJECTS + (COLLECTIVELY "CONTENT"). USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS AGREEMENT AND/OR THE TERMS AND + CONDITIONS OF LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU AGREE THAT YOUR USE + OF THE CONTENT IS GOVERNED BY THIS AGREEMENT AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR + NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND + CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW, THEN YOU MAY NOT USE THE CONTENT.

+ +

Applicable Licenses

+ +

Unless otherwise indicated, all Content made available by the Eclipse Foundation is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 + ("EPL"). A copy of the EPL is provided with this Content and is also available at http://www.eclipse.org/legal/epl-v10.html. + For purposes of the EPL, "Program" will mean the Content.

+ +

Content includes, but is not limited to, source code, object code, documentation and other files maintained in the Eclipse Foundation source code + repository ("Repository") in software modules ("Modules") and made available as downloadable archives ("Downloads").

+ +
    +
  • Content may be structured and packaged into modules to facilitate delivering, extending, and upgrading the Content. Typical modules may include plug-ins ("Plug-ins"), plug-in fragments ("Fragments"), and features ("Features").
  • +
  • Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java™ ARchive) in a directory named "plugins".
  • +
  • A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material. Each Feature may be packaged as a sub-directory in a directory named "features". Within a Feature, files named "feature.xml" may contain a list of the names and version numbers of the Plug-ins + and/or Fragments associated with that Feature.
  • +
  • Features may also include other Features ("Included Features"). Within a Feature, files named "feature.xml" may contain a list of the names and version numbers of Included Features.
  • +
+ +

The terms and conditions governing Plug-ins and Fragments should be contained in files named "about.html" ("Abouts"). The terms and conditions governing Features and +Included Features should be contained in files named "license.html" ("Feature Licenses"). Abouts and Feature Licenses may be located in any directory of a Download or Module +including, but not limited to the following locations:

+ +
    +
  • The top-level (root) directory
  • +
  • Plug-in and Fragment directories
  • +
  • Inside Plug-ins and Fragments packaged as JARs
  • +
  • Sub-directories of the directory named "src" of certain Plug-ins
  • +
  • Feature directories
  • +
+ +

Note: if a Feature made available by the Eclipse Foundation is installed using the Provisioning Technology (as defined below), you must agree to a license ("Feature Update License") during the +installation process. If the Feature contains Included Features, the Feature Update License should either provide you with the terms and conditions governing the Included Features or +inform you where you can locate them. Feature Update Licenses may be found in the "license" property of files named "feature.properties" found within a Feature. +Such Abouts, Feature Licenses, and Feature Update Licenses contain the terms and conditions (or references to such terms and conditions) that govern your use of the associated Content in +that directory.

+ +

THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS. SOME OF THESE +OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):

+ + + +

IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License is provided, please +contact the Eclipse Foundation to determine what terms and conditions govern that particular Content.

+ + +

Use of Provisioning Technology

+ +

The Eclipse Foundation makes available provisioning software, examples of which include, but are not limited to, p2 and the Eclipse + Update Manager ("Provisioning Technology") for the purpose of allowing users to install software, documentation, information and/or + other materials (collectively "Installable Software"). This capability is provided with the intent of allowing such users to + install, extend and update Eclipse-based products. Information about packaging Installable Software is available at http://eclipse.org/equinox/p2/repository_packaging.html + ("Specification").

+ +

You may use Provisioning Technology to allow other parties to install Installable Software. You shall be responsible for enabling the + applicable license agreements relating to the Installable Software to be presented to, and accepted by, the users of the Provisioning Technology + in accordance with the Specification. By using Provisioning Technology in such a manner and making it available in accordance with the + Specification, you further acknowledge your agreement to, and the acquisition of all necessary rights to permit the following:

+ +
    +
  1. A series of actions may occur ("Provisioning Process") in which a user may execute the Provisioning Technology + on a machine ("Target Machine") with the intent of installing, extending or updating the functionality of an Eclipse-based + product.
  2. +
  3. During the Provisioning Process, the Provisioning Technology may cause third party Installable Software or a portion thereof to be + accessed and copied to the Target Machine.
  4. +
  5. Pursuant to the Specification, you will provide to the user the terms and conditions that govern the use of the Installable + Software ("Installable Software Agreement") and such Installable Software Agreement shall be accessed from the Target + Machine in accordance with the Specification. Such Installable Software Agreement must inform the user of the terms and conditions that govern + the Installable Software and must solicit acceptance by the end user in the manner prescribed in such Installable Software Agreement. Upon such + indication of agreement by the user, the provisioning Technology will complete installation of the Installable Software.
  6. +
+ +

Cryptography

+ +

Content may contain encryption software. The country in which you are currently may have restrictions on the import, possession, and use, and/or re-export to + another country, of encryption software. BEFORE using any encryption software, please check the country's laws, regulations and policies concerning the import, + possession, or use, and re-export of encryption software, to see if this is permitted.

+ +

Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both.

+ + diff --git a/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/pom.xml b/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/pom.xml new file mode 100644 index 00000000000..d63af096830 --- /dev/null +++ b/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/pom.xml @@ -0,0 +1,18 @@ + + + 4.0.0 + + + org.eclipse.cdt + cdt-parent + 8.1.0-SNAPSHOT + ../../pom.xml + + + org.eclipse.cdt.features + 1.0.0-SNAPSHOT + org.eclipse.cdt.multicorevisualizer + eclipse-feature + diff --git a/visualizer/org.eclipse.cdt.visualizer-feature/.project b/visualizer/org.eclipse.cdt.visualizer-feature/.project new file mode 100755 index 00000000000..085bc9060c2 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer-feature/.project @@ -0,0 +1,17 @@ + + + org.eclipse.cdt.visualizer-feature + + + + + + org.eclipse.pde.FeatureBuilder + + + + + + org.eclipse.pde.FeatureNature + + diff --git a/visualizer/org.eclipse.cdt.visualizer-feature/ABOUT.txt b/visualizer/org.eclipse.cdt.visualizer-feature/ABOUT.txt new file mode 100644 index 00000000000..7184727dae9 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer-feature/ABOUT.txt @@ -0,0 +1,359 @@ +############################################################################### +# Copyright (c) 2012 Tilera 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 +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# William R. Swanson (Tilera Corporation) +############################################################################### + +Visualizer View Framework +========================= +Version: 1.0 +Last updated: 1/19/12 + +Overview +-------- + +- The Visualizer framework supports the addition of visual (i.e. graphical) + representations of run/debug launches to the Eclipse workbench. + It provides interfaces and default implementations to be used by + integrators in adding their own graphical views to Eclipse. + +- The Visualizer framework is an optional feature of CDT. + +- The Visualizer framework consists of the following features/plugins: + - org.eclipse.cdt.visualizer-feature: + - org.eclipse.cdt.visualizer.core -- non-UI interface and utilities + - org.eclipse.cdt.visualizer.ui -- UI classes and utilities + +- The Visualizer framework has the following goals: + - make it easy to present multiple graphical presentations of + a running/debugging launch, and allow the user to select between them + - provide a pluggable infrastructure that does not limit an integrator + to a specific model, event, or graphic "canvas" in creating such presentations + - provide sufficient default implementations to make creating a new + custom presentation as simple as possible + +- The framework consists of the following set of interfaces and classes: + + ========================== + | VisualizerView | + ========================== + | VisualizerViewer | + | | + | -------------------- | ------------------ + | | | | | | + | | IVisualizer's | <=== | IVisualizer | ===> (Model Object) + | | graphic | | | implementation | + | | control | | | | + | | | | ------------------ + | -------------------- | + | | + ========================== + + - VisualizerView -- a top-level Eclipse workbench view that + contains and presents a VisualizerViewer + + The VisualizerView also provides support for a toolbar and + context menu, which can be populated by IVisualizers when + they are selected. + + - VisualierViewer -- a container control that manages one or more + IVisualizers and their corresponding graphic controls. + + The VisualizerViewer automatically switches between its available + IVisualizers based on the current workbench selection. + + The viewer also mediates between its parent View and child IVisualizers + on things like: + - content selection (workbench selection <==> IVisulizer selection) + - toolbar population and updating + - context menu events and updating + + - IVisualizer -- an API for a class that encapsulates: + - a graphic representation of one or more model object types + - a top-level graphic display control (e.g. an SWT canvas, GEF canvas, etc.) + that is used to present this graphic representation in the VisualizerViewer + + - the "model" class -- this is not a specific class type, + it's basically any top-level Object that can be selected and + used to obtain the state to be presented by an IVisualizer + (for example, a Launch in the Debug View, or a text selection + in an editor) + +- The framework provides default implementations of VisualizerView, + and VisualizerViewer, and base classes that can be used to + create IVisualizer implementations. + +- The framework provides an extension point by which IVisualizer implementations + can be registered. This is read by the default VisualizerViewer, + and used to populate its initial set of IVisualizer views + + +Extension Points: +----------------- + +The base class VisualizerViewer checks the following extension point +for plugin contributions of IVisualizer implementations: + +- org.eclipse.cdt.visualizer.ui.vizualizer + - id: unique ID of this visualizer type + - class: implementation of IVisualizer interface + + Examples: + + + + + + + + + + + + + + + + +Package/Class hierarchy: +------------------------ + +- feature: org.eclipse.cdt.visualizer + + - plugin: org.eclipse.cdt.visualizer.core + + - org.eclipse.cdt.visualizer.core.plugin + + - CDTVisualizerCorePlugin -- plugin activator class (mainly used to access ResourceManager) + + - org.eclipse.cdt.visualizer.core + + - ResourceManager -- resource manager, handles strings only (see UIResourceManager below) + - Extension -- utility class for dealing with extension points + - ExtensionElement -- utility class for dealing with extension definitions + + - plugin: org.eclipse.cdt.visualizer.ui + + - org.eclipse.cdt.visualizer.ui.plugin + + - CDTVisualizerUIPlugin -- plugin activator class (mainly used for logging and UIResourceManager) + + - org.eclipse.cdt.visualizer.ui + + - VisualizerView -- base class for top-level Visualizer "view" in Eclipse workbench + - handles: + - display of single IVisualizerViewer + - boilerplate code for workbench views + + - IVisualizerViewer -- visualizer "viewer" container interface + - VisualizerViewer -- base class for IVisualizerViewer implementations + - handles: + - loading and managing a list of IVisualizers + - routing of selection + - from workbench into current IVisualizer + - from current IVisualizer back to workbench + - manages viewer toolbar and content menu, + asks current IVisualizer to populate these as needed + + - IVisualizer -- interface for visualizer (graphic representation, like Grid View) + - Visualizer -- base class for IVisualizer implementations + - handles: + - creating and painting a graphic component + - management of selection for that component + - populating toolbar and context menu content on demand + + - VisualizerAction -- base class for toolbar/menu actions (convenience wrapper for Action class) + + - org.eclipse.cdt.visualizer.ui.events + + - VisualizerViewerEvent -- event raised by VisualizerViewer (visualizer changed, context menu event) + - IVisualizerViewerListener -- listener interface for VisualizerViewerEvent listeners + + - org.eclipse.cdt.visualizer.ui.canvas + + - GraphicCanvasVisualizer -- base class for visualizers based on GraphicCanvas component + - GraphicCanvas -- simple canvas that paints a list of GraphicObjects + - IGraphicObject -- interface for objects to be drawn on GraphicCanvas + - GraphicObject -- base class implementation of IGraphicObject + - BufferedCanvas -- base class for GraphicCanvas (or any canvas component with back-buffering) + + - org.eclipse.cdt.visualizer.ui.test + + - TestCanvasVisualizer -- IVisualizer wrapper for TestCanvas + - TestCanvas -- simple canvas example that displays current selection as text + + - org.eclipse.cdt.visualizer.ui.util + + - GUIUtils -- assorted UI utility methods + - UIResourceManager -- resource manager, includes strings, images, fonts, colors + - Colors -- SWT color resource manager, used with UIResourceManager + - SelectionUtils -- ISelection manipulation utilities + - SelectionManager -- ISelectionProvider implementation, manages selection for a containing class + - SelectionProviderAdapter -- ISelectionProvider wrapper for classes that don't implement it + - ListenerList -- listener manager class + - Event -- event base class + - MouseMonitor -- mouse event tracking utility class + - RunnableWithResult -- Runnable that returns a result + - Timer -- UI timer class + - Todo -- work tracking utility class + - WorkbenchSelectionAdapter -- manages interaction between workbench selection and a specified IViewPart + + +Creating a Visualizer +--------------------- + +This is a summary of the steps to take in developing a visualizer. +(For a specific example of this, see the Multicore Debug Visualizer, +defined in the org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui plugin.) + +- Add the VisualizerView to the workbench. + Note: this implicitly creates a VisualizerViewer instance. + + NOTE: This is currently done by the Visualizer framework itself, + with the following plugin.xml extension markup: + + For example: + + + + + + + +- declare your visualizer class via the extension point + (described below under Extension Points) + + + + + + + + +- Define your IVisualizer class, either: + + - completely from scratch, implementing IVisualizer + + - derived from the Visualizer base class + + - if you want to use the supplied GraphicCanvas as your control, + use the GraphicCanvasVisualizer base class instead + + +- Implement the IVisualizer interface: + + - implement getName(), getDisplayName(), and getDescription() + to provide a UI-visible name and tooltip for your visualizer + + - implement createControl() to return the UI control to be + displayed for your visualizer in the VisualizerView + (if you're using the GraphicCanvasVisualizer base class, + override createCanvas() and initializeCanvas() instead) + + - implement handlesSelection() to determine whether your + visualizer can display the current selection + (your visualizer is only selected if it returns a higher + value from this call than any other visualizer) + + - implement visualizerSelected()/visualizerDeselected() + to handle any setup/cleanup when your visualizer becomes + active or inactive + + - implement workbenchSelectionChanged() to handle changes in + the workbench selection (typically, this means updating the + visualizer's displayed content, and/or mapping the current + selection to selected item(s) in the visualizer display) + + - implement the selection-management methods + (getSelection(), setSelection() and add/removeSelectionChangedListener()) + to handle exposing the visualizer's selection to the workbench + (typically, these methods can be delegated to an instance of + the SelectionManager utility class, and then your visualizer + just needs to keep the SelectionManager's content up to date) + + - when your visualizer's selection changes (i.e. by the user clicking + or dragging on the visualizer's control, update the exposed + selection (i.e. update the SelectionManager instance) + + - optionally, to enable toolbar/menu support: + - implement createActions()/updateActions() to create and + update the enabling of your actions + - implement populateToolbar() to add actions to the visualizer toolbar + (note: the toolbar is initially empty each time this is called) + - implement populateMenu() to add actions to the toolbar's menu + - implement populateContextMenu() to add actions to the + VisualizerView's context menu + - whenever the selection changes (workbench or visualizer), + invoke updateActions() to keep your toolbar/menu actions + enabled properly + +- If you use the GraphicCanvasVisualizer, here's some additional hints: + + - create an internal "model" class for your canvas, if you don't + already have such a model + + - when the workbench selection changes update this model + with any needed changes; this allows you to decouple the + canvas repaint step from workbench events, + + - have your GraphicCanvas implementation create and update instances + of GraphicObject classes associated with your model objects; + also cache GraphicObjects for model state that doesn't + change on every repaint + + - don't repaint your visualizer canvas on every event; + use a Timer instance and "batch up" requests that come in + during the timer interval (for example, start the timer when + the first update request comes in, and when the timer goes off, + display the current state, effectively "rolling up" any update + requests that came in during the timer interval) + + - add selection support to your canvas (i.e. let the user click- + and drag-select items in the visualization), and use the + selection-management interface of the IVisualizer class to + expose this to the workbench + + - remember that the IVisualizerViewer/IVisualizer API provides + support for a context menu on the visualizer, so you don't need + to provide one for your canvas control + +- Remember the goal of the visualizer: to provide a clear, high-level + view of the selected object -- for example, the hierarchy of processes + and threads in a running program. You can provide options or overlays + for additional detail, but keep the basic picture simple. + + +Current State, Future Plans +--------------------------- + +- In the initial implementation, the IVisualizer implementation + is required to use the selection to locate the object (i.e. the current launch) + that it is to represent visually, and to construct and maintain + a graphic representation of it. + +- In future, the Visualizer framework will want to provide APIs + that factor out and simplify common aspects of interaction with + launches and launch targets. For example: + + - a service-based target introspection layer, which can be used by + IPresentation implementations to discover details of the current + launch target in a platform-neutral way diff --git a/visualizer/org.eclipse.cdt.visualizer-feature/build.properties b/visualizer/org.eclipse.cdt.visualizer-feature/build.properties new file mode 100755 index 00000000000..7a4864dbb62 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer-feature/build.properties @@ -0,0 +1,17 @@ +############################################################################### +# Copyright (c) 2012 Tilera 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 +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# William R. Swanson (Tilera Corporation) +############################################################################### +bin.includes = feature.xml,\ + feature.properties,\ + license.html,\ + epl-v10.html,\ + eclipse_update_120.jpg,\ + About.txt + \ No newline at end of file diff --git a/visualizer/org.eclipse.cdt.visualizer-feature/eclipse_update_120.jpg b/visualizer/org.eclipse.cdt.visualizer-feature/eclipse_update_120.jpg new file mode 100644 index 0000000000000000000000000000000000000000..bfdf708ad617e4974cac04cc5c1c8192b09bbeb3 GIT binary patch literal 21695 zcmeHvcU)7=((p+_uhNSGp%(=Nr3wV321I%h5riZ_XrTltiYTH8C`eTiL3$Grle6uPge`61wfz> zKnMH-2t(wlntoUZ0MOS5!~g)G0LUSX01Sj6;2!|t1W0#b0I-Mb{{cHgM85GrK^`dp zjDh{&;{}o4g_%M4W+)aQ`Ia{W{A~pvuts93d%tREoIM6^=!C=Lyq$0!aCH;71=byn z^YsR#4K)C?^2G&J-q>`Y87Oib(yG`r#3&tBpmV+buZH7y1PEApjKiowyHxkU(Hi5-2G-83ief<_Jh+fRXSrN|CA=*)j2XUX~_f zj!rE)&M&}XTx);is8?{CI=Nts$=uL9%3Fptt@w(NMyx4Xvo0Mk%hql-j9GXRQs3b- zvZy5-mvQxJd_(8wrOc8SU8Bq94(F~VWR|-ORQhr>Gf{$CgY0`@~*!7=J4EGX}z^MYhV0my}9>e@je z(%I0OX0mw9@DCCGwFJUHMIiJ7G_c(|82|)Oi{wp>=YxfmePK;|DXQxvrWTTxXk~1? z^ePNXDHa!l9_K|0#ONA>QCtjCAX6X)DN1OqMP^*#<-32yEbpl-hv8E_ysyVYi|YpH z_wmj9%H}+7W~e)u2#VPZAEUWkNBy|qTxz9XGMk&Drkm^Fyow%MPMK>-bpS&Xm4?>n zmzf6^OG&vOu(&oW4*kxUCj|$xJaBDvD){)Bu9LyY#4lB;Z>8x;6}^~2QL_ncF9u9Pl}h7jCzp`Rxd_to{*TD39d(hOkDJ*i zaQgS}TVz;u%v%>46=lT9E%Ob%N{x-L^f9VqzLsoqEnjvduO#q^So|Ync**pr8uF!X zxE_04j3~UKD9p2<&!ElsQ{ltX{I#zi4U@I5is;!e>-gw`3S_M&wAY@v-p5J8s(U-% zc2->TfnQmrUXa$N(#enI2HWcfxoFNQ7sm;X&FBD2mwBX9lz+!(7W#)Kwwa$W{7=x~ z4WTm*3df)DozLSgI^m{&_G$NNv1cDelNL-Vkt8`;qC%=UqVSk=A??N-R~=~w$K)Dx zAKttcbRsA(NW`dN=dpj*X*px0Am%2aqxK{dpLF&!%ge*&saCMuwq)gF2WKff)+Y!+ zpxQ<=@*=-0Y@8i|*czp$>zyxjiO33kG#6Y_oWsHXHD|}8b$vxI-I+gvBcfg)ELJb4 zqN`kul*&ZBKrag^ZJya75C@M3vY`6TJ_kO>Gv2%;_|^9k?5mmE1=7?|qr7WZmhR8` zHe?MQI3>AiBp#a)qubs{=xksuN$>sO8>UnBbwm5}gCz0emy8dS7IrMu_lo+j(x+X} z4sLRdg|PD&s4cYwk#KmviuD=1J@xdnsq)CgWddMY5en^LeRiA;6OlwgQ$Dpx0M-Rf za+eer)Shv|-aXSM-^gJIxVkPiACSJHRH@TrKcN0v9E;@^gXA3%v&#ZRuVsg1N}CwR z*~~#5-$Nx32BpJ1euoNI{X7XkQ%*_rgDiRZFPqAaQEi7Oz8vomt+#r4?WwxfC6ZTz z@)T5?=FQ*>6VOBGsy*3?ymX7?4n;<|2CYpHY0gv9&!%wa#Wf-9*8!>%&7(TZR6_zo zjhCCv4>lF2mqcDt;EK1pq1WQBB1-D4ExJX zZ`tM#xEoY>gb5VbOnKQ`(8TDBq~v>ARjGF!DWFV@!O}huW@xN`PLf9?4g>PX zk@_TpyJPgeZzJ`OA0iDl^NqGQWf7-(;qVogn zx(<69q1a6mH34b?s=D`l(=j)Q{gs!Kn1mt0Xs@-zB&h#y4;5erxC3|q3qGy@20#Pi zfD}mku3aMU_wXz3d;agV-QQmsz7xI)Nld!?xVnNr#Kw@><9yuF-Ujy0C@}RcpD_wg zta`WYrl7axigR}a)4SmW#sU9p`Zylv_AN~m1u%AW`c5aN$-G^$D2%tc>j`f#1^H7w zq`Nc_%?Li^y9uPmFJ+TEdf|LL{)8gKd0`!~?ihC;H!u&4rU|ihgIye$rnU3ITh%_o!(2)KKOJk42g9i0acxteVo&J%1_x%(h76#CO4+Jr{3-7&|#LtpF z6W$${NQfK&StuA0)%NYJfj9v`P7R260oXye{kNn4+tL5B^4rn>?dbn@^nW}0|Cf&b z-Wfo>lTum{~gIA91kfiNC?ymukc{RJJRf6oC2)c1SRbUkTqM5;!kMNht*d16X=#k{#<}|JGRjFye&_ua{e$<^ zU-SNo{=xf`)yy4>SCRfE!#|+^JE{W*xxeo7@1q~l1mQ|xN>SYl1AaehfR74sb3**E zthkh%>G#bEapHCb_y+z1=l9I|I5gJ5|3At63+Io_;An}q!`uBw*?;BzUcj#C;FlRV z!m8}<@5(E;b> zW`|e7y4g8mB%M7lj!Ke0v41V^-p~!sl;E5x`C}F)+VTH=_+820((!L~{Z`lC(!k$h z{%u{q)%CYD@VA(MTi0)O{VfgrE#}|W^;=zkO9Ow4`L}ibR@dLsz~5s2ZC$_B^|v(e zx0wI8)u=Aa*Ek4}B9Y;^_qdsi_Y42APQP&#=qX1phV%| zE`>Z?2jlCC!Q;gZ!OayrFEm^o=jLJO?hgQaZ6@Xd7>T-tgG!c_QjnDumzE%&!1*5j zE%7_k|L{xf+dY;=quoA(u)g_;`c5Sd2lmtKx6_n2dgp%tqkk#2zIwS8oRr@gmwQ{J^a7S_KOTe zaL=wmfGJ}KV78S2_O&nru$eai2@^E{vrYynkRSbag3=t^WCQ>Up0Pc<2Vs!D8~-VS zMuADFH+J{H6rgTw3P<^Po!es}A^wm8RN&?%Gr$3G1N?vpcydh|kOPhZs(>b-3m5>V zz$w56K!MwsZh#ly3tRv$1J{5E;1&=MBmyZw29OIp0*Zk$;18e{cnQ1)FA#JAeZVJR z6qo|$fE8d9JgQC(p@lF(I3PR_LC8UfG(;Yv0?~w=fEYtgLC!)PA?^?#$OXt1NCYGX zk_btKwtZNO~ckn$Viw-;3VQC$4GQY%t%lqo+KAZZjdCB~+V43W%{?2yuu z9w0qPsz{0?wIp>U^(DPVnn0RGT0;7Qw2O3=ckm)k>4eMNM23ePCiP$MnO%%Lm^F}MPWtZP7zFz zK#@oBoT8m#jAD~=AEh9rBBcQ(n$n*#iZX+;lCp(zlyZ}bfl8Q4naY&Pnd&mt9jZrE zFR1#d7OAPJ`KT4Bji|BIm#FVhKc;S?9->~SVWbhGQKzw{@u7*N$)>5H`9QNsOG_(6 zt4eD{i>HmG&84lU9i&~OW1^FwL(-w?g6QtimD07-&C*lS3(~96+t3HlC(u8kZ=s*w zN4ZaEpZY$#eHZuL+gGu#XWudd6N40k0fQUE4Te01W`=P_az-IWO-3|h2xB^9J>v)y zjESE~oe9Nsg(-vS1=A=q8M81mlG&L#g1LbC9rGLuBg;`1a~40Adn{EfpIBk6Laazu zSJo)jV%Bcf4K^+|H8u=e7~3PZcD7aa{p_mj81``XLiR594GuVmCWi}0G)Ec704E8j z7^e}ZFK0663(o2N%=?e+N9_;aU%bEf0Q7*^0pkPb52PP>b6}Z^n@gL^gX=C=J=Zih zE4M1QGj|;KbM6TqCLR?YEKeLyHP0lR1+E5nh2McUz~^`m@apjT@TT&<39 z<}2hI;HTo3=Xcw6_XKj61ykXau9k@_8|7){ex|XNDnC- zazB)Is7IVeTuuC(c)s|M1gpdeiC~E`iCIYjNh`@{$wtYY!!n0m4`&?ilVX(8l?s-s zlvZ^G6RJ#T-pO`d)@fMqegWrcP#CR!-JS_L1y_oPgX} zxg@zBd1iS-`5W?03Zx3h6@nE0P*_)#Rm3Y6D}FsDe$3@q-m!5dVI_=GhSG>KpR%2D zs`4ilxXM|T2P&Tsya+o)8e&+LUlpyIr8=f2s^+ZrP;K`3;p1M%OOCIqE2;;o*J!{r zv^Byt-f1#wnrS9#4r=jfIcnu=&1uVMpVzL@A=S~-iPq^sav@R3T;!atoNl0QgC32Z ziC&`K@CmUKUMDK`q58V|vHJZd1y8!4EHeNMkOr{^1BSweo`%ni$czk)?iqbCmNLFz z+-SmNVr!CTvSNDNG|IHkOvKE`tj?U?+}b?XeAPn3BF5sArKDw`lAg6Vn|F50&cH6sZrL7b zpJYFWQb*lJO`%oMap(z*GA0Hy=Ai5l<1p^1>=^4f;e>EXaGJ)dV-vCS&N|L1&Z{m4 zF4-;wR}0rdHww42ZWZo~?k?^PIBuLDuFd11$2E^no{FCFo^xJ$URmA{?=#-zcxKR< zdgCMFbJb_)oXWX-=hl49eV_O-___PN@fY(C^B)V)3dlT9avpWQ?gHnQf^b-_PPD(&WStacLna=y1SL=l-PCe_`SlU z14&^?tM}3O+mlt3AEj`mM5Jsyz&?1Ns-0SzCX|+tPL_Ty{Y!>#mbsZQW+w?|ZC! zKD|f3AOGO`VZQfV?`Gene$xK%fqerBg9irFK8k)U{3QFSYDi<~&9KRE-w0}C>a+Lf ztaLCZjo=@*%sZd+|k?VC%A#9?tfl> zQw4p2y~}TVSIhpR82U57euQ6g60dqee-QptfbjG38+cpn=jAtg@bVkz)&gWu@B-J5 zKu$qMN|=DIk;p74<#<3W0&w-(W^>`PT&ZevFBxW`)EP+)S@||qh3@TwQVxOLngAp^D$`}rrw%b za@r^nGjj{h;=1976sy*uw$|8Z< zXj?eQ|G2yN^WvV4rIX+FJ2~Y|@5k2^kf*TzVRv&YnmUIo-BY<*?K4ZvTX=re=ARLS*4!L{xi_(-G=`DvXHEr))i2O*Ha@?y zZa6nCdxQD2SwKKyB+U)UQ<1FEq+=N)Rzc=!+nEI5`l=NRoXJcjP}If#^{{sQggjrO zmYCUPvIYhhZ+GnyUe#*xAg<{xRKh9iVok8WZ zd)8-F-nj6%e}aEIwCdARhi0dYSGL~ybm0`FKxC5Q+vSy>6FwjReG}SpZL?K2=vz?_ z<5*;lE=PBoC|Ia3?Yxdyh(x5WY+Pav7NgfPcW-_C!gQXCcI`}|_A@@KSL_W6Bt>}{ zk4X!b@jUT}p_!wRXGh`|#>aaFUI~V-;1A6V=H=y?*_OD>(Y6wR7xYgV2lI9$?zElY zRu)^}I%Yva`j($wfBi;O;nJt`c5{%cxe(d<6ztScpQe0$(t&VwrZ-_1l?*zJW2O{WzL#A?0zpf$wQTVx&XO#J8h&w z?u;1_?deuGSB!){F5gKz&e?DgzloHXC~DAcbUa$Hc=pnElED@lujh+(bnry7} zdV+l2V&_Qf8HDp}uOprScoqkQnFumjQ_~yFwCvjo3LE=ix|!r4e`tqXs?GD{_ zAw6y3+Aj18sH+Asm=JdfObrNM8l z8Wpd-zG1NRs%8S!8h>eqEB8J=+qtZvyMpTJ2i04LZf^7CTLhR_Z1dhfQ&_ioie>qa z42c5q@t~IatmHvcmQ0J$)`;bmCs~SL!B@a$b+)RfYO~OX(4MOxk>|(1?fEs8I<^%{ z?lI9w55!=|`lDw?>eEGThiZ-G9TpeI9J&<~LuO#Sqs?Zla*Y6tOy?~Giq*`GcT;lm zQOHmBZ)j&`449xA%NzV{oKk#OE~L%O(liK4v)vsmZv{ zWBs-6m3YO~6E9IbET+M{V(rrTCaUFFIQX)Q6ELN&(Z!d>Q^}J=1gXtx7YzuYxj9-2 zwJlC}h^@)S0aVTeKyKstyWGtuo;Mux5*+-|_Pxnk5@Yuk-oCB6Gv!a0ZEuh}E_Y1n zMhibHsv#*kEMY3s6x+BltqFSL>Li;5J*Y z%$(fOZnDjboR|kpWavOt8T-Mng&H*Q_Lt0JDg{) zd+}r0*7p7j?z*9p>iRK_rh;ZH*7iEWQHFG7Vru48VlJe#kWNb0@Z8z)>W&f+ZZVjUu{<2nHs&I*VP)VuVkaC z;&ji<*`(_A$-Oy*##c5~8ju9pE?33OQs^cg@EO_Pc+Gmb=wsd1AP=@3weTS%Vm2Rs zGaU(?%*?`bUaZdYHw-rD($2n;b3SxE-92%LUC^a9p~D$p%A}M1($f$T;(yU`-8{MK zz{Tm=ft+)1&BcQA6wuL>cM?=hufjD-1$O+wzL;hynX%A2m)Utq5h;cDW-OySN&v`B zsTcNpwwarn|KT3OB)So)fS5XeXC>!@k+WjXreZGlyMmjabKp_=J3$9h=2irZ!hMhw z55{BNn=P7;*j~;FijqUjT&-HasmjG_Z4x&Ahhq{4{aS?WmH}d(ds==;XDk$nOGOL? ztzMp~c+Svq>(eroK`H^T45}gkFSoOVl||LUm&q5Z=Ztoik~>a#T>QAWl*X$|e_P$a zbavw0wmoV}2vJ)sef8F{0Fg<{@yH@~*X#NTwwc{;f^?p-?r)skY@>O*BgzZ(%q2sf zw+yd4zAm&mwKjK``C{>n3ypU`6WLVW&*Md|_I!7`B6Q|z8NO0uBLJ|ksX*%zhskmJ zQ}bpe^1W9RV$!Uz%n|GZar^f#KvuGCGSkuE#VOxI8vEXlPb|>|@m8*i3(1Mnu*CVT zofbZ0JTW!baTLoeSS2UJBApg}KCaWhXyw}QplrUN_UqJa$rqc0^Y-XGc=!7S64asq zeQ}jlJiV7}YrW}bn{1uT>lBZ=|Cl{~{E$w0w;KPpj!ONpYyDTbJ_PKam5OljcW3tx zIuf;fp_1}QkbraX(S^GQ2NKU{3>y2p^xrGmxH7H4`aXQ)=`vT$sR*XnHr45itqMHl z;wCwzX@Nmsd1k8a_ti0IlAm7lThj6!9A|nu)}&B978|r$=n_YNGFEp@IIXC{%Wf;< zv0#Lk!pH<_n-bItZnkh9kf#fOBv6|>&eYs8dbgsSgaDNCe3e`IRG<>bQhGWos-9_` z=c{n9f21mx$aV9QNs@wko)uQaP;=QPZZ!oP#ht<(sIl|m%O`63>}5p97O;|N(pQg| zBmf9qK8}(0bk0iq(*!`10Qf&+2s%6S;f3wu_&Yc@`Q}I4FZX0hCpaB@%v4XRWQILc zxNKO0RQToot%Grmf71`z?+kOY*=nT?O_y{Yrk$&H!o!pSjLkoz=HLi2S(l ze5r0_R%(^i$wc{~FtyJfFP}zl>k@#_;;J@P4P8&fCjt;LUVk6G@AT<d- zyJ-JB5PIy2cVh78=GuyldzMVivIKzse9cf}hVk2m*jBl_ub)oWT8%`5gRb3L`D4(L z;+`bG%Q2pZq)y@vk4IkhdmQ*&P9Wkzy* zPW#h|=ju(Td;8}!zt(OM0Ijl3)J%+vNyjA*F8eT_;;3b}^_|dd+)DHeOZ@~*Ah{kN z*CDKlE@TOukQXd~s1@#-dr4hgZ820Lx3h#cpsD2BW*BS+GE}Q_w=Dj*IB7Su=XnEZwsK~akcrl|puF%M!vt!Ljaj0C z5*IU4mcQ=w?*y(TdQLtqGzxr%KI;fRYAN*_}umWBIVJ4x2@3ldt2-i@^d%PHBdJmch( z;LzRV%TdQ`=-n2gXRK%{7` zP!bSod)Q^C@I&X=%>AYf@s~}>qqlTa0m3lcIn}$F z$M|;hXyFXkKKH^t#`PG3>7gB_w!5o}c)cF*+b+c10iq@_cZiYz1gy524@F*y&OZXA zWoIS}yEq)Idj)5XBLKZQ5Bb<@cJkPR{Wi{@c!glP_%4L?9OGe{;VY?Q*>Wd8PHumV zXzFt0OqFJ9=3}(Ak6dadJI+{Q*&FPya`a)COz(^I zLy|3Jv%GAw3&;JUx3((ptR7^h<>>UDwbF(&Ni6`|=jZqu0pov}vd zo%O@_54AltQSz$$IOCz4Y0xt<4fhchsf(ngm}1Ax2ozT)4x)MEueZE@ogtUF3bWV* z$Tz#9s##wkC)n5NitegZYwncExnE4WSO~h7lC~+QQ#Tds+HF1sT;E98fZ}#){dw*M z70hN<`32=~+m24wy3|K)RCn#1eEejwF}HA;87Jd&sHZ75TD5<4)31@16;6 z-O1X|kQq0fn{`ov)PA=ttnWX+l9gWZw8SvyL3N?gC#Us9PMUJcgP>6!@upbYFy)q1BZ;U9&k`zzWb1J$pqWzLt!S|#BN zP}D0+BX#tvAHRmJFjhTZdsbPYsNIq=ixOuMIC-k>{r-EAq*1V~z^jrHQ`SrO@5DAL zBk(CUX6IOk^hXo3?Vgk_+f<5-7M<8}kFVFH5|xYPxtY*@vawAd)qa^?L=9J#lq*|f{GH5cK#F8%J)3B3+I}87wt1mNbL4YNZB_M$In%E;kDRFv zyqSM(y_VceQtN$$9zF6pn_1q07u;zrj8ECZ%7`bsx$t{z>exrsWfRbni2I%<-( z@v-vEn-%xA76xtZ^sQ}8-_vKh;%>4u2wDa#-3#U6400d_9`JAguuNu-L z13Yxh$Xn^>2tfFbepR&fto6x9NzfGD9^q(yp3{KBXAi_+!SpeoawaP|Ge^KEKo7H6 zWSkD{q))Jp-i>M%+eXSgE_*!scGM-YCyScN@JMUeV-vnx7>V2 zf)c)pm-;p4xtNB=1rPx(1{d&m4q_+qR$=` zLUoN*%*f~P_@tUzRDG+leUT}CZOe^>p}oz>_+^nvM@L;MDqN%!$V=Z2Q%Vl}%ys`E z>$$n!-nyc`mk-2p9sp+nMWKp-7?(~Y?R)SOX9dgNsIkCZwCS5wN$A-7a_H=3cgVdD zzsji{9h{dVkRVh8APP$bY){6Yp7b?UGgqe6%Dd-eQlKO#CdYE(oOivDqAX9(Jv~%Q zX%}!te=aCA)m5D92FmDR%4DPd+D6)=_GW%PrGiJNtOxFgRezp?tOTFK()sz*CG^=O zoNZVt&1iZpma#8(^nMI8EY??6DJb}3ujOzToII2}Waah}Oqse|oB$;E$`qmI6tKBY zIjIa?#sk9Xc{#UuL<6whIzHQ4nUKa$QO-iimLjbs+|QHMQ^`8Yl}MACoCa-dpX8n{ zQ@A?KDVs51>56fR=Fmgxv7AtS%;xkdw|o8>Lou5U+W=#4*8Zc)BV2r+pg#@G3o9GtQ<)R3{U%Jr_Z@{j+lB9~7H`SkRg=B9{60v#>;?glDd#CO7;O{iFHOs^4G+pJ zT-UbAUduPgJ&kzoEEv)8IkVp0KJ&aK8$*wUS+{tzEJ?>jNnDMbF9tVwN3l3d-J+T_9FPnbtRR@ZCUON_|I?h>(8dut>jUA{Gg7>-y(G zt_5qsQc5HD`H#eUK5BV&jQibd@q$|}(L2|-XI0K7i4p)^wv2Xa7Y_}+6qDGU!s7cP zQ)0M_ff3P){FTWiEy#(_;F8Cna=zwxI95z&60-7`itd(F?$qFFcO|$eF==%w?~4vx zD@GemYUJIrF}OjaPZ~hWcjU1di*V-WC&tsS447>cZ@w_$S(6@V3!TK}FfJ}_LvOAMccEFAf!fyaR8z(FV5*Y^^V2VY)+zcU;x7@>vJ6JE0N`D zckJKtR}ETVxe7P#Hp?NpdmgXEXmmHMz7L*`m5x6A{M;$O8FXX{jA^eSRhB<@UlVG6+&g20xt z1eI{dYN3h=gvqJ%i!;ZwHJ%J~S4>3uzqXET9O;cWI2kUK_&iYV7^_MbUq{+%z{n$& z{)unPJ6#3xQ=Xf)+)-Nd-40XsG*R_}%6UWw{Cu`SBX15YO0R#^ctom`-RX`$G(7J$w-uJO&FZ5O=jrXJQmRC} zzf4Uq`va2!-Q-xK9)@+5Ua6(tGtpz6nN1Aah2ZQ;KA + + + + + + + +Eclipse Public License - Version 1.0 + + + + + + +
+ +

Eclipse Public License - v 1.0 +

+ +

THE ACCOMPANYING PROGRAM IS PROVIDED UNDER +THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, +REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE +OF THIS AGREEMENT.

+ +

1. DEFINITIONS

+ +

"Contribution" means:

+ +

a) +in the case of the initial Contributor, the initial code and documentation +distributed under this Agreement, and
+b) in the case of each subsequent Contributor:

+ +

i) +changes to the Program, and

+ +

ii) +additions to the Program;

+ +

where +such changes and/or additions to the Program originate from and are distributed +by that particular Contributor. A Contribution 'originates' from a Contributor +if it was added to the Program by such Contributor itself or anyone acting on +such Contributor's behalf. Contributions do not include additions to the +Program which: (i) are separate modules of software distributed in conjunction +with the Program under their own license agreement, and (ii) are not derivative +works of the Program.

+ +

"Contributor" means any person or +entity that distributes the Program.

+ +

"Licensed Patents " mean patent +claims licensable by a Contributor which are necessarily infringed by the use +or sale of its Contribution alone or when combined with the Program.

+ +

"Program" means the Contributions +distributed in accordance with this Agreement.

+ +

"Recipient" means anyone who +receives the Program under this Agreement, including all Contributors.

+ +

2. GRANT OF RIGHTS

+ +

a) +Subject to the terms of this Agreement, each Contributor hereby grants Recipient +a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly +display, publicly perform, distribute and sublicense the Contribution of such +Contributor, if any, and such derivative works, in source code and object code +form.

+ +

b) +Subject to the terms of this Agreement, each Contributor hereby grants +Recipient a non-exclusive, worldwide, royalty-free +patent license under Licensed Patents to make, use, sell, offer to sell, import +and otherwise transfer the Contribution of such Contributor, if any, in source +code and object code form. This patent license shall apply to the combination +of the Contribution and the Program if, at the time the Contribution is added +by the Contributor, such addition of the Contribution causes such combination +to be covered by the Licensed Patents. The patent license shall not apply to +any other combinations which include the Contribution. No hardware per se is +licensed hereunder.

+ +

c) +Recipient understands that although each Contributor grants the licenses to its +Contributions set forth herein, no assurances are provided by any Contributor +that the Program does not infringe the patent or other intellectual property +rights of any other entity. Each Contributor disclaims any liability to Recipient +for claims brought by any other entity based on infringement of intellectual +property rights or otherwise. As a condition to exercising the rights and +licenses granted hereunder, each Recipient hereby assumes sole responsibility +to secure any other intellectual property rights needed, if any. For example, +if a third party patent license is required to allow Recipient to distribute +the Program, it is Recipient's responsibility to acquire that license before +distributing the Program.

+ +

d) +Each Contributor represents that to its knowledge it has sufficient copyright +rights in its Contribution, if any, to grant the copyright license set forth in +this Agreement.

+ +

3. REQUIREMENTS

+ +

A Contributor may choose to distribute the +Program in object code form under its own license agreement, provided that: +

+ +

a) +it complies with the terms and conditions of this Agreement; and

+ +

b) +its license agreement:

+ +

i) +effectively disclaims on behalf of all Contributors all warranties and +conditions, express and implied, including warranties or conditions of title +and non-infringement, and implied warranties or conditions of merchantability +and fitness for a particular purpose;

+ +

ii) +effectively excludes on behalf of all Contributors all liability for damages, +including direct, indirect, special, incidental and consequential damages, such +as lost profits;

+ +

iii) +states that any provisions which differ from this Agreement are offered by that +Contributor alone and not by any other party; and

+ +

iv) +states that source code for the Program is available from such Contributor, and +informs licensees how to obtain it in a reasonable manner on or through a +medium customarily used for software exchange.

+ +

When the Program is made available in source +code form:

+ +

a) +it must be made available under this Agreement; and

+ +

b) a +copy of this Agreement must be included with each copy of the Program.

+ +

Contributors may not remove or alter any +copyright notices contained within the Program.

+ +

Each Contributor must identify itself as the +originator of its Contribution, if any, in a manner that reasonably allows +subsequent Recipients to identify the originator of the Contribution.

+ +

4. COMMERCIAL DISTRIBUTION

+ +

Commercial distributors of software may +accept certain responsibilities with respect to end users, business partners +and the like. While this license is intended to facilitate the commercial use +of the Program, the Contributor who includes the Program in a commercial +product offering should do so in a manner which does not create potential +liability for other Contributors. Therefore, if a Contributor includes the +Program in a commercial product offering, such Contributor ("Commercial +Contributor") hereby agrees to defend and indemnify every other +Contributor ("Indemnified Contributor") against any losses, damages and +costs (collectively "Losses") arising from claims, lawsuits and other +legal actions brought by a third party against the Indemnified Contributor to +the extent caused by the acts or omissions of such Commercial Contributor in +connection with its distribution of the Program in a commercial product +offering. The obligations in this section do not apply to any claims or Losses +relating to any actual or alleged intellectual property infringement. In order +to qualify, an Indemnified Contributor must: a) promptly notify the Commercial +Contributor in writing of such claim, and b) allow the Commercial Contributor +to control, and cooperate with the Commercial Contributor in, the defense and +any related settlement negotiations. The Indemnified Contributor may participate +in any such claim at its own expense.

+ +

For example, a Contributor might include the +Program in a commercial product offering, Product X. That Contributor is then a +Commercial Contributor. If that Commercial Contributor then makes performance +claims, or offers warranties related to Product X, those performance claims and +warranties are such Commercial Contributor's responsibility alone. Under this +section, the Commercial Contributor would have to defend claims against the +other Contributors related to those performance claims and warranties, and if a +court requires any other Contributor to pay any damages as a result, the +Commercial Contributor must pay those damages.

+ +

5. NO WARRANTY

+ +

EXCEPT AS EXPRESSLY SET FORTH IN THIS +AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, +WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, +MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely +responsible for determining the appropriateness of using and distributing the +Program and assumes all risks associated with its exercise of rights under this +Agreement , including but not limited to the risks and costs of program errors, +compliance with applicable laws, damage to or loss of data, programs or +equipment, and unavailability or interruption of operations.

+ +

6. DISCLAIMER OF LIABILITY

+ +

EXCEPT AS EXPRESSLY SET FORTH IN THIS +AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY +OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF +THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGES.

+ +

7. GENERAL

+ +

If any provision of this Agreement is invalid +or unenforceable under applicable law, it shall not affect the validity or +enforceability of the remainder of the terms of this Agreement, and without +further action by the parties hereto, such provision shall be reformed to the +minimum extent necessary to make such provision valid and enforceable.

+ +

If Recipient institutes patent litigation +against any entity (including a cross-claim or counterclaim in a lawsuit) +alleging that the Program itself (excluding combinations of the Program with +other software or hardware) infringes such Recipient's patent(s), then such +Recipient's rights granted under Section 2(b) shall terminate as of the date +such litigation is filed.

+ +

All Recipient's rights under this Agreement +shall terminate if it fails to comply with any of the material terms or +conditions of this Agreement and does not cure such failure in a reasonable +period of time after becoming aware of such noncompliance. If all Recipient's +rights under this Agreement terminate, Recipient agrees to cease use and +distribution of the Program as soon as reasonably practicable. However, +Recipient's obligations under this Agreement and any licenses granted by +Recipient relating to the Program shall continue and survive.

+ +

Everyone is permitted to copy and distribute +copies of this Agreement, but in order to avoid inconsistency the Agreement is +copyrighted and may only be modified in the following manner. The Agreement +Steward reserves the right to publish new versions (including revisions) of +this Agreement from time to time. No one other than the Agreement Steward has +the right to modify this Agreement. The Eclipse Foundation is the initial +Agreement Steward. The Eclipse Foundation may assign the responsibility to +serve as the Agreement Steward to a suitable separate entity. Each new version +of the Agreement will be given a distinguishing version number. The Program +(including Contributions) may always be distributed subject to the version of +the Agreement under which it was received. In addition, after a new version of +the Agreement is published, Contributor may elect to distribute the Program +(including its Contributions) under the new version. Except as expressly stated +in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to +the intellectual property of any Contributor under this Agreement, whether +expressly, by implication, estoppel or otherwise. All rights in the Program not +expressly granted under this Agreement are reserved.

+ +

This Agreement is governed by the laws of the +State of New York and the intellectual property laws of the United States of +America. No party to this Agreement will bring a legal action under this +Agreement more than one year after the cause of action arose. Each party waives +its rights to a jury trial in any resulting litigation.

+ +

 

+ +
+ + + + \ No newline at end of file diff --git a/visualizer/org.eclipse.cdt.visualizer-feature/feature.properties b/visualizer/org.eclipse.cdt.visualizer-feature/feature.properties new file mode 100644 index 00000000000..41c07c9a829 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer-feature/feature.properties @@ -0,0 +1,166 @@ +# ============================================================================= +# Copyright (c) 2012 Tilera 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 +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# William R. Swanson (Tilera Corporation) +# ============================================================================= + +# ----------------------------------------------------------------------------- +# Feature string resources +# ----------------------------------------------------------------------------- + +# "featureName" property - name of the feature +featureName=CDT Visualizer Framework + +# "providerName" property - name of the company that provides the feature +providerName=Eclipse CDT + +# "updateSiteName" property - label for the update site +updateSiteName=Eclipse CDT Update Site + +# "description" property - description of the feature +description=Visualizer View and Framework that allows to build custom visualizers. + +# copyright +copyright=\ +Copyright (c) 2012 Tilera Corporation and others.\n\ +All rights reserved. This program and the accompanying materials\n\ +are made available under the terms of the Eclipse Public License v1.0\n\ +which accompanies this distribution, and is available at\n\ +http://www.eclipse.org/legal/epl-v10.html + +# "licenseURL" property - URL of the "Feature License" +# do not translate value - just change to point to a locale-specific HTML page +licenseURL=license.html + +# "license" property - text of the "Feature Update License" +# should be plain text version of license agreement pointed to be "licenseURL" +license=\ +Eclipse Foundation Software User Agreement\n\ +February 1, 2011\n\ +\n\ +Usage Of Content\n\ +\n\ +THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR\n\ +OTHER MATERIALS FOR OPEN SOURCE PROJECTS (COLLECTIVELY "CONTENT").\n\ +USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS\n\ +AGREEMENT AND/OR THE TERMS AND CONDITIONS OF LICENSE AGREEMENTS OR\n\ +NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU\n\ +AGREE THAT YOUR USE OF THE CONTENT IS GOVERNED BY THIS AGREEMENT\n\ +AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS\n\ +OR NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE\n\ +TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND CONDITIONS\n\ +OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED\n\ +BELOW, THEN YOU MAY NOT USE THE CONTENT.\n\ +\n\ +Applicable Licenses\n\ +\n\ +Unless otherwise indicated, all Content made available by the\n\ +Eclipse Foundation is provided to you under the terms and conditions of\n\ +the Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is\n\ +provided with this Content and is also available at http://www.eclipse.org/legal/epl-v10.html.\n\ +For purposes of the EPL, "Program" will mean the Content.\n\ +\n\ +Content includes, but is not limited to, source code, object code,\n\ +documentation and other files maintained in the Eclipse Foundation source code\n\ +repository ("Repository") in software modules ("Modules") and made available\n\ +as downloadable archives ("Downloads").\n\ +\n\ + - Content may be structured and packaged into modules to facilitate delivering,\n\ + extending, and upgrading the Content. Typical modules may include plug-ins ("Plug-ins"),\n\ + plug-in fragments ("Fragments"), and features ("Features").\n\ + - Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java(TM) ARchive)\n\ + in a directory named "plugins".\n\ + - A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material.\n\ + Each Feature may be packaged as a sub-directory in a directory named "features".\n\ + Within a Feature, files named "feature.xml" may contain a list of the names and version\n\ + numbers of the Plug-ins and/or Fragments associated with that Feature.\n\ + - Features may also include other Features ("Included Features"). Within a Feature, files\n\ + named "feature.xml" may contain a list of the names and version numbers of Included Features.\n\ +\n\ +The terms and conditions governing Plug-ins and Fragments should be\n\ +contained in files named "about.html" ("Abouts"). The terms and\n\ +conditions governing Features and Included Features should be contained\n\ +in files named "license.html" ("Feature Licenses"). Abouts and Feature\n\ +Licenses may be located in any directory of a Download or Module\n\ +including, but not limited to the following locations:\n\ +\n\ + - The top-level (root) directory\n\ + - Plug-in and Fragment directories\n\ + - Inside Plug-ins and Fragments packaged as JARs\n\ + - Sub-directories of the directory named "src" of certain Plug-ins\n\ + - Feature directories\n\ +\n\ +Note: if a Feature made available by the Eclipse Foundation is installed using the\n\ +Provisioning Technology (as defined below), you must agree to a license ("Feature \n\ +Update License") during the installation process. If the Feature contains\n\ +Included Features, the Feature Update License should either provide you\n\ +with the terms and conditions governing the Included Features or inform\n\ +you where you can locate them. Feature Update Licenses may be found in\n\ +the "license" property of files named "feature.properties" found within a Feature.\n\ +Such Abouts, Feature Licenses, and Feature Update Licenses contain the\n\ +terms and conditions (or references to such terms and conditions) that\n\ +govern your use of the associated Content in that directory.\n\ +\n\ +THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER\n\ +TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS.\n\ +SOME OF THESE OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):\n\ +\n\ + - Eclipse Distribution License Version 1.0 (available at http://www.eclipse.org/licenses/edl-v1.0.html)\n\ + - Common Public License Version 1.0 (available at http://www.eclipse.org/legal/cpl-v10.html)\n\ + - Apache Software License 1.1 (available at http://www.apache.org/licenses/LICENSE)\n\ + - Apache Software License 2.0 (available at http://www.apache.org/licenses/LICENSE-2.0)\n\ + - Metro Link Public License 1.00 (available at http://www.opengroup.org/openmotif/supporters/metrolink/license.html)\n\ + - Mozilla Public License Version 1.1 (available at http://www.mozilla.org/MPL/MPL-1.1.html)\n\ +\n\ +IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR\n\ +TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License\n\ +is provided, please contact the Eclipse Foundation to determine what terms and conditions\n\ +govern that particular Content.\n\ +\n\ +\n\Use of Provisioning Technology\n\ +\n\ +The Eclipse Foundation makes available provisioning software, examples of which include,\n\ +but are not limited to, p2 and the Eclipse Update Manager ("Provisioning Technology") for\n\ +the purpose of allowing users to install software, documentation, information and/or\n\ +other materials (collectively "Installable Software"). This capability is provided with\n\ +the intent of allowing such users to install, extend and update Eclipse-based products.\n\ +Information about packaging Installable Software is available at\n\ +http://eclipse.org/equinox/p2/repository_packaging.html ("Specification").\n\ +\n\ +You may use Provisioning Technology to allow other parties to install Installable Software.\n\ +You shall be responsible for enabling the applicable license agreements relating to the\n\ +Installable Software to be presented to, and accepted by, the users of the Provisioning Technology\n\ +in accordance with the Specification. By using Provisioning Technology in such a manner and\n\ +making it available in accordance with the Specification, you further acknowledge your\n\ +agreement to, and the acquisition of all necessary rights to permit the following:\n\ +\n\ + 1. A series of actions may occur ("Provisioning Process") in which a user may execute\n\ + the Provisioning Technology on a machine ("Target Machine") with the intent of installing,\n\ + extending or updating the functionality of an Eclipse-based product.\n\ + 2. During the Provisioning Process, the Provisioning Technology may cause third party\n\ + Installable Software or a portion thereof to be accessed and copied to the Target Machine.\n\ + 3. Pursuant to the Specification, you will provide to the user the terms and conditions that\n\ + govern the use of the Installable Software ("Installable Software Agreement") and such\n\ + Installable Software Agreement shall be accessed from the Target Machine in accordance\n\ + with the Specification. Such Installable Software Agreement must inform the user of the\n\ + terms and conditions that govern the Installable Software and must solicit acceptance by\n\ + the end user in the manner prescribed in such Installable Software Agreement. Upon such\n\ + indication of agreement by the user, the provisioning Technology will complete installation\n\ + of the Installable Software.\n\ +\n\ +Cryptography\n\ +\n\ +Content may contain encryption software. The country in which you are\n\ +currently may have restrictions on the import, possession, and use,\n\ +and/or re-export to another country, of encryption software. BEFORE\n\ +using any encryption software, please check the country's laws,\n\ +regulations and policies concerning the import, possession, or use, and\n\ +re-export of encryption software, to see if this is permitted.\n\ +\n\ +Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both.\n +########### end of license property ########################################## diff --git a/visualizer/org.eclipse.cdt.visualizer-feature/feature.xml b/visualizer/org.eclipse.cdt.visualizer-feature/feature.xml new file mode 100755 index 00000000000..532b8663439 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer-feature/feature.xml @@ -0,0 +1,34 @@ + + + + + %description + + + + %copyright + + + + %license + + + + + + + diff --git a/visualizer/org.eclipse.cdt.visualizer-feature/license.html b/visualizer/org.eclipse.cdt.visualizer-feature/license.html new file mode 100644 index 00000000000..f19c483b9c8 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer-feature/license.html @@ -0,0 +1,108 @@ + + + + + +Eclipse Foundation Software User Agreement + + + +

Eclipse Foundation Software User Agreement

+

February 1, 2011

+ +

Usage Of Content

+ +

THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR OTHER MATERIALS FOR OPEN SOURCE PROJECTS + (COLLECTIVELY "CONTENT"). USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS AGREEMENT AND/OR THE TERMS AND + CONDITIONS OF LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU AGREE THAT YOUR USE + OF THE CONTENT IS GOVERNED BY THIS AGREEMENT AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR + NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND + CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW, THEN YOU MAY NOT USE THE CONTENT.

+ +

Applicable Licenses

+ +

Unless otherwise indicated, all Content made available by the Eclipse Foundation is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 + ("EPL"). A copy of the EPL is provided with this Content and is also available at http://www.eclipse.org/legal/epl-v10.html. + For purposes of the EPL, "Program" will mean the Content.

+ +

Content includes, but is not limited to, source code, object code, documentation and other files maintained in the Eclipse Foundation source code + repository ("Repository") in software modules ("Modules") and made available as downloadable archives ("Downloads").

+ +
    +
  • Content may be structured and packaged into modules to facilitate delivering, extending, and upgrading the Content. Typical modules may include plug-ins ("Plug-ins"), plug-in fragments ("Fragments"), and features ("Features").
  • +
  • Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java™ ARchive) in a directory named "plugins".
  • +
  • A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material. Each Feature may be packaged as a sub-directory in a directory named "features". Within a Feature, files named "feature.xml" may contain a list of the names and version numbers of the Plug-ins + and/or Fragments associated with that Feature.
  • +
  • Features may also include other Features ("Included Features"). Within a Feature, files named "feature.xml" may contain a list of the names and version numbers of Included Features.
  • +
+ +

The terms and conditions governing Plug-ins and Fragments should be contained in files named "about.html" ("Abouts"). The terms and conditions governing Features and +Included Features should be contained in files named "license.html" ("Feature Licenses"). Abouts and Feature Licenses may be located in any directory of a Download or Module +including, but not limited to the following locations:

+ +
    +
  • The top-level (root) directory
  • +
  • Plug-in and Fragment directories
  • +
  • Inside Plug-ins and Fragments packaged as JARs
  • +
  • Sub-directories of the directory named "src" of certain Plug-ins
  • +
  • Feature directories
  • +
+ +

Note: if a Feature made available by the Eclipse Foundation is installed using the Provisioning Technology (as defined below), you must agree to a license ("Feature Update License") during the +installation process. If the Feature contains Included Features, the Feature Update License should either provide you with the terms and conditions governing the Included Features or +inform you where you can locate them. Feature Update Licenses may be found in the "license" property of files named "feature.properties" found within a Feature. +Such Abouts, Feature Licenses, and Feature Update Licenses contain the terms and conditions (or references to such terms and conditions) that govern your use of the associated Content in +that directory.

+ +

THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS. SOME OF THESE +OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):

+ + + +

IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License is provided, please +contact the Eclipse Foundation to determine what terms and conditions govern that particular Content.

+ + +

Use of Provisioning Technology

+ +

The Eclipse Foundation makes available provisioning software, examples of which include, but are not limited to, p2 and the Eclipse + Update Manager ("Provisioning Technology") for the purpose of allowing users to install software, documentation, information and/or + other materials (collectively "Installable Software"). This capability is provided with the intent of allowing such users to + install, extend and update Eclipse-based products. Information about packaging Installable Software is available at http://eclipse.org/equinox/p2/repository_packaging.html + ("Specification").

+ +

You may use Provisioning Technology to allow other parties to install Installable Software. You shall be responsible for enabling the + applicable license agreements relating to the Installable Software to be presented to, and accepted by, the users of the Provisioning Technology + in accordance with the Specification. By using Provisioning Technology in such a manner and making it available in accordance with the + Specification, you further acknowledge your agreement to, and the acquisition of all necessary rights to permit the following:

+ +
    +
  1. A series of actions may occur ("Provisioning Process") in which a user may execute the Provisioning Technology + on a machine ("Target Machine") with the intent of installing, extending or updating the functionality of an Eclipse-based + product.
  2. +
  3. During the Provisioning Process, the Provisioning Technology may cause third party Installable Software or a portion thereof to be + accessed and copied to the Target Machine.
  4. +
  5. Pursuant to the Specification, you will provide to the user the terms and conditions that govern the use of the Installable + Software ("Installable Software Agreement") and such Installable Software Agreement shall be accessed from the Target + Machine in accordance with the Specification. Such Installable Software Agreement must inform the user of the terms and conditions that govern + the Installable Software and must solicit acceptance by the end user in the manner prescribed in such Installable Software Agreement. Upon such + indication of agreement by the user, the provisioning Technology will complete installation of the Installable Software.
  6. +
+ +

Cryptography

+ +

Content may contain encryption software. The country in which you are currently may have restrictions on the import, possession, and use, and/or re-export to + another country, of encryption software. BEFORE using any encryption software, please check the country's laws, regulations and policies concerning the import, + possession, or use, and re-export of encryption software, to see if this is permitted.

+ +

Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both.

+ + diff --git a/visualizer/org.eclipse.cdt.visualizer-feature/pom.xml b/visualizer/org.eclipse.cdt.visualizer-feature/pom.xml new file mode 100644 index 00000000000..9dc4a21f830 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer-feature/pom.xml @@ -0,0 +1,18 @@ + + + 4.0.0 + + + org.eclipse.cdt + cdt-parent + 8.1.0-SNAPSHOT + ../../pom.xml + + + org.eclipse.cdt.features + 1.0.0-SNAPSHOT + org.eclipse.cdt.visualizer + eclipse-feature + diff --git a/visualizer/org.eclipse.cdt.visualizer.core/.classpath b/visualizer/org.eclipse.cdt.visualizer.core/.classpath new file mode 100755 index 00000000000..31db9a91174 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.core/.classpath @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/visualizer/org.eclipse.cdt.visualizer.core/.project b/visualizer/org.eclipse.cdt.visualizer.core/.project new file mode 100755 index 00000000000..77747f8e3ea --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.core/.project @@ -0,0 +1,28 @@ + + + org.eclipse.cdt.visualizer.core + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/visualizer/org.eclipse.cdt.visualizer.core/.settings/org.eclipse.jdt.core.prefs b/visualizer/org.eclipse.cdt.visualizer.core/.settings/org.eclipse.jdt.core.prefs new file mode 100755 index 00000000000..743b93d39ff --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.core/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Fri Jul 01 09:20:33 EDT 2011 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/visualizer/org.eclipse.cdt.visualizer.core/ABOUT.txt b/visualizer/org.eclipse.cdt.visualizer.core/ABOUT.txt new file mode 100755 index 00000000000..ad3ea21360a --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.core/ABOUT.txt @@ -0,0 +1,17 @@ +# ============================================================================= +# Copyright (c) 2012 Tilera 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 +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# William R. Swanson (Tilera Corporation) +# ============================================================================= + +This plugin defines the non-UI components of the CDT Visualizer feature. + +For an overview of the Visualizer feature, see the following file: + + /org.eclipse.cdt.visualizer-feature/ABOUT.txt. + \ No newline at end of file diff --git a/visualizer/org.eclipse.cdt.visualizer.core/META-INF/MANIFEST.MF b/visualizer/org.eclipse.cdt.visualizer.core/META-INF/MANIFEST.MF new file mode 100755 index 00000000000..6fec5fa40a4 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.core/META-INF/MANIFEST.MF @@ -0,0 +1,15 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: %plugin.name +Bundle-SymbolicName: org.eclipse.cdt.visualizer.core;singleton:=true +Bundle-Version: 1.0.0.qualifier +Bundle-Activator: org.eclipse.cdt.visualizer.core.plugin.CDTVisualizerCorePlugin +Bundle-Vendor: %provider.name +Require-Bundle: org.eclipse.ui, + org.eclipse.core.runtime, + org.eclipse.core.resources +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Bundle-ActivationPolicy: lazy +Bundle-Localization: plugin +Export-Package: org.eclipse.cdt.visualizer.core, + org.eclipse.cdt.visualizer.core.plugin diff --git a/visualizer/org.eclipse.cdt.visualizer.core/about.html b/visualizer/org.eclipse.cdt.visualizer.core/about.html new file mode 100644 index 00000000000..cb740ae8bc8 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.core/about.html @@ -0,0 +1,24 @@ + + + + +About +

About This Content

+ +

June 5, 2007

+

License

+ +

The Eclipse Foundation makes available all content in this plug-in ("Content"). Unless otherwise +indicated below, the Content is provided to you under the terms and conditions of the +Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available +at http://www.eclipse.org/legal/epl-v10.html. +For purposes of the EPL, "Program" will mean the Content.

+ +

If you did not receive this Content directly from the Eclipse Foundation, the Content is +being redistributed by another party ("Redistributor") and different terms and conditions may +apply to your use of any object code in the Content. Check the Redistributor's license that was +provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise +indicated below, the terms and conditions of the EPL still apply to any source code in the Content +and such source code may be obtained at http://www.eclipse.org.

+ + \ No newline at end of file diff --git a/visualizer/org.eclipse.cdt.visualizer.core/build.properties b/visualizer/org.eclipse.cdt.visualizer.core/build.properties new file mode 100755 index 00000000000..07409e935ad --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.core/build.properties @@ -0,0 +1,17 @@ +############################################################################### +# Copyright (c) 2012 Tilera 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 +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# William R. Swanson (Tilera Corporation) +############################################################################### +source.. = src/,\ + resources/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + plugin.properties,\ + about.html \ No newline at end of file diff --git a/visualizer/org.eclipse.cdt.visualizer.core/plugin.properties b/visualizer/org.eclipse.cdt.visualizer.core/plugin.properties new file mode 100644 index 00000000000..43181240cd1 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.core/plugin.properties @@ -0,0 +1,17 @@ +# ============================================================================= +# Copyright (c) 2012 Tilera 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 +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# William R. Swanson (Tilera Corporation) +# ============================================================================= + +# ----------------------------------------------------------------------------- +# Plugin string resources +# ----------------------------------------------------------------------------- + +plugin.name=CDT Visualizer Core Plug-in +provider.name=Eclipse CDT diff --git a/visualizer/org.eclipse.cdt.visualizer.core/pom.xml b/visualizer/org.eclipse.cdt.visualizer.core/pom.xml new file mode 100644 index 00000000000..bde189daa95 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.core/pom.xml @@ -0,0 +1,17 @@ + + + 4.0.0 + + + org.eclipse.cdt + cdt-parent + 8.1.0-SNAPSHOT + ../../pom.xml + + + 1.0.0-SNAPSHOT + org.eclipse.cdt.visualizer.core + eclipse-plugin + diff --git a/visualizer/org.eclipse.cdt.visualizer.core/resources/messages.properties b/visualizer/org.eclipse.cdt.visualizer.core/resources/messages.properties new file mode 100644 index 00000000000..70fa2ec9226 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.core/resources/messages.properties @@ -0,0 +1,14 @@ +# ============================================================================= +# Copyright (c) 2012 Tilera 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 +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# William R. Swanson (Tilera Corporation) +# ============================================================================= + +# ----------------------------------------------------------------------------- +# Application string resources +# ----------------------------------------------------------------------------- diff --git a/visualizer/org.eclipse.cdt.visualizer.core/src/org/eclipse/cdt/visualizer/core/Extension.java b/visualizer/org.eclipse.cdt.visualizer.core/src/org/eclipse/cdt/visualizer/core/Extension.java new file mode 100644 index 00000000000..10aac2651c2 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.core/src/org/eclipse/cdt/visualizer/core/Extension.java @@ -0,0 +1,92 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.core; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IExtensionPoint; +import org.eclipse.core.runtime.Platform; + + +// --------------------------------------------------------------------------- +// Extension +// --------------------------------------------------------------------------- + +/** Facade/utility class for dealing with Eclipse extensions. */ +public class Extension extends ExtensionElement +{ + // --- static methods --- + + /** Gets extension point declaration with specified full ID (including plugin ID prefix). */ + public static IExtensionPoint getExtensionPoint(String extensionPointID) + { + IExtensionPoint extensionPoint = + Platform.getExtensionRegistry().getExtensionPoint( + extensionPointID); + return extensionPoint; + } + + /** Gets extension point declaration with specified name defined by specified plugin. */ + public static IExtensionPoint getExtensionPoint(String pluginID, String extensionPointName) + { + IExtensionPoint extensionPoint = + Platform.getExtensionRegistry().getExtensionPoint( + pluginID, extensionPointName); + return extensionPoint; + } + + /** Gets list of extensions for specified extension point ID (including plugin ID prefix). */ + public static List getExtensions(String extensionPointID) + { + IExtensionPoint extensionPoint = getExtensionPoint(extensionPointID); + return getExtensions(extensionPoint); + } + + /** Gets list of extensions for specified plugin and extension point name. */ + public static List getExtensions(String pluginID, String extensionPointName) + { + IExtensionPoint extensionPoint = getExtensionPoint(pluginID, extensionPointName); + return getExtensions(extensionPoint); + } + + /** Gets list of extensions for specified plugin and extension point name. */ + public static List getExtensions(IExtensionPoint extensionPoint) + { + return (extensionPoint == null) ? null : + Extension.wrapExtensions(extensionPoint.getConfigurationElements()); + } + + /** Wraps list of raw extension declarations. */ + public static List wrapExtensions(IConfigurationElement[] elements) + { + int count = (elements == null) ? 0 : elements.length; + List result = new ArrayList(count); + for (int i=0; i wrapExtensionElements(IConfigurationElement[] elements) + { + int count = (elements == null) ? 0 : elements.length; + List result = new ArrayList(count); + for (int i=0; i T getClassAttribute() + { + return getClassAttribute("class"); + } + + /** Creates and returns instance of implementing class, using class name found in specified attribute. */ + @SuppressWarnings("unchecked") + public T getClassAttribute(String attributeName) + { + T result = null; + try { + // TODO: Hmm... is there a right way to do this, without an unchecked cast? + result = (T) m_element.createExecutableExtension(attributeName); + } + catch (ClassCastException ex) { + // For now, eat it, and don't return this extension. + // TODO: decide how to log this + } + catch (CoreException ex) { + // For now, eat it, and don't return this extension. + // TODO: decide how to log this + } + return result; + } + + /** Creates and returns instance of implementing class, using class name found in specified attribute. */ + @SuppressWarnings("unchecked") + public T getClassAttribute(String attributeName, Object... arguments) + { + // Make sure we default to zero-argument form if we can. + if (arguments == null || arguments.length == 0) + return getClassAttribute(attributeName); + + // If we have arguments, have to do a little extra work. + T result = null; + try { + // Get name of class we're trying to load from attribute. + String className = getAttribute(attributeName); + + // Attempt to load class using the source plugin's class loader. + // TODO: is there a better way? + IContributor contributor = m_element.getContributor(); + String pluginID = contributor.getName(); + Bundle plugin = Platform.getBundle(pluginID); + Class instance = plugin.loadClass(className); + + // Select appropriate constructor for provided argument(s). + int argumentsLength = (arguments == null) ? 0 : arguments.length; + Class[] argumentTypes = new Class[argumentsLength]; + for (int i=0; i constructor = (Constructor) + instance.getConstructor(argumentTypes); + + // Invoke the constructor. + result = (T) constructor.newInstance(arguments); + } + catch (ClassNotFoundException ex) { + // TODO: decide how to log this + } + catch (NoSuchMethodException ex) { + // TODO: decide how to log this + } + catch (InvocationTargetException ex) { + // TODO: decide how to log this + } + catch (IllegalAccessException ex) { + // TODO: decide how to log this + } + catch (InstantiationException ex) { + // TODO: decide how to log this + } + catch (ClassCastException ex) { + // TODO: decide how to log this + } + catch (Exception ex) { + // TODO: decide how to log this + } + return result; + } + + /** Returns child elements of this element. */ + public List getChildren() + { + return wrapExtensionElements(m_element.getChildren()); + } +} diff --git a/visualizer/org.eclipse.cdt.visualizer.core/src/org/eclipse/cdt/visualizer/core/ResourceManager.java b/visualizer/org.eclipse.cdt.visualizer.core/src/org/eclipse/cdt/visualizer/core/ResourceManager.java new file mode 100755 index 00000000000..91e4c54377f --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.core/src/org/eclipse/cdt/visualizer/core/ResourceManager.java @@ -0,0 +1,195 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.core; + +import java.text.MessageFormat; +import java.util.Locale; +import java.util.MissingResourceException; +import java.util.ResourceBundle; + +import org.eclipse.core.runtime.Plugin; + + +// --------------------------------------------------------------------------- +// ResourceManager +// --------------------------------------------------------------------------- + +/** + * Plugin resource manager. + * This class should be instanced in the plugin's "start()" method, + * and disposed in the "stop()" method. + */ +public class ResourceManager{ + + // --- members --- + + /** Plugin ID */ + protected String m_pluginID = null; + + /** Plugin */ + protected Plugin m_plugin = null; + + /** Parent resource manager, if any */ + protected ResourceManager m_parentManager = null; + + /** String resource manager */ + protected ResourceBundle m_stringResources = null; + + /** String resource property file name */ + protected String m_stringResourceFilename = null; + + + // --- constructors/destructors --- + + /** + * Constructor, + * Assumes string resources are in the file "messages.properties". + */ + public ResourceManager(Plugin plugin) { + this(plugin, "messages.properties"); + } + + /** Constructor */ + public ResourceManager(Plugin plugin, String stringResourceFilename) { + m_pluginID = plugin.getBundle().getSymbolicName(); + m_plugin = plugin; + m_stringResourceFilename = stringResourceFilename; + getStringRegistry(); // creates registry object + } + + /** Dispose method */ + public void dispose() { + disposeStringRegistry(); + m_stringResourceFilename = null; + m_plugin = null; + m_pluginID = null; + } + + + // --- accessors --- + + /** Returns plugin we're associated with */ + public Plugin getPlugin() { + return m_plugin; + } + + + // --- parent manager management --- + + /** Sets parent resource manager, if any */ + public void setParentManager(ResourceManager parentManager) { + m_parentManager = parentManager; + } + + /** Gets parent resource manager, if any */ + public ResourceManager getParentManager() { + return m_parentManager; + } + + + // --- string resource management --- + + /** Creates/returns string registry */ + protected ResourceBundle getStringRegistry() { + if (m_stringResources == null) { + String filename = m_stringResourceFilename; + + // The ".properties" extension is assumed, so we trim it here + String propertiesExtension = ".properties"; + if (filename.endsWith(propertiesExtension)) { + filename = filename.substring(0, filename.length() - + propertiesExtension.length()); + } + + // NOTE: We have to be careful to pick up the class loader + // from the plugin class, otherwise we default to the classloader + // of the ResourceManager class, which is the classloader + // for the plugin the ResourceManager comes from. + ClassLoader classLoader = m_plugin.getClass().getClassLoader(); + Locale locale = Locale.getDefault(); + + // we'll check for .properties file first + // in the same directory as the plugin activator class + String propertyFileName1 = m_pluginID + ".plugin." + filename; + try { + m_stringResources = + ResourceBundle.getBundle(propertyFileName1, + locale, classLoader); + } + catch (MissingResourceException e) { + // TODO: log this exception (probably a .properties file is missing) + m_stringResources = null; + } + + // if not found, we try in the default package + // (that is, the top-level "src" or "resources" folder) + String propertyFileName2 = filename; + if (m_stringResources == null) { + try { + m_stringResources = + ResourceBundle.getBundle(propertyFileName2, + locale, classLoader); + } + catch (MissingResourceException e) { + // TODO: log this exception (probably a .properties file is missing) + m_stringResources = null; + } + } + } + return m_stringResources; + } + + /** Disposes of string registry */ + protected void disposeStringRegistry() { + m_stringResources = null; + } + + /** Returns string resource for specified key */ + public String getString(String key) { + String result = null; + if (key == null) return "(null resource)"; + + // get string registry, look up key + ResourceBundle strings = getStringRegistry(); + if (strings == null) { + // if we can't get the registry, display the key instead, + // so we know what's missing (e.g. the .properties file) + result = "(" + key + ")"; + } + else { + try { + result = strings.getString(key); + } + catch (MissingResourceException e) { + // we fail, but don't throw an exception + // so we don't screw any UI setup that depends + // on this string resource + result = null; + } + } + + // if we fail, try the parent manager if there is one + if (result == null && m_parentManager != null) { + result = m_parentManager.getString(key); + } + + // if we still fail, display the key instead, + // so we know what's missing + if (result == null) result = "[" + key + "]"; + return result; + } + + /** Formats string resource with specified argument(s) */ + public String getString(String key, Object... arguments) { + return MessageFormat.format(getString(key), arguments); + } +} diff --git a/visualizer/org.eclipse.cdt.visualizer.core/src/org/eclipse/cdt/visualizer/core/plugin/CDTVisualizerCorePlugin.java b/visualizer/org.eclipse.cdt.visualizer.core/src/org/eclipse/cdt/visualizer/core/plugin/CDTVisualizerCorePlugin.java new file mode 100755 index 00000000000..5b6b7e44881 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.core/src/org/eclipse/cdt/visualizer/core/plugin/CDTVisualizerCorePlugin.java @@ -0,0 +1,126 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.core.plugin; + +import org.eclipse.cdt.visualizer.core.ResourceManager; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.Status; +import org.eclipse.ui.plugin.AbstractUIPlugin; +import org.osgi.framework.BundleContext; + + +// ---------------------------------------------------------------------------- +// CDTVisualizerCorePlugin +// ---------------------------------------------------------------------------- + +/** + * CDT visualizer core plugin class. + * + * This plugin contains the non-UI components of the visualizer framework. + */ +public class CDTVisualizerCorePlugin extends AbstractUIPlugin +{ + // --- constants --- + + /** The plug-in ID */ + public static final String PLUGIN_ID = "org.eclipse.cdt.visualizer.core"; //$NON-NLS-1$ + + + // --- static members --- + + /** Singleton instance */ + protected static CDTVisualizerCorePlugin s_plugin; + + /** Returns the singleton instance */ + public static CDTVisualizerCorePlugin getDefault() { + return s_plugin; + } + + /** Resource manager */ + protected static ResourceManager s_resources = null; + + + // --- constructors/destructors --- + + /** Constructor */ + public CDTVisualizerCorePlugin() { + } + + + // --- plugin startup/shutdown methods --- + + /** Invoked when plugin is loaded. */ + public void start(BundleContext context) throws Exception { + super.start(context); + s_plugin = this; + + // touch activator classes of any plugins we depend on, + // to ensure their start() methods are called first + // (None for now.) + + // initialize resource management (strings, images, fonts, colors, etc.) + getPluginResources(); + } + + /** Invoked when plugin is stopped. */ + public void stop(BundleContext context) throws Exception { + // clean up resource management + cleanupPluginResources(); + + s_plugin = null; + super.stop(context); + } + + + // --- logging --- + + /** + * Writes message to Eclipse log. + * Severity can be one of: + * Status.OK, Status.ERROR, Status.INFO, Status.WARNING, Status.CANCEL + */ + public static void log(int severity, String text) + { + Status status = new Status(severity, PLUGIN_ID, text); + ResourcesPlugin.getPlugin().getLog().log(status); + } + + + // --- resource management --- + + /** Returns resource manager for this plugin */ + public ResourceManager getPluginResources() { + if (s_resources == null) { + s_resources = new ResourceManager(this); + } + return s_resources; + } + + /** Releases resource manager for this plugin. */ + public void cleanupPluginResources() { + s_resources.dispose(); + } + + /** Convenience method for getting plugin resource manager */ + public static ResourceManager getResources() { + return getDefault().getPluginResources(); + } + + /** Convenience method for looking up string resources */ + public static String getString(String key) { + return getDefault().getPluginResources().getString(key); + } + /** Convenience method for looking up string resources */ + public static String getString(String key, Object... arguments) { + return getDefault().getPluginResources().getString(key, arguments); + } +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/.classpath b/visualizer/org.eclipse.cdt.visualizer.ui/.classpath new file mode 100755 index 00000000000..31db9a91174 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/.classpath @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/.project b/visualizer/org.eclipse.cdt.visualizer.ui/.project new file mode 100755 index 00000000000..a76968ea1d3 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/.project @@ -0,0 +1,28 @@ + + + org.eclipse.cdt.visualizer.ui + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/.settings/org.eclipse.jdt.core.prefs b/visualizer/org.eclipse.cdt.visualizer.ui/.settings/org.eclipse.jdt.core.prefs new file mode 100755 index 00000000000..a2d0967c487 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Fri Jul 01 09:07:15 EDT 2011 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/ABOUT.txt b/visualizer/org.eclipse.cdt.visualizer.ui/ABOUT.txt new file mode 100755 index 00000000000..ed483c41987 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/ABOUT.txt @@ -0,0 +1,17 @@ +# ============================================================================= +# Copyright (c) 2012 Tilera 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 +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# William R. Swanson (Tilera Corporation) +# ============================================================================= + +This plugin defines the UI components of the CDT Visualizer feature. + +For an overview of the Visualizer feature, see the following file: + + /org.eclipse.cdt.visualizer-feature/ABOUT.txt. + diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/META-INF/MANIFEST.MF b/visualizer/org.eclipse.cdt.visualizer.ui/META-INF/MANIFEST.MF new file mode 100755 index 00000000000..baacda0774b --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/META-INF/MANIFEST.MF @@ -0,0 +1,20 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: %plugin.name +Bundle-SymbolicName: org.eclipse.cdt.visualizer.ui;singleton:=true +Bundle-Version: 1.0.0.qualifier +Bundle-Activator: org.eclipse.cdt.visualizer.ui.plugin.CDTVisualizerUIPlugin +Bundle-Vendor: %provider.name +Require-Bundle: org.eclipse.ui, + org.eclipse.core.runtime, + org.eclipse.cdt.visualizer.core, + org.eclipse.core.resources +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Bundle-ActivationPolicy: lazy +Bundle-Localization: plugin +Export-Package: org.eclipse.cdt.visualizer.ui, + org.eclipse.cdt.visualizer.ui.canvas, + org.eclipse.cdt.visualizer.ui.events, + org.eclipse.cdt.visualizer.ui.plugin, + org.eclipse.cdt.visualizer.ui.test, + org.eclipse.cdt.visualizer.ui.util diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/about.html b/visualizer/org.eclipse.cdt.visualizer.ui/about.html new file mode 100644 index 00000000000..cb740ae8bc8 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/about.html @@ -0,0 +1,24 @@ + + + + +About +

About This Content

+ +

June 5, 2007

+

License

+ +

The Eclipse Foundation makes available all content in this plug-in ("Content"). Unless otherwise +indicated below, the Content is provided to you under the terms and conditions of the +Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available +at http://www.eclipse.org/legal/epl-v10.html. +For purposes of the EPL, "Program" will mean the Content.

+ +

If you did not receive this Content directly from the Eclipse Foundation, the Content is +being redistributed by another party ("Redistributor") and different terms and conditions may +apply to your use of any object code in the Content. Check the Redistributor's license that was +provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise +indicated below, the terms and conditions of the EPL still apply to any source code in the Content +and such source code may be obtained at http://www.eclipse.org.

+ + \ No newline at end of file diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/build.properties b/visualizer/org.eclipse.cdt.visualizer.ui/build.properties new file mode 100755 index 00000000000..cd7654a8664 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/build.properties @@ -0,0 +1,23 @@ +############################################################################### +# Copyright (c) 2012 Tilera 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 +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# William R. Swanson (Tilera Corporation) +############################################################################### +source.. = src/,\ + resources/ +src.includes = schema/,\ + about.html +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + plugin.properties,\ + about.html,\ + icons/,\ + plugin.xml +src.includes = about.html + \ No newline at end of file diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/icons/full/view16/visualizer_view.png b/visualizer/org.eclipse.cdt.visualizer.ui/icons/full/view16/visualizer_view.png new file mode 100755 index 0000000000000000000000000000000000000000..c7d0e9f44a5ba8ee321d865e6a3a676edd8af99b GIT binary patch literal 2921 zcmV-v3zqbWP)KLZ*U+IBfRsybQWXdwQbLP>6pAqfylh#{fb6;Z(vMMVS~$e@S=j*ftg6;Uhf59&ghTmgWD0l;*T zI709Y^p6lP1rIRMx#05C~cW=H_Aw*bJ-5DT&Z2n+x)QHX^p z00esgV8|mQcmRZ%02D^@S3L16t`O%c004NIvOKvYIYoh62rY33S640`D9%Y2D-rV&neh&#Q1i z007~1e$oCcFS8neI|hJl{-P!B1ZZ9hpmq0)X0i`JwE&>$+E?>%_LC6RbVIkUx0b+_+BaR3cnT7Zv!AJxW zizFb)h!jyGOOZ85F;a?DAXP{m@;!0_IfqH8(HlgRxt7s3}k3K`kFu>>-2Q$QMFfPW!La{h336o>X zu_CMttHv6zR;&ZNiS=X8v3CR#fknUxHUxJ0uoBa_M6WNWeqIg~6QE69c9o#eyhGvpiOA@W-aonk<7r1(?fC{oI5N*U!4 zfg=2N-7=cNnjjOr{yriy6mMFgG#l znCF=fnQv8CDz++o6_Lscl}eQ+l^ZHARH>?_s@|##Rr6KLRFA1%Q+=*RRWnoLsR`7U zt5vFIcfW3@?wFpwUVxrVZ>QdQz32KIeJ}k~{cZZE^+ya? z2D1z#2HOnI7(B%_ac?{wFUQ;QQA1tBKtrWrm0_3Rgps+?Jfqb{jYbcQX~taRB;#$y zZN{S}1|}gUOHJxc?wV3fxuz+mJ4`!F$IZ;mqRrNsHJd##*D~ju=bP7?-?v~|cv>vB zsJ6IeNwVZxrdjT`yl#bBIa#GxRa#xMMy;K#CDyyGyQdMSxlWT#tDe?p!?5wT$+oGt z8L;Kp2HUQ-ZMJ=3XJQv;x5ci*?vuTfeY$;({XGW_huIFR9a(?@3)XSs8O^N5RyOM=TTmp(3=8^+zpz2r)C z^>JO{deZfso3oq3?Wo(Y?l$ge?uXo;%ru`Vo>?<<(8I_>;8Eq#KMS9gFl*neeosSB zfoHYnBQIkwkyowPu(zdms`p{<7e4kra-ZWq<2*OsGTvEV%s0Td$hXT+!*8Bnh2KMe zBmZRodjHV?r+_5^X9J0WL4jKW`}lf%A-|44I@@LTvf1rHjG(ze6+w@Jt%Bvjts!X0 z?2xS?_ve_-kiKB_KiJlZ$9G`c^=E@oNG)mWWaNo-3TIW8)$Hg0Ub-~8?KhvJ>$ z3*&nim@mj(aCxE5!t{lw7O5^0EIO7zOo&c6l<+|iDySBWCGrz@C5{St!X3hAA}`T4 z(TLbXTq+(;@<=L8dXnssyft|w#WSTW<++3>sgS%(4NTpeI-VAqb|7ssJvzNHgOZVu zaYCvgO_R1~>SyL=cFU|~g|hy|Zi}}s9+d~lYqOB71z9Z$wnC=pR9Yz4DhIM>Wmjgu z&56o6maCpC&F##y%G;1PobR9i?GnNg;gYtchD%p19a!eQtZF&3JaKv33gZ<8D~47E ztUS1iwkmDaPpj=$m#%)jCVEY4fnLGNg2A-`YwHVD3gv};>)hAvT~AmqS>Lr``i7kw zJ{5_It`yrBmlc25DBO7E8;5VoznR>Ww5hAaxn$2~(q`%A-YuS64wkBy=9dm`4cXeX z4c}I@?e+FW+b@^RDBHV(wnMq2zdX3SWv9u`%{xC-q*U}&`cyXV(%rRT*Z6MH?i+i& z_B8C(+grT%{XWUQ+f@NoP1R=AW&26{v-dx)iK^-Nmiuj8txj!m?Z*Ss1N{dh4z}01 z)YTo*JycSU)+_5r4#yw9{+;i4Ee$peRgIj+;v;ZGdF1K$3E%e~4LaI(jC-u%2h$&R z9cLXcYC@Xwnns&bn)_Q~Te?roKGD|d-g^8;+aC{{G(1^(O7m37Y1-+6)01cN&y1aw zoqc{T`P^XJqPBbIW6s}d4{z_f5Om?vMgNQEJG?v2T=KYd^0M3I6IZxbny)%vZR&LD zJpPl@Psh8QyPB@KTx+@RdcC!KX7}kEo;S|j^u2lU7XQ}Oo;f|;z4Ll+_r>@1-xl3| zawq-H%e&ckC+@AhPrP6BKT#_XdT7&;F71j}Joy zkC~6lh7E@6o;W@^IpRNZ{ptLtL(gQ-CY~4mqW;US7Zxvm_|@yz&e53Bp_lTPlfP|z zrTyx_>lv@x#=^!PzR7qqF<$gm`|ZJZ+;<)Cqu&ot2z=0000WV@Og>004R=004l4008;_004mL004C`008P>0026e000+nl3&F} z0001#Nkl zRH6*_8kpJ8_y)q)7V-yO_h{iQ9-!WW6BtgSPsY0gg$k~-0PrqdZy{~Myeyl;7V;4P z46+3LiD}suN!Zst+~;kUfHpGI^`C(ypb}PZtrAddK|$J=pGTE6WmZ#V0XYT$>1b~3 TT5Llw00000NkvXXu0mjfdW300 literal 0 HcmV?d00001 diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/plugin.properties b/visualizer/org.eclipse.cdt.visualizer.ui/plugin.properties new file mode 100644 index 00000000000..9e0a6a8cdc8 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/plugin.properties @@ -0,0 +1,19 @@ +# ============================================================================= +# Copyright (c) 2012 Tilera 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 +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# William R. Swanson (Tilera Corporation) +# ============================================================================= + +# ----------------------------------------------------------------------------- +# Plugin string resources +# ----------------------------------------------------------------------------- + +plugin.name=CDT Visualizer UI Plug-in +provider.name=Eclipse CDT + +view.visualizer.name=Visualizer diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/plugin.xml b/visualizer/org.eclipse.cdt.visualizer.ui/plugin.xml new file mode 100755 index 00000000000..5b5ea5e7d9c --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/plugin.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/pom.xml b/visualizer/org.eclipse.cdt.visualizer.ui/pom.xml new file mode 100644 index 00000000000..b52eb491215 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/pom.xml @@ -0,0 +1,17 @@ + + + 4.0.0 + + + org.eclipse.cdt + cdt-parent + 8.1.0-SNAPSHOT + ../../pom.xml + + + 1.0.0-SNAPSHOT + org.eclipse.cdt.visualizer.ui + eclipse-plugin + diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/resources/messages.properties b/visualizer/org.eclipse.cdt.visualizer.ui/resources/messages.properties new file mode 100644 index 00000000000..56de5d40b3b --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/resources/messages.properties @@ -0,0 +1,17 @@ +# ============================================================================= +# Copyright (c) 2012 Tilera 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 +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# William R. Swanson (Tilera Corporation) +# ============================================================================= + +# ----------------------------------------------------------------------------- +# Application string resources +# ----------------------------------------------------------------------------- + +# Visualizer viewer +VisualizerViewer.no.visualizers.defined=No visualizers defined. diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/schema/org.eclipse.cdt.visualizer.ui.visualizer.exsd b/visualizer/org.eclipse.cdt.visualizer.ui/schema/org.eclipse.cdt.visualizer.ui.visualizer.exsd new file mode 100644 index 00000000000..3f7e5e5f788 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/schema/org.eclipse.cdt.visualizer.ui.visualizer.exsd @@ -0,0 +1,123 @@ + + + + + + + + + [Enter description of this extension point.] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + IVisualizer type definition. + + + + + + + IVisualizer unique ID. + + + + + + + IVisualizer implementing class. + + + + + + + + + + + + + + + [Enter the first release in which this extension point appears.] + + + + + + + + + [Enter extension point usage example here.] + + + + + + + + + [Enter API information here.] + + + + + + + + + [Enter information about supplied implementation of this extension point.] + + + + + diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/IVisualizer.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/IVisualizer.java new file mode 100644 index 00000000000..7f5f63b84a3 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/IVisualizer.java @@ -0,0 +1,171 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui; + +import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.action.IToolBarManager; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; + + +// ---------------------------------------------------------------------------- +// IVisualizer +// ---------------------------------------------------------------------------- + +/** + * CDT Visualizer interface. + * + * An IVisualizer encapsulates a specific graphic presentation of the + * currently selected object (launch, target, etc.). + * + * It knows how to create a Control to draw on, which is displayed by + * the Visualizer Viewer, and also knows how to draw its presentation on + * that control. + * + * A visualizer can be generic (e.g. knows how to draw any kind of + * launch) or specific (e.g. specialized for a particular type of + * launch or execution target). The viewer automatically chooses + * the most specific IVisualizer that reports it is able to render + * the current selection. + */ +public interface IVisualizer + extends ISelectionProvider +{ + // --- init methods --- + + /** Invoked when visualizer is created, to permit any initialization. */ + public void initializeVisualizer(); + + /** Invoked when visualizer is disposed, to permit any cleanup. */ + public void disposeVisualizer(); + + + // --- accessors --- + + /** Sets non-localized name. */ + public void setName(String name); + /** Gets non-localized name. */ + + public String getName(); + + /** Sets localized display name. */ + public void setDisplayName(String displayName); + + /** Gets localized display name. */ + public String getDisplayName(); + + /** Sets localized description string. */ + public void setDescription(String description); + + /** Gets localized description string. */ + public String getDescription(); + + + // --- viewer management --- + + /** Called by viewer when visualizer is added to it. */ + public void setViewer(IVisualizerViewer viewer); + + /** Returns viewer control for this visualizer. */ + public IVisualizerViewer getViewer(); + + + // --- visualizer selection management --- + + /** Invoked when visualizer has been selected. */ + public void visualizerSelected(); + + /** Invoked when another visualizer has been selected, hiding this one. */ + public void visualizerDeselected(); + + + // --- control management --- + + /** Creates and returns visualizer's UI control on specified parent control. */ + public Control createControl(Composite parent); + + /** Gets visualizer control. + * Returns null if createControl() has not yet been called. + */ + public Control getControl(); + + + // --- menu/toolbar management --- + + /** + * Invoked when visualizer is selected, to populate the toolbar. + * The toolbar starts in a completely cleared state. + * The Visualizer can add/edit actions as desired. + * There is no need to invoke update on the toolbar, the viewer handles that. + */ + public void populateToolBar(IToolBarManager toolBarManager); + + /** + * Invoked when visualizer is selected, to populate the toolbar's menu. + * The toolbar starts in a completely cleared state. + * The Visualizer can add/edit actions as desired. + * There is no need to invoke update on the toolbar, the viewer handles that. + */ + public void populateMenu(IMenuManager menuManager); + + /** + * Invoked when visualizer view's context menu is invoked, to populate it. + * The toolbar starts in a completely cleared state. + * The Visualizer can add/edit actions as desired. + * There is no need to invoke update on the toolbar, the viewer handles that. + */ + public void populateContextMenu(IMenuManager menuManager); + + + // --- workbench selection management --- + + /** + * Tests whether if the IVisualizer can display the selection + * (or something reachable from it). + * + * Returns a positive "weight" if true, and zero otherwise. + * If multiple visualizers can handle a given selection, + * the one reporting the highest weight value "wins". + * In case of ties, an arbitrary visualizer is selected. + * + * The weight should reflect the specificity of the visualizer; + * in other words, a "default" visualization for a given selection + * should have a low weight, and a special case should have + * a higher weight; this allows the visualizer view to "fall back" + * to the default visualization in the general case. + */ + public int handlesSelection(ISelection selection); + + /** + * Invoked by VisualizerViewer when workbench selection changes. + */ + public void workbenchSelectionChanged(ISelection selection); + + + // --- selection changed event handling --- + + /** Adds external listener for selection change events. */ + public void addSelectionChangedListener(ISelectionChangedListener listener); + + /** Removes external listener for selection change events. */ + public void removeSelectionChangedListener(ISelectionChangedListener listener); + + /** Gets current externally-visible selection. */ + public ISelection getSelection(); + + /** Sets current externally-visible selection. */ + public void setSelection(ISelection selection); + +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/IVisualizerViewer.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/IVisualizerViewer.java new file mode 100644 index 00000000000..5cdda14cc78 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/IVisualizerViewer.java @@ -0,0 +1,111 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui; + +import org.eclipse.cdt.visualizer.ui.events.IVisualizerViewerListener; +import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.action.IToolBarManager; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.widgets.Control; + + +// ---------------------------------------------------------------------------- +// IVisualizerViewer +// ---------------------------------------------------------------------------- + +/** + * CDT Visualizer Viewer interface. + * + * An IVisualizerViewer is a simple container for multiple + * IVisualizers, where the currently selected IVisualizer + * determines which IVisualizer control is displayed in the viewer. + */ +public interface IVisualizerViewer +{ + // --- accessors --- + + /** Gets containing view. */ + public VisualizerView getView(); + + /** Returns non-localized unique name for selected visualizer. */ + public String getVisualizerName(); + + /** Returns localized name to display for selected visualizer. */ + public String getVisualizerDisplayName(); + + /** Returns localized tooltip text to display for selected visualizer. */ + public String getVisualizerDescription(); + + + + // --- control management --- + + /** Gets viewer control. */ + public Control getControl(); + + + // --- focus handling --- + + /** + * Invoked by VisualizerView when currently selected presentation, + * if any, should take the focus. + */ + public boolean setFocus(); + + + // --- menu/toolbar management --- + + /** Invoked when visualizer is selected, to populate the toolbar. */ + public void populateToolBar(IToolBarManager toolBarManager); + + /** Invoked when visualizer is selected, to populate the toolbar's menu. */ + public void populateMenu(IMenuManager menuManager); + + + // --- context menu handling --- + + /** Invoked when context menu is about to be shown. */ + public void populateContextMenu(IMenuManager m); + + /** Gets context menu location. */ + public Point getContextMenuLocation(); + + + // --- selection handling --- + + /** + * Invoked by VisualizerView when workbench selection changes, + * and the change was made by some other view. + */ + public void workbenchSelectionChanged(ISelection selection); + + /** Adds external listener for selection change events. */ + public void addSelectionChangedListener(ISelectionChangedListener listener); + + /** Removes external listener for selection change events. */ + public void removeSelectionChangedListener(ISelectionChangedListener listener); + + /** Gets current externally-visible selection. */ + public ISelection getSelection(); + + + // --- events --- + + /** Adds listener for viewer events. */ + public void addVisualizerViewerListener(IVisualizerViewerListener listener); + + /** Removes listener for viewer events. */ + public void removeVisualizerViewerListener(IVisualizerViewerListener listener); + +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/Visualizer.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/Visualizer.java new file mode 100755 index 00000000000..a2b110b60c5 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/Visualizer.java @@ -0,0 +1,275 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui; + +import org.eclipse.cdt.visualizer.ui.util.SelectionManager; +import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.action.IToolBarManager; +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.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; + + +// --------------------------------------------------------------------------- +// Visualizer +// --------------------------------------------------------------------------- + +/** + * Base class for IVisualizer implementations. + */ +abstract public class Visualizer + implements IVisualizer, ISelectionProvider, ISelectionChangedListener +{ + // --- members --- + + /** Visualizer's non-localized name. */ + protected String m_name; + + /** Visualizer's localized, displayable name. */ + protected String m_displayName; + + /** Visualizer's localized, displayable description. */ + protected String m_description; + + /** The parent view control. */ + protected IVisualizerViewer m_viewer; + + /** The visualizer control. */ + protected Control m_control; + + /** Externally visible selection manager. */ + protected SelectionManager m_selectionManager; + + + // --- constructors/destructors --- + + /** Constructor. */ + public Visualizer() { + // TODO: internationalize these strings. + this("visualizer", "Visualizer", "Displays graphic representation of selection."); + } + + /** Constructor. */ + public Visualizer(String name, String displayName, String description) { + setName(name); + setDisplayName(displayName); + setDescription(description); + m_selectionManager = new SelectionManager(this, "Visualizer selection manager"); + } + + /** Dispose method. */ + public void dispose() { + m_name = null; + m_displayName = null; + m_description = null; + disposeControl(); + m_viewer = null; + if (m_selectionManager != null) { + m_selectionManager.dispose(); + m_selectionManager = null; + } + } + + + // --- init methods --- + + /** Invoked when visualizer is created, to permit any initialization. + * Intended to be overridden. Default implementation does nothing. + */ + public void initializeVisualizer() + { + } + + /** Invoked when visualizer is disposed, to permit any cleanup. + * Intended to be overridden. Default implementation calls dispose(). + */ + public void disposeVisualizer() + { + dispose(); + } + + + // --- accessors --- + + /** Sets non-localized name. */ + public void setName(String name) { + m_name = name; + } + /** Gets non-localized name. */ + public String getName() { + return m_name; + } + + /** Sets localized display name. */ + public void setDisplayName(String displayName) { + m_displayName = displayName; + } + /** Gets localized display name. */ + public String getDisplayName() { + return m_displayName; + } + + /** Sets localized description string. */ + public void setDescription(String description) { + m_description = description; + } + /** Gets localized description string. */ + public String getDescription() { + return m_description; + } + + + // --- viewer management --- + + /** Sets viewer we're associated with. */ + public void setViewer(IVisualizerViewer viewer) { + m_viewer = viewer; + } + + /** Gets viewer we're associated with. */ + public IVisualizerViewer getViewer() { + return m_viewer; + } + + + // --- visualizer selection management --- + + /** Invoked when visualizer has been selected. */ + public void visualizerSelected() { + }; + + /** Invoked when another visualizer has been selected, hiding this one. */ + public void visualizerDeselected() { + }; + + + // --- control management --- + + /** Creates and returns visualizer's UI control on specified parent control. */ + abstract public Control createControl(Composite parent); + + /** Invoked when visualizer control should be disposed. */ + abstract public void disposeControl(); + + /** + * Sets visualizer control. + * Intended to be called from createControl(); + */ + protected void setControl(Control control) { + m_control = control; + } + + /** Gets visualizer control. + * Returns null if createControl() has not yet been called. + */ + public Control getControl() { + return m_control; + } + + + // --- menu/toolbar management --- + + /** Invoked by VisualizerViewer when toolbar needs to be populated. */ + public void populateToolBar(IToolBarManager toolBarManager) { + } + + /** Invoked by VisualizerViewer when toolbar menu needs to be populated. */ + public void populateMenu(IMenuManager menuManager) { + } + + + // --- context menu handling --- + + /** Invoked by VisualizerViewer when context menu needs to be populated. */ + public void populateContextMenu(IMenuManager menuManager) { + } + + + // --- workbench selection management --- + + /** + * Tests whether if the IVisualizer can display the selection + * (or something reachable from it). + */ + public int handlesSelection(ISelection selection) + { + // Default implementation doesn't know how to display anything. + return 0; + } + + /** + * Invoked by VisualizerViewer when workbench selection changes. + */ + public void workbenchSelectionChanged(ISelection selection) + { + // Default implementation does nothing. + } + + + // --- ISelectionProvider implementation --- + + // Delegate to selection manager. + + /** Adds external listener for selection change events. */ + public void addSelectionChangedListener(ISelectionChangedListener listener) { + m_selectionManager.addSelectionChangedListener(listener); + } + + /** Removes external listener for selection change events. */ + public void removeSelectionChangedListener(ISelectionChangedListener listener) { + m_selectionManager.removeSelectionChangedListener(listener); + } + + /** Raises selection changed event. */ + public void raiseSelectionChangedEvent() { + m_selectionManager.raiseSelectionChangedEvent(); + } + + /** Gets current externally-visible selection. */ + public ISelection getSelection() + { + return m_selectionManager.getSelection(); + } + + /** Sets externally-visible selection. */ + public void setSelection(ISelection selection) + { + m_selectionManager.setSelection(selection); + } + + /** Sets externally-visible selection. */ + public void setSelection(ISelection selection, boolean raiseEvent) + { + m_selectionManager.setSelection(selection, raiseEvent); + } + + /** Returns true if we currently have a non-empty selection. */ + public boolean hasSelection() + { + return m_selectionManager.hasSelection(); + } + + + // --- ISelectionChangedListener implementation --- + + /** + * Intended to be invoked when visualizer control's selection changes. + * Sets control selection as its own selection, + * and raises selection changed event for any listeners. + */ + public void selectionChanged(SelectionChangedEvent event) { + setSelection(event.getSelection()); + } +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/VisualizerAction.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/VisualizerAction.java new file mode 100755 index 00000000000..0098d84854d --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/VisualizerAction.java @@ -0,0 +1,79 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui; + +import org.eclipse.jface.action.Action; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.swt.widgets.Event; + + +// --------------------------------------------------------------------------- +// VisualizerAction +// --------------------------------------------------------------------------- + +/** Base class for visualizer actions. + * (Viewers are not required to use this class. This is simply a + * convenience wrapper for the standard Action class.) + */ +public class VisualizerAction extends Action +{ + // --- members --- + + // --- constructors/destructors --- + + /** Constructor. */ + protected VisualizerAction() { + // NOTE: this constructor is only intended for deriving classes + // that need to construct the text/description/image attributes + // programmatically. + } + + /** Constructor. */ + public VisualizerAction(String text, String description) { + super(text); + setDescription(description); + } + + /** Constructor. */ + public VisualizerAction(String text, String description, + ImageDescriptor image) { + super(text, image); + setDescription(description); + } + + /** Constructor. */ + public VisualizerAction(String text, String description, + ImageDescriptor enabledImage, ImageDescriptor disabledImage) { + super(text, enabledImage); + setDescription(description); + setDisabledImageDescriptor(disabledImage); + } + + /** Dispose method. */ + public void dispose() + { + } + + + // --- methods --- + + /** Invoked when action is triggered. */ + public void run() { + } + + /** Invoked when action is triggered, + * with the event that caused it. + */ + public void runWithEvent(Event event) { + run(); + } +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/VisualizerView.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/VisualizerView.java new file mode 100644 index 00000000000..ec5ce2d73db --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/VisualizerView.java @@ -0,0 +1,415 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +// Package declaration +package org.eclipse.cdt.visualizer.ui; + +// Java classes +import java.util.List; + +// SWT/JFace classes +import org.eclipse.jface.action.IMenuListener2; +import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.action.MenuManager; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.jface.action.IToolBarManager; + +// Eclipse/CDT classes +import org.eclipse.ui.part.ViewPart; +import org.eclipse.ui.IActionBars; + +// Custom classes +import org.eclipse.cdt.visualizer.ui.events.IVisualizerViewerListener; +import org.eclipse.cdt.visualizer.ui.events.VisualizerViewerEvent; +import org.eclipse.cdt.visualizer.ui.util.SelectionProviderAdapter; +import org.eclipse.cdt.visualizer.ui.util.SelectionUtils; +import org.eclipse.cdt.visualizer.ui.util.WorkbenchSelectionAdapter; + + +// ---------------------------------------------------------------------------- +// VisualizerView +// ---------------------------------------------------------------------------- + +/** + * CDT Visualizer View class. + * + * This is the default implementation of the Visualizer View. + * It can also serve as a base class for custom visualizer views. + * + * The Visualizer View is a simple container with a toolbar, + * which presents an instance of an IVisualizerViewer, + * and mediates passing of selections to and from the viewer. + * + * The intent of the VisualizerView class is to encapsulate the + * standard Eclipse workbench view support, so the viewer does + * not have to worry about such things. + */ +public class VisualizerView + extends ViewPart + implements IVisualizerViewerListener, + ISelectionChangedListener +{ + // --- members --- + + /** Whether view has been initialized */ + protected boolean m_initialized = false; + + /** Parent control of view. */ + protected Composite m_parentControl = null; + + /** Contained IVisualizerViewer control. */ + protected IVisualizerViewer m_viewer = null; + + /** Selection change event manager */ + protected WorkbenchSelectionAdapter m_workbenchSelectionAdapter = null; + + /** Context menu manager. */ + protected MenuManager m_contextMenuManager = null; + + /** Last context menu display location. */ + protected Point m_contextMenuLocation = null; + + + // --- constructors/destructors --- + + /** Constructor */ + public VisualizerView() { + super(); + } + + /** Dispose method */ + public void dispose() { + super.dispose(); + setViewer(null); + disposeSelectionHandling(); + } + + + // --- accessors --- + + /** Returns whether view has been initialized. */ + public boolean isInitialized() + { + return m_initialized; + } + + /** Gets contained viewer control. */ + public IVisualizerViewer getViewer() + { + return m_viewer; + } + + /** Sets contained viewer control. */ + public void setViewer(IVisualizerViewer viewer) + { + if (m_viewer != null) { + m_viewer.removeSelectionChangedListener(this); + m_viewer.removeVisualizerViewerListener(this); + } + + m_viewer = viewer; + + if (m_viewer != null) + { + m_viewer.addVisualizerViewerListener(this); + m_viewer.addSelectionChangedListener(this); + updateUI(); + } + } + + + // --- ViewPart implementation --- + + // IMPORTANT: a view may be loaded before the plugins, etc. + // that its content depends on, since Eclipse loads saved workbench "memento" state, + // including current perspective and view layout, before loading dependent plugins, + // and lazily loads plugins based on classes that get touched. + // + // Hence, a view class should invoke setInitialized(true) at the end + // of its createPartControl() method, and any methods that touch/repaint/update + // the view's controls, etc. should call isInitialized() to be sure + // these controls have been created. + + /** Invoked when UI controls need to be created */ + public void createPartControl(Composite parent) { + m_parentControl = parent; + + // Reminder: Don't muck with the toolbar or toolbar menu here. + // (I.e. don't try to clean them out or set initial items.) + // VisualizerViewer's selection handling code + // allows the selected visualizer to set their content, and + // any fiddling you do here will only interfere with that. + + // set up context menu support + initializeContextMenu(); + + // set up selection handling + initializeSelectionHandling(); + + // initialize viewer control + initializeViewer(); + + m_initialized = true; + } + + /** Invoked when view should take the focus. + * Note: this can be invoked before the view is fully initialized + * (for example, when loading views from workspace memento information), + * in which case it should silently do nothing. + */ + public void setFocus() { + if (m_viewer != null) m_viewer.setFocus(); + } + + + // --- initialization support --- + + /** + * Creates and returns VisualizerViewer control. + * Intended to be overridden by derived types. + */ + protected IVisualizerViewer createViewer(Composite parent) + { + return (m_viewer != null) ? m_viewer : new VisualizerViewer(this, parent); + } + + /** + * Invoked by createPartControl() method when view instance is created. + * Intended to be overridden by derived classes. + */ + protected void initializeViewer() { + IVisualizerViewer viewer = createViewer(m_parentControl); + setViewer(viewer); + } + + + // --- tab name management --- + + /** Sets displayed tab name and description for this view. */ + public void setTabName(String displayName) + { + setPartName(displayName); + } + + /** Sets displayed tab name and description for this view. */ + public void setTabDescription(String description) + { + setTitleToolTip(description); + } + + + // --- selection handling --- + + /** Initializes selection handling for this view. */ + protected void initializeSelectionHandling() { + // create workbench selection change adapter, + // to hook us into the workbench selection event mechanism + m_workbenchSelectionAdapter = new WorkbenchSelectionAdapter(this); + m_workbenchSelectionAdapter.addSelectionChangedListener(this); + } + + /** Disposes selection handling for this view. */ + protected void disposeSelectionHandling() { + if (m_workbenchSelectionAdapter != null) { + m_workbenchSelectionAdapter.dispose(); + m_workbenchSelectionAdapter = null; + } + } + + /** Gets current workbench selection. */ + public ISelection getWorkbenchSelection() { + return m_workbenchSelectionAdapter.getSelection(); + } + + /** Sets current workbench selection, and raises selection changed event. */ + public void setWorkbenchSelection(ISelection selection) { + m_workbenchSelectionAdapter.setSelection(this, selection); + } + + /** Sets current workbench selection, and raises selection changed event. */ + public void setWorkbenchSelection(List selection) { + ISelection iselection = SelectionUtils.toSelection(selection); + m_workbenchSelectionAdapter.setSelection(this, iselection); + } + + // --- ISelectionChangedListener implementation --- + + /** Invoked by WorkbenchSelectionAdapter when selection changes, + * and by viewer when visualizer selection changes. + */ + public void selectionChanged(SelectionChangedEvent event) { + Object source = event.getSource(); + if (source instanceof SelectionProviderAdapter) { + source = ((SelectionProviderAdapter) source).getActualSource(); + } + // if the source is the current VisualizerViewer, + // it's a user selection in the viewer, so we want to pass + // the selection change on to the workbench + if (source == m_viewer) { + // tell viewer about workbench selection + ISelection selection = event.getSelection(); + setWorkbenchSelection(selection); + + // update toolbar/menu to reflect changed selection + updateUI(); + } + // if the source is this view, it's an echo of a workbench + // event we sent out, so ignore it. + else if (source == this) { + // Do nothing. + } + // else this is a selection change from some other view + // in the workbench, which we should pass down to the viewer + else { + ISelection selection = event.getSelection(); + workbenchSelectionChanged(selection); + + // update toolbar/menu to reflect changed selection + updateUI(); + } + } + + /** + * Invoked from selectionChanged() when workbench's selection changes, + * but only if the selection change did not come from this view. + */ + public void workbenchSelectionChanged(ISelection selection) { + if (m_viewer != null) { + m_viewer.workbenchSelectionChanged(selection); + } + } + + + // --- IVisulizerViewerListener implementation --- + + /** Invoked when visualizer in view has changed. */ + public void visualizerEvent(IVisualizerViewer source, VisualizerViewerEvent event) { + switch (event.getType()) { + case VisualizerViewerEvent.VISUALIZER_CHANGED: + updateUI(); + break; + case VisualizerViewerEvent.VISUALIZER_CONTEXT_MENU: + showContextMenu(event.x, event.y); + } + } + + + // --- update methods --- + + /** Updates tab name, toolbar, etc. from viewer. */ + public void updateUI() { + + // Update tab name/tooltip + // TODO: internationalize these default strings + String name = "Visualizer View"; + String description = "Displays visualizations of launches."; + if (m_viewer != null) { + name = m_viewer.getVisualizerDisplayName(); + description = m_viewer.getVisualizerDescription(); + + } + setTabName(name); + setTabDescription(description); + + // Update toolbar & toolbar menu + if (m_viewer != null) { + IActionBars actionBars = getViewSite().getActionBars(); + + // Allow presentation to set the displayed toolbar content, if any + IToolBarManager toolBarManager = actionBars.getToolBarManager(); + toolBarManager.removeAll(); + m_viewer.populateToolBar(toolBarManager); + toolBarManager.update(true); + + // Allow presentation to set the toolbar's menu content, if any + IMenuManager menuManager = actionBars.getMenuManager(); + menuManager.removeAll(); + m_viewer.populateMenu(menuManager); + menuManager.update(true); + + // Note: when context menu is invoked, + // the poplateContextMenu() method is called by the view, + // which in turn delegates to the current visualizer + // to populate the context menu. + + // Propagate the changes + actionBars.updateActionBars(); + } + } + + + // --- context menu support --- + + /** Sets up context menu support. */ + protected void initializeContextMenu() { + m_contextMenuManager = new MenuManager(); + m_contextMenuManager.addMenuListener(new IMenuListener2() { + public void menuAboutToShow(IMenuManager m) { + VisualizerView.this.contextMenuShow(m); + } + public void menuAboutToHide(IMenuManager m) { + VisualizerView.this.contextMenuHide(m); + } + }); + + // We associate the view's context menu with the parent control. + // Viewer has the option of calling showContextMenu() + // to display the view's context menu. + Menu menu= m_contextMenuManager.createContextMenu(m_parentControl); + m_parentControl.setMenu(menu); + } + + /** Invoked when context menu is about to be shown. */ + protected void contextMenuShow(IMenuManager m) + { + m.removeAll(); + m_viewer.populateContextMenu(m); + m.update(); + } + + /** Invoked when context menu is about to be hidden. */ + protected void contextMenuHide(IMenuManager m) + { + } + + /** Shows view's context menu at specified position. */ + public void showContextMenu(int x, int y) + { + Menu menu = m_parentControl.getMenu(); + if (menu != null) { + menu.setLocation(x, y); + + // capture context menu location in relative coordinates + m_contextMenuLocation = m_parentControl.toControl(x,y); + + // Note: showing menu implicitly invokes populateContextMenu() + // to populate context menu items. + menu.setVisible(true); + + // Make sure we have the focus now + // so we'll still have it when the menu goes away, + // and user doesn't have to click twice. + setFocus(); + } + } + + /** Gets context menu location. */ + public Point getContextMenuLocation() { + // Just asking the menu for its own location doesn't work, + // so we have to capture it above and return it here. + return m_contextMenuLocation; + } +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/VisualizerViewer.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/VisualizerViewer.java new file mode 100644 index 00000000000..a9c71c2d1b3 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/VisualizerViewer.java @@ -0,0 +1,540 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui; + +import java.util.Hashtable; +import java.util.List; +import java.util.Map; + +import org.eclipse.cdt.visualizer.core.Extension; +import org.eclipse.cdt.visualizer.ui.events.IVisualizerViewerListener; +import org.eclipse.cdt.visualizer.ui.events.VisualizerViewerEvent; +import org.eclipse.cdt.visualizer.ui.plugin.CDTVisualizerUIPlugin; +import org.eclipse.cdt.visualizer.ui.util.ListenerList; +import org.eclipse.cdt.visualizer.ui.util.SelectionManager; +import org.eclipse.cdt.visualizer.ui.util.SelectionUtils; +import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.action.IToolBarManager; +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.swt.SWT; +import org.eclipse.swt.events.MenuDetectEvent; +import org.eclipse.swt.events.MenuDetectListener; +import org.eclipse.swt.events.PaintEvent; +import org.eclipse.swt.events.PaintListener; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.part.PageBook; + + +// ---------------------------------------------------------------------------- +// VisualizerViewer +// ---------------------------------------------------------------------------- + +/** + * CDT Visualizer Viewer class. + * + * This is the default implementation of IVisualizerViewer. + * It can also serve as a base class for custom visualizer viewers. + * + * The Visualizer Viewer is a simple container for multiple + * IVisualizers, where the currently selected IVisualizer + * determines which IVisualizer control is displayed in the viewer. + * + * The base implementation simply displays a single IVisualizer at a time. + * One can programmatically switch selections, but there are no user + * controls for doing so. (The intent is that derived types can add + * various kinds of switching controls, like a combo box, etc.) + */ +public class VisualizerViewer extends PageBook + implements IVisualizerViewer, MenuDetectListener, + ISelectionProvider, ISelectionChangedListener +{ + // --- constants --- + + /** Extension point name for list of IVisualizer types. */ + public static final String VISUALIZER_EXTENSION_POINT_NAME = "visualizer"; //$NON-NLS-1$ + + + // --- members --- + + /** Containing view. */ + protected VisualizerView m_view = null; + + /** Parent control. */ + protected Composite m_parent = null; + + /** List of registered visualizer types. */ + protected Map m_visualizers = null; + + /** Currently selected visualizer. */ + protected IVisualizer m_currentVisualizer = null; + + /** Event listeners. */ + protected ListenerList m_listeners = null; + + /** Viewer selection manager. */ + protected SelectionManager m_selectionManager = null; + + + // --- constructors/destructors --- + + /** Constructor. */ + public VisualizerViewer(VisualizerView view, Composite parent) { + super(parent, SWT.NONE); + initVisualizerViewer(view, parent); + } + + /** Dispose method. */ + public void dispose() { + cleanupVisualizerViewer(); + super.dispose(); + } + + /** Overridden to permit subclassing of SWT component */ + protected void checkSubclass() { + // Do nothing. + // (Superclass implementation throws "Subclassing not allowed" exception.) + } + + + // --- init methods --- + + /** Initializes control */ + protected void initVisualizerViewer(VisualizerView view, Composite parent) { + m_view = view; + m_parent = parent; + + // Event listener support + m_listeners = new ListenerList(this, "VisualizerViewer event listeners") + { + public void raise(Object listener, Object event) { + if (listener instanceof IVisualizerViewerListener && + event instanceof VisualizerViewerEvent) + { + IVisualizerViewerListener typedListener = (IVisualizerViewerListener) listener; + VisualizerViewerEvent typedEvent = (VisualizerViewerEvent) event; + typedListener.visualizerEvent(VisualizerViewer.this, typedEvent); + } + } + }; + + // Selection change listener support + m_selectionManager = new SelectionManager(this, "Visualizer Viewer selection manager"); + + // Set default colors for empty viewer. + Display display = getDisplay(); + setBackground(display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); + setForeground(display.getSystemColor(SWT.COLOR_WIDGET_FOREGROUND)); + + // Listen to paint event to draw "No visualizers" warning if needed. + this.addPaintListener(new PaintListener() { + public void paintControl(PaintEvent e) { + VisualizerViewer.this.paint(e.gc); + } + }); + + // Load any visualizers defined through extension point. + loadVisualizers(); + } + + /** Cleans up control */ + protected void cleanupVisualizerViewer() { + // perform any cleanup here + disposeVisualizers(); + if (m_selectionManager != null) { + m_selectionManager.dispose(); + m_selectionManager = null; + } + } + + + // --- accessors --- + + /** Gets containing view. */ + public VisualizerView getView() { + return m_view; + } + + /** Returns non-localized unique name for selected visualizer. */ + public String getVisualizerName() + { + String result = "visualizer"; + if (m_currentVisualizer != null) result = m_currentVisualizer.getName(); + return result; + } + + /** Returns localized name to display for selected visualizer. */ + public String getVisualizerDisplayName() + { + String result = "Visualizer"; + if (m_currentVisualizer != null) result = m_currentVisualizer.getDisplayName(); + return result; + } + + /** Returns localized tooltip text to display for selected visualizer. */ + public String getVisualizerDescription() + { + String result = "Visualizer"; + if (m_currentVisualizer != null) result = m_currentVisualizer.getDescription(); + return result; + } + + + // --- control management --- + + /** Gets viewer control. */ + public Control getControl() { + return this; + } + + + // --- focus handling --- + + /** + * Invoked by VisualizerView when currently selected presentation, + * if any, should take the focus. + */ + public boolean setFocus() + { + boolean result = false; + if (m_currentVisualizer != null) { + // Tell current visualizer's control to take the focus. + m_currentVisualizer.getControl().setFocus(); + } + else { + // Otherwise, let viewer take the focus. + result = super.setFocus(); + } + return result; + } + + + // --- viewer events --- + + /** Adds listener for viewer events. */ + public void addVisualizerViewerListener(IVisualizerViewerListener listener) + { + m_listeners.addListener(listener); + } + + /** Removes listener for viewer events. */ + public void removeVisualizerViewerListener(IVisualizerViewerListener listener) + { + m_listeners.removeListener(listener); + } + + /** Raises change event for all listeners. */ + public void raiseVisualizerChangedEvent() + { + VisualizerViewerEvent event = + new VisualizerViewerEvent(this, VisualizerViewerEvent.VISUALIZER_CHANGED); + m_listeners.raise(event); + } + + /** Raises context menu event for all listeners. */ + public void raiseContextMenuEvent(int x, int y) + { + VisualizerViewerEvent event = + new VisualizerViewerEvent(this, VisualizerViewerEvent.VISUALIZER_CONTEXT_MENU, x, y); + m_listeners.raise(event); + } + + + // --- visualizer management --- + + /** Loads initial set of visualizers and constructs viewer controls. */ + protected void loadVisualizers() + { + // TODO: add error checking, logging for errors in extension declarations + // TODO: do we need to worry about this being called more than once? + + m_visualizers = new Hashtable(); + + List visualizers = Extension.getExtensions( + CDTVisualizerUIPlugin.FEATURE_ID, VISUALIZER_EXTENSION_POINT_NAME); + + if (visualizers != null) { + for(Extension e : visualizers) { + String id = e.getAttribute("id"); + IVisualizer visualizerInstance = e.getClassAttribute(); + if (id != null && visualizerInstance != null) { + // Add visualizer's control to viewer's "pagebook" of controls. + visualizerInstance.setViewer(this); + visualizerInstance.initializeVisualizer(); + visualizerInstance.createControl(this); + m_visualizers.put(id, visualizerInstance); + } + } + } + + // select initial visualization + selectDefaultVisualizer(); + } + + /** Cleans up visualizers. */ + protected void disposeVisualizers() + { + for (String id : m_visualizers.keySet()) { + IVisualizer v = m_visualizers.get(id); + Control c = v.getControl(); + c.dispose(); + v.disposeVisualizer(); + } + m_visualizers.clear(); + } + + + /** Selects default visualizer. + * Default implementation displays visualizer that can handle + * the current selection. + */ + public void selectDefaultVisualizer() + { + // fake a workbench selection changed event + updateVisualizerFromWorkbenchSelection(); + } + + /** Selects specified visualizer, makes its control visible. */ + public void selectVisualizer(IVisualizer visualizer) + { + if (visualizer == null) return; + if (visualizer == m_currentVisualizer) return; + + if (m_currentVisualizer != null) { + // let the visualizer know it's being hidden + m_currentVisualizer.visualizerDeselected(); + + // stop listening for context menu events + m_currentVisualizer.getControl().removeMenuDetectListener(this); + + // stop listening for selection changed events + m_currentVisualizer.removeSelectionChangedListener(this); + } + + m_currentVisualizer = visualizer; + + if (m_currentVisualizer != null) { + // We've added visualizer's control in loadVisualizers(), + // so all we need to do here is select it. + showPage(visualizer.getControl()); + + // start listening for context menu events + m_currentVisualizer.getControl().addMenuDetectListener(this); + + // start listening for selection changed events + m_currentVisualizer.addSelectionChangedListener(this); + + // raise visualizer changed event, so view knows + // it should update tab name, toolbar, etc. + raiseVisualizerChangedEvent(); + + // make sure workbench knows about current visualizer selection + updateWorkbenchFromVisualizerSelection(); + + // no need to update visualizer from workbench selection, + // we already do that whenever the workbench selection changes + + // let the visualizer know it's been shown + m_currentVisualizer.visualizerDeselected(); + } + } + + /** Gets current visualizer. */ + public IVisualizer getVisualizer() + { + return m_currentVisualizer; + } + + + // --- menu/toolbar management --- + + /** Invoked when visualizer is selected, to populate the toolbar. */ + public void populateToolBar(IToolBarManager toolBarManager) + { + if (m_currentVisualizer != null) + m_currentVisualizer.populateToolBar(toolBarManager); + } + + /** Invoked when visualizer is selected, to populate the toolbar's menu. */ + public void populateMenu(IMenuManager menuManager) + { + if (m_currentVisualizer != null) + m_currentVisualizer.populateMenu(menuManager); + } + + + // --- context menu handling --- + + /** Invoked when context menu gesture happens on current + * visualizer control. + */ + public void menuDetected(MenuDetectEvent e) { + // raise event to allow view to show context menu + raiseContextMenuEvent(e.x, e.y); + } + + /** Invoked when context menu is about to be shown. */ + public void populateContextMenu(IMenuManager m) + { + if (m_currentVisualizer != null) { + m_currentVisualizer.populateContextMenu(m); + } + } + + /** Gets context menu location. */ + public Point getContextMenuLocation() { + return m_view.getContextMenuLocation(); + } + + + // --- paint methods --- + + /** + * Invoked when viewer needs to be repainted. + * May be overridden by derived classes. + * Default implementation displays "No visualizers defined." message + */ + public void paint(GC gc) + { + gc.fillRectangle(getClientArea()); + if (m_visualizers == null || m_visualizers.size() == 0) { + String noVisualizersMessage = + CDTVisualizerUIPlugin.getString("VisualizerViewer.no.visualizers.defined"); + gc.drawString("(" + noVisualizersMessage + ")", 10, 10); + } + } + + + // --- ISelectionProvider implementation --- + + // Delegate to selection manager. + + /** Adds external listener for selection change events. */ + public void addSelectionChangedListener(ISelectionChangedListener listener) { + m_selectionManager.addSelectionChangedListener(listener); + } + + /** Removes external listener for selection change events. */ + public void removeSelectionChangedListener(ISelectionChangedListener listener) { + m_selectionManager.removeSelectionChangedListener(listener); + } + + /** Raises selection changed event. */ + public void raiseSelectionChangedEvent() { + m_selectionManager.raiseSelectionChangedEvent(); + } + + /** Gets current externally-visible selection. */ + public ISelection getSelection() + { + return m_selectionManager.getSelection(); + } + + /** Sets externally-visible selection. */ + public void setSelection(ISelection selection) + { + m_selectionManager.setSelection(selection); + } + + + // --- workbench selection handling --- + + /** + * Updates visualizer from current workbench selection. + * NOTE: normally VisulizerView keeps the viewer in synch + * with the selection, so this should not need to be called + * except in special cases. + */ + public void updateVisualizerFromWorkbenchSelection() { + ISelection selection = SelectionUtils.getWorkbenchSelection(); + workbenchSelectionChanged(selection); + } + + /** + * Invoked by VisualizerView when workbench selection changes, + * and change's source is not this view. + * + * Selects visualizer (if any) that knows how to display current + * selection. Also invokes workbenchSelectionChanged() on visualizer + * so it can update itself accordingly. + */ + public void workbenchSelectionChanged(ISelection selection) + { + // See if we need to change visualizers to handle selection type. + IVisualizer handles = null; + int weight = 0; + + // First, see if the current visualizer can handle the new selection. + // (This gives it automatic precedence if there's a tie.) + if (m_currentVisualizer != null) { + int w = m_currentVisualizer.handlesSelection(selection); + if (w > weight) { + handles = m_currentVisualizer; + weight = w; + } + } + + // Next, check the list of other visualizers, to see if any + // of them is more specific than the current one. + for (IVisualizer v : m_visualizers.values()) { + if (v == m_currentVisualizer) continue; // already checked + int w = v.handlesSelection(selection); + if (w > weight) { + handles = v; + weight = w; + } + } + + // If NOBODY claims ownership, and we don't have a visualizer yet, + // then pick somebody and let them take a whack at it. + if (handles == null && m_visualizers.size() > 0) { + handles = m_visualizers.values().iterator().next(); + } + + // If we need to change visualizers, select the new one. + // Note: this also reports the new visualizer's selection to the workbench + if (handles != null && handles != m_currentVisualizer) { + selectVisualizer(handles); + } + + // Notify current visualizer that workbench selection has changed. + // (This means a visualizer is only notified of workbench selection changes + // if the selection is something it has reported that it can display.) + if (m_currentVisualizer != null) { + m_currentVisualizer.workbenchSelectionChanged(selection); + } + } + + + // --- visualizer selection handling --- + + /** Updates workbench selection from current visualizer selection. + * Note: normally the viewer keeps the selection in synch, + * so you should not need to call this method except in special cases. + */ + public void updateWorkbenchFromVisualizerSelection() { + // fake a selection changed event + m_selectionManager.raiseSelectionChangedEvent(); + } + + /** Invoked when visualizer's selection changes. */ + public void selectionChanged(SelectionChangedEvent event) { + // Publish changed visualizer selection to any listeners. + setSelection(event.getSelection()); + } +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/BufferedCanvas.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/BufferedCanvas.java new file mode 100755 index 00000000000..b4f2778cef4 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/BufferedCanvas.java @@ -0,0 +1,201 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui.canvas; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ControlEvent; +import org.eclipse.swt.events.ControlListener; +import org.eclipse.swt.events.PaintEvent; +import org.eclipse.swt.events.PaintListener; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.widgets.Canvas; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; + + +// --------------------------------------------------------------------------- +// BufferedCanvas +// --------------------------------------------------------------------------- + +/** Canvas control with double-buffering support. */ +public class BufferedCanvas extends Canvas + implements PaintListener, ControlListener +{ + // --- members --- + + /** double-buffering image */ + protected Image m_doubleBuffer = null; + + /** buffer GC */ + protected GC m_doubleBufferGC = null; + + + // --- constructors/destructors --- + + /** Constructor. */ + public BufferedCanvas(Composite parent) { + super(parent, + SWT.NO_BACKGROUND | // don't automatically clear background on paint event + SWT.NO_REDRAW_RESIZE // don't automatically repaint on resize event + ); + initBufferedCanvas(); + } + + /** Dispose method. */ + public void dispose() { + super.dispose(); + cleanupBufferedCanvas(); + } + + // --- init methods --- + + /** Initializes control. */ + protected void initBufferedCanvas() { + addControlListener(this); + addPaintListener(this); + } + + /** Cleans up control. */ + protected void cleanupBufferedCanvas() { + removePaintListener(this); + removeControlListener(this); + if (m_doubleBuffer != null) { + m_doubleBuffer.dispose(); + m_doubleBuffer = null; + } + } + + + // --- event handlers --- + + /** Invoked when control is moved/resized */ + public void controlMoved(ControlEvent e) { + // do nothing, we don't care + } + + /** Invoked when control is resized */ + public void controlResized(ControlEvent e) { + resized(getBounds()); + } + + + // --- resize methods --- + + /** Invoked when control is resized. + * Default implementation does nothing, + * intended to be overridden by derived types. + */ + public void resized(Rectangle bounds) { + + } + + + // --- GC management --- + + /** Gets/creates GC for current background buffer. + * NOTE: The GC is disposed whenever the canvas size changes, + * so caller should not retain a reference to this GC. + */ + protected synchronized GC getBufferedGC() { + if (m_doubleBufferGC == null) { + + m_doubleBufferGC = new GC(m_doubleBuffer); + } + return m_doubleBufferGC; + } + + /** Disposes of current background buffer GC. */ + protected synchronized void disposeBufferedGC() { + if (m_doubleBufferGC != null) { + m_doubleBufferGC.dispose(); + m_doubleBufferGC = null; + } + } + + + // --- paint methods --- + + /** Invoked when control needs to be repainted */ + public void paintControl(PaintEvent e) { + // Handle last paint event of a cluster. + if (e.count<=1) { + Display display = e.display; + GC gc = e.gc; + paintDoubleBuffered(display, gc); + } + } + + /** Internal -- handles double-buffering support, calls paintCanvas() */ + // NOTE: need display to create image buffer, not for painting code + protected void paintDoubleBuffered(Display display, GC gc) { + // get/create background image buffer + Rectangle clientArea = getClientArea(); + int width = clientArea.width; + int height = clientArea.height; + if (m_doubleBuffer == null + || m_doubleBuffer.getBounds().width < width + || m_doubleBuffer.getBounds().height < height) + { + m_doubleBuffer = new Image(display, width, height); + disposeBufferedGC(); + } + + // create graphics context for buffer + GC bgc = getBufferedGC(); + + // copy current GC properties into it as defaults + bgc.setBackground(gc.getBackground()); + bgc.setForeground(gc.getForeground()); + bgc.setFont(gc.getFont()); + bgc.setAlpha(255); + + // invoke paintCanvas() method to paint into the buffer + try { + paintCanvas(bgc); + } + catch (Throwable t) { + // Throwing an exception in painting code can hang Eclipse, + // so catch any exceptions here. + System.err.println("BufferedCanvas: Exception thrown in painting code: \n" + t); + } + + // then copy image buffer to actual canvas (reduces repaint flickering) + gc.drawImage(m_doubleBuffer, 0,0); + } + + /** Invoked when canvas repaint event is raised. + * Default implementation clears canvas to background color. + */ + public void paintCanvas(GC gc) { + clearCanvas(gc); + } + + /** Clears canvas to background color. */ + public void clearCanvas(GC gc) { + Rectangle bounds = getClientArea(); + gc.fillRectangle(bounds); + } + + + // --- update methods --- + + /** Redraws control */ + public void update() { + // guard against update events that happen + // after app has shut down + if (! isDisposed()) { + redraw(); + } + } +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/GraphicCanvas.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/GraphicCanvas.java new file mode 100755 index 00000000000..1fbf1a4c590 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/GraphicCanvas.java @@ -0,0 +1,167 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui.canvas; + +import java.util.ArrayList; + +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.widgets.Composite; + + +// --------------------------------------------------------------------------- +// GraphicCanvas +// --------------------------------------------------------------------------- + +/** + * Viewer canvas -- base class for canvas that displays a collection + * of persistent, repositionable graphic objects. + * + * Note: painting is done in order objects were added, + * so objects added last are drawn "on top" of others. + * Use raise/lower methods to change the object z-ordering, if needed. + */ +public class GraphicCanvas extends BufferedCanvas +{ + // --- members --- + + /** Viewer elements. */ + protected ArrayList m_objects = null; + + + // --- constructors/destructors --- + + /** Constructor. */ + public GraphicCanvas(Composite parent) { + super(parent); + m_objects = new ArrayList(); + } + + /** Dispose method. */ + public void dispose() { + if (m_objects != null) { + m_objects.clear(); + m_objects = null; + } + super.dispose(); + } + + + // --- object management methods --- + + /** Removes all elements */ + public void clear() { + m_objects.clear(); + } + + /** Adds an element */ + public IGraphicObject add(IGraphicObject element) { + if (! m_objects.contains(element)) { + m_objects.add(element); + } + return element; + } + + /** Removes an element */ + public void remove(IGraphicObject element) { + m_objects.remove(element); + } + + /** Raises an element to top of repaint z-ordering */ + public void raiseToFront(IGraphicObject element) { + if (m_objects.contains(element)) { + m_objects.remove(element); + m_objects.add(element); + } + } + + /** Lowers an element to bottom of repaint z-ordering */ + public void lowerToBack(IGraphicObject element) { + if (m_objects.contains(element)) { + m_objects.remove(element); + m_objects.add(0, element); + } + } + + + // --- painting methods --- + + /** Paints elements on canvas. */ + public void paintCanvas(GC gc) { + // paint background first + clearCanvas(gc); + + // we paint object list from start to end, + // so end of the list is "top" in z-ordering + + // allow objects to draw themselves + for (IGraphicObject gobj : m_objects) { + gobj.paint(gc, false); + } + + // allow objects to paint any "decorations" on top of other stuff + for (IGraphicObject gobj : m_objects) { + if (gobj.hasDecorations()) + gobj.paint(gc, true); + } + } + + + // --- point-to-object accessors --- + + /** Returns first graphic object found under specified point */ + public IGraphicObject getGraphicObject(int x, int y) { + return getGraphicObject(null, x, y); + } + + /** Returns first graphic object found under specified point. + * If type argument is non-null, returns first object assignable to specified type. + */ + public IGraphicObject getGraphicObject(Class type, int x, int y) { + IGraphicObject result = null; + + // note: have to search list in reverse order we draw it, + // so we hit items "on top" in the z-ordering first + int count = (m_objects == null) ? 0 : m_objects.size(); + for (int i=count-1; i>=0; i--) { + IGraphicObject gobj = m_objects.get(i); + if (gobj.contains(x, y)) { + if (type != null) { + Class objType = gobj.getClass(); + if (! type.isAssignableFrom(objType)) continue; + } + result = gobj; + break; + } + } + + return result; + } + + // --- model data accessors --- + + /** Returns graphic object (if any) that has specified data value. */ + public IGraphicObject getGraphicObjectFor(Object value) { + IGraphicObject result = null; + for (IGraphicObject gobj : m_objects) { + if (gobj.getData() == value) { + result = gobj; + break; + } + } + return result; + } + + /** Returns data value (if any) for the specified graphic element. */ + public Object getDataFor(IGraphicObject IGraphicObject) { + return (IGraphicObject == null) ? null : IGraphicObject.getData(); + } +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/GraphicCanvasVisualizer.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/GraphicCanvasVisualizer.java new file mode 100644 index 00000000000..5fcef0d92d8 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/GraphicCanvasVisualizer.java @@ -0,0 +1,123 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui.canvas; + +import org.eclipse.cdt.visualizer.ui.Visualizer; +import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.action.IToolBarManager; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; + + +// --------------------------------------------------------------------------- +// GraphicCanvasVisualizer +// --------------------------------------------------------------------------- + +/** + * Viewer canvas -- base class for canvas that displays a collection + * of persistent, repositionable graphic objects. + * + * Note: painting is done in order objects were added, + * so objects added last are drawn "on top" of others. + * Use raise/lower methods to change the object z-ordering, if needed. + */ +public class GraphicCanvasVisualizer extends Visualizer +{ + // --- members --- + + + // --- constructors/destructors --- + + /** Constructor. */ + public GraphicCanvasVisualizer() + { + // TODO: internationalize these strings. + super("canvas", "Canvas Visualizer", "Displays graphic representation of selection."); + } + + /** Dispose method. */ + public void dispose() { + super.dispose(); + } + + + // --- control management --- + + /** Creates and returns visualizer control on specified parent. */ + public Control createControl(Composite parent) + { + if (m_control == null) { + GraphicCanvas canvas = createCanvas(parent); + canvas.setMenu(parent.getMenu()); + setControl(canvas); + initializeCanvas(canvas); + } + return getControl(); + } + + /** Invoked when visualizer control should be disposed. */ + public void disposeControl() + { + if (m_control != null) { + disposeCanvas(); + m_control.dispose(); + setControl(null); + } + } + + + // --- canvas management --- + + /** Creates and returns visualizer canvas control. */ + public GraphicCanvas createCanvas(Composite parent) + { + return new GraphicCanvas(parent); + } + + /** Invoked when canvas control should be disposed. */ + public void disposeCanvas() + { + + } + + /** Invoked after visualizer control creation, + * to allow derived classes to do any initialization of canvas. + */ + protected void initializeCanvas(GraphicCanvas canvas) + { + } + + /** Gets downcast reference to canvas control. */ + public GraphicCanvas getCanvas() + { + return (GraphicCanvas) getControl(); + } + + + // --- menu/toolbar management --- + + /** Invoked when visualizer is selected, to populate the toolbar. */ + public void populateToolBar(IToolBarManager toolBarManager) + {} + + /** Invoked when visualizer is selected, to populate the toolbar's menu. */ + public void populateMenu(IMenuManager menuManager) + {} + + + // --- context menu handling --- + + /** Invoked when visualizer view's context menu is invoked, to populate it. */ + public void populateContextMenu(IMenuManager menuManager) + {} + +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/GraphicObject.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/GraphicObject.java new file mode 100755 index 00000000000..e89ad65bd23 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/GraphicObject.java @@ -0,0 +1,278 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui.canvas; + +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Rectangle; + + +// --------------------------------------------------------------------------- +// GraphicObject +// --------------------------------------------------------------------------- + +/** + * Graphic object base class. + * Base class for objects that can be displayed and manipulated on a GraphicCanvas. + */ +public class GraphicObject + implements IGraphicObject +{ + // --- members --- + + /** Data object, if any, associated with this graphic object. */ + protected Object m_data = null; + + /** Bounding rectangle of this element. */ + protected Rectangle m_bounds = new Rectangle(0,0,0,0); + + /** Whether this element is visible. */ + protected boolean m_visible = true; + + /** Whether this element is selected. */ + protected boolean m_selected = false; + + /** Foreground color (null means inherit from canvas) */ + protected Color m_foreground = null; + + /** Background color (null means inherit from canvas) */ + protected Color m_background = null; + + + // --- constructors/destructors --- + + /** Constructor. */ + public GraphicObject() { + } + + /** Constructor. */ + public GraphicObject(int x, int y, int width, int height) { + m_bounds.x = x; + m_bounds.y = y; + m_bounds.width = width; + m_bounds.height = height; + } + + /** Constructor. */ + public GraphicObject(Rectangle bounds) { + m_bounds.x = bounds.x; + m_bounds.y = bounds.y; + m_bounds.width = bounds.width; + m_bounds.height = bounds.height; + } + + /** Constructor. */ + public GraphicObject(Object data) { + m_data = data; + } + + /** Constructor. */ + public GraphicObject(int x, int y, int width, int height, Object data) { + m_bounds.x = x; + m_bounds.y = y; + m_bounds.width = width; + m_bounds.height = height; + m_data = data; + } + + + /** Constructor. */ + public GraphicObject(Rectangle bounds, Object data) + { + m_bounds.x = bounds.x; + m_bounds.y = bounds.y; + m_bounds.width = bounds.width; + m_bounds.height = bounds.height; + m_data = data; + } + + /** Dispose method. */ + public void dispose() { + m_data = null; + } + + + // --- accessors --- + + /** Gets data object associated with this view element. */ + public Object getData() { + return m_data; + } + /** Sets data object associated with this view element. */ + public void setData(Object data) { + m_data = data; + } + + + /** Gets x location of this element */ + public int getX() { return m_bounds.x; } + /** Sets x location of this element */ + public void setX(int x) { + m_bounds.x = x; + } + + /** Gets y location of this element */ + public int getY() { return m_bounds.y; } + /** Sets y location of this element */ + public void setY(int y) { m_bounds.y = y; } + + /** Sets x/y position of this element */ + public void setPosition(int x, int y) { + m_bounds.x = x; m_bounds.y = y; + } + + + /** Gets width of this element */ + public int getWidth() { return m_bounds.width; } + /** Sets width of this element */ + public void setWidth(int w) { m_bounds.width = w; } + + /** Gets y location of this element */ + public int getHeight() { return m_bounds.height; } + /** Sets y location of this element */ + public void setHeight(int h) { m_bounds.height = h; } + + /** Sets width/height of this element */ + public void setSize(int w, int h) { + m_bounds.width = w; m_bounds.height = h; + } + + /** Gets bounding rectangle of this element. */ + public Rectangle getBounds() { + return m_bounds; + } + /** Sets bounding rectangle of this element. */ + public void setBounds(int x, int y, int w, int h) { + m_bounds.x = x; + m_bounds.y = y; + m_bounds.width = w; + m_bounds.height = h; + } + /** Sets bounding rectangle of this element. */ + public void setBounds(Rectangle bounds) { + m_bounds.x = bounds.x; + m_bounds.y = bounds.y; + m_bounds.width = bounds.width; + m_bounds.height = bounds.height; + } + + /** Returns true if element bounds contains point. */ + public boolean contains(int x, int y) { + return m_bounds.contains(x,y); + } + /** Returns true if element bounds are within specified rectangle. */ + public boolean isWithin(Rectangle region) { + return (region.x <= m_bounds.x && + region.y <= m_bounds.y && + region.x + region.width >= m_bounds.x + m_bounds.width && + region.y + region.height >= m_bounds.y + m_bounds.height); + } + + /** Gets whether this element is visible. */ + public boolean isVisible() { + return m_visible; + } + + /** Sets whether this element is visible. */ + public void setVisible(boolean visible) { + m_visible = visible; + } + + /** Gets whether this element is selected. */ + public boolean isSelected() { + return m_selected; + } + + /** Sets whether this element is selected. */ + public void setSelected(boolean selected) { + m_selected = selected; + } + + /** Sets foreground color (null means inherit from container) */ + public void setForeground(Color color) { + m_foreground = color; + } + /** Gets foreground color (null means inherit from container) */ + public Color getForeground() { + return m_foreground; + } + + /** Sets foreground color (null means inherit from container) */ + public void setBackground(Color color) { + m_background = color; + } + /** Gets background color (null means inherit from container) */ + public Color getBackground() { + return m_background; + } + + + // --- methods --- + + /** Invoked to allow element to paint itself on the viewer canvas */ + public void paint(GC gc, boolean decorations) { + if (isVisible()) { + // Set GC to reflect object properties, if set. + Color oldForeground = null; + Color oldBackground = null; + if (m_foreground != null) { + oldForeground = gc.getForeground(); + gc.setForeground(m_foreground); + } + if (m_background != null) { + oldBackground = gc.getBackground(); + gc.setBackground(m_background); + } + + // Paint the object. + if (! decorations) + paintContent(gc); + else + paintDecorations(gc); + + // Restore old state. + if (m_foreground != null) gc.setForeground(oldForeground); + if (m_background != null) gc.setBackground(oldBackground); + } + } + + /** + * Paints content of graphic object. + * GC has already been set to this object's + * current foreground/background colors. + * Default implementation draws object's bounding box. + */ + public void paintContent(GC gc) { + // Draw boundary rectangle of object. + gc.drawRectangle(m_bounds); + + // Display selection as thicker boundary. + if (isSelected()) { + int x = m_bounds.x + 1; + int y = m_bounds.y + 1; + int width = m_bounds.width - 2; if (width < 0) width = 0; + int height = m_bounds.height - 2; if (height < 0) height = 0; + gc.drawRectangle(x,y,width,height); + } + } + + /** Returns true if object has decorations to paint. */ + public boolean hasDecorations() { + return false; + } + + /** Invoked to allow element to paint decorations + * on top of other items drawn on top of it. + */ + public void paintDecorations(GC gc) { + } +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/IGraphicObject.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/IGraphicObject.java new file mode 100755 index 00000000000..dc9c5f18df5 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/canvas/IGraphicObject.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui.canvas; + +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Rectangle; + + +// --------------------------------------------------------------------------- +// IGraphicObject +// --------------------------------------------------------------------------- + +/** + * An object that can be displayed and manipulated on a GraphicCanvas. + */ +public interface IGraphicObject +{ + // --- methods --- + + /** Paints object using specified graphics context. + * If decorations is false, draws ordinary object content. + * If decorations is true, paints optional "decorations" layer. + */ + public void paint(GC gc, boolean decorations); + + /** Returns true if object has decorations to paint. */ + public boolean hasDecorations(); + + /** Gets model data (if any) associated with this graphic object */ + public Object getData(); + + /** Sets model data (if any) associated with this graphic object */ + public void setData(Object data); + + /** Whether graphic object contains the specified point. */ + public boolean contains(int x, int y); + + /** Returns true if element bounds are within specified rectangle. */ + public boolean isWithin(Rectangle region); +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/events/IVisualizerViewerListener.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/events/IVisualizerViewerListener.java new file mode 100644 index 00000000000..82e20d0c3c8 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/events/IVisualizerViewerListener.java @@ -0,0 +1,31 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui.events; + +import org.eclipse.cdt.visualizer.ui.IVisualizerViewer; + + +// --------------------------------------------------------------------------- +// IVisualizerViewerListener +// --------------------------------------------------------------------------- + +/** + * IVisualizerViewer event listener. + */ +public interface IVisualizerViewerListener +{ + // --- methods --- + + /** Invoked when VisualizerViewer's selected IVisualizer changes. */ + public void visualizerEvent(IVisualizerViewer source, VisualizerViewerEvent event); + +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/events/VisualizerViewerEvent.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/events/VisualizerViewerEvent.java new file mode 100644 index 00000000000..825d24d0305 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/events/VisualizerViewerEvent.java @@ -0,0 +1,79 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui.events; + +import org.eclipse.cdt.visualizer.ui.IVisualizerViewer; +import org.eclipse.cdt.visualizer.ui.util.Event; + + +// --------------------------------------------------------------------------- +// VisualizerViewerEvent +// --------------------------------------------------------------------------- + +/** + * IVisualizerViewer event + */ +public class VisualizerViewerEvent extends Event +{ + // --- event types --- + + /** Event type constant */ + public static final int VISUALIZER_CHANGED = 1; + + /** Event type constant */ + public static final int VISUALIZER_CONTEXT_MENU = 2; + + + // --- members --- + + /** X coordinate, for menu events. */ + public int x; + + /** Y coordinate, for menu events. */ + public int y; + + + // --- constructors/destructors --- + + /** Constructor. */ + public VisualizerViewerEvent(IVisualizerViewer source, int eventType) { + super(source, eventType); + } + + /** Constructor. */ + public VisualizerViewerEvent(IVisualizerViewer source, int eventType, int x, int y) { + super(source, eventType); + this.x = x; + this.y = y; + } + + /** Dispose method. */ + public void dispose() { + super.dispose(); + } + + // --- Object methods --- + + /** Converts event type to string */ + public String typeToString(int type) { + String result = ""; + switch (type) { + case VISUALIZER_CHANGED: + result = "VISUALIZER_CHANGED"; break; + default: + result = super.typeToString(type); + break; + } + return result; + } + +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/plugin/CDTVisualizerUIPlugin.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/plugin/CDTVisualizerUIPlugin.java new file mode 100755 index 00000000000..3d47d69ea1f --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/plugin/CDTVisualizerUIPlugin.java @@ -0,0 +1,159 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui.plugin; + +import org.eclipse.cdt.visualizer.core.plugin.CDTVisualizerCorePlugin; +import org.eclipse.cdt.visualizer.ui.util.Colors; +import org.eclipse.cdt.visualizer.ui.util.UIResourceManager; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.Image; +import org.eclipse.ui.plugin.AbstractUIPlugin; +import org.osgi.framework.BundleContext; + + +// ---------------------------------------------------------------------------- +// CDTVisualizerUIPlugin +// ---------------------------------------------------------------------------- + +/** + * CDT visualizer UI plugin class. + * + * This plugin contains the UI components of the visualizer framework. + */ +public class CDTVisualizerUIPlugin extends AbstractUIPlugin +{ + // --- constants --- + + /** Feature ID (used as prefix for extension points, etc). */ + public static final String FEATURE_ID = "org.eclipse.cdt.visualizer.ui"; //$NON-NLS-1$ + + /** The plug-in ID */ + public static final String PLUGIN_ID = "org.eclipse.cdt.visualizer.ui"; //$NON-NLS-1$ + + + // --- static members --- + + /** Singleton instance */ + protected static CDTVisualizerUIPlugin s_plugin; + + /** Returns the singleton instance */ + public static CDTVisualizerUIPlugin getDefault() { + return s_plugin; + } + + /** Resource manager */ + protected static UIResourceManager s_resources = null; + + + // --- constructors/destructors --- + + /** + * Constructor + */ + public CDTVisualizerUIPlugin() { + } + + + // --- plugin startup/shutdown methods --- + + /** Invoked when plugin is loaded. */ + public void start(BundleContext context) throws Exception { + super.start(context); + s_plugin = this; + + // touch activator classes of any plugins we depend on, + // to ensure their start() methods are called first + // (None for now.) + + // initialize resource management (strings, images, fonts, colors, etc.) + getPluginResources(); + } + + /** Invoked when plugin is stopped. */ + public void stop(BundleContext context) throws Exception { + // clean up resource management + cleanupPluginResources(); + + s_plugin = null; + super.stop(context); + } + + + // --- logging --- + + /** + * Writes message to Eclipse log. + * Severity can be one of: + * Status.OK, Status.ERROR, Status.INFO, Status.WARNING, Status.CANCEL + */ + public static void log(int severity, String text) + { + Status status = new Status(severity, PLUGIN_ID, text); + ResourcesPlugin.getPlugin().getLog().log(status); + } + + + // --- resource management --- + + /** Returns resource manager for this plugin */ + public UIResourceManager getPluginResources() { + if (s_resources == null) { + s_resources = new UIResourceManager(this); + s_resources.setParentManager(CDTVisualizerCorePlugin.getResources()); + + // initialize Colors class, now that UIResources object is available. + Colors.initialize(s_resources); + } + + return s_resources; + } + + /** Releases resource manager for this plugin. */ + public void cleanupPluginResources() { + s_resources.dispose(); + } + + /** Convenience method for getting plugin resource manager */ + public static UIResourceManager getResources() { + return getDefault().getPluginResources(); + } + + /** Convenience method for looking up string resources */ + public static String getString(String key) { + return getDefault().getPluginResources().getString(key); + } + /** Convenience method for looking up string resources */ + public static String getString(String key, Object... arguments) { + return getDefault().getPluginResources().getString(key, arguments); + } + + /** Convenience method for looking up image resources */ + public static Image getImage(String key) { + return getDefault().getPluginResources().getImage(key); + } + /** Convenience method for looking up image resources */ + public static ImageDescriptor getImageDescriptor(String key) { + return getDefault().getPluginResources().getImageDescriptor(key); + } + + /** Convenience method for looking up font resources */ + public static Font getFont(String fontName, int height) { + return getDefault().getPluginResources().getFont(fontName, height); + } + /** Convenience method for looking up font resources */ + public static Font getFont(String fontName, int height, int style) { + return getDefault().getPluginResources().getFont(fontName, height, style); + } +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/test/TestCanvas.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/test/TestCanvas.java new file mode 100755 index 00000000000..13ea52d2e7a --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/test/TestCanvas.java @@ -0,0 +1,106 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui.test; + +import org.eclipse.cdt.visualizer.ui.canvas.GraphicCanvas; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.widgets.Composite; + + +// --------------------------------------------------------------------------- +// TestCanvas +// --------------------------------------------------------------------------- + +/** + * Default canvas control, used by TestCanvasVisualizer. + */ +public class TestCanvas extends GraphicCanvas +{ + // --- members --- + + /** Text string to display. */ + String m_text = null; + + + // --- constructors/destructors --- + + /** Constructor. */ + public TestCanvas(Composite parent) { + super(parent); + initDefaultCanvas(parent); + } + + /** Dispose method. */ + public void dispose() { + cleanupDefaultCanvas(); + super.dispose(); + } + + + // --- init methods --- + + /** Initializes control */ + protected void initDefaultCanvas(Composite parent) { + // perform any initialization here + } + + /** Cleans up control */ + protected void cleanupDefaultCanvas() { + } + + + // --- accessors --- + + /** Sets text string to display. */ + public void setText(String text) + { + m_text = text; + } + + + // --- methods --- + + /** Invoked when canvas repaint event is raised. + * Default implementation clears canvas to background color. + */ + public void paintCanvas(GC gc) { + super.paintCanvas(gc); + + int margin = 10; + drawStringWrapNewlines(gc, m_text, margin, margin); + } + + + // --- utilities --- + + /** Gets line height of text, based on current font */ + public static int getTextHeight(GC gc) { + return gc.getFontMetrics().getHeight(); + } + + /** Draw string, wrapping if there are any newline chars. */ + public static void drawStringWrapNewlines(GC gc, String text, int x, int y) { + int lineHeight = getTextHeight(gc); + drawStringWrapNewlines(gc, text, x, y, lineHeight); + } + + /** Draw string, wrapping if there are any newline chars. */ + public static void drawStringWrapNewlines(GC gc, String text, int x, int y, int lineHeight) { + if (text != null) { + String[] lines = text.split("\n"); + for (int i=0; i m_listeners = null; + + + // --- constructors/destructors --- + + /** Constructor. */ + public ListenerList(Object owner, String label) { + m_owner = owner; + m_label = label; + } + + /** Dispose method. */ + public void dispose() { + m_owner = null; + m_label = null; + if (m_listeners != null) { + clear(); + m_listeners = null; + } + } + + + // --- methods --- + + /** Clears list of listeners */ + public synchronized void clear() { + if (m_listeners != null) { + m_listeners.clear(); + } + } + + /** Returns count of current listeners. */ + public synchronized int size() { + return (m_listeners == null) ? 0 : m_listeners.size(); + } + + /** Adds a listener */ + public synchronized void addListener(Object listener) { + if (m_listeners == null) { + m_listeners = new ArrayList(); + } + if (! m_listeners.contains(listener)) { + m_listeners.add(listener); + } + } + + /** Removes a listener */ + public synchronized void removeListener(Object listener) { + if (m_listeners != null) { + m_listeners.remove(listener); + } + } + + /** + * Dispatches event to all attached listeners + * Invokes raise(listener, event) for each attached listener. + */ + public void raise (final Object event) + { + // we can't use an iterator here, because + // the listener list might change while we're walking it, + // which would make the iterator throw a ConcurrentModificationException, + // hence we'll make a private copy of the listener list + ArrayList listeners = null; + synchronized (this) { + // keep the lock on the listener list as brief as possible + if (m_listeners != null) { + listeners = new ArrayList(m_listeners); + } + } + int count = (listeners == null) ? 0 : listeners.size(); + for (int i=0; i MOUSE_DRAG_HYSTERESIS) { + m_mouseDrag = true; + + // initialize mouse drag + drag(m_mouseDownButton, m_mouseDownPoint.x, m_mouseDownPoint.y, keys, MOUSE_DRAG_BEGIN); + } + } + if (m_mouseDrag) { + // update mouse drag + int dx = x - m_mouseDownPoint.x; + int dy = y - m_mouseDownPoint.y; + setDragPoint(x,y); + setDragRegionFromPoints(m_mouseDownPoint.x, m_mouseDownPoint.y, x, y); + drag(m_mouseDownButton, dx, dy, keys, MOUSE_DRAG); + } + } + mouseMove(x, y, keys); + } + + /** Invoked when mouse button is released */ + protected void mouseUpHandler(int button, int x, int y, int keys) { + if (m_mouseDown) { + if (m_mouseDrag) { + // finish mouse drag + int dx = x - m_mouseDownPoint.x; + int dy = y - m_mouseDownPoint.y; + setDragPoint(x,y); + setDragRegionFromPoints(m_mouseDownPoint.x, m_mouseDownPoint.y, x, y); + drag(m_mouseDownButton, dx, dy, keys, MOUSE_DRAG_END); + m_mouseDrag = false; + } + else { + if (button == RIGHT_BUTTON) { + contextMenu(x, y, keys); + } + else { + select(x, y, keys); + } + } + m_mouseDown = false; + } + mouseUp(button, x, y, keys); + } + + /** Invoked when mouse button is double-clicked */ + protected void mouseDoubleClickHandler(int button, int x, int y, int keys) { + mouseDoubleClick(button, x, y, keys); + } + + /** Invoked when mouse pointer enters control region */ + protected void mouseEnterHandler(int x, int y) { + if (! m_mouseDown) { + mouseEnter(x, y); + } + } + + /** Invoked when mouse pointer exits control region */ + protected void mouseExitHandler(int x, int y) { + if (! m_mouseDown) { + mouseExit(x, y); + } + } + + /** Invoked when mouse pointer hovers over control */ + protected void mouseHoverHandler(int x, int y) { + if (! m_mouseDown) { + mouseHover(x, y); + } + } + + + // --- event handlers --- + + // These are intended to be overridden by derived types. + // A user of this class need only override methods for events + // that need to be tracked. + + /** Invoked when mouse button is pressed */ + public void mouseDown(int button, int x, int y, int keys) {} + + /** Invoked when mouse is moved */ + public void mouseMove(int x, int y, int keys) {} + + /** Invoked when mouse button is released */ + public void mouseUp(int button, int x, int y, int keys) {} + + /** Invoked for a selection click at the specified point. */ + public void select(int x, int y, int keys) {} + + /** Invoked for a context menu click at the specified point. */ + public void contextMenu(int x, int y, int keys) {} + + /** Invoked when mouse button is double-clicked */ + public void mouseDoubleClick(int button, int x, int y, int keys) {} + + /** Invoked when mouse is dragged (moved with mouse button down). + * Drag state indicates stage of drag: + * - MOUSE_DRAG_BEGIN -- dx, dy offset from initial mouse down point (initial mouse down) + * - MOUSE_DRAG -- dx, dy of intermediate drag offset (initial mouse down, then each mouse move) + * - MOUSE_DRAG_END -- dx, dy of final drag offset (mouse up) + * The pattern of calls is always: BEGIN, DRAG(+), END. + */ + public void drag(int button, int x, int y, int keys, int dragState) {} + + /** Invoked when mouse pointer enters control region */ + public void mouseEnter(int x, int y) {} + + /** Invoked when mouse pointer exits control region */ + public void mouseExit(int x, int y) {} + + /** Invoked when mouse pointer hovers over control */ + public void mouseHover(int x, int y) {} + +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/RunnableWithResult.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/RunnableWithResult.java new file mode 100644 index 00000000000..952d17730da --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/RunnableWithResult.java @@ -0,0 +1,159 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui.util; + +import java.util.concurrent.Callable; + + +/** + * Runnable object that returns a result object. + * + * This is like Future from the concurrent package, + * but with a few less bells and whistles. + * + * Intended to be used, for example, as follows: + * + * RunnableWithResult runnable = new RunnableWithResult() { + * public X call() { + * ... do work, return an X object ... + * } + * } + * + * Thread thread = new Thread(runnable); + * thread.start(); + * X result = runnable.getResult(0); + * + * or, to run it on the UI thread... + * + * GUIUtils.execAndWait(runnable); + * X result = runnable.getResult(0); + * + * Note: if you're invoking this from the UI thread, + * it's important to use execAndWait(), so that the runnable + * gets a turn on the event loop, otherwise you'll hang the UI! + * + */ +public class RunnableWithResult + implements Runnable, Callable +{ + // --- members --- + + /** Result to return */ + protected V m_result = null; + + /** Whether run() has completed */ + protected boolean m_done = false; + + + // --- constructors/destructors --- + + /** Constructor. */ + public RunnableWithResult() { + } + + /** Dispose method. */ + public void dispose() { + m_result = null; + } + + + // --- accessors --- + + /** Sets result value */ + public void setResult(V result) { + m_result = result; + } + + /** Gets result value. */ + public V getResult() { + return m_result; + } + + + // --- Runnable implementation --- + + /** Run method. + * Derived types should override call() rather than this method. + */ + public void run() { + m_done = false; + setResult(call()); + m_done = true; + synchronized (this) { + notifyAll(); + } + } + + + // --- Callable implementation --- + + /** Method that returns the value. + * Default implementation returns null. + */ + public V call() { + return null; + } + + + // --- methods --- + + /** Waits for result and returns it. */ + public V waitForResult() { + return waitForResult(0, null); + } + + /** Waits for result and returns it. */ + public V waitForResult(long timeout) { + return waitForResult(timeout, null); + } + + /** Waits for result and returns it. + * Returns null if specified timeout is exceeded. + */ + public V waitForResult(long timeout, V defaultValue) { + V result = defaultValue; + try { + if (timeout == 0) { + // wait forever + // (guard against spurious thread wakeup -- see wait() Javadoc) + while (! m_done) { + synchronized (this) { + this.wait(0); + } + } + } + else { + // wait until specified timeout + // (guard against spurious thread wakeup -- see wait() Javadoc) + long then = now(); + long waitstep = timeout / 10; + if (waitstep == 0) waitstep = 1; + do { + synchronized (this) { + this.wait(waitstep); + } + } + while (! m_done && ((now() - then) < timeout)); + } + } + catch (InterruptedException e) { + } + if (m_done) result = getResult(); + return result; + } + + /** Returns current time in milliseconds. */ + protected static long now() { + return System.currentTimeMillis(); + } +} + diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/SelectionManager.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/SelectionManager.java new file mode 100755 index 00000000000..0609d566243 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/SelectionManager.java @@ -0,0 +1,166 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui.util; + +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.jface.viewers.SelectionChangedEvent; + + +// --------------------------------------------------------------------------- +// SelectionManager +// --------------------------------------------------------------------------- + +/** + * Selection management utility class + */ +public class SelectionManager + implements ISelectionProvider +{ + // --- members --- + + /** Actual source to report for selection change events. */ + protected ISelectionProvider m_source = null; + + /** Manager label, also used on listener list. */ + protected String m_label = null; + + /** Current selection, if any. */ + protected ISelection m_selection = SelectionUtils.EMPTY_SELECTION; + + /** Selection changed listeners */ + protected ListenerList m_selectionListeners = null; + + /** Whether selection events are enabled */ + protected boolean m_selectionEventsEnabled = true; + + // --- constructors/destructors --- + + /** Constructor. */ + public SelectionManager(ISelectionProvider source, String label) + { + m_source = (source == null) ? this : source; + m_label = label; + m_selectionListeners = new ListenerList(this, label + ", listener list") { + public void raise(Object listener, Object event) { + if (listener instanceof ISelectionChangedListener && + event instanceof SelectionChangedEvent) + { + ISelectionChangedListener typedListener = (ISelectionChangedListener) listener; + SelectionChangedEvent typedEvent = (SelectionChangedEvent) event; + typedListener.selectionChanged(typedEvent); + } + } + }; + } + + /** Dispose method. */ + public void dispose() + { + m_selectionEventsEnabled = false; + m_selection = SelectionUtils.EMPTY_SELECTION; + if (m_selectionListeners != null) { + m_selectionListeners.clear(); + m_selectionListeners = null; + } + // m_label = null; // leave label, to aid in debugging cleanup + m_source = null; + } + + // --- ISelectionProvider implementation --- + + /** Adds selection changed listener. */ + public void addSelectionChangedListener(ISelectionChangedListener listener) + { + if (listener == null) return; + m_selectionListeners.addListener(listener); + // fake a selection changed event so new listener can update itself properly + listener.selectionChanged(new SelectionChangedEvent(m_source, getSelection())); + } + + /** Removes selection changed listener. */ + public void removeSelectionChangedListener(ISelectionChangedListener listener) + { + if (listener == null) return; + m_selectionListeners.removeListener(listener); + } + + /** Returns current selection. */ + public ISelection getSelection() + { + return m_selection; + } + + /** Sets selection, and raises change event. */ + public void setSelection(ISelection selection) + { + setSelection(selection, true); + } + + /** Sets selection, and raises change event with specified provider as the source. */ + public void setSelection(ISelectionProvider provider, ISelection selection) + { + setSelection(provider, selection, true); + } + + /** Sets selection, and raises change event + * if raiseEvent is true. */ + public void setSelection(ISelection selection, boolean raiseEvent) + { + if (selection == null) + selection = SelectionUtils.EMPTY_SELECTION; + m_selection = selection; + if (raiseEvent) raiseSelectionChangedEvent(); + } + + /** Sets selection, and raises change event with specified provider as the source + * if raiseEvent is true. */ + public void setSelection(ISelectionProvider provider, ISelection selection, boolean raiseEvent) + { + if (selection == null) + selection = SelectionUtils.EMPTY_SELECTION; + m_selection = selection; + if (raiseEvent) raiseSelectionChangedEvent(provider); + } + + /** Returns true if we currently have a non-emptr selection. */ + public boolean hasSelection() + { + return (SelectionUtils.getSelectionSize(m_selection) > 0); + } + + + // --- methods --- + + /** Gets whether selection events are enabled. */ + public boolean getSelectionEventsEnabled() { + return m_selectionEventsEnabled; + } + + /** Sets whether selection events are enabled. */ + public void setSelectionEventsEnabled(boolean enabled) { + m_selectionEventsEnabled = enabled; + } + + /** Raises selection changed event. */ + public void raiseSelectionChangedEvent() { + if (m_selectionEventsEnabled) + m_selectionListeners.raise(new SelectionChangedEvent(m_source, getSelection())); + } + + /** Raises selection changed event with specified provider as source. */ + public void raiseSelectionChangedEvent(ISelectionProvider provider) { + if (m_selectionEventsEnabled) + m_selectionListeners.raise(new SelectionChangedEvent(provider, getSelection())); + } +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/SelectionProviderAdapter.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/SelectionProviderAdapter.java new file mode 100755 index 00000000000..522700edb60 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/SelectionProviderAdapter.java @@ -0,0 +1,97 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui.util; + +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.ISelectionProvider; + + +// --------------------------------------------------------------------------- +// SelectionProviderAdapter +// --------------------------------------------------------------------------- + +/** + * Wrapper for selection "providers" that don't happen to implement + * ISelectionProvider interface. + */ +public class SelectionProviderAdapter + implements ISelectionProvider +{ + // --- members --- + + /** Real source object. */ + protected Object m_source = null; + + /** Selection manager. */ + protected SelectionManager m_selectionManager = null; + + + // --- constructors/destructors --- + + /** Constructor. */ + public SelectionProviderAdapter(Object source) { + m_source = source; + m_selectionManager = new SelectionManager(this, "SelectionProviderAdapter for source " + m_source.toString()); + } + + /** Dispose method. */ + public void dispose() { + m_source = null; + if (m_selectionManager != null) { + m_selectionManager.dispose(); + m_selectionManager = null; + } + } + + + // --- accessors --- + + /** Gets wrapped selection source. */ + public Object getActualSource() { + return m_source; + } + + + // --- ISelectionProvider implementation --- + + /** Adds selection change listener. + * Default implementation does nothing. + */ + public void addSelectionChangedListener(ISelectionChangedListener listener) + { + m_selectionManager.addSelectionChangedListener(listener); + } + + /** Removes selection change listener. + * Default implementation does nothing. + */ + public void removeSelectionChangedListener(ISelectionChangedListener listener) + { + m_selectionManager.removeSelectionChangedListener(listener); + } + + /** Gets selection. + * Default implementation does nothing. + */ + public ISelection getSelection() { + return m_selectionManager.getSelection(); + } + + /** Sets selection. + * Default implementation does nothing. + */ + public void setSelection(ISelection selection) + { + m_selectionManager.setSelection(selection); + } +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/SelectionUtils.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/SelectionUtils.java new file mode 100644 index 00000000000..fd6f9a5b637 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/SelectionUtils.java @@ -0,0 +1,280 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui.util; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PlatformUI; + + +//---------------------------------------------------------------------------- +// SelectionUtils +//---------------------------------------------------------------------------- + +/** Eclipse ISelection munging utilities. */ +public class SelectionUtils +{ + // --- constants --- + + /** Special value for an "empty" selection, + * since selection cannot be null. + */ + public static final ISelection EMPTY_SELECTION = new EmptySelection(); + + /** "Empty" or undefined selection. */ + public static class EmptySelection + implements ISelection, IStructuredSelection + { + public boolean isEmpty() { + return true; + } + + public Iterator iterator() { + return new ArrayList().iterator(); + } + + public List toList() { + return new ArrayList(); + } + + public int size() { + return 0; + } + + public Object getFirstElement() { + return null; + } + + public Object[] toArray() { + return new Object[0]; + } + } + + + // --- selection utilities --- + + /** + * Returns workbench selection, if any. + */ + public static ISelection getWorkbenchSelection() { + ISelection result = null; + IWorkbenchPage page = getWorkbenchPage(); + if (page != null) { + result = page.getSelection(); + } + return result; + } + + /** Creates an ISelection from a collection of objects */ + public static ISelection toSelection(Collection objects) { + return (objects == null) ? null : new StructuredSelection(toList(objects)); + } + + /** Creates an ISelection from a list of objects */ + public static ISelection toSelection(List objects) { + return (objects == null) ? null : new StructuredSelection(objects); + } + + /** Creates an ISelection from the specified object(s) */ + public static ISelection toSelection(T... objects) { + return (objects == null) ? null : new StructuredSelection(objects); + } + + /** + * Gets number of top-level object(s) from an Eclipse ISelection. + */ + public static int getSelectionSize(ISelection selection) { + int result = 0; + if (selection == EMPTY_SELECTION) { + // nothing to do + } + else if (selection instanceof IStructuredSelection) { + IStructuredSelection structuredSelection = (IStructuredSelection) selection; + result = structuredSelection.size(); + } + else if (selection instanceof ISelection) { + result = ((ISelection) selection).isEmpty() ? 0 : 1; + } + // collections are not ISelections, this just makes the method a little more generic + else if (selection instanceof Collection) { + Collection collection = (Collection) selection; + result = collection.size(); + } + else if (selection != null) { + result = 1; + } + return result; + } + + /** + * Gets selected object(s) from an Eclipse ISelection as a List. + * If selection is a multiple selection (an IStructuredSelection or Collection), + * the list contains the top-level elements of the selection. + * Otherwise the list contains the ISelection itself. + */ + public static List getSelectedObjects(ISelection selection) { + List result = null; + if (selection instanceof IStructuredSelection) { + IStructuredSelection structuredSelection = (IStructuredSelection) selection; + result = new ArrayList((List) structuredSelection.toList()); + } + else if (selection instanceof Collection) { + Collection collection = (Collection) selection; + result = new ArrayList(collection); + } + else { + List list = new ArrayList(); + list.add(selection); + result = list; + } + return result; + } + + /** + * Gets single selected object from an Eclipse ISelection. + * If selection is a single selection, returns it. + * If selection is multiple selection, returns first selected item. + */ + public static Object getSelectedObject(ISelection selection) { + Object result = null; + if (selection instanceof IStructuredSelection) { + IStructuredSelection structuredSelection = (IStructuredSelection) selection; + result = structuredSelection.getFirstElement(); + } + else if (selection instanceof Collection) { + Collection collection = (Collection) selection; + Iterator i = collection.iterator(); + if (i.hasNext()) result = i.next(); + } + else { + result = selection; + } + return result; + } + + /** + * Creates Eclipse ISelection from a list. + */ + public static ISelection toISelection(List items) { + return new StructuredSelection(items); + } + + /** + * Creates Eclipse ISelection from one or more items or an array of items. + */ + public static ISelection toISelection(T... items) { + return new StructuredSelection(items); + } + + /** + * Gets iterator for an ISelection. + * Note: returns null if ISelection is not an IStructuredSelection, + * which is the only interface that currently defines an Iterator. + */ + public static Iterator getSelectionIterator(ISelection iselection) { + Iterator result = null; + if (iselection instanceof IStructuredSelection) { + result = ((IStructuredSelection) iselection).iterator(); + } + return result; + } + + + // --- debugging tools --- + + /** Converts selection to string, for debug display. */ + public static String toString(ISelection selection) { + String result = null; + // convert selection to text string + if (selection == null) { + result = "No selection"; + } + else if (selection instanceof IStructuredSelection) { + IStructuredSelection structuredSelection = (IStructuredSelection) selection; + List elements = structuredSelection.toList(); + int size = elements.size(); + if (size == 0) { + result = "Empty selection"; + } + else { + result = "Selection: "; + for (int i=0; i0) result += "\n"; + Object o = elements.get(i); + String type = o.getClass().getName(); + String value = o.toString(); + result += "[" + i + "]: type= + " + type + ", value='" + value + "'"; + } + } + } + else { + String type = selection.getClass().getName(); + String value = selection.toString(); + result = "Selection: (type = " + type + ") " + value; + } + return result; + } + + // --- utilities --- + + /** Creates list from array/set of elements */ + public static List toList(Collection collection) { + int size = (collection == null) ? 0 : collection.size(); + List result = new ArrayList(size); + if (collection != null) result.addAll(collection); + return result; + } + + /** Gets current Eclipse workbench */ + public static IWorkbench getWorkbench() { + IWorkbench result = null; + try { + result = PlatformUI.getWorkbench(); + } + catch (IllegalStateException e) { + // Workbench is not defined for some reason. Oh well. + } + return result; + } + + /** Gets current Eclipse workbench window. + * Returns null if workbench does not exist. + */ + public static IWorkbenchWindow getWorkbenchWindow() { + IWorkbenchWindow result = null; + IWorkbench workbench = getWorkbench(); + if (workbench != null) { + result = workbench.getActiveWorkbenchWindow(); + if (result == null) { + if (workbench.getWorkbenchWindowCount() > 0) { + result = (IWorkbenchWindow) workbench.getWorkbenchWindows()[0]; + } + } + } + return result; + } + + /** Gets current Eclipse workbench page */ + public static IWorkbenchPage getWorkbenchPage() { + IWorkbenchWindow window = getWorkbenchWindow(); + return (window == null) ? null : window.getActivePage(); + } +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/Timer.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/Timer.java new file mode 100755 index 00000000000..28b31bd3267 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/Timer.java @@ -0,0 +1,100 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui.util; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + + +// --------------------------------------------------------------------------- +// Timer +// --------------------------------------------------------------------------- + +/** + * Periodic event timer class. + */ +public class Timer + implements ActionListener, Runnable +{ + // --- members --- + + /** Actual timer */ + // NOTE: we delegate rather than subclassing, because + // Timer class implements ISerializable, so every derived type + // must either declare a serialization ID, or suppress the warning. + protected javax.swing.Timer m_timer = null; + + + // --- constructors/destructors --- + + /** Constructor. */ + public Timer(int intervalMilliseconds) { + m_timer = new javax.swing.Timer(intervalMilliseconds, null); + m_timer.addActionListener(this); + m_timer.setRepeats(true); + m_timer.setCoalesce(true); + m_timer.start(); + } + + /** Dispose method. */ + public void dispose() { + if (m_timer != null) { + if (m_timer.isRunning()) { + m_timer.stop(); + } + m_timer = null; + } + } + + + // --- methods --- + + /** Gets whether timer repeatedly fires events. */ + public boolean isRepeating() { + return m_timer.isRepeats(); + } + + /** Sets whether timer repeatedly fires events. */ + public void setRepeating(boolean repeats) { + m_timer.setRepeats(repeats); + } + + /** Starts/restarts timer. + * Has no effect if timer is already running + */ + public void start() { + if (! m_timer.isRunning()) m_timer.start(); + } + + /** Stops timer. + * Has no effect if timer is already stopped. + */ + public void stop() { + if (m_timer.isRunning()) m_timer.stop(); + } + + + // --- ActionListener implementation --- + + /** + * Invoked each time the timer fires. + * Default implementation invokes the run() method on the UI thread. + */ + public void actionPerformed(ActionEvent e) { + GUIUtils.exec(this); + } + + /** Invoked each time the timer fires. */ + public void run() { + } + +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/Todo.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/Todo.java new file mode 100644 index 00000000000..3dfdec2d8a9 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/Todo.java @@ -0,0 +1,99 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) - initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui.util; + +/** Counter for objects that need to track asynchronous progress. */ +public class Todo { + + // --- members --- + + /** Count of things left to do. */ + int m_count = 0; + + + // --- constructors/destructors --- + + /** Constructor. */ + public Todo() { + } + + /** Constructor. */ + public Todo(int count) { + m_count = count; + } + + /** Dispose method. */ + public void dispose() { + m_count = 0; + } + + + // --- accessors --- + + /** Gets count. */ + public int get() { + return m_count; + } + + /** Sets count. */ + public void set(int count) { + m_count = count; + } + + /** Returns true if count has reached zero. */ + public boolean isDone() { + return m_count <= 0; + } + + /** Increments count, returns new value. */ + public int increment(int n) { + return (m_count += n); + } + + /** Increments count, returns new value. */ + public int increment() { + return (m_count += 1); + } + + /** Decrements count, returns new value. */ + public int decrement(int n) { + return (m_count -= n); + } + + /** Decrements count, returns new value. */ + public int decrement() { + return (m_count -= 1); + } + + + // --- methods --- + + /** Adds completion steps to count. */ + public void add(int n) { + increment(n); + } + + /** Adds completion step to count. */ + public void add() { + increment(1); + } + + /** Decrements count, returns true when it's reached zero. */ + public boolean done(int n) { + return decrement(n) <= 0; + } + + /** Decrements count, returns true when it's reached zero. */ + public boolean done() { + return decrement() <= 0; + } +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/UIResourceManager.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/UIResourceManager.java new file mode 100755 index 00000000000..353481b2d7b --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/UIResourceManager.java @@ -0,0 +1,375 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui.util; + +import java.net.URL; + +import org.eclipse.cdt.visualizer.core.ResourceManager; +import org.eclipse.jface.resource.ColorRegistry; +import org.eclipse.jface.resource.FontRegistry; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.resource.ImageRegistry; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.FontData; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.plugin.AbstractUIPlugin; + + +// --------------------------------------------------------------------------- +// UIResourceManager +// --------------------------------------------------------------------------- + +/** + * Plugin resource manager. + * Provides one-stop-shopping for UI plugin resources + * (strings, images, fonts, colors). + * This class should be instanced in the UI plugin's "start()" method, + * and disposed in the "stop()" method. + */ +public class UIResourceManager extends ResourceManager +{ + // --- members --- + + /** UI Plugin */ + protected AbstractUIPlugin m_UIplugin = null; + + /** Parent resource manager, if any */ + protected UIResourceManager m_parentUIManager = null; + + /** Image resource manager */ + protected ImageRegistry m_images = null; + + /** Font resource manager */ + protected FontRegistry m_fonts = null; + + /** Color resource manager */ + protected ColorRegistry m_colors = null; + + + // --- constructors/destructors --- + + /** Constructor + * Note: the plugin ID is assumed to also be the parent package name + * of the plugin, for example "com.tilera.ide.core"; it's assumed that string + * resources are found in the plugin directory in "messages.properties". + */ + public UIResourceManager(AbstractUIPlugin plugin) { + super(plugin); + m_UIplugin = plugin; + getImageRegistry(); // creates registry object + getFontRegistry(); // creates registry object + getColorRegistry(); // creates registry object + } + + /** Dispose method */ + public void dispose() { + disposeImageRegistry(); + disposeFontRegistry(); + disposeColorRegistry(); + } + + + // --- parent manager management --- + + /** Sets parent resource manager, if any */ + public void setParentManager(ResourceManager parentManager) { + super.setParentManager(parentManager); + if (parentManager instanceof UIResourceManager) { + m_parentUIManager = (UIResourceManager) parentManager; + } + else { + m_parentUIManager = null; + } + } + + /** Gets parent UI resource manager, if any */ + public UIResourceManager getParentManager() { + return m_parentUIManager; + } + + + // --- image resource management --- + + /** Creates/returns image registry */ + protected ImageRegistry getImageRegistry() { + if (m_images == null) { + // use the plugin's image registry + m_images = m_UIplugin.getImageRegistry(); + } + return m_images; + } + + /** Disposes image registry */ + protected void disposeImageRegistry() { + if (m_images != null) { + // we're using the plugin's image registry, so it will dispose of it + //m_images.dispose(); + m_images = null; + } + } + + /** + * Returns an image descriptor for the image file at the given + * plug-in relative path. + */ + public ImageDescriptor getImageDescriptor(String path) { + ImageDescriptor result = null; + if (path == null) return result; + + // get image registry, look up path + ImageRegistry images = getImageRegistry(); + result = images.getDescriptor(path); + + // if we don't find it, see if it exists as a file in this plugin + if (result == null) { + URL url = m_UIplugin.getBundle().getEntry(path); + if (url != null) { + // if so, we'll add an entry for it to this resource manager + ImageDescriptor desc = ImageDescriptor.createFromURL(url); + images.put(path, desc); + result = images.getDescriptor(path); + } + else { + // if not, see if we can find it in the parent manager + // NOTE: this may be in a different plugin, so the path will be + // resolved relative to that plugin's base directory + UIResourceManager parent = getParentManager(); + if (parent != null) { + result = parent.getImageDescriptor(path); + } + } + } + return result; + } + + /** + * Gets specified image from plugin directory. + * Caches images so subsequent requests will be faster. + */ + public Image getImage(String path) { + Image result = null; + if (path == null) return result; + + // get image registry, look up path + ImageRegistry images = getImageRegistry(); + result = images.get(path); + + // if we don't find it, see if it exists as a file in this plugin + if (result == null) { + URL url = m_UIplugin.getBundle().getEntry(path); + if (url != null) { + // if so, we'll add an entry for it to this resource manager + ImageDescriptor desc = ImageDescriptor.createFromURL(url); + images.put(path, desc); + result = images.get(path); + } + else { + // if not, see if we can find it in the parent manager + // NOTE: this may be in a different plugin, so the path will be + // resolved relative to that plugin's base directory + UIResourceManager parent = getParentManager(); + if (parent != null) { + result = parent.getImage(path); + } + } + } + return result; + } + + + // --- font registry --- + + /** Creates/returns font registry */ + protected FontRegistry getFontRegistry() { + if (m_fonts == null) { + Display display = getDisplay(); + m_fonts = new FontRegistry(display); + } + return m_fonts; + } + + /** Disposes font registry */ + protected void disposeFontRegistry() { + if (m_fonts != null) { + // doesn't appear to be a way to flush the registry cache + // so let finalizer handle it + m_fonts = null; + } + } + + /** Sets cached font for specified ID */ + public void setFont(String fontID, String fontName, int height, int style) { + setCachedFont(fontID, fontName, height, style); + } + + /** Gets cached font for specified ID */ + public Font getFont(String fontID) { + return getCachedFont(fontID); + } + + /** Gets/creates font with specified properties */ + public Font getFont(String fontName, int height) { + return getCachedFont(fontName, height, SWT.NORMAL); + } + + /** Gets/creates font with specified properties */ + public Font getFont(String fontName, int height, int style) { + return getCachedFont(fontName, height, style); + } + + /** Sets cached font for specified ID */ + protected void setCachedFont(String fontID, String fontName, int height, int style) { + FontData[] fontData = new FontData[1]; + fontData[0] = new FontData(fontName, height, style); + FontRegistry fonts = getFontRegistry(); + fonts.put(fontID, fontData); + } + + /** Gets cached font, if any, for specified ID */ + protected Font getCachedFont(String fontID) { + Font result = null; + + // get font registry, look up font ID + FontRegistry fonts = getFontRegistry(); + if (fonts.hasValueFor(fontID)) { + result = fonts.get(fontID); + } + else { + // if we don't find it, see if parent manager has it + UIResourceManager parent = getParentManager(); + if (parent != null) { + result = parent.getCachedFont(fontID); + } + } + return result; + } + + /** Gets/creates font with specified properties */ + protected Font getCachedFont(String fontName, int height, int style) { + Font result = null; + String fontID = fontName + "," + height + "," + style; + + // look for the cached font (this checks the parent manager too) + result = getCachedFont(fontID); + + // if we didn't find it, add an entry to this resource manager + if (result == null) { + setCachedFont(fontID, fontName, height, style); + result = getCachedFont(fontID); + } + return result; + } + + + // --- color registry --- + + /** Creates/returns color registry */ + protected ColorRegistry getColorRegistry() { + if (m_colors == null) { + Display display = getDisplay(); + m_colors = new ColorRegistry(display); + } + return m_colors; + } + + /** Disposes color registry */ + protected void disposeColorRegistry() { + if (m_colors != null) { + // doesn't appear to be a way to flush the registry cache + // so let finalizer handle it + m_colors = null; + } + } + + /** Gets cached color with specified SWT color ID */ + public Color getColor(int colorID) { + // NOTE: we don't cache these colors, we just look them up every time + return getDisplay().getSystemColor(colorID); + } + + /** Gets cached color with specified ID */ + public Color getColor(String colorID) { + return getCachedColor(colorID); + } + + /** Gets/creates color with specified properties */ + public Color getColor(int red, int green, int blue) { + return getCachedColor(red, green, blue); + } + + /** Sets cached color for specified ID */ + protected void setCachedColor(String colorID, int red, int green, int blue) { + RGB rgb = new RGB(red, green, blue); + ColorRegistry colors = getColorRegistry(); + colors.put(colorID, rgb); + } + + /** Gets cached color with specified ID */ + protected Color getCachedColor(String colorID) { + Color result = null; + ColorRegistry colors = getColorRegistry(); + if (colors.hasValueFor(colorID)) { + result = colors.get(colorID); + } + else { + // if we don't find it, see if parent manager has it + UIResourceManager parent = getParentManager(); + if (parent != null) { + result = parent.getCachedColor(colorID); + } + } + return result; + } + + /** Gets/creates color with specified properties */ + protected Color getCachedColor(int red, int green, int blue) { + Color result = null; + String colorID = "Color[R=" + red + ",G=" + green + ",B=" + blue + "]"; + + // look for the cached color (this checks the parent manager too) + result = getCachedColor(colorID); + + // if we don't find it, create an entry in this resource manager + if (result == null) { + setCachedColor(colorID, red, green, blue); + result = getCachedColor(colorID); + } + return result; + } + + + // --- utilities --- + + /** + * Returns the current SWT display. + * + * The method first checks whether the caller already has + * an associated display. If so, this display is returned. + * Otherwise the method returns the default display. + * + * This allows GUIUtils to work in contexts like tests + * where the SWT display has not already been defined. + * + * (Credit: Borrowed from DebugUIPlugin.) + */ + public static Display getDisplay() { + Display display= Display.getCurrent(); + if (display == null) { + display= Display.getDefault(); + } + return display; + } +} diff --git a/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/WorkbenchSelectionAdapter.java b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/WorkbenchSelectionAdapter.java new file mode 100755 index 00000000000..0c268491f51 --- /dev/null +++ b/visualizer/org.eclipse.cdt.visualizer.ui/src/org/eclipse/cdt/visualizer/ui/util/WorkbenchSelectionAdapter.java @@ -0,0 +1,220 @@ +/******************************************************************************* + * Copyright (c) 2012 Tilera 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * William R. Swanson (Tilera Corporation) + *******************************************************************************/ + +package org.eclipse.cdt.visualizer.ui.util; + +import java.util.List; + +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.ui.ISelectionListener; +import org.eclipse.ui.IViewPart; +import org.eclipse.ui.IWorkbenchPart; + + +// --------------------------------------------------------------------------- +// WorkbenchSelectionAdapter +// --------------------------------------------------------------------------- + +/** + * Selection change event manager + */ +public class WorkbenchSelectionAdapter + implements ISelectionListener, ISelectionProvider +{ + // --- members --- + + /** Workbench part (view) this adapter is associated with. */ + protected IViewPart m_view = null; + + /** Current selection */ + protected ISelection m_selection = null; + + /** Listeners for selection changed events. */ + protected ListenerList m_selectionListeners = null; + + /** Whether selection events are reported */ + protected boolean m_trackSelection = true; + + + // --- constructors/destructors --- + + /** Constructor. */ + public WorkbenchSelectionAdapter(IViewPart view) { + m_view = view; + m_selection = null; + m_selectionListeners = new ListenerList(view, "WorkbenchSelectionAdapter for view " + view.getClass().getSimpleName()) + { + /** Dispatches event to listeners */ + public void raise(Object listener, Object event) { + if (listener instanceof ISelectionChangedListener && + event instanceof SelectionChangedEvent) + { + ISelectionChangedListener typedListener = (ISelectionChangedListener) listener; + SelectionChangedEvent typedEvent = (SelectionChangedEvent) event; + typedListener.selectionChanged(typedEvent); + } + } + }; + + // listen for external selection changed events + m_view.getSite().getPage().addSelectionListener(this); + + // set selection provider for this view + m_view.getSite().setSelectionProvider(this); + + // initialize selection + setSelection(m_view.getSite().getPage().getSelection()); + + } + + /** Dispose method. */ + public void dispose() { + if (m_view != null) { + m_view.getSite().getPage().removeSelectionListener(this); + m_view.getViewSite().setSelectionProvider(null); + m_view = null; + } + m_selection = null; + if (m_selectionListeners != null) { + m_selectionListeners.clear(); + m_selectionListeners = null; + } + } + + + // --- accessors --- + + /** Gets whether selection change events are reported. */ + public boolean getTrackSelection() { + return m_trackSelection; + } + + /** Sets whether selection change events are reported. */ + public void setTrackSelection(boolean trackSelection) { + m_trackSelection = trackSelection; + } + + + // --- ISelectionListener implementation --- + + /** Invoked when selection changes externally. */ + public void selectionChanged(IWorkbenchPart part, ISelection selection) { + // ignore selection change events that came from us + if (part == m_view) return; + if (m_trackSelection) { + workbenchSelectionChanged(part, selection); + } + } + + /** Invoked when selection changes. + * Intended to be overloaded by derived implementations. + */ + public void workbenchSelectionChanged(ISelection selection) { + setSelection(selection); + } + + /** Invoked when selection changes. + * Intended to be overloaded by derived implementations. + */ + public void workbenchSelectionChanged(ISelectionProvider provider, ISelection selection) { + setSelection(provider, selection); + } + + /** Invoked when selection changes. + * Intended to be overloaded by derived implementations. + */ + public void workbenchSelectionChanged(Object provider, ISelection selection) { + setSelection(provider, selection); + } + + + // --- ISelectionProvider implementation --- + + /** Gets current selection. */ + public ISelection getSelection() { + return m_selection; + } + + /** Sets current selection, and raises selection changed event. */ + public void setSelection(ISelection selection) { + // for some reason, SelectionChangedEvent can't stand a null selection + if (selection == null) selection = StructuredSelection.EMPTY; + m_selection = selection; + m_selectionListeners.raise(new SelectionChangedEvent(this, m_selection)); + } + + /** Sets current selection, and raises selection changed event. */ + public void setSelection(ISelectionProvider source, ISelection selection) { + // for some reason, SelectionChangedEvent can't stand a null selection + if (selection == null) selection = StructuredSelection.EMPTY; + m_selection = selection; + m_selectionListeners.raise(new SelectionChangedEvent(source, m_selection)); + } + + /** Sets current selection, and raises selection changed event. */ + public void setSelection(Object source, ISelection selection) { + // for some reason, SelectionChangedEvent can't stand a null selection + if (selection == null) selection = StructuredSelection.EMPTY; + m_selection = selection; + m_selectionListeners.raise(new SelectionChangedEvent(new SelectionProviderAdapter(source), m_selection)); + } + + /** Adds external listener for selection change events. */ + public void addSelectionChangedListener(ISelectionChangedListener listener) { + m_selectionListeners.addListener(listener); + } + + /** Removes external listener for selection change events. */ + public void removeSelectionChangedListener(ISelectionChangedListener listener) { + m_selectionListeners.removeListener(listener); + } + + + // --- utilities --- + + /** Converts selection to string, for debug display. */ + protected String selectionToString(ISelection selection) { + String result = null; + // convert selection to text string + if (m_selection == null) { + result = "No Selection"; + } + else if (m_selection instanceof IStructuredSelection) { + IStructuredSelection structuredSelection = (IStructuredSelection) m_selection; + List elements = structuredSelection.toList(); + int size = elements.size(); + if (size == 0) { + result = "Empty Selection"; + } + else { + result = ""; + for (int i=0; i0) result += "\n"; + Object o = elements.get(i); + String type = o.getClass().getName(); + String value = o.toString(); + result += "[" + i + "]: type= + " + type + ", value='" + value + "'"; + } + } + } + else { + String type = m_selection.getClass().getName(); + String value = m_selection.toString(); + result = "type=" + type + ", value='" + value + "'"; + } + return result; + } +} From 7ab76fca2c473589af53b5ba1bc82feb22a5cad8 Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Fri, 10 Feb 2012 14:57:05 -0500 Subject: [PATCH 26/43] Bug 335027: Visualizer View feature. Releng updates. --- pom.xml | 6 ++++++ releng/org.eclipse.cdt.repo/category.xml | 2 ++ 2 files changed, 8 insertions(+) diff --git a/pom.xml b/pom.xml index d7c09b09c0e..40d891af184 100644 --- a/pom.xml +++ b/pom.xml @@ -87,8 +87,10 @@ dsf-gdb/org.eclipse.cdt.dsf.gdb dsf-gdb/org.eclipse.cdt.dsf.gdb.ui + dsf-gdb/org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui dsf-gdb/org.eclipse.cdt.gnu.dsf-feature dsf-gdb/org.eclipse.cdt.gnu.dsf.source-feature + dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature p2/org.eclipse.cdt.p2 p2/org.eclipse.cdt.p2-feature @@ -150,6 +152,10 @@ dsf/org.eclipse.cdt.examples.dsf.pda.ui dsf/org.eclipse.cdt.examples.dsf-feature + visualizer/org.eclipse.cdt.visualizer.core + visualizer/org.eclipse.cdt.visualizer.ui + visualizer/org.eclipse.cdt.visualizer-feature + core/org.eclipse.cdt.core.tests core/org.eclipse.cdt.ui.tests build/org.eclipse.cdt.managedbuilder.core.tests diff --git a/releng/org.eclipse.cdt.repo/category.xml b/releng/org.eclipse.cdt.repo/category.xml index 31618a27716..e5ead8cb1de 100644 --- a/releng/org.eclipse.cdt.repo/category.xml +++ b/releng/org.eclipse.cdt.repo/category.xml @@ -16,4 +16,6 @@ + + From ddab4b3f49f1dbba00b42b7f051419adb6c1b518 Mon Sep 17 00:00:00 2001 From: Marc-Andre Laperle Date: Fri, 10 Feb 2012 19:37:14 -0500 Subject: [PATCH 27/43] Fix gnu.multicorevisualizer's artifactId --- dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/pom.xml b/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/pom.xml index d63af096830..cb7a1998d06 100644 --- a/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/pom.xml +++ b/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/pom.xml @@ -13,6 +13,6 @@ org.eclipse.cdt.features 1.0.0-SNAPSHOT - org.eclipse.cdt.multicorevisualizer + org.eclipse.cdt.gnu.multicorevisualizer eclipse-feature From 6322c0691d6bd114586312e84baafd760f263d33 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Fri, 10 Feb 2012 16:24:02 -0800 Subject: [PATCH 28/43] Bug 371165 - Invalid formatting of newly created classes. --- .../internal/formatter/CCodeFormatter.java | 88 ++++++++++--------- 1 file changed, 46 insertions(+), 42 deletions(-) diff --git a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/formatter/CCodeFormatter.java b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/formatter/CCodeFormatter.java index 2c891e50939..0dd294b1e29 100644 --- a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/formatter/CCodeFormatter.java +++ b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/formatter/CCodeFormatter.java @@ -23,6 +23,7 @@ import org.eclipse.cdt.core.formatter.CodeFormatter; import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants; import org.eclipse.cdt.core.formatter.DefaultCodeFormatterOptions; import org.eclipse.cdt.core.index.IIndex; +import org.eclipse.cdt.core.model.CModelException; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ILanguage; import org.eclipse.cdt.core.model.ITranslationUnit; @@ -34,8 +35,8 @@ import org.eclipse.cdt.core.parser.ScannerInfo; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; -import org.eclipse.text.edits.TextEdit; import org.eclipse.jface.text.IRegion; +import org.eclipse.text.edits.TextEdit; public class CCodeFormatter extends CodeFormatter { private DefaultCodeFormatterOptions preferences; @@ -106,10 +107,10 @@ public class CCodeFormatter extends CodeFormatter { if (options != null) { this.options= options; Map formatterPrefs= new HashMap(options.size()); - for (String key : options.keySet()) { - Object value= options.get(key); + for (Map.Entry entry : options.entrySet()) { + Object value = entry.getValue(); if (value instanceof String) { - formatterPrefs.put(key, (String) value); + formatterPrefs.put(entry.getKey(), (String) value); } } preferences= new DefaultCodeFormatterOptions(formatterPrefs); @@ -122,13 +123,6 @@ public class CCodeFormatter extends CodeFormatter { @Override public TextEdit format(int kind, String source, int offset, int length, int indentationLevel, String lineSeparator) { TextEdit edit= null; - ITranslationUnit tu= (ITranslationUnit) options.get(DefaultCodeFormatterConstants.FORMATTER_TRANSLATION_UNIT); - if (tu == null) { - IFile file= (IFile) options.get(DefaultCodeFormatterConstants.FORMATTER_CURRENT_FILE); - if (file != null) { - tu= (ITranslationUnit) CoreModel.getDefault().create(file); - } - } if (lineSeparator != null) { preferences.line_separator = lineSeparator; } else { @@ -136,6 +130,7 @@ public class CCodeFormatter extends CodeFormatter { } preferences.initial_indentation_level = indentationLevel; + ITranslationUnit tu = getTranslationUnit(source); if (tu != null) { IIndex index; try { @@ -149,7 +144,7 @@ public class CCodeFormatter extends CodeFormatter { IASTTranslationUnit ast; try { try { - ast= tu.getAST(index, ITranslationUnit.AST_SKIP_ALL_HEADERS); + ast= tu.getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS); } catch (CoreException exc) { throw new AbortFormatting(exc); } @@ -191,19 +186,13 @@ public class CCodeFormatter extends CodeFormatter { @Override public TextEdit[] format(int kind, String source, IRegion[] regions, String lineSeparator) { TextEdit[] edits= new TextEdit[regions.length]; - ITranslationUnit tu= (ITranslationUnit) options.get(DefaultCodeFormatterConstants.FORMATTER_TRANSLATION_UNIT); - if (tu == null) { - IFile file= (IFile) options.get(DefaultCodeFormatterConstants.FORMATTER_CURRENT_FILE); - if (file != null) { - tu= (ITranslationUnit) CoreModel.getDefault().create(file); - } - } if (lineSeparator != null) { preferences.line_separator = lineSeparator; } else { preferences.line_separator = System.getProperty("line.separator"); //$NON-NLS-1$ } + ITranslationUnit tu = getTranslationUnit(source); if (tu != null) { IIndex index; try { @@ -217,20 +206,11 @@ public class CCodeFormatter extends CodeFormatter { IASTTranslationUnit ast; try { try { - ast= tu.getAST(index, ITranslationUnit.AST_SKIP_ALL_HEADERS); - } catch (CoreException exc) { - throw new AbortFormatting(exc); - } - for (int i = 0; i < regions.length; i++) { - IRegion region = regions[i]; - CodeFormatterVisitor codeFormatter = - new CodeFormatterVisitor(preferences, region.getOffset(), region.getLength()); - edits[i] = codeFormatter.format(source, ast); - IStatus status= codeFormatter.getStatus(); - if (!status.isOK()) { - CCorePlugin.log(status); - } + ast= tu.getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS); + } catch (CoreException e) { + throw new AbortFormatting(e); } + formatRegions(source, regions, edits, ast); } finally { index.releaseReadLock(); } @@ -247,20 +227,44 @@ public class CCodeFormatter extends CodeFormatter { try { ast= language.getASTTranslationUnit(content, scanInfo, contentProvider, null, 0, ParserUtil.getParserLogService()); - for (int i = 0; i < regions.length; i++) { - IRegion region = regions[i]; - CodeFormatterVisitor codeFormatter = - new CodeFormatterVisitor(preferences, region.getOffset(), region.getLength()); - edits[i]= codeFormatter.format(source, ast); - IStatus status= codeFormatter.getStatus(); - if (!status.isOK()) { - CCorePlugin.log(status); - } - } + formatRegions(source, regions, edits, ast); } catch (CoreException e) { throw new AbortFormatting(e); } } return edits; } + + private void formatRegions(String source, IRegion[] regions, TextEdit[] edits, + IASTTranslationUnit ast) { + for (int i = 0; i < regions.length; i++) { + IRegion region = regions[i]; + CodeFormatterVisitor codeFormatter = + new CodeFormatterVisitor(preferences, region.getOffset(), region.getLength()); + edits[i] = codeFormatter.format(source, ast); + IStatus status= codeFormatter.getStatus(); + if (!status.isOK()) { + CCorePlugin.log(status); + } + } + } + + private ITranslationUnit getTranslationUnit(String source) { + ITranslationUnit tu= (ITranslationUnit) options.get(DefaultCodeFormatterConstants.FORMATTER_TRANSLATION_UNIT); + if (tu == null) { + IFile file= (IFile) options.get(DefaultCodeFormatterConstants.FORMATTER_CURRENT_FILE); + if (file != null) { + tu= (ITranslationUnit) CoreModel.getDefault().create(file); + } + } + if (tu != null && source != null) { + try { + tu = tu.getWorkingCopy(); + tu.getBuffer().setContents(source); + } catch (CModelException e) { + throw new AbortFormatting(e); + } + } + return tu; + } } From da28cc19fcfc124dfdfac6ed590b8fa0e7fe2d83 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Fri, 10 Feb 2012 17:34:15 -0800 Subject: [PATCH 29/43] Java 1.5-style loops, etc. --- .../ui/quickfix/CaseBreakQuickFixBreak.java | 13 ++-- .../internal/checkers/CaseBreakChecker.java | 23 +++--- .../core/model/AbstractProblemReporter.java | 6 +- .../model/CodanMarkerProblemReporter.java | 39 ++++------ .../core/model/CodanProblemMarker.java | 72 ++++--------------- .../parser/scanner/LocationCtxContainer.java | 3 +- 6 files changed, 50 insertions(+), 106 deletions(-) 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 index 7de791f5e8c..d2699c4f724 100644 --- 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 @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Gil Barash - Initial implementation + * Gil Barash - Initial implementation *******************************************************************************/ package org.eclipse.cdt.codan.internal.checkers.ui.quickfix; @@ -33,7 +33,7 @@ import org.eclipse.ltk.core.refactoring.Change; public class CaseBreakQuickFixBreak extends AbstractAstRewriteQuickFix { @Override public boolean isApplicable(IMarker marker) { - int line = marker.getAttribute(IMarker.LINE_NUMBER, -1) - 1; + int line = marker.getAttribute(IMarker.LINE_NUMBER, 0) - 1; if (line < 0) return false; return true; @@ -45,17 +45,18 @@ public class CaseBreakQuickFixBreak extends AbstractAstRewriteQuickFix { } protected IASTStatement getStmtBeforeBreak(IMarker marker, IASTTranslationUnit ast) throws BadLocationException { - int line = marker.getAttribute(IMarker.LINE_NUMBER, -1) - 1; + int line = marker.getAttribute(IMarker.LINE_NUMBER, 0) - 1; if (line < 0) return null; IRegion lineInformation = getDocument().getLineInformation(line); IASTNodeSelector nodeSelector = ast.getNodeSelector(null); IASTNode containedNode = nodeSelector.findFirstContainedNode(lineInformation.getOffset(), lineInformation.getLength()); IASTNode beforeBreakNode = null; - if (containedNode != null) + if (containedNode != null) { beforeBreakNode = CxxAstUtils.getEnclosingStatement(containedNode); - else + } else { beforeBreakNode = nodeSelector.findEnclosingNode(lineInformation.getOffset(), lineInformation.getLength()); + } if (beforeBreakNode instanceof IASTCompoundStatement) { while (beforeBreakNode != null) { if (beforeBreakNode.getParent() instanceof IASTCompoundStatement @@ -79,7 +80,7 @@ public class CaseBreakQuickFixBreak extends AbstractAstRewriteQuickFix { try { IASTTranslationUnit ast = getTranslationUnitViaEditor(marker).getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS); IASTStatement beforeBreak = getStmtBeforeBreak(marker, ast); - if (beforeBreak.getParent() instanceof IASTCompoundStatement) { + if (beforeBreak != null && beforeBreak.getParent() instanceof IASTCompoundStatement) { IASTCompoundStatement enclosingStatement = (IASTCompoundStatement) beforeBreak.getParent(); IASTStatement after = getAfterStatement(beforeBreak); ASTRewrite r = ASTRewrite.create(enclosingStatement.getTranslationUnit()); 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 dc39e19c277..b6b001ae71a 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 @@ -43,12 +43,9 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke public static final String PARAM_EMPTY_CASE = "empty_case_param"; //$NON-NLS-1$ public static final String PARAM_NO_BREAK_COMMENT = "no_break_comment"; //$NON-NLS-1$ public static final String DEFAULT_NO_BREAK_COMMENT = "no break"; //$NON-NLS-1$ - private Boolean _checkLastCase; // Should we check the last case in the switch? - private Boolean _checkEmptyCase; // Should we check an empty case (a case without any statements within it) - private String _noBreakComment; // The comment suppressing this warning - - public CaseBreakChecker() { - } + private boolean fCheckLastCase; // Should we check the last case in the switch? + private boolean fCheckEmptyCase; // Should we check an empty case (a case without any statements within it) + private String fNoBreakComment; // The comment suppressing this warning /** * This visitor looks for "switch" statements and invokes "SwitchVisitor" on them. @@ -99,10 +96,10 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke // Next is case or end of switch - means this one is the last if (prevCase != null && (isCaseStatement(next) || next == null)) { // Check that current statement end with break or any other exit statement - if (!_checkEmptyCase && isCaseStatement(curr) && next != null) { + if (!fCheckEmptyCase && isCaseStatement(curr) && next != null) { continue; // Empty case and we don't care } - if (!_checkLastCase && next == null) { + if (!fCheckLastCase && next == null) { continue; // Last case and we don't care } if (!isProducedByMacroExpansion(prevCase) && isFallThroughStamement(curr)) { @@ -116,7 +113,7 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke } if (comment != null) { String str = getTrimmedComment(comment); - if (str.toLowerCase().contains(_noBreakComment.toLowerCase())) + if (str.toLowerCase().contains(fNoBreakComment.toLowerCase())) continue; } reportProblem(curr, prevCase); @@ -162,7 +159,7 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke } } - public void reportProblem(IASTStatement curr, IASTStatement prevCase) { + private void reportProblem(IASTStatement curr, IASTStatement prevCase) { reportProblem(ER_ID, getProblemLocationAtEndOfNode(curr)); } @@ -227,9 +224,9 @@ public class CaseBreakChecker extends AbstractIndexAstChecker implements IChecke @Override public void processAst(IASTTranslationUnit ast) { - _checkLastCase = (Boolean) getPreference(getProblemById(ER_ID, getFile()), PARAM_LAST_CASE); - _checkEmptyCase = (Boolean) getPreference(getProblemById(ER_ID, getFile()), PARAM_EMPTY_CASE); - _noBreakComment = (String) getPreference(getProblemById(ER_ID, getFile()), PARAM_NO_BREAK_COMMENT); + fCheckLastCase = (Boolean) getPreference(getProblemById(ER_ID, getFile()), PARAM_LAST_CASE); + fCheckEmptyCase = (Boolean) getPreference(getProblemById(ER_ID, getFile()), PARAM_EMPTY_CASE); + fNoBreakComment = (String) getPreference(getProblemById(ER_ID, getFile()), PARAM_NO_BREAK_COMMENT); SwitchFindingVisitor visitor = new SwitchFindingVisitor(); ast.accept(visitor); } diff --git a/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/core/model/AbstractProblemReporter.java b/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/core/model/AbstractProblemReporter.java index 0b842fa58fd..967b17fe1ce 100644 --- a/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/core/model/AbstractProblemReporter.java +++ b/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/core/model/AbstractProblemReporter.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * QNX Software Systems (Alena Laskavaia) - initial API and implementation + * QNX Software Systems (Alena Laskavaia) - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.codan.core.model; @@ -16,7 +16,7 @@ import org.eclipse.core.resources.IResource; /** * Abstract implementation of a IProblemReporter - * + * * @since 2.0 */ public abstract class AbstractProblemReporter implements IProblemReporter { @@ -30,7 +30,7 @@ public abstract class AbstractProblemReporter implements IProblemReporter { IProblem problem = CheckersRegistry.getInstance().getResourceProfile(file).findProblem(id); if (problem == null) throw new IllegalArgumentException("Id is not registered:" + id); //$NON-NLS-1$ - if (problem.isEnabled() == false) + if (!problem.isEnabled()) return; // skip ICodanProblemMarker codanProblemMarker = new CodanProblemMarker(problem, loc, args); reportProblem(codanProblemMarker); diff --git a/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/internal/core/model/CodanMarkerProblemReporter.java b/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/internal/core/model/CodanMarkerProblemReporter.java index deda9238a8f..4a7cc5f81c1 100644 --- a/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/internal/core/model/CodanMarkerProblemReporter.java +++ b/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/internal/core/model/CodanMarkerProblemReporter.java @@ -6,14 +6,13 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Alena Laskavaia - initial API and implementation + * Alena Laskavaia - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.codan.internal.core.model; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Iterator; import org.eclipse.cdt.codan.core.CodanCorePlugin; import org.eclipse.cdt.codan.core.CodanRuntime; @@ -36,16 +35,15 @@ import org.eclipse.core.runtime.IProgressMonitor; /** * Problem reported that created eclipse markers */ -public class CodanMarkerProblemReporter extends AbstractProblemReporter implements - IProblemReporterPersistent, IProblemReporterSessionPersistent { +public class CodanMarkerProblemReporter extends AbstractProblemReporter + implements IProblemReporterPersistent, IProblemReporterSessionPersistent { private IResource resource; private IChecker checker; private ArrayList toAdd = new ArrayList(); /** * Create instance, which can be use as factory for - * IProblemReporterSessionPersistent or - * as IProblemReporterPersistent. + * IProblemReporterSessionPersistent or as IProblemReporterPersistent. */ public CodanMarkerProblemReporter() { super(); @@ -117,9 +115,8 @@ public class CodanMarkerProblemReporter extends AbstractProblemReporter implemen @Override public void run(IProgressMonitor monitor) throws CoreException { Collection markers = findResourceMarkers(file, checker); - for (Iterator iterator = markers.iterator(); iterator.hasNext();) { - IMarker iMarker = iterator.next(); - iMarker.delete(); + for (IMarker marker : markers) { + marker.delete(); } } }, null, IWorkspace.AVOID_UPDATE, null); @@ -146,9 +143,8 @@ public class CodanMarkerProblemReporter extends AbstractProblemReporter implemen for (int i = 0; i < markers.length; i++) { IMarker m = markers[i]; String id = m.getAttribute(ICodanProblemMarker.ID, ""); //$NON-NLS-1$ - for (Iterator iterator = problems.iterator(); iterator.hasNext();) { - IProblem iProblem = iterator.next(); - if (iProblem.getId().equals(id)) { + for (IProblem problem : problems) { + if (problem.getId().equals(id)) { res.add(m); } } @@ -176,10 +172,11 @@ public class CodanMarkerProblemReporter extends AbstractProblemReporter implemen @Override public void done() { if (checker != null) { - if (toAdd.size() == 0) + if (toAdd.isEmpty()) { deleteProblems(false); - else + } else { reconcileMarkers(); + } toAdd.clear(); } } @@ -190,8 +187,7 @@ public class CodanMarkerProblemReporter extends AbstractProblemReporter implemen @Override public void run(IProgressMonitor monitor) throws CoreException { Collection markers = findResourceMarkers(resource, checker); - for (Iterator iterator = markers.iterator(); iterator.hasNext();) { - IMarker m = iterator.next(); + for (IMarker m : markers) { ICodanProblemMarker cm = similarMarker(m); if (cm == null) { m.delete(); @@ -200,8 +196,7 @@ public class CodanMarkerProblemReporter extends AbstractProblemReporter implemen toAdd.remove(cm); } } - for (Iterator iterator = toAdd.iterator(); iterator.hasNext();) { - ICodanProblemMarker cm = iterator.next(); + for (ICodanProblemMarker cm : toAdd) { cm.createMarker(); } } @@ -244,8 +239,7 @@ public class CodanMarkerProblemReporter extends AbstractProblemReporter implemen protected ICodanProblemMarker similarMarker(IMarker m) { ICodanProblemMarker mcm = CodanProblemMarker.createCodanProblemMarkerFromResourceMarker(m); ArrayList cand = new ArrayList(); - for (Iterator iterator = toAdd.iterator(); iterator.hasNext();) { - ICodanProblemMarker cm = iterator.next(); + for (ICodanProblemMarker cm : toAdd) { if (mcm.equals(cm)) return cm; if (markersAreSimilar(mcm, cm)) { @@ -276,11 +270,6 @@ public class CodanMarkerProblemReporter extends AbstractProblemReporter implemen return true; } - /* - * (non-Javadoc) - * - * @see IProblemReporterSessionPersistent#deleteProblems(boolean) - */ @Override public void deleteProblems(boolean all) { if (all) diff --git a/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/internal/core/model/CodanProblemMarker.java b/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/internal/core/model/CodanProblemMarker.java index 58d0c525ffa..8bf70a95b95 100644 --- a/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/internal/core/model/CodanProblemMarker.java +++ b/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/internal/core/model/CodanProblemMarker.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * QNX Software Systems (Alena Laskavaia) - initial API and implementation + * QNX Software Systems (Alena Laskavaia) - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.codan.internal.core.model; @@ -31,7 +31,7 @@ import org.eclipse.core.runtime.CoreException; /** * Instance of a problem. Intermediate representation before problem become a * marker - * + * * @since 1.1 */ public class CodanProblemMarker implements ICodanProblemMarker { @@ -40,11 +40,6 @@ public class CodanProblemMarker implements ICodanProblemMarker { private IProblem problem; private Object args[]; - @Override - public Object[] getArgs() { - return args; - } - /** * @param problem * @param loc @@ -56,41 +51,26 @@ public class CodanProblemMarker implements ICodanProblemMarker { this.args = args; } - /* - * (non-Javadoc) - * - * @see org.eclipse.cdt.codan.core.model.ICodanProblemMarker#getLocation() - */ + @Override + public Object[] getArgs() { + return args; + } + @Override public IProblemLocation getLocation() { return loc; } - /* - * (non-Javadoc) - * - * @see org.eclipse.cdt.codan.core.model.ICodanProblemMarker#getProblem() - */ @Override public IProblem getProblem() { return problem; } - /* - * (non-Javadoc) - * - * @see org.eclipse.cdt.codan.core.model.ICodanProblemMarker#getResource() - */ @Override public IResource getResource() { return loc.getFile(); } - /* - * (non-Javadoc) - * - * @see org.eclipse.cdt.codan.core.model.ICodanProblemMarker#createMarker() - */ @Override public IMarker createMarker() throws CoreException { IResource file = loc.getFile(); @@ -112,11 +92,6 @@ public class CodanProblemMarker implements ICodanProblemMarker { return marker; } - /* - * (non-Javadoc) - * - * @see org.eclipse.cdt.codan.core.model.ICodanProblemMarker#createMessage() - */ @Override public String createMessage() { String messagePattern = problem.getMessagePattern(); @@ -130,10 +105,6 @@ public class CodanProblemMarker implements ICodanProblemMarker { return message; } - /** - * @param args2 - * @return - */ private static String serializeArgs(Object[] args) { if (args != null) { Properties prop = new Properties(); @@ -155,9 +126,9 @@ public class CodanProblemMarker implements ICodanProblemMarker { } /** - * Return the argument of a problem that checker passed to "reportProblem" + * Returns the argument of a problem that checker passed to "reportProblem" * method - * + * * @param marker - problem marker * @param index - index of the argument 0 based * @return problem argument at index, can be null if not set. Can throw AUBE @@ -169,9 +140,9 @@ public class CodanProblemMarker implements ICodanProblemMarker { } /** - * Return the arguments of a problem that checker passed to "reportProblem" + * Returns the arguments of a problem that checker passed to "reportProblem" * method - * + * * @param marker - problem marker * @return problem arguments, can not be null. Can be 0 sized array. */ @@ -194,8 +165,8 @@ public class CodanProblemMarker implements ICodanProblemMarker { } /** - * Return problemId from marker - * + * Returns problemId from marker + * * @param marker * @return codan problemId */ @@ -225,8 +196,8 @@ public class CodanProblemMarker implements ICodanProblemMarker { } /** - * Attempt to restore CodamProblemMaker from the resource marker - * + * Attempts to restore CodamProblemMaker from the resource marker + * * @param marker * @return new instanceof of ICodanProblemMarker or null if marker is not * codan marker @@ -239,10 +210,6 @@ public class CodanProblemMarker implements ICodanProblemMarker { return new CodanProblemMarker(problem, loc, getProblemArguments(marker)); } - /** - * @param marker - * @return - */ public static CodanProblem getProblem(IMarker marker) { String id = getProblemId(marker); if (id == null) @@ -255,10 +222,6 @@ public class CodanProblemMarker implements ICodanProblemMarker { return problem; } - /** - * @param resource - * @return - */ public static IProblemProfile getProfile(IResource resource) { IProblemProfile profile = CheckersRegistry.getInstance().getResourceProfile(resource); return profile; @@ -276,11 +239,6 @@ public class CodanProblemMarker implements ICodanProblemMarker { return loc; } - /** - * @param marker - * @param res - * @throws CoreException - */ public static void setProblemArguments(IMarker marker, String[] args) throws CoreException { String propArgs = serializeArgs(args); marker.setAttribute(PROBLEM_ARGS, propArgs); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/LocationCtxContainer.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/LocationCtxContainer.java index bd4e98ad844..ab7420409ee 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/LocationCtxContainer.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/scanner/LocationCtxContainer.java @@ -241,7 +241,7 @@ class LocationCtxContainer extends LocationCtx { if (idx < 0) { return -idx; } - return idx+1; + return idx + 1; } private int[] computeLineOffsets() { @@ -255,7 +255,6 @@ class LocationCtxContainer extends LocationCtx { int[] result= new int[offsets.size()]; for (int i = 0; i < result.length; i++) { result[i]= offsets.get(i).intValue(); - } return result; } From 8034e44101b1c565c8cfed01ee42d6bb75761013 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Fri, 10 Feb 2012 17:37:35 -0800 Subject: [PATCH 30/43] Fixed few failing Codan tests. --- .../checkers/StatementHasNoEffectCheckerTest.java | 11 +++++------ .../ui/quickfix/CatchByReferenceQuickFixTest.java | 6 +----- .../ui/quickfix/SuggestedParenthesisQuickFixTest.java | 9 ++++----- .../cdt/core/testplugin/util/TestSourceReader.java | 6 ++++-- 4 files changed, 14 insertions(+), 18 deletions(-) diff --git a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/StatementHasNoEffectCheckerTest.java b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/StatementHasNoEffectCheckerTest.java index 3848fedd717..53b7b037077 100644 --- a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/StatementHasNoEffectCheckerTest.java +++ b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/StatementHasNoEffectCheckerTest.java @@ -10,14 +10,14 @@ *******************************************************************************/ package org.eclipse.cdt.codan.core.internal.checkers; +import java.io.File; +import java.io.IOException; + import org.eclipse.cdt.codan.core.param.IProblemPreference; import org.eclipse.cdt.codan.core.test.CheckerTestCase; import org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectChecker; import org.eclipse.core.resources.IMarker; -import java.io.File; -import java.io.IOException; - /** * Test for {@see StatementHasNoEffectChecker} class * @@ -94,19 +94,18 @@ public class StatementHasNoEffectCheckerTest extends CheckerTestCase { checkNoErrors(); } - /* first file */ // main() { // int a; // +a; // error here on line 3 // } - /* second file */ + // foo() { // int a; // // +a; // error here on line 4 // } - /* this test is using two files */ public void test2FilesUnaryExpression() throws IOException { + /* This test is using two files */ CharSequence[] code = getContents(2); File f1 = loadcode(code[0].toString()); File f2 = loadcode(code[1].toString()); diff --git a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/CatchByReferenceQuickFixTest.java b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/CatchByReferenceQuickFixTest.java index 3d28009ae56..f2770e6d93e 100644 --- a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/CatchByReferenceQuickFixTest.java +++ b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/CatchByReferenceQuickFixTest.java @@ -16,8 +16,8 @@ import org.eclipse.cdt.codan.ui.AbstractCodanCMarkerResolution; /** * @author Tomasz Wesolowski */ +@SuppressWarnings("restriction") public class CatchByReferenceQuickFixTest extends QuickFixTestCase { - @Override public void setUp() throws Exception { super.setUp(); @@ -41,7 +41,6 @@ public class CatchByReferenceQuickFixTest extends QuickFixTestCase { // } catch (C exception) { // } // } - @SuppressWarnings("restriction") public void testCatchByReference() throws Exception { setQuickFix(new CatchByReferenceQuickFix()); loadcode(getAboveComment()); @@ -56,7 +55,6 @@ public class CatchByReferenceQuickFixTest extends QuickFixTestCase { // } catch (C) { // } // } - @SuppressWarnings("restriction") public void testCatchByReferenceNoDeclName() throws Exception { setQuickFix(new CatchByReferenceQuickFix()); loadcode(getAboveComment()); @@ -71,7 +69,6 @@ public class CatchByReferenceQuickFixTest extends QuickFixTestCase { // } catch (C exception) { // } // } - @SuppressWarnings("restriction") public void testCatchByConstReference() throws Exception { setQuickFix(new CatchByConstReferenceQuickFix()); loadcode(getAboveComment()); @@ -86,7 +83,6 @@ public class CatchByReferenceQuickFixTest extends QuickFixTestCase { // } catch (C) { // } // } - @SuppressWarnings("restriction") public void testCatchByConstReferenceNoDeclName() throws Exception { setQuickFix(new CatchByConstReferenceQuickFix()); loadcode(getAboveComment()); diff --git a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/SuggestedParenthesisQuickFixTest.java b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/SuggestedParenthesisQuickFixTest.java index 14195e97256..3213b763c50 100644 --- a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/SuggestedParenthesisQuickFixTest.java +++ b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/SuggestedParenthesisQuickFixTest.java @@ -39,17 +39,16 @@ public class SuggestedParenthesisQuickFixTest extends QuickFixTestCase { // @file:header.h // int foo(); - /* ---- */ + // @file:main.c // #include "header.h" // main() { // foo(); // } - /* - * this test is using two files, there was not actually bugs here so - * quick fix is not called - */ public void test2FilesExample() throws Exception { + /* + * There are no problems in either of the two files, so quick fix is not called. + */ CharSequence[] code = getContents(2); File f1 = loadcode(code[0].toString()); File f2 = loadcode(code[1].toString()); diff --git a/core/org.eclipse.cdt.core.tests/suite/org/eclipse/cdt/core/testplugin/util/TestSourceReader.java b/core/org.eclipse.cdt.core.tests/suite/org/eclipse/cdt/core/testplugin/util/TestSourceReader.java index c43165b2a58..b9767eed4f2 100644 --- a/core/org.eclipse.cdt.core.tests/suite/org/eclipse/cdt/core/testplugin/util/TestSourceReader.java +++ b/core/org.eclipse.cdt.core.tests/suite/org/eclipse/cdt/core/testplugin/util/TestSourceReader.java @@ -117,7 +117,7 @@ public class TestSourceReader { if (line.startsWith("//")) { content.append(line.substring(2) + "\n"); } else { - if (content.length() > 0) { + if (!line.startsWith("@") && content.length() > 0) { contents.add(content); if (sections > 0 && contents.size() == sections + 1) contents.remove(0); @@ -128,7 +128,9 @@ public class TestSourceReader { if (idx != -1 && !Character.isJavaIdentifierPart(line.charAt(idx + testName.length()))) { return contents.toArray(new StringBuilder[contents.size()]); } - contents.clear(); + if (!line.startsWith("@")) { + contents.clear(); + } } } } From 5db78a20c84976de899c8516e8038d209bbacb84 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Fri, 10 Feb 2012 17:45:16 -0800 Subject: [PATCH 31/43] Cosmetics. --- .../ClassMembersInitializationCheckerTest.java | 2 +- .../checkers/ui/quickfix/QuickFixTestCase.java | 2 +- .../cdt/codan/core/model/ICodanBuilder.java | 2 +- .../ui/CodanProblemMarkerResolutionGenerator.java | 14 +++++++------- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/ClassMembersInitializationCheckerTest.java b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/ClassMembersInitializationCheckerTest.java index 343a37d16ae..c640ec645f7 100644 --- a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/ClassMembersInitializationCheckerTest.java +++ b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/ClassMembersInitializationCheckerTest.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Anton Gorenkov - initial implementation + * Anton Gorenkov - initial implementation *******************************************************************************/ package org.eclipse.cdt.codan.core.internal.checkers; diff --git a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/QuickFixTestCase.java b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/QuickFixTestCase.java index d2976091416..f7144b1f029 100644 --- a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/QuickFixTestCase.java +++ b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/internal/checkers/ui/quickfix/QuickFixTestCase.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009,2010 QNX Software Systems + * Copyright (c) 2009, 2010 QNX Software Systems * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/core/model/ICodanBuilder.java b/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/core/model/ICodanBuilder.java index cf45bfdd537..a9463a92e38 100644 --- a/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/core/model/ICodanBuilder.java +++ b/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/core/model/ICodanBuilder.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Alena Laskavaia - initial API and implementation + * Alena Laskavaia - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.codan.core.model; diff --git a/codan/org.eclipse.cdt.codan.ui/src/org/eclipse/cdt/codan/internal/ui/CodanProblemMarkerResolutionGenerator.java b/codan/org.eclipse.cdt.codan.ui/src/org/eclipse/cdt/codan/internal/ui/CodanProblemMarkerResolutionGenerator.java index ce6121332b9..74942d07c78 100644 --- a/codan/org.eclipse.cdt.codan.ui/src/org/eclipse/cdt/codan/internal/ui/CodanProblemMarkerResolutionGenerator.java +++ b/codan/org.eclipse.cdt.codan.ui/src/org/eclipse/cdt/codan/internal/ui/CodanProblemMarkerResolutionGenerator.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Andrew Gvozdev - initial API and implementation + * Andrew Gvozdev - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.codan.internal.ui; @@ -32,22 +32,22 @@ import org.eclipse.ui.IMarkerResolutionGenerator; public class CodanProblemMarkerResolutionGenerator implements IMarkerResolutionGenerator { private static final String EXTENSION_POINT_NAME = "codanMarkerResolution"; //$NON-NLS-1$ - private static Map> resolutions = new HashMap>(); - private static boolean resolutionsLoaded = false; + private static final Map> resolutions = new HashMap>(); + private static boolean resolutionsLoaded; static class ConditionalResolution { IMarkerResolution res; String messagePattern; - public ConditionalResolution(IMarkerResolution res2, String messagePattern2) { - res = res2; - messagePattern = messagePattern2; + public ConditionalResolution(IMarkerResolution res, String messagePattern) { + this.res = res; + this.messagePattern = messagePattern; } } @Override public IMarkerResolution[] getResolutions(IMarker marker) { - if (resolutionsLoaded == false) { + if (!resolutionsLoaded) { readExtensions(); } String id = marker.getAttribute(ICodanProblemMarker.ID, null); From 12c72ed17e8b3ebf6775319f9851c34f07ab1b36 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Sat, 11 Feb 2012 10:36:01 -0800 Subject: [PATCH 32/43] Let formatter know about the translation unit so that it can resolve includes. --- .../changegenerator/ChangeGenerator.java | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/changegenerator/ChangeGenerator.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/changegenerator/ChangeGenerator.java index 40eb821584b..eb35b998fbd 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/changegenerator/ChangeGenerator.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/changegenerator/ChangeGenerator.java @@ -51,7 +51,9 @@ import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTFunctionDefinition; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNamespaceDefinition; import org.eclipse.cdt.core.formatter.CodeFormatter; import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants; +import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ICProject; +import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.internal.core.dom.rewrite.ASTModification; import org.eclipse.cdt.internal.core.dom.rewrite.ASTModification.ModificationKind; import org.eclipse.cdt.internal.core.dom.rewrite.ASTModificationMap; @@ -63,7 +65,6 @@ import org.eclipse.cdt.internal.core.dom.rewrite.astwriter.ProblemRuntimeExcepti import org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.NodeCommentMap; import org.eclipse.cdt.internal.core.dom.rewrite.util.FileHelper; import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; @@ -122,10 +123,12 @@ public class ChangeGenerator extends ASTVisitor { change = new CompositeChange(ChangeGeneratorMessages.ChangeGenerator_compositeChange); classifyModifications(); rootNode.accept(pathProvider); - for (IFile currentFile : changes.keySet()) { - MultiTextEdit edit = changes.get(currentFile); - edit = formatChangedCode(edit, rootNode.getTranslationUnit().getRawSignature(), currentFile.getProject()); - TextFileChange subchange= ASTRewriteAnalyzer.createCTextFileChange(currentFile); + for (IFile file : changes.keySet()) { + MultiTextEdit edit = changes.get(file); + IASTTranslationUnit ast = rootNode.getTranslationUnit(); + ITranslationUnit tu = (ITranslationUnit) CoreModel.getDefault().create(file); + edit = formatChangedCode(edit, ast.getRawSignature(), tu); + TextFileChange subchange= ASTRewriteAnalyzer.createCTextFileChange(file); subchange.setEdit(edit); change.add(subchange); } @@ -317,11 +320,11 @@ public class ChangeGenerator extends ASTVisitor { * * @param multiEdit The text edit produced by refactoring. * @param code The code being modified. - * @param project The project containing the code. + * @param tu The translation unit containing the code. * @return The text edit containing formatted refactoring changes, or the original text edit * in case of errors. */ - private MultiTextEdit formatChangedCode(MultiTextEdit multiEdit, String code, IProject project) { + private MultiTextEdit formatChangedCode(MultiTextEdit multiEdit, String code, ITranslationUnit tu) { IDocument document = new Document(code); try { // Apply refactoring changes to a temporary document. @@ -364,8 +367,9 @@ public class ChangeGenerator extends ASTVisitor { } // Calculate formatting changes for the regions after the refactoring changes. - ICProject proj = CCorePlugin.getDefault().getCoreModel().create(project); - Map options = proj.getOptions(true); + ICProject project = tu.getCProject(); + Map options = new HashMap(project.getOptions(true)); + options.put(DefaultCodeFormatterConstants.FORMATTER_TRANSLATION_UNIT, tu); // Allow all comments to be indented. options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_NEVER_INDENT_LINE_COMMENTS_ON_FIRST_COLUMN, DefaultCodeFormatterConstants.FALSE); From d7b07a626d8c17614b282ce82c2af74b6dc1ce40 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Sat, 11 Feb 2012 10:37:56 -0800 Subject: [PATCH 33/43] Bug 371165 - Invalid formatting of newly created classes. --- .../org/eclipse/cdt/internal/formatter/CCodeFormatter.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/formatter/CCodeFormatter.java b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/formatter/CCodeFormatter.java index 0dd294b1e29..6e2734dd1a5 100644 --- a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/formatter/CCodeFormatter.java +++ b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/formatter/CCodeFormatter.java @@ -27,6 +27,7 @@ import org.eclipse.cdt.core.model.CModelException; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ILanguage; import org.eclipse.cdt.core.model.ITranslationUnit; +import org.eclipse.cdt.core.model.IWorkingCopy; import org.eclipse.cdt.core.parser.FileContent; import org.eclipse.cdt.core.parser.IScannerInfo; import org.eclipse.cdt.core.parser.IncludeFileContentProvider; @@ -259,6 +260,9 @@ public class CCodeFormatter extends CodeFormatter { } if (tu != null && source != null) { try { + // Create a private working copy and set it contents to source. + if (tu.isWorkingCopy()) + tu = ((IWorkingCopy) tu).getOriginalElement(); tu = tu.getWorkingCopy(); tu.getBuffer().setContents(source); } catch (CModelException e) { From 2fd430eb63dbbb970dd781aea41ac9c38fa726c5 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Sat, 11 Feb 2012 12:27:26 -0800 Subject: [PATCH 34/43] Added IASTNode.getOriginalNode method. --- .../.settings/.api_filters | 13 ++++ .../cdt/core/dom/ast/IASTCopyLocation.java | 6 +- .../eclipse/cdt/core/dom/ast/IASTNode.java | 7 +++ .../cdt/internal/core/dom/parser/ASTNode.java | 10 +-- .../core/dom/rewrite/ASTLiteralNode.java | 5 ++ .../rewrite/astwriter/ASTWriterVisitor.java | 12 ++-- .../astwriter/MacroExpansionHandler.java | 61 +++++++------------ .../dom/rewrite/astwriter/NodeWriter.java | 21 +++---- .../core/pdom/dom/PDOMASTAdapter.java | 5 ++ .../extractfunction/FunctionExtractor.java | 4 +- ...eFromInHeaderToImplementationStrategy.java | 12 ++-- 11 files changed, 79 insertions(+), 77 deletions(-) diff --git a/core/org.eclipse.cdt.core/.settings/.api_filters b/core/org.eclipse.cdt.core/.settings/.api_filters index bf5b479e6bf..543278bb554 100644 --- a/core/org.eclipse.cdt.core/.settings/.api_filters +++ b/core/org.eclipse.cdt.core/.settings/.api_filters @@ -14,6 +14,19 @@ + + + + + + + + + + + + + diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTCopyLocation.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTCopyLocation.java index 4671066b93f..b313cba0959 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTCopyLocation.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTCopyLocation.java @@ -13,9 +13,13 @@ package org.eclipse.cdt.core.dom.ast; /** * @author Emanuel Graf IFS + * @noextend This interface is not intended to be extended by clients. + * @noimplement This interface is not intended to be implemented by clients. * @since 5.3 */ public interface IASTCopyLocation extends IASTNodeLocation { - + /** + * @noreference This method is not intended to be referenced by clients. + */ public IASTNode getOriginalNode(); } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTNode.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTNode.java index 7db3fed28ea..7ec5a145ce7 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTNode.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTNode.java @@ -277,4 +277,11 @@ public interface IASTNode { * if this node or one of its descendants does not support copying */ public IASTNode copy(CopyStyle style); + + /** + * If the node is a copy of some other node, returns the original node. + * Otherwise returns the node itself. + * @since 5.4 + */ + public IASTNode getOriginalNode(); } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTNode.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTNode.java index 5aa930983af..a5ed9162714 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTNode.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTNode.java @@ -15,7 +15,6 @@ package org.eclipse.cdt.internal.core.dom.parser; import org.eclipse.cdt.core.dom.ast.ASTNodeProperty; import org.eclipse.cdt.core.dom.ast.ASTVisitor; import org.eclipse.cdt.core.dom.ast.ExpansionOverlapsBoundaryException; -import org.eclipse.cdt.core.dom.ast.IASTCopyLocation; import org.eclipse.cdt.core.dom.ast.IASTFileLocation; import org.eclipse.cdt.core.dom.ast.IASTImageLocation; import org.eclipse.cdt.core.dom.ast.IASTNode; @@ -375,17 +374,14 @@ public abstract class ASTNode implements IASTNode { locations = new IASTNodeLocation[] { new ASTCopyLocation(originalNode) }; } - /** - * If the node is a copy of some other node, returns the original node. - * Otherwise returns the node itself. - */ + @Override public IASTNode getOriginalNode() { IASTNode node = this; while (true) { IASTNodeLocation[] locations = node.getNodeLocations(); - if (locations.length == 0 || !(locations[0] instanceof IASTCopyLocation)) + if (locations.length == 0 || !(locations[0] instanceof ASTCopyLocation)) break; - node = ((IASTCopyLocation) locations[0]).getOriginalNode(); + node = ((ASTCopyLocation) locations[0]).getOriginalNode(); } return node; } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/ASTLiteralNode.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/ASTLiteralNode.java index f4e3bcbb436..4bfd9b5d47f 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/ASTLiteralNode.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/ASTLiteralNode.java @@ -131,4 +131,9 @@ public class ASTLiteralNode implements IASTNode { public boolean isActive() { return true; } + + @Override + public IASTNode getOriginalNode() { + return this; + } } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/astwriter/ASTWriterVisitor.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/astwriter/ASTWriterVisitor.java index ef08a0ba868..4f63e427e7c 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/astwriter/ASTWriterVisitor.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/astwriter/ASTWriterVisitor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik + * Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik * Rapperswil, University of applied sciences and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 @@ -19,7 +19,6 @@ import org.eclipse.cdt.core.dom.ast.ASTVisitor; import org.eclipse.cdt.core.dom.ast.IASTArrayModifier; import org.eclipse.cdt.core.dom.ast.IASTComment; import org.eclipse.cdt.core.dom.ast.IASTCompoundStatement; -import org.eclipse.cdt.core.dom.ast.IASTCopyLocation; import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier; import org.eclipse.cdt.core.dom.ast.IASTDeclaration; import org.eclipse.cdt.core.dom.ast.IASTDeclarator; @@ -27,7 +26,6 @@ import org.eclipse.cdt.core.dom.ast.IASTExpression; import org.eclipse.cdt.core.dom.ast.IASTInitializer; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNode; -import org.eclipse.cdt.core.dom.ast.IASTNodeLocation; import org.eclipse.cdt.core.dom.ast.IASTParameterDeclaration; import org.eclipse.cdt.core.dom.ast.IASTPointerOperator; import org.eclipse.cdt.core.dom.ast.IASTStatement; @@ -130,11 +128,9 @@ public class ASTWriterVisitor extends ASTVisitor { private List getLeadingComments(IASTNode node) { List leadingComments = commentMap.getLeadingCommentsForNode(node); - IASTNodeLocation[] locs = node.getNodeLocations(); - if (locs != null && locs.length > 0 && locs[0] instanceof IASTCopyLocation) { - IASTCopyLocation copyLoc = (IASTCopyLocation) locs[0]; - leadingComments.addAll(commentMap.getLeadingCommentsForNode(copyLoc.getOriginalNode())); - } + IASTNode originalNode = node.getOriginalNode(); + if (originalNode != node) + leadingComments.addAll(commentMap.getLeadingCommentsForNode(originalNode)); return leadingComments; } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/astwriter/MacroExpansionHandler.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/astwriter/MacroExpansionHandler.java index 1a6910dfea6..49315c0d272 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/astwriter/MacroExpansionHandler.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/astwriter/MacroExpansionHandler.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2009 Institute for Software, HSR Hochschule fuer Technik + * Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik * Rapperswil, University of applied sciences and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 @@ -8,6 +8,7 @@ * * Contributors: * Institute for Software - initial API and implementation + * Sergey Prigogin (Google) *******************************************************************************/ package org.eclipse.cdt.internal.core.dom.rewrite.astwriter; @@ -18,7 +19,6 @@ import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; -import org.eclipse.cdt.core.dom.ast.IASTCopyLocation; import org.eclipse.cdt.core.dom.ast.IASTFileLocation; import org.eclipse.cdt.core.dom.ast.IASTMacroExpansionLocation; import org.eclipse.cdt.core.dom.ast.IASTNode; @@ -41,9 +41,9 @@ import org.eclipse.core.runtime.CoreException; * @author Emanuel Graf IFS */ public class MacroExpansionHandler { - private int lastMacroExpOffset; private final Scribe scribe; - private IASTTranslationUnit tu; + private int lastMacroExpOffset; + private IASTTranslationUnit ast; private Map> macroExpansion = new TreeMap>(); public MacroExpansionHandler(Scribe scribe) { @@ -81,11 +81,11 @@ public class MacroExpansionHandler { protected boolean checkisMacroExpansionNode(IASTNode node, boolean write) { IASTTranslationUnit unit = node.getTranslationUnit(); - if (tu == null || !tu.equals(unit)) { + if (ast == null || !ast.equals(unit)) { initEmptyMacros(unit); } IASTNodeLocation[] locs = getNodeLocations(node); - if (locs != null && locs.length ==1) { + if (locs != null && locs.length == 1) { if (locs[0] instanceof IASTMacroExpansionLocation) { IASTMacroExpansionLocation macroNode = (IASTMacroExpansionLocation) locs[0]; @@ -94,7 +94,7 @@ public class MacroExpansionHandler { } if (write) { lastMacroExpOffset = macroNode.asFileLocation().getNodeOffset(); - node = getOriginalNode(node); + node = node.getOriginalNode(); scribe.print(node.getRawSignature()); } return true; @@ -105,24 +105,13 @@ public class MacroExpansionHandler { return false; } - private IASTNode getOriginalNode(IASTNode node) { - IASTNodeLocation[] locs = node.getNodeLocations(); - if (locs != null && locs.length == 1 && locs[0] instanceof IASTCopyLocation) { - node = ((IASTCopyLocation) locs[0]).getOriginalNode(); - } - return node; - } - private IASTNodeLocation[] getNodeLocations(IASTNode node) { - IASTNodeLocation[] locs = node.getNodeLocations(); - if (locs != null && locs.length == 1 && locs[0] instanceof IASTCopyLocation) { - locs = ((IASTCopyLocation) locs[0]).getOriginalNode().getNodeLocations(); - } - return locs; + return node.getOriginalNode().getNodeLocations(); } private void handleEmptyMacroExpansion(IASTNode node) { - if (node.getTranslationUnit() == null)return; + if (node.getTranslationUnit() == null) + return; String file = node.getContainingFilename(); List exps = macroExpansion.get(file); if (exps != null && !exps.isEmpty()) { @@ -144,46 +133,40 @@ public class MacroExpansionHandler { } private IASTFileLocation getFileLocation(IASTNode node) { - IASTFileLocation fileLocation = node.getFileLocation(); - if (fileLocation == null) { - IASTNodeLocation[] locs = node.getNodeLocations(); - if (locs != null && locs.length > 0 && locs[0] instanceof IASTCopyLocation) { - fileLocation = ((IASTCopyLocation) locs[0]).getOriginalNode().getFileLocation(); - } - } - return fileLocation; + return node.getOriginalNode().getFileLocation(); } private void initEmptyMacros(IASTTranslationUnit unit) { if (unit != null) { - tu = unit; - IIndex index = tu.getIndex(); + ast = unit; + IIndex index = ast.getIndex(); if (index != null) { macroExpansion = new TreeMap>(); - IASTPreprocessorMacroDefinition[] md = tu.getMacroDefinitions(); + IASTPreprocessorMacroDefinition[] md = ast.getMacroDefinitions(); TreeSetpaths = new TreeSet(); - for (IASTPreprocessorIncludeStatement is :tu.getIncludeDirectives()) { + for (IASTPreprocessorIncludeStatement is :ast.getIncludeDirectives()) { if (!is.isSystemInclude()) { paths.add(is.getContainingFilename()); } } - paths.add(tu.getContainingFilename()); + paths.add(ast.getContainingFilename()); for (IASTPreprocessorMacroDefinition iastPreprocessorMacroDefinition : md) { if (iastPreprocessorMacroDefinition.getExpansion().length() == 0) { try { - IIndexMacro[] macroBinding = index.findMacros(iastPreprocessorMacroDefinition.getName().toCharArray(), + IIndexMacro[] macroBinding = index.findMacros( + iastPreprocessorMacroDefinition.getName().toCharArray(), IndexFilter.ALL, null); if (macroBinding.length > 0) { IIndexName[] refs = index.findReferences(macroBinding[0]); for (IIndexName iIndexName : refs) { - String filename2 = iIndexName.getFileLocation().getFileName(); - List fileList = macroExpansion.get(filename2); - if (paths.contains(filename2)) { + String filename = iIndexName.getFileLocation().getFileName(); + List fileList = macroExpansion.get(filename); + if (paths.contains(filename)) { if (fileList == null) { fileList = new ArrayList(); - macroExpansion.put(filename2, fileList); + macroExpansion.put(filename, fileList); } fileList.add(iIndexName); } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/astwriter/NodeWriter.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/astwriter/NodeWriter.java index aa160a77bdf..1a5e4b1e44f 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/astwriter/NodeWriter.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/rewrite/astwriter/NodeWriter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik + * Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik * Rapperswil, University of applied sciences and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 @@ -8,15 +8,14 @@ * * Contributors: * Institute for Software - initial API and implementation + * Sergey Prigogin (Google) *******************************************************************************/ package org.eclipse.cdt.internal.core.dom.rewrite.astwriter; import java.util.List; import org.eclipse.cdt.core.dom.ast.IASTComment; -import org.eclipse.cdt.core.dom.ast.IASTCopyLocation; import org.eclipse.cdt.core.dom.ast.IASTNode; -import org.eclipse.cdt.core.dom.ast.IASTNodeLocation; import org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.NodeCommentMap; /** @@ -108,11 +107,9 @@ public class NodeWriter { private List getTrailingComments(IASTNode node) { List trailingComments = commentMap.getTrailingCommentsForNode(node); - IASTNodeLocation[] locs = node.getNodeLocations(); - if (locs != null && locs.length > 0 && locs[0] instanceof IASTCopyLocation) { - IASTCopyLocation loc = (IASTCopyLocation) locs[0]; - trailingComments.addAll(commentMap.getTrailingCommentsForNode(loc.getOriginalNode())); - } + IASTNode originalNode = node.getOriginalNode(); + if (originalNode != node) + trailingComments.addAll(commentMap.getTrailingCommentsForNode(originalNode)); return trailingComments; } @@ -122,11 +119,9 @@ public class NodeWriter { private List getFreestandingComments(IASTNode node) { List freestandingComments = commentMap.getFreestandingCommentsForNode(node); - IASTNodeLocation[] locs = node.getNodeLocations(); - if (locs != null && locs.length > 0 && locs[0] instanceof IASTCopyLocation) { - IASTCopyLocation loc = (IASTCopyLocation) locs[0]; - freestandingComments.addAll(commentMap.getFreestandingCommentsForNode(loc.getOriginalNode())); - } + IASTNode originalNode = node.getOriginalNode(); + if (originalNode != node) + freestandingComments.addAll(commentMap.getFreestandingCommentsForNode(originalNode)); return freestandingComments; } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/dom/PDOMASTAdapter.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/dom/PDOMASTAdapter.java index 45fb3973180..133265932d7 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/dom/PDOMASTAdapter.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/dom/PDOMASTAdapter.java @@ -280,6 +280,11 @@ public class PDOMASTAdapter { public boolean isQualified() { return fDelegate.isQualified(); } + + @Override + public IASTNode getOriginalNode() { + return this; + } } private static class AnonymousEnumeration implements IEnumeration { diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/FunctionExtractor.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/FunctionExtractor.java index 37ca4c431c8..41ce0f3b2d7 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/FunctionExtractor.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/extractfunction/FunctionExtractor.java @@ -39,8 +39,6 @@ import org.eclipse.cdt.core.dom.ast.INodeFactory; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTFunctionDeclarator; import org.eclipse.cdt.core.dom.rewrite.ASTRewrite; -import org.eclipse.cdt.internal.core.dom.parser.ASTNode; - import org.eclipse.cdt.internal.ui.refactoring.NameInformation; import org.eclipse.cdt.internal.ui.refactoring.NameInformation.Indirection; @@ -134,7 +132,7 @@ public abstract class FunctionExtractor { @Override public int visit(IASTName name) { - NameInformation param = changedParameters.get(((ASTNode) name).getOriginalNode()); + NameInformation param = changedParameters.get(name.getOriginalNode()); if (param != null) { IASTName newName = null; if (param.isRenamed()) { diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/togglefunction/ToggleFromInHeaderToImplementationStrategy.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/togglefunction/ToggleFromInHeaderToImplementationStrategy.java index ff13a676cd2..2b165c72248 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/togglefunction/ToggleFromInHeaderToImplementationStrategy.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/togglefunction/ToggleFromInHeaderToImplementationStrategy.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011 Institute for Software, HSR Hochschule fuer Technik + * Copyright (c) 2011, 2012 Institute for Software, HSR Hochschule fuer Technik * Rapperswil, University of applied sciences and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 @@ -7,7 +7,8 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Martin Schwab & Thomas Kallenberg - initial API and implementation + * Martin Schwab & Thomas Kallenberg - initial API and implementation + * Sergey Prigogin (Google) ******************************************************************************/ package org.eclipse.cdt.internal.ui.refactoring.togglefunction; @@ -18,7 +19,6 @@ import org.eclipse.text.edits.TextEditGroup; import org.eclipse.cdt.core.dom.ast.ASTVisitor; import org.eclipse.cdt.core.dom.ast.IASTArrayModifier; import org.eclipse.cdt.core.dom.ast.IASTComment; -import org.eclipse.cdt.core.dom.ast.IASTCopyLocation; import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier; import org.eclipse.cdt.core.dom.ast.IASTDeclaration; import org.eclipse.cdt.core.dom.ast.IASTDeclarator; @@ -229,9 +229,9 @@ public class ToggleFromInHeaderToImplementationStrategy implements IToggleRefact private void copyComments(IASTNode node, ASTRewrite newRewriter, ASTRewrite oldRewriter, CommentPosition pos) { - if (node.getNodeLocations().length > 0 && node.getNodeLocations()[0] instanceof IASTCopyLocation) { - IASTCopyLocation copyLoc = (IASTCopyLocation) node.getNodeLocations()[0]; - List comments = oldRewriter.getComments(copyLoc.getOriginalNode(), pos); + IASTNode originalNode = node.getOriginalNode(); + if (originalNode != node) { + List comments = oldRewriter.getComments(originalNode, pos); for (IASTComment comment : comments) { newRewriter.addComment(node, comment, pos); } From 4b09a45f5f3df3e78bd823a0a1a9f156278c895e Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Sat, 11 Feb 2012 12:29:58 -0800 Subject: [PATCH 35/43] Code streamlining. --- .../internal/formatter/CCodeFormatter.java | 69 ++----------------- 1 file changed, 7 insertions(+), 62 deletions(-) diff --git a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/formatter/CCodeFormatter.java b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/formatter/CCodeFormatter.java index 6e2734dd1a5..e5308f20819 100644 --- a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/formatter/CCodeFormatter.java +++ b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/internal/formatter/CCodeFormatter.java @@ -37,6 +37,7 @@ import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.Region; import org.eclipse.text.edits.TextEdit; public class CCodeFormatter extends CodeFormatter { @@ -108,10 +109,10 @@ public class CCodeFormatter extends CodeFormatter { if (options != null) { this.options= options; Map formatterPrefs= new HashMap(options.size()); - for (Map.Entry entry : options.entrySet()) { - Object value = entry.getValue(); + for (String key : options.keySet()) { + Object value= options.get(key); if (value instanceof String) { - formatterPrefs.put(entry.getKey(), (String) value); + formatterPrefs.put(key, (String) value); } } preferences= new DefaultCodeFormatterOptions(formatterPrefs); @@ -122,66 +123,10 @@ public class CCodeFormatter extends CodeFormatter { } @Override - public TextEdit format(int kind, String source, int offset, int length, int indentationLevel, String lineSeparator) { - TextEdit edit= null; - if (lineSeparator != null) { - preferences.line_separator = lineSeparator; - } else { - preferences.line_separator = System.getProperty("line.separator"); //$NON-NLS-1$ - } + public TextEdit format(int kind, String source, int offset, int length, int indentationLevel, + String lineSeparator) { preferences.initial_indentation_level = indentationLevel; - - ITranslationUnit tu = getTranslationUnit(source); - if (tu != null) { - IIndex index; - try { - index = CCorePlugin.getIndexManager().getIndex(tu.getCProject()); - index.acquireReadLock(); - } catch (CoreException e) { - throw new AbortFormatting(e); - } catch (InterruptedException e) { - return null; - } - IASTTranslationUnit ast; - try { - try { - ast= tu.getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS); - } catch (CoreException exc) { - throw new AbortFormatting(exc); - } - CodeFormatterVisitor codeFormatter = new CodeFormatterVisitor(preferences, offset, length); - edit= codeFormatter.format(source, ast); - IStatus status= codeFormatter.getStatus(); - if (!status.isOK()) { - CCorePlugin.log(status); - } - } finally { - index.releaseReadLock(); - } - } else { - IncludeFileContentProvider contentProvider = IncludeFileContentProvider.getSavedFilesProvider(); - IScannerInfo scanInfo = new ScannerInfo(); - FileContent content = FileContent.create("", source.toCharArray()); //$NON-NLS-1$ - - ILanguage language= (ILanguage) options.get(DefaultCodeFormatterConstants.FORMATTER_LANGUAGE); - if (language == null) { - language= GPPLanguage.getDefault(); - } - IASTTranslationUnit ast; - try { - ast= language.getASTTranslationUnit(content, scanInfo, contentProvider, null, 0, - ParserUtil.getParserLogService()); - CodeFormatterVisitor codeFormatter = new CodeFormatterVisitor(preferences, offset, length); - edit= codeFormatter.format(source, ast); - IStatus status= codeFormatter.getStatus(); - if (!status.isOK()) { - CCorePlugin.log(status); - } - } catch (CoreException e) { - throw new AbortFormatting(e); - } - } - return edit; + return format(kind, source, new IRegion[] { new Region(offset, length) }, lineSeparator)[0]; } @Override From 57813d4bd59466a85173310887f7b6547a2909da Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Sat, 11 Feb 2012 17:27:53 -0500 Subject: [PATCH 36/43] Rename "CDT Multicore Visualizer" feature to "C/C++ Multicore Visualizer" --- .../feature.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/feature.properties b/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/feature.properties index 85e9b92c711..72a23837501 100644 --- a/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/feature.properties +++ b/dsf-gdb/org.eclipse.cdt.gnu.multicorevisualizer-feature/feature.properties @@ -14,7 +14,7 @@ # ----------------------------------------------------------------------------- # "featureName" property - name of the feature -featureName=CDT Multicore Visualizer +featureName=C/C++ Multicore Visualizer # "providerName" property - name of the company that provides the feature providerName=Eclipse CDT From 3991fd86580becbb6465467824cd2d22b3f14373 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Sat, 11 Feb 2012 16:50:42 -0800 Subject: [PATCH 37/43] Fixed two broken tests. --- .../ui/quickfix/CaseBreakQuickFixTest.java | 53 ++++++++++--------- 1 file changed, 27 insertions(+), 26 deletions(-) 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 index f9a5d2323eb..d8b20403f49 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2010, 2011 Tomasz Wesolowski and others + * Copyright (c) 2010, 2012 Tomasz Wesolowski and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -20,41 +20,42 @@ public class CaseBreakQuickFixTest extends QuickFixTestCase { return new CaseBreakQuickFixBreak(); } - // void func() { - // int a; - // switch(a) { - // case 1: - // hello(); - // case 2: - // } - // } + //void func() { + // int a; + // switch(a) { + // case 1: + // hello(); + // case 2: + // break; + // } + //} public void testMiddleCase() throws Exception { loadcode(getAboveComment()); String result = runQuickFixOneFile(); - assertContainedIn("break; case 2:", result); + assertContainedIn("break;\tcase 2:", result); } - // void func() { - // int a; - // switch(a) { - // case 1: - // hello(); - // } - // } + //void func() { + // int a; + // switch(a) { + // case 1: + // hello(); + // } + //} public void testLastCase() throws Exception { loadcode(getAboveComment()); String result = runQuickFixOneFile(); - assertContainedIn("break; }", result); + assertContainedIn("break;\t}", result); } - // void func() { - // int a; - // switch(a) { - // case 1: { - // hello(); - // } - // } - // } + //void func() { + // int a; + // switch(a) { + // case 1: { + // hello(); + // } + // } + //} public void testLastCaseComp() throws Exception { loadcode(getAboveComment()); String result = runQuickFixOneFile(); From 1548edd7e57470d841cb37f6b8f99397adedb063 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Sat, 11 Feb 2012 16:53:32 -0800 Subject: [PATCH 38/43] Cosmetics. --- .../checkers/ClassMembersInitializationCheckerTest.java | 2 -- .../src/org/eclipse/cdt/codan/core/test/TestUtils.java | 2 +- .../codan/internal/core/model/CodanMarkerProblemReporter.java | 3 +-- 3 files changed, 2 insertions(+), 5 deletions(-) diff --git a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/ClassMembersInitializationCheckerTest.java b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/ClassMembersInitializationCheckerTest.java index c640ec645f7..9ae480af840 100644 --- a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/ClassMembersInitializationCheckerTest.java +++ b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/ClassMembersInitializationCheckerTest.java @@ -15,7 +15,6 @@ import org.eclipse.cdt.codan.internal.checkers.ClassMembersInitializationChecker /** * Test for {@see ClassMembersInitializationChecker} class - * */ public class ClassMembersInitializationCheckerTest extends CheckerTestCase { @Override @@ -476,5 +475,4 @@ public class ClassMembersInitializationCheckerTest extends CheckerTestCase { loadCodeAndRun(getAboveComment()); checkErrorLines(8,9,10,11); } - } diff --git a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/test/TestUtils.java b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/test/TestUtils.java index 020c60bb21f..6417d4f6cb9 100644 --- a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/test/TestUtils.java +++ b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/test/TestUtils.java @@ -41,7 +41,7 @@ public class TestUtils { public static String loadFile(InputStream st) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(st)); String buffer; - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); while ((buffer = br.readLine()) != null) { result.append(buffer); } diff --git a/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/internal/core/model/CodanMarkerProblemReporter.java b/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/internal/core/model/CodanMarkerProblemReporter.java index 4a7cc5f81c1..331aa5d46d1 100644 --- a/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/internal/core/model/CodanMarkerProblemReporter.java +++ b/codan/org.eclipse.cdt.codan.core/src/org/eclipse/cdt/codan/internal/core/model/CodanMarkerProblemReporter.java @@ -140,8 +140,7 @@ public class CodanMarkerProblemReporter extends AbstractProblemReporter } ICheckersRegistry reg = CodanRuntime.getInstance().getCheckersRegistry(); Collection problems = reg.getRefProblems(checker); - for (int i = 0; i < markers.length; i++) { - IMarker m = markers[i]; + for (IMarker m : markers) { String id = m.getAttribute(ICodanProblemMarker.ID, ""); //$NON-NLS-1$ for (IProblem problem : problems) { if (problem.getId().equals(id)) { From aa4eae00dd3a136b915bdfa5891965a66ee820f4 Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Sat, 11 Feb 2012 17:10:24 -0800 Subject: [PATCH 39/43] Fixed a broken test. --- .../checkers/ClassMembersInitializationCheckerTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/ClassMembersInitializationCheckerTest.java b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/ClassMembersInitializationCheckerTest.java index 9ae480af840..90a4334324a 100644 --- a/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/ClassMembersInitializationCheckerTest.java +++ b/codan/org.eclipse.cdt.codan.core.test/src/org/eclipse/cdt/codan/core/internal/checkers/ClassMembersInitializationCheckerTest.java @@ -182,10 +182,11 @@ public class ClassMembersInitializationCheckerTest extends CheckerTestCase { // T1 t1; // T2 t2; // }; - // C::C() : i1(0), t1(T1()) {} // 1 warning for: i2. + // template + // C::C() : i1(0), t1(T1()) {} // 1 warning for: i2. public void testExternalConstructorOfTemplateClassHandling() { loadCodeAndRun(getAboveComment()); - checkErrorLines(8); + checkErrorLines(9); } // class C { From e65759e510832c7d7ec881fe74cfd00d5620231a Mon Sep 17 00:00:00 2001 From: Sergey Prigogin Date: Sat, 11 Feb 2012 17:42:32 -0800 Subject: [PATCH 40/43] UI for new code style preferences. --- .../ui/preferences/CodeStyleBlock.java | 39 ++++++++++++++++++- .../ui/preferences/PreferencesMessages.java | 6 +++ .../PreferencesMessages.properties | 10 ++++- 3 files changed, 51 insertions(+), 4 deletions(-) diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/preferences/CodeStyleBlock.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/preferences/CodeStyleBlock.java index fcd29643ff2..609121633ce 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/preferences/CodeStyleBlock.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/preferences/CodeStyleBlock.java @@ -23,14 +23,21 @@ import org.eclipse.cdt.ui.PreferenceConstants; import org.eclipse.cdt.internal.ui.dialogs.IStatusChangeListener; /** - * Configures C Editor typing preferences. + * Configures elements of C/C++ code style affecting refactoring. */ class CodeStyleBlock extends OptionsConfigurationBlock { - private static final Key CLASS_MEMBER_ASCENDING_VISIBILITY_ORDER = getCDTUIKey(PreferenceConstants.CLASS_MEMBER_ASCENDING_VISIBILITY_ORDER); + private static final Key CLASS_MEMBER_ASCENDING_VISIBILITY_ORDER = + getCDTUIKey(PreferenceConstants.CLASS_MEMBER_ASCENDING_VISIBILITY_ORDER); + private static final Key FUNCTION_OUTPUT_PARAMETERS_BEFORE_INPUT = + getCDTUIKey(PreferenceConstants.FUNCTION_OUTPUT_PARAMETERS_BEFORE_INPUT); + private static final Key FUNCTION_PASS_OUTPUT_PARAMETERS_BY_POINTER = + getCDTUIKey(PreferenceConstants.FUNCTION_PASS_OUTPUT_PARAMETERS_BY_POINTER); private static Key[] getAllKeys() { return new Key[] { CLASS_MEMBER_ASCENDING_VISIBILITY_ORDER, + FUNCTION_OUTPUT_PARAMETERS_BEFORE_INPUT, + FUNCTION_PASS_OUTPUT_PARAMETERS_BY_POINTER, }; } @@ -52,6 +59,12 @@ class CodeStyleBlock extends OptionsConfigurationBlock { Composite composite = addSubsection(control, PreferencesMessages.CodeStyleBlock_class_member_order); fillClassMemberOrderSection(composite); + composite = addSubsection(control, PreferencesMessages.CodeStyleBlock_function_parameter_order); + fillFunctionParameterOrderSection(composite); + + composite = addSubsection(control, PreferencesMessages.CodeStyleBlock_function_output_parameter_style); + fillFunctionOutputParameterStyleSection(composite); + scrolled.setContent(control); final Point size= control.computeSize(SWT.DEFAULT, SWT.DEFAULT); scrolled.setMinSize(size.x, size.y); @@ -69,6 +82,28 @@ class CodeStyleBlock extends OptionsConfigurationBlock { CLASS_MEMBER_ASCENDING_VISIBILITY_ORDER, TRUE_FALSE, 0); } + private void fillFunctionParameterOrderSection(Composite composite) { + GridLayout layout= new GridLayout(); + layout.numColumns= 3; + composite.setLayout(layout); + + addRadioButton(composite, PreferencesMessages.CodeStyleBlock_input_output, + FUNCTION_OUTPUT_PARAMETERS_BEFORE_INPUT, FALSE_TRUE, 0); + addRadioButton(composite, PreferencesMessages.CodeStyleBlock_output_input, + FUNCTION_OUTPUT_PARAMETERS_BEFORE_INPUT, TRUE_FALSE, 0); + } + + private void fillFunctionOutputParameterStyleSection(Composite composite) { + GridLayout layout= new GridLayout(); + layout.numColumns= 3; + composite.setLayout(layout); + + addRadioButton(composite, PreferencesMessages.CodeStyleBlock_pass_by_reference, + FUNCTION_PASS_OUTPUT_PARAMETERS_BY_POINTER, FALSE_TRUE, 0); + addRadioButton(composite, PreferencesMessages.CodeStyleBlock_pass_by_pointer, + FUNCTION_PASS_OUTPUT_PARAMETERS_BY_POINTER, TRUE_FALSE, 0); + } + @Override protected void validateSettings(Key changedKey, String oldValue, String newValue) { } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/preferences/PreferencesMessages.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/preferences/PreferencesMessages.java index 97fa545a614..e2836348847 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/preferences/PreferencesMessages.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/preferences/PreferencesMessages.java @@ -198,6 +198,12 @@ public final class PreferencesMessages extends NLS { public static String CodeStyleBlock_class_member_order; public static String CodeStyleBlock_public_private; public static String CodeStyleBlock_private_public; + public static String CodeStyleBlock_function_parameter_order; + public static String CodeStyleBlock_input_output; + public static String CodeStyleBlock_output_input; + public static String CodeStyleBlock_function_output_parameter_style; + public static String CodeStyleBlock_pass_by_reference; + public static String CodeStyleBlock_pass_by_pointer; public static String TodoTaskPreferencePage_title; public static String TodoTaskPreferencePage_description; diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/preferences/PreferencesMessages.properties b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/preferences/PreferencesMessages.properties index b7cf751fbfe..79381abcfd8 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/preferences/PreferencesMessages.properties +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/preferences/PreferencesMessages.properties @@ -231,8 +231,14 @@ CodeFormatterPreferencePage_description=A&ctive profile: # Code Style CodeStylePreferencePage_title=Code Style CodeStyleBlock_class_member_order=Class member visiblity order: -CodeStyleBlock_public_private=P&ublic, protected, private -CodeStyleBlock_private_public=P&rivate, protected, public +CodeStyleBlock_public_private=Pu&blic, protected, private +CodeStyleBlock_private_public=Pri&vate, protected, public +CodeStyleBlock_function_parameter_order=Function parameter order: +CodeStyleBlock_input_output=&Input parameters first +CodeStyleBlock_output_input=&Output parameters first +CodeStyleBlock_function_output_parameter_style=Output parameters of C++ functions: +CodeStyleBlock_pass_by_reference=Pass by &reference +CodeStyleBlock_pass_by_pointer=Pass by poi&nter # Task tags. TodoTaskPreferencePage_title=Task Tags From 088185204c04f304896540521a423111ae2afc36 Mon Sep 17 00:00:00 2001 From: Baltasar Belyavsky Date: Thu, 9 Feb 2012 10:18:31 -0500 Subject: [PATCH 41/43] bug 340219: Project metadata files are saved unnecessarily, test cases --- .../projectmodel/tests/ProjectModelTests.java | 68 ++++++++++++++++++- 1 file changed, 67 insertions(+), 1 deletion(-) diff --git a/build/org.eclipse.cdt.managedbuilder.core.tests/tests/org/eclipse/cdt/projectmodel/tests/ProjectModelTests.java b/build/org.eclipse.cdt.managedbuilder.core.tests/tests/org/eclipse/cdt/projectmodel/tests/ProjectModelTests.java index d0ba05072c4..570339fe693 100644 --- a/build/org.eclipse.cdt.managedbuilder.core.tests/tests/org/eclipse/cdt/projectmodel/tests/ProjectModelTests.java +++ b/build/org.eclipse.cdt.managedbuilder.core.tests/tests/org/eclipse/cdt/projectmodel/tests/ProjectModelTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2010 Intel Corporation and others. + * Copyright (c) 2007, 2012 Intel Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -7,9 +7,11 @@ * * Contributors: * Intel Corporation - Initial API and implementation + * Baltasar Belyavsky (Texas Instruments) - bug 340219: Project metadata files are saved unnecessarily *******************************************************************************/ package org.eclipse.cdt.projectmodel.tests; +import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -56,6 +58,7 @@ import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceDescription; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.IWorkspaceRunnable; +import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; @@ -685,6 +688,69 @@ public class ProjectModelTests extends TestCase implements IElementChangedListen } + /** + * Verifies that project-model is not re-serialized unnecessarily. + */ + public void testCompulsiveSerialization_Bug340219() throws Exception { + final String projectName = "test_bug340219"; + + CoreModel coreModel = CoreModel.getDefault(); + + IProject project = null; + try { + project = createProject(projectName, "cdt.managedbuild.target.gnu30.exe"); + + File projectFile = project.getFile(".project").getLocation().toFile(); + File cprojectFile = project.getFile(".cproject").getLocation().toFile(); + + final long projectFileStamp = projectFile.lastModified(); + final long cprojectFileStamp = cprojectFile.lastModified(); + + ICProjectDescription des = coreModel.getProjectDescription(project); + ICConfigurationDescription[] cfgs = des.getConfigurations(); + + // verify pre-condition - there are two configurations, and the first one is active by default + assertEquals(2, cfgs.length); + assertTrue(cfgs[0].isActive()); + + // verify that changing active or setting configuration does not touch project-model files + des.setActiveConfiguration(cfgs[1]); + des.setDefaultSettingConfiguration(cfgs[1]); + coreModel.setProjectDescription(project, des); + assertEquals(cfgs[1].getId(), des.getActiveConfiguration().getId()); + assertEquals(projectFileStamp, projectFile.lastModified()); + assertEquals(cprojectFileStamp, cprojectFile.lastModified()); + + // verify that closing/reopening the project preserves active configuration and does not touch project-model files + project.close(null); + project.open(null); + des = coreModel.getProjectDescription(project); + cfgs = des.getConfigurations(); + assertEquals(cfgs[1].getId(), des.getActiveConfiguration().getId()); + assertEquals(projectFileStamp, projectFile.lastModified()); + assertEquals(cprojectFileStamp, cprojectFile.lastModified()); + + // verify that deleting/reimporting the project resets active configuration but does not touch project-model files + project.delete(false, true, null); + project.create(null); + project.open(null); + des = coreModel.getProjectDescription(project); + cfgs = des.getConfigurations(); + assertEquals(cfgs[0].getId(), des.getActiveConfiguration().getId()); + assertEquals(projectFileStamp, projectFile.lastModified()); + assertEquals(cprojectFileStamp, cprojectFile.lastModified()); + + // verify that building the project does not touch project-model files + project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, null); + assertEquals(projectFileStamp, projectFile.lastModified()); + assertEquals(cprojectFileStamp, cprojectFile.lastModified()); + } + finally { + if(project != null) + project.delete(true, null); + } + } + private void checkArrays(Object[] a1, Object[] a2){ if(a1 == null){ assertTrue(a2 == null); From 6b66aef60bc1a3ee2f5fa862ed63f48721b1c15f Mon Sep 17 00:00:00 2001 From: Baltasar Belyavsky Date: Thu, 9 Feb 2012 10:18:56 -0500 Subject: [PATCH 42/43] bug 340219: Project metadata files are saved unnecessarily, patch to address .project file modifications --- .../make/internal/core/BuildInfoFactory.java | 32 ++++-- .../internal/core/BuilderFactory.java | 97 ++++++++----------- .../internal/dataprovider/BuildBuildData.java | 22 ++++- .../ConfigurationDataProvider.java | 44 +-------- .../settings/model/extension/CBuildData.java | 20 +++- 5 files changed, 103 insertions(+), 112 deletions(-) diff --git a/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/BuildInfoFactory.java b/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/BuildInfoFactory.java index 10bbd648e88..52e7f70416b 100644 --- a/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/BuildInfoFactory.java +++ b/build/org.eclipse.cdt.make.core/src/org/eclipse/cdt/make/internal/core/BuildInfoFactory.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 QNX Software Systems and others. + * Copyright (c) 2000, 2012 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -7,6 +7,7 @@ * * Contributors: * QNX Software Systems - Initial API and implementation + * Baltasar Belyavsky (Texas Instruments) - bug 340219: Project metadata files are saved unnecessarily *******************************************************************************/ package org.eclipse.cdt.make.internal.core; @@ -18,6 +19,10 @@ import java.util.Map.Entry; import java.util.StringTokenizer; import org.eclipse.cdt.core.ErrorParserManager; +import org.eclipse.cdt.core.model.CoreModel; +import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; +import org.eclipse.cdt.core.settings.model.ICProjectDescription; +import org.eclipse.cdt.core.settings.model.extension.CBuildData; import org.eclipse.cdt.make.core.IMakeBuilderInfo; import org.eclipse.cdt.make.core.IMakeCommonBuildInfo; import org.eclipse.cdt.make.core.MakeCorePlugin; @@ -493,12 +498,27 @@ public class BuildInfoFactory { BuildInfoProject(IProject project, String builderID) throws CoreException { this.project = project; this.builderID = builderID; - ICommand builder; - builder = MakeProjectNature.getBuildSpec(project.getDescription(), builderID); - if (builder == null) { - throw new CoreException(new Status(IStatus.ERROR, MakeCorePlugin.getUniqueIdentifier(), -1, - MakeMessages.getString("BuildInfoFactory.Missing_Builder") + builderID, null)); //$NON-NLS-1$ + + ICommand builder = null; + + // first, give the build-system a chance to return the build-command overlayed with data managed by it + ICProjectDescription cProjectDescription = CoreModel.getDefault().getProjectDescription(project, false); + if(cProjectDescription != null) { + ICConfigurationDescription cConfigDescription = cProjectDescription.getActiveConfiguration(); + CBuildData buildData = cConfigDescription.getConfigurationData().getBuildData(); + if(buildData != null) { + builder = buildData.getBuildSpecCommand(); + } } + + if(builder == null) { + builder = MakeProjectNature.getBuildSpec(project.getDescription(), builderID); + if (builder == null) { + throw new CoreException(new Status(IStatus.ERROR, MakeCorePlugin.getUniqueIdentifier(), -1, + MakeMessages.getString("BuildInfoFactory.Missing_Builder") + builderID, null)); //$NON-NLS-1$ + } + } + Map builderArgs = builder.getArguments(); args = builderArgs; } diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/BuilderFactory.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/BuilderFactory.java index 31f262ebfe4..bd0fd00a033 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/BuilderFactory.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/BuilderFactory.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2010 Intel Corporation and others. + * Copyright (c) 2007, 2012 Intel Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -7,6 +7,7 @@ * * Contributors: * Intel Corporation - Initial API and implementation + * Baltasar Belyavsky (Texas Instruments) - bug 340219: Project metadata files are saved unnecessarily *******************************************************************************/ package org.eclipse.cdt.managedbuilder.internal.core; @@ -25,7 +26,6 @@ import org.eclipse.cdt.managedbuilder.core.IManagedProject; import org.eclipse.cdt.managedbuilder.core.IToolChain; import org.eclipse.cdt.managedbuilder.core.ManagedBuildManager; import org.eclipse.cdt.managedbuilder.core.ManagedBuilderCorePlugin; -import org.eclipse.cdt.managedbuilder.core.ManagedCProjectNature; import org.eclipse.core.resources.ICommand; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; @@ -59,7 +59,6 @@ public class BuilderFactory { static final String CONTENTS_BUILDER = PREFIX + ".builder"; //$NON-NLS-1$ static final String CONTENTS_BUILDER_CUSTOMIZATION = PREFIX + ".builderCustomization"; //$NON-NLS-1$ static final String CONTENTS_CONFIGURATION_IDS = PREFIX + ".configurationIds"; //$NON-NLS-1$ - static final String CONTENTS_ACTIVE_CFG_SETTINGS = PREFIX + ".activeConfigSettings"; //$NON-NLS-1$ // static final String IDS = PREFIX + ".ids"; //$NON-NLS-1$ static final String CONFIGURATION_IDS = PREFIX + ".configurationIds"; //$NON-NLS-1$ @@ -225,19 +224,6 @@ public class BuilderFactory { return el.toStringMap(); } - private static Map builderBuildArgsMap(IBuilder builder){ - MapStorageElement el = new BuildArgsStorageElement("", null); //$NON-NLS-1$ - ((Builder)builder).serializeRawData(el); - - Boolean d = Boolean.valueOf(builder.isDefaultBuildCmd()); - el.setAttribute(BuilderFactory.USE_DEFAULT_BUILD_CMD, d.toString()); - - Map map = el.toStringMap(); - map.put(CONTENTS, CONTENTS_ACTIVE_CFG_SETTINGS); - - return map; - } - public static IBuilder createCustomBuilder(IConfiguration cfg, String builderId) throws CoreException{ IBuilder builder = cfg.getBuilder(); if(!builderId.equals(builder.getId())){ @@ -293,6 +279,31 @@ public class BuilderFactory { // return createBuilder(cfg, args); } + /** + * Creates a new build-command containing data dynamically obtained from the Builder. + */ + public static ICommand createCommandFromBuilder(IBuilder builder) throws CoreException { + IProject project = builder.getParent().getParent().getOwner().getProject(); + ICommand command = getBuildSpec(project.getDescription(), CommonBuilder.BUILDER_ID); + if(command == null) + return null; + + MapStorageElement el = new BuildArgsStorageElement("", null); //$NON-NLS-1$ + ((Builder)builder).serializeRawData(el); + + // always set to false - the raw data will always explicitly contain the build-command + el.setAttribute(BuilderFactory.USE_DEFAULT_BUILD_CMD, Boolean.FALSE.toString()); + + command.setArguments(el.toStringMap()); + + command.setBuilding(IncrementalProjectBuilder.AUTO_BUILD, builder.isAutoBuildEnable()); + command.setBuilding(IncrementalProjectBuilder.FULL_BUILD, builder.isFullBuildEnabled()); + command.setBuilding(IncrementalProjectBuilder.INCREMENTAL_BUILD, builder.isIncrementalBuildEnabled()); + command.setBuilding(IncrementalProjectBuilder.CLEAN_BUILD, builder.isCleanBuildEnabled()); + + return command; + } + public static ICommand getBuildSpec(IProjectDescription description, String builderID) { ICommand[] commands = description.getBuildSpec(); for (int i = 0; i < commands.length; ++i) { @@ -350,6 +361,7 @@ public class BuilderFactory { IConfiguration cfg = info.getDefaultConfiguration(); IBuilder builder = cfg.getEditableBuilder(); builders = new IBuilder[]{builder}; + } else { String type = args.get(CONTENTS); if(type == null || CONTENTS_BUILDER_CUSTOMIZATION.equals(type)){ @@ -361,12 +373,6 @@ public class BuilderFactory { builder = createBuilder(cfg, args, true); } builders = new IBuilder[]{builder}; - } else if (CONTENTS_ACTIVE_CFG_SETTINGS.equals(type)) { - IConfiguration cfg = info.getDefaultConfiguration(); - - IBuilder builder = cfg.getEditableBuilder(); - - builders = new IBuilder[]{builder}; } else if (CONTENTS_BUILDER.equals(type)){ IConfiguration cfgs[] = configsFromMap(args, info); @@ -379,6 +385,7 @@ public class BuilderFactory { } builders = list.toArray(new IBuilder[list.size()]); } + } else if (CONTENTS_CONFIGURATION_IDS.equals(type)){ IConfiguration cfgs[] = configsFromMap(args, info); if(cfgs.length != 0){ @@ -388,6 +395,17 @@ public class BuilderFactory { } builders = list.toArray(new IBuilder[list.size()]); } + + } else if ("org.eclipse.cdt.make.core.activeConfigSettings".equals(type)) { //$NON-NLS-1$ + /* NOTE: Here, only for backwards-compatibility support, since bug 340219 was fixed. + * Existing projects will still be going through this execution path, but new + * projects will no longer store the active-configuration's builder-arguments in the + * build-command, and will be going through the "args == null" condition above. + */ + IConfiguration cfg = info.getDefaultConfiguration(); + IBuilder builder = cfg.getEditableBuilder(); + builders = new IBuilder[]{builder}; + } /*else if (CONTENTS_BUILDER_CUSTOMIZATION.equals(type)){ String idsString = (String)args.get(CONFIGURATION_IDS); if(idsString != null){ @@ -415,39 +433,4 @@ public class BuilderFactory { return EMPTY_BUILDERS_ARRAY; } - public static int applyBuilder(IProjectDescription eDes, IBuilder builder){ - return applyBuilder(eDes, CommonBuilder.BUILDER_ID, builder); - } - - public static final int CMD_UNDEFINED = -1; - public static final int NO_CHANGES = 0; - public static final int CMD_CHANGED = 1; - - public static int applyBuilder(IProjectDescription eDes, String eBuilderId, IBuilder builder){ - ICommand cmd = ManagedCProjectNature.getBuildSpec(eDes, eBuilderId); - if(cmd == null) - return CMD_UNDEFINED; - - if(applyBuilder(cmd, builder)){ - ManagedCProjectNature.setBuildSpec(eDes, cmd); - return CMD_CHANGED; - } - return NO_CHANGES; - } - - public static boolean applyBuilder(ICommand cmd, IBuilder builder) { - Map oldMap = cmd.getArguments(); - Map map = builderBuildArgsMap(builder); - - if(oldMap.equals(map)) - return false; - - cmd.setArguments(map); - - cmd.setBuilding(IncrementalProjectBuilder.AUTO_BUILD, builder.isAutoBuildEnable()); - cmd.setBuilding(IncrementalProjectBuilder.FULL_BUILD, builder.isFullBuildEnabled()); - cmd.setBuilding(IncrementalProjectBuilder.INCREMENTAL_BUILD, builder.isIncrementalBuildEnabled()); - cmd.setBuilding(IncrementalProjectBuilder.CLEAN_BUILD, builder.isCleanBuildEnabled()); - return true; - } } diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/dataprovider/BuildBuildData.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/dataprovider/BuildBuildData.java index 9f539b6a2fb..d4f94adcf2b 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/dataprovider/BuildBuildData.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/dataprovider/BuildBuildData.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007 Intel Corporation and others. + * Copyright (c) 2007, 2012 Intel Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -7,6 +7,7 @@ * * Contributors: * Intel Corporation - Initial API and implementation + * Baltasar Belyavsky (Texas Instruments) - bug 340219: Project metadata files are saved unnecessarily *******************************************************************************/ package org.eclipse.cdt.managedbuilder.internal.dataprovider; @@ -14,8 +15,12 @@ import org.eclipse.cdt.core.envvar.IEnvironmentContributor; import org.eclipse.cdt.core.settings.model.ICOutputEntry; import org.eclipse.cdt.core.settings.model.extension.CBuildData; import org.eclipse.cdt.managedbuilder.core.IBuilder; +import org.eclipse.cdt.managedbuilder.core.ManagedBuilderCorePlugin; import org.eclipse.cdt.managedbuilder.internal.core.Builder; +import org.eclipse.cdt.managedbuilder.internal.core.BuilderFactory; import org.eclipse.cdt.managedbuilder.internal.core.Configuration; +import org.eclipse.core.resources.ICommand; +import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; @@ -32,7 +37,7 @@ public class BuildBuildData extends CBuildData { public IPath getBuilderCWD() { return new Path(fBuilder.getBuildPath());//ManagedBuildManager.getBuildLocation(fCfg, fBuilder); } - + // private IPath createAbsolutePathFromWorkspacePath(IPath path){ // IStringVariableManager mngr = VariablesPlugin.getDefault().getStringVariableManager(); // String locationString = mngr.generateVariableExpression("workspace_loc", path.toString()); //$NON-NLS-1$ @@ -90,7 +95,18 @@ public class BuildBuildData extends CBuildData { // return fEnvContibutor; return new BuildEnvironmentContributor(this); } - + + @Override + public ICommand getBuildSpecCommand() { + try { + return BuilderFactory.createCommandFromBuilder(this.fBuilder); + } + catch(CoreException cx) { + ManagedBuilderCorePlugin.log(cx); + return null; + } + } + public IBuilder getBuilder(){ return fBuilder; } diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/dataprovider/ConfigurationDataProvider.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/dataprovider/ConfigurationDataProvider.java index 2e57720201e..82a1c9c805e 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/dataprovider/ConfigurationDataProvider.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/dataprovider/ConfigurationDataProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2010 Intel Corporation and others. + * Copyright (c) 2007, 2012 Intel Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -7,6 +7,7 @@ * * Contributors: * Intel Corporation - Initial API and implementation + * Baltasar Belyavsky (Texas Instruments) - bug 340219: Project metadata files are saved unnecessarily *******************************************************************************/ package org.eclipse.cdt.managedbuilder.internal.dataprovider; @@ -29,7 +30,6 @@ import org.eclipse.cdt.core.settings.model.IModificationContext; import org.eclipse.cdt.core.settings.model.extension.CConfigurationData; import org.eclipse.cdt.core.settings.model.extension.CConfigurationDataProvider; import org.eclipse.cdt.managedbuilder.core.BuildException; -import org.eclipse.cdt.managedbuilder.core.IBuilder; import org.eclipse.cdt.managedbuilder.core.IConfiguration; import org.eclipse.cdt.managedbuilder.core.IFolderInfo; import org.eclipse.cdt.managedbuilder.core.IInputType; @@ -43,7 +43,6 @@ import org.eclipse.cdt.managedbuilder.core.IToolChain; import org.eclipse.cdt.managedbuilder.core.ManagedBuildManager; import org.eclipse.cdt.managedbuilder.core.ManagedBuilderCorePlugin; import org.eclipse.cdt.managedbuilder.internal.core.Builder; -import org.eclipse.cdt.managedbuilder.internal.core.BuilderFactory; import org.eclipse.cdt.managedbuilder.internal.core.Configuration; import org.eclipse.cdt.managedbuilder.internal.core.ISettingsChangeListener; import org.eclipse.cdt.managedbuilder.internal.core.InputType; @@ -54,7 +53,6 @@ import org.eclipse.cdt.managedbuilder.internal.core.SettingsChangeEvent; import org.eclipse.cdt.managedbuilder.internal.core.Tool; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; -import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.QualifiedName; @@ -83,28 +81,6 @@ public class ConfigurationDataProvider extends CConfigurationDataProvider implem } } - private static class DesApplyRunnable implements IWorkspaceRunnable { - IBuilder fBuilder; - IProject fProject; - - DesApplyRunnable(IProject project, IBuilder builder){ - fProject = project; - fBuilder = builder; - } - - @Override - public void run(IProgressMonitor monitor) throws CoreException { - try { - IProjectDescription eDes = fProject.getDescription(); - if(BuilderFactory.applyBuilder(eDes, fBuilder) == BuilderFactory.CMD_CHANGED) { - fProject.setDescription(eDes, monitor); - } - } catch (Exception e){ - ManagedBuilderCorePlugin.log(e); - } - } - - } static BuildConfigurationData writeConfiguration(ICConfigurationDescription cfgDescription, BuildConfigurationData base) throws CoreException { BuildConfigurationData appliedCfg = base; @@ -178,22 +154,6 @@ public class ConfigurationDataProvider extends CConfigurationDataProvider implem setPersistedFlag(cfgDescription); cacheNaturesIdsUsedOnCache(cfgDescription); - - if(cfgDescription.isActive()){ - IConfiguration cfg = appliedCfg.getConfiguration(); - IBuilder builder = cfg.getEditableBuilder(); - IProject project = context.getProject(); - IProjectDescription eDes = context.getEclipseProjectDescription(); - switch(BuilderFactory.applyBuilder(eDes, builder)){ - case BuilderFactory.CMD_UNDEFINED: - IWorkspaceRunnable applyR = new DesApplyRunnable(project, builder); - context.addWorkspaceRunnable(applyR); - break; - case BuilderFactory.CMD_CHANGED: - context.setEclipseProjectDescription(eDes); - break; - } - } } return appliedCfg; } diff --git a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/settings/model/extension/CBuildData.java b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/settings/model/extension/CBuildData.java index 4d42f178832..d1f67b34860 100644 --- a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/settings/model/extension/CBuildData.java +++ b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/settings/model/extension/CBuildData.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 Intel Corporation and others. + * Copyright (c) 2007, 2012 Intel Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -7,12 +7,14 @@ * * Contributors: * Intel Corporation - Initial API and implementation + * Baltasar Belyavsky (Texas Instruments) - bug 340219: Project metadata files are saved unnecessarily *******************************************************************************/ package org.eclipse.cdt.core.settings.model.extension; import org.eclipse.cdt.core.envvar.IEnvironmentContributor; import org.eclipse.cdt.core.settings.model.ICOutputEntry; import org.eclipse.cdt.core.settings.model.ICSettingBase; +import org.eclipse.core.resources.ICommand; import org.eclipse.core.runtime.IPath; public abstract class CBuildData extends CDataObject { @@ -26,12 +28,22 @@ public abstract class CBuildData extends CDataObject { public abstract void setBuilderCWD(IPath path); public abstract ICOutputEntry[] getOutputDirectories(); - + public abstract void setOutputDirectories(ICOutputEntry[] entries); - + public abstract String[] getErrorParserIDs(); public abstract void setErrorParserIDs(String[] ids); - + public abstract IEnvironmentContributor getBuildEnvironmentContributor(); + + /** + * Override to return the build-command overlayed with data (eg. builder-arguments) managed by the build-system. + * + * @since 5.4 + */ + public ICommand getBuildSpecCommand() { + return null; + } + } From 88bf01e541760bb2aeeb82656f80d5ed9ffbf67b Mon Sep 17 00:00:00 2001 From: Baltasar Belyavsky Date: Sat, 11 Feb 2012 08:29:43 -0500 Subject: [PATCH 43/43] bug 340219: Project metadata files are saved unnecessarily, patch to address .cproject file modifications --- .../settings/model/CProjectDescription.java | 34 +++++++++---------- .../SetCProjectDescriptionOperation.java | 16 ++++----- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/settings/model/CProjectDescription.java b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/settings/model/CProjectDescription.java index f4a39275739..e140e2f0bc0 100644 --- a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/settings/model/CProjectDescription.java +++ b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/settings/model/CProjectDescription.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2010 Intel Corporation and others. + * Copyright (c) 2007, 2012 Intel Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -8,6 +8,7 @@ * Contributors: * Intel Corporation - Initial API and implementation * James Blackburn (Broadcom Corp.) + * Baltasar Belyavsky (Texas Instruments) - bug 340219: Project metadata files are saved unnecessarily *******************************************************************************/ package org.eclipse.cdt.internal.core.settings.model; @@ -50,7 +51,6 @@ public class CProjectDescription implements ICProjectDescription, ICDataProxyCon private boolean fIsReadOnly; private boolean fIsModified; private HashMap fPropertiesMap; -// private boolean fNeedsActiveCfgIdPersistence; private boolean fIsLoading; private boolean fIsApplying; private boolean fIsCreating; @@ -549,17 +549,10 @@ public class CProjectDescription implements ICProjectDescription, ICDataProxyCon return cfg; } - @Override - public boolean isModified() { + boolean needsDescriptionPersistence() { if(fIsModified) return true; - if(fActiveCfgInfo.fIsCfgModified) - return true; - - if(fSettingCfgInfo.fIsCfgModified) - return true; - if(fPrefs.isModified()) return true; @@ -573,6 +566,20 @@ public class CProjectDescription implements ICProjectDescription, ICDataProxyCon return false; } + @Override + public boolean isModified() { + if(needsDescriptionPersistence()) + return true; + + if(needsActiveCfgPersistence()) + return true; + + if(needsSettingCfgPersistence()) + return true; + + return false; + } + private void setModified(boolean modified){ fIsModified = modified; @@ -665,13 +672,6 @@ public class CProjectDescription implements ICProjectDescription, ICDataProxyCon } } -// boolean checkPersistCfgChanges(boolean force){ -// boolean stored = false; -// stored |= checkPersistActiveCfg(force); -// stored |= checkPersistSettingCfg(force); -// return stored; -// } - boolean checkPersistActiveCfg(String oldId, boolean force){ return fActiveCfgInfo.store(oldId, force); } diff --git a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/settings/model/SetCProjectDescriptionOperation.java b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/settings/model/SetCProjectDescriptionOperation.java index d8414d40197..2734232f2c9 100644 --- a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/settings/model/SetCProjectDescriptionOperation.java +++ b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/settings/model/SetCProjectDescriptionOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2010 Intel Corporation and others. + * Copyright (c) 2007, 2012 Intel Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -8,6 +8,7 @@ * Contributors: * Intel Corporation - Initial API and implementation * James Blackburn (Broadcom Corp.) + * Baltasar Belyavsky (Texas Instruments) - bug 340219: Project metadata files are saved unnecessarily *******************************************************************************/ package org.eclipse.cdt.internal.core.settings.model; @@ -65,14 +66,14 @@ public class SetCProjectDescriptionOperation extends CModelOperation { AbstractCProjectDescriptionStorage.fireAboutToApplyEvent(fSetDescription, fOldDescriptionCache); CProjectDescription fNewDescriptionCache = null; SettingsContext context = new SettingsContext(project); - boolean modified = false; + boolean needsSerialization = false; if(fSetDescription != null){ ICStorageElement newEl = null; ICSettingsStorage newStorage = null; try { ICStorageElement base = fSetDescription.getRootStorageElement(); - modified = fSetDescription.isModified(); + needsSerialization = fSetDescription.needsDescriptionPersistence(); // el = base; // FIXME JBB there is deep magic going on here. The project descriptions are being // changed in non-obvious ways @@ -94,13 +95,11 @@ public class SetCProjectDescriptionOperation extends CModelOperation { boolean envStates[] = getEnvStates(fNewDescriptionCache); try { fPrjDescStorage.setThreadLocalProjectDesc(fNewDescriptionCache); - modified |= fNewDescriptionCache.applyDatas(context); + fNewDescriptionCache.applyDatas(context); } finally { fPrjDescStorage.setThreadLocalProjectDesc(null); setEnvStates(fNewDescriptionCache, envStates); } - } else { - modified = fOldDescriptionCache != null; } ICDescriptionDelta delta = mngr.createDelta(fNewDescriptionCache, fOldDescriptionCache); @@ -143,7 +142,7 @@ public class SetCProjectDescriptionOperation extends CModelOperation { try { IWorkspaceRunnable toRun = null; if(fNewDescriptionCache != null && !CProjectDescriptionManager.checkFlags(fFlags, ICProjectDescriptionManager.SET_NO_SERIALIZE)){ - if(modified || isPersistentCoreSettingChanged(event)){ + if(needsSerialization || isPersistentCoreSettingChanged(event)){ toRun = fPrjDescStorage.createDesSerializationRunnable(); if (toRun != null) context.addWorkspaceRunnable(toRun); @@ -182,7 +181,8 @@ public class SetCProjectDescriptionOperation extends CModelOperation { return true; int flags = delta.getChangeFlags(); - if(flags != 0 && flags != ICDescriptionDelta.ACTIVE_CFG) + // check for any flag except ACTIVE_CFG and SETTING_CFG + if((flags & ~(ICDescriptionDelta.ACTIVE_CFG | ICDescriptionDelta.SETTING_CFG)) != 0) return true; return false;