1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-06-09 18:56:02 +02:00

Revert "Cosmetics."

This reverts commit e98bf3e3e3.
This commit is contained in:
Sergey Prigogin 2015-02-06 14:12:45 -08:00
parent 9de6de9fd4
commit 1b6b3f0f06
10 changed files with 182 additions and 107 deletions

View file

@ -123,13 +123,14 @@ public interface ILanguage extends IAdaptable {
throws CoreException; throws CoreException;
/** /**
* Returns the AST completion node for the given offset. * Return the AST completion node for the given offset.
* @since 5.2 * @since 5.2
*/ */
public IASTCompletionNode getCompletionNode(FileContent reader, IScannerInfo scanInfo, public IASTCompletionNode getCompletionNode(FileContent reader, IScannerInfo scanInfo,
IncludeFileContentProvider fileCreator, IIndex index, IParserLogService log, int offset) IncludeFileContentProvider fileCreator, IIndex index, IParserLogService log, int offset)
throws CoreException; throws CoreException;
/** /**
* Used to override the default model building behavior for a translation unit. * Used to override the default model building behavior for a translation unit.
* *

View file

@ -468,10 +468,11 @@ public interface ITranslationUnit extends ICElement, IParent, IOpenable, ISource
public IASTTranslationUnit getAST(IIndex index, int style) throws CoreException; public IASTTranslationUnit getAST(IIndex index, int style) throws CoreException;
/** /**
* Returns the completion node using the given index and parsing style at the given offset. * Return the completion node using the given index and parsing style at the given offset.
*/ */
public IASTCompletionNode getCompletionNode(IIndex index, int style, int offset) throws CoreException; public IASTCompletionNode getCompletionNode(IIndex index, int style, int offset) throws CoreException;
/** /**
* @deprecated use {@link #getSharedWorkingCopy(IProgressMonitor, IProblemRequestor)}, * @deprecated use {@link #getSharedWorkingCopy(IProgressMonitor, IProblemRequestor)},
* or CDTUITools.getWorkingCopyManager() instead. * or CDTUITools.getWorkingCopyManager() instead.

View file

@ -213,7 +213,7 @@ public abstract class AbstractCLikeLanguage extends AbstractLanguage implements
} }
/** /**
* Creates the parser. * Create the parser.
* *
* @param scanner the IScanner to get tokens from * @param scanner the IScanner to get tokens from
* @param log the parser log service * @param log the parser log service

View file

@ -57,6 +57,7 @@ import org.eclipse.cdt.internal.ui.text.contentassist.CContentAssistInvocationCo
import org.eclipse.cdt.internal.ui.text.contentassist.TemplateCompletionProposalComputer; import org.eclipse.cdt.internal.ui.text.contentassist.TemplateCompletionProposalComputer;
public class SurroundWithTemplateMenuAction implements IWorkbenchWindowPulldownDelegate2 { public class SurroundWithTemplateMenuAction implements IWorkbenchWindowPulldownDelegate2 {
public static final String SURROUND_WITH_QUICK_MENU_ACTION_ID= "org.eclipse.cdt.ui.edit.text.c.surround.with.quickMenu"; //$NON-NLS-1$ public static final String SURROUND_WITH_QUICK_MENU_ACTION_ID= "org.eclipse.cdt.ui.edit.text.c.surround.with.quickMenu"; //$NON-NLS-1$
private static final String C_TEMPLATE_PREFERENCE_PAGE_ID= "org.eclipse.cdt.ui.preferences.TemplatePreferencePage"; //$NON-NLS-1$ private static final String C_TEMPLATE_PREFERENCE_PAGE_ID= "org.eclipse.cdt.ui.preferences.TemplatePreferencePage"; //$NON-NLS-1$
@ -66,10 +67,14 @@ public class SurroundWithTemplateMenuAction implements IWorkbenchWindowPulldownD
private static final String CONFIG_GROUP= "configGroup"; //$NON-NLS-1$ private static final String CONFIG_GROUP= "configGroup"; //$NON-NLS-1$
private static class ConfigureTemplatesAction extends Action { private static class ConfigureTemplatesAction extends Action {
public ConfigureTemplatesAction() { public ConfigureTemplatesAction() {
super(ActionMessages.SurroundWithTemplateMenuAction_ConfigureTemplatesActionName); super(ActionMessages.SurroundWithTemplateMenuAction_ConfigureTemplatesActionName);
} }
/**
* {@inheritDoc}
*/
@Override @Override
public void run() { public void run() {
PreferencesUtil.createPreferenceDialogOn(getShell(), C_TEMPLATE_PREFERENCE_PAGE_ID, new String[] {C_TEMPLATE_PREFERENCE_PAGE_ID}, null).open(); PreferencesUtil.createPreferenceDialogOn(getShell(), C_TEMPLATE_PREFERENCE_PAGE_ID, new String[] {C_TEMPLATE_PREFERENCE_PAGE_ID}, null).open();
@ -85,7 +90,6 @@ public class SurroundWithTemplateMenuAction implements IWorkbenchWindowPulldownD
public void run() { public void run() {
//Do nothing //Do nothing
} }
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return false; return false;
@ -95,6 +99,7 @@ public class SurroundWithTemplateMenuAction implements IWorkbenchWindowPulldownD
private Menu fMenu; private Menu fMenu;
private IPartService fPartService; private IPartService fPartService;
private IPartListener fPartListener= new IPartListener() { private IPartListener fPartListener= new IPartListener() {
@Override @Override
public void partActivated(IWorkbenchPart part) { public void partActivated(IWorkbenchPart part) {
} }
@ -130,6 +135,9 @@ public class SurroundWithTemplateMenuAction implements IWorkbenchWindowPulldownD
} }
} }
/**
* {@inheritDoc}
*/
@Override @Override
public Menu getMenu(Menu parent) { public Menu getMenu(Menu parent) {
setMenu(new Menu(parent)); setMenu(new Menu(parent));
@ -138,6 +146,9 @@ public class SurroundWithTemplateMenuAction implements IWorkbenchWindowPulldownD
return fMenu; return fMenu;
} }
/**
* {@inheritDoc}
*/
@Override @Override
public Menu getMenu(Control parent) { public Menu getMenu(Control parent) {
setMenu(new Menu(parent)); setMenu(new Menu(parent));
@ -160,6 +171,9 @@ public class SurroundWithTemplateMenuAction implements IWorkbenchWindowPulldownD
menu.add(new ConfigureTemplatesAction()); menu.add(new ConfigureTemplatesAction());
} }
/**
* {@inheritDoc}
*/
@Override @Override
public void dispose() { public void dispose() {
if (fPartService != null) { if (fPartService != null) {
@ -169,6 +183,9 @@ public class SurroundWithTemplateMenuAction implements IWorkbenchWindowPulldownD
setMenu(null); setMenu(null);
} }
/**
* {@inheritDoc}
*/
@Override @Override
public void init(IWorkbenchWindow window) { public void init(IWorkbenchWindow window) {
if (fPartService != null) { if (fPartService != null) {
@ -185,6 +202,9 @@ public class SurroundWithTemplateMenuAction implements IWorkbenchWindowPulldownD
} }
} }
/**
* {@inheritDoc}
*/
@Override @Override
public void run(IAction action) { public void run(IAction action) {
IWorkbenchPart activePart= CUIPlugin.getActivePage().getActivePart(); IWorkbenchPart activePart= CUIPlugin.getActivePage().getActivePart();
@ -201,6 +221,9 @@ public class SurroundWithTemplateMenuAction implements IWorkbenchWindowPulldownD
}.createMenu(); }.createMenu();
} }
/**
* {@inheritDoc}
*/
@Override @Override
public void selectionChanged(IAction action, ISelection selection) { public void selectionChanged(IAction action, ISelection selection) {
// Default do nothing // Default do nothing
@ -211,6 +234,7 @@ public class SurroundWithTemplateMenuAction implements IWorkbenchWindowPulldownD
* @param menu the menu to fill entries into it * @param menu the menu to fill entries into it
*/ */
protected void fillMenu(Menu menu) { protected void fillMenu(Menu menu) {
IWorkbenchPart activePart= CUIPlugin.getActivePage().getActivePart(); IWorkbenchPart activePart= CUIPlugin.getActivePage().getActivePart();
if (!(activePart instanceof CEditor)) { if (!(activePart instanceof CEditor)) {
ActionContributionItem item= new ActionContributionItem(NONE_APPLICABLE_ACTION); ActionContributionItem item= new ActionContributionItem(NONE_APPLICABLE_ACTION);
@ -218,7 +242,7 @@ public class SurroundWithTemplateMenuAction implements IWorkbenchWindowPulldownD
return; return;
} }
CEditor editor= (CEditor) activePart; CEditor editor= (CEditor)activePart;
IAction[] actions= getTemplateActions(editor); IAction[] actions= getTemplateActions(editor);
if ( actions == null || actions.length <= 0) { if ( actions == null || actions.length <= 0) {
@ -243,9 +267,9 @@ public class SurroundWithTemplateMenuAction implements IWorkbenchWindowPulldownD
fMenu.addMenuListener(new MenuAdapter() { fMenu.addMenuListener(new MenuAdapter() {
@Override @Override
public void menuShown(MenuEvent e) { public void menuShown(MenuEvent e) {
Menu m = (Menu) e.widget; Menu m = (Menu)e.widget;
MenuItem[] items = m.getItems(); MenuItem[] items = m.getItems();
for (int i= 0; i < items.length; i++) { for (int i=0; i < items.length; i++) {
items[i].dispose(); items[i].dispose();
} }
fillMenu(m); fillMenu(m);
@ -291,19 +315,21 @@ public class SurroundWithTemplateMenuAction implements IWorkbenchWindowPulldownD
return (ITextSelection)selection; return (ITextSelection)selection;
} }
private static IAction[] getActionsFromProposals(List<ICompletionProposal> proposals, final int offset, private static IAction[] getActionsFromProposals(List<ICompletionProposal> proposals, final int offset, final ITextViewer viewer) {
final ITextViewer viewer) { List<Action> result= new ArrayList<Action>();
List<Action> result= new ArrayList<>();
int j = 1; int j = 1;
for (Iterator<ICompletionProposal> it= proposals.iterator(); it.hasNext();) { for (Iterator<ICompletionProposal> it= proposals.iterator(); it.hasNext();) {
final ICompletionProposal proposal= it.next(); final ICompletionProposal proposal= it.next();
StringBuilder actionName= new StringBuilder(); StringBuffer actionName= new StringBuffer();
if (j < 10) { if (j < 10) {
actionName.append('&').append(j).append(' '); actionName.append('&').append(j).append(' ');
} }
actionName.append(proposal.getDisplayString()); actionName.append(proposal.getDisplayString());
Action action= new Action(actionName.toString()) { Action action= new Action(actionName.toString()) {
/**
* {@inheritDoc}
*/
@Override @Override
public void run() { public void run() {
applyProposal(proposal, viewer, (char)0, 0, offset); applyProposal(proposal, viewer, (char)0, 0, offset);
@ -313,19 +339,19 @@ public class SurroundWithTemplateMenuAction implements IWorkbenchWindowPulldownD
result.add(action); result.add(action);
j++; j++;
} }
if (result.isEmpty()) if (result.size() == 0)
return null; return null;
return result.toArray(new IAction[result.size()]); return result.toArray(new IAction[result.size()]);
} }
private static void applyProposal(ICompletionProposal proposal, ITextViewer viewer, char trigger, private static void applyProposal(ICompletionProposal proposal, ITextViewer viewer, char trigger, int stateMask, final int offset) {
int stateMask, final int offset) {
Assert.isTrue(proposal instanceof ICompletionProposalExtension2); Assert.isTrue(proposal instanceof ICompletionProposalExtension2);
IRewriteTarget target= null; IRewriteTarget target= null;
IEditingSupportRegistry registry= null; IEditingSupportRegistry registry= null;
IEditingSupport helper= new IEditingSupport() { IEditingSupport helper= new IEditingSupport() {
@Override @Override
public boolean isOriginator(DocumentEvent event, IRegion focus) { public boolean isOriginator(DocumentEvent event, IRegion focus) {
return focus.getOffset() <= offset && focus.getOffset() + focus.getLength() >= offset; return focus.getOffset() <= offset && focus.getOffset() + focus.getLength() >= offset;

View file

@ -78,17 +78,12 @@ public class CContentAssistInvocationContext extends ContentAssistInvocationCont
@Override @Override
protected IASTCompletionNode calculateValue() { protected IASTCompletionNode calculateValue() {
int offset = getParseOffset(); int offset = getParseOffset();
if (offset < 0) if (offset < 0) return null;
return null;
ICProject proj= getProject(); ICProject proj= getProject();
if (proj == null) if (proj == null) return null;
return null;
try { try {
if (fIndex != null)
throw new IllegalStateException("The method should not be called multiple times."); //$NON-NLS-1$
IIndexManager manager= CCorePlugin.getIndexManager(); IIndexManager manager= CCorePlugin.getIndexManager();
fIndex = manager.getIndex(proj, IIndexManager.ADD_DEPENDENCIES | IIndexManager.ADD_EXTENSION_FRAGMENTS_CONTENT_ASSIST); fIndex = manager.getIndex(proj, IIndexManager.ADD_DEPENDENCIES | IIndexManager.ADD_EXTENSION_FRAGMENTS_CONTENT_ASSIST);
@ -206,19 +201,18 @@ public class CContentAssistInvocationContext extends ContentAssistInvocationCont
* @param editor the editor that content assist is invoked in * @param editor the editor that content assist is invoked in
* @param isAutoActivated indicates whether content assist was auto-activated * @param isAutoActivated indicates whether content assist was auto-activated
*/ */
public CContentAssistInvocationContext(ITextViewer viewer, int offset, IEditorPart editor, public CContentAssistInvocationContext(ITextViewer viewer, int offset, IEditorPart editor, boolean isCompletion, boolean isAutoActivated) {
boolean isCompletion, boolean isAutoActivated) {
super(viewer, offset); super(viewer, offset);
Assert.isNotNull(editor); Assert.isNotNull(editor);
fEditor= editor; fEditor= editor;
fIsCompletion= isCompletion; fIsCompletion= isCompletion;
fIsAutoActivated= isAutoActivated; fIsAutoActivated= isAutoActivated;
fTU = new Lazy<ITranslationUnit>() { fTU = new Lazy<ITranslationUnit>() {
@Override @Override
protected ITranslationUnit calculateValue() { protected ITranslationUnit calculateValue() {
return CUIPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(fEditor.getEditorInput()); return CUIPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(fEditor.getEditorInput());
} }
}; };
} }
/** /**
@ -264,13 +258,13 @@ public class CContentAssistInvocationContext extends ContentAssistInvocationCont
@Override @Override
public IASTCompletionNode getCompletionNode() { public IASTCompletionNode getCompletionNode() {
// For scalability. //for scalability
if (fEditor != null && fEditor instanceof CEditor) { if (fEditor != null && fEditor instanceof CEditor) {
CEditor editor = (CEditor) fEditor; CEditor editor = (CEditor)fEditor;
// Check to make sure we should attempt local parsing completions... for remote projects // check to make sure we should attempt local parsing completions... for remote projects
// we should not do this. // we should not do this
if (!editor.shouldProcessLocalParsingCompletions()) { if(!editor.shouldProcessLocalParsingCompletions()) {
return null; return null;
} }
if (editor.isEnableScalablilityMode()) { if (editor.isEnableScalablilityMode()) {

View file

@ -37,16 +37,15 @@ import org.eclipse.cdt.ui.CUIPlugin;
* exit policy. * exit policy.
*/ */
public class FunctionCompletionProposal extends CCompletionProposal { public class FunctionCompletionProposal extends CCompletionProposal {
private boolean fHasParametersComputed; private boolean fHasParametersComputed= false;
private boolean fHasParameters; private boolean fHasParameters;
protected IParameter[] fFunctionParameters; protected IParameter [] fFunctionParameters;
protected CContentAssistInvocationContext fContext; protected CContentAssistInvocationContext fContext;
public FunctionCompletionProposal(String replacementString, int replacementOffset, int replacementLength, public FunctionCompletionProposal(String replacementString, int replacementOffset, int replacementLength,
Image image, String displayString, String idString, int relevance, ITextViewer viewer, Image image, String displayString, String idString, int relevance, ITextViewer viewer, IFunction function, CContentAssistInvocationContext context) {
IFunction function, CContentAssistInvocationContext context) { super(replacementString, replacementOffset, replacementLength, image, displayString, idString, relevance,
super(replacementString, replacementOffset, replacementLength, image, displayString, viewer);
idString, relevance, viewer);
fFunctionParameters = function.getParameters(); fFunctionParameters = function.getParameters();
fContext = context; fContext = context;
} }
@ -64,8 +63,8 @@ public class FunctionCompletionProposal extends CCompletionProposal {
} }
/** /**
* Returns <code>true</code> if the method has any parameters, <code>false</code> if it has * @return <code>true</code> if the method has any parameters, <code>false</code> if it has
* no parameters. * no parameters
*/ */
protected final boolean hasParameters() { protected final boolean hasParameters() {
if (!fHasParametersComputed) { if (!fHasParametersComputed) {
@ -76,24 +75,28 @@ public class FunctionCompletionProposal extends CCompletionProposal {
} }
private boolean computeHasParameters() { private boolean computeHasParameters() {
return fFunctionParameters != null && fFunctionParameters.length != 0; return (fFunctionParameters != null && fFunctionParameters.length != 0);
} }
protected static class ExitPolicy implements IExitPolicy { protected static class ExitPolicy implements IExitPolicy {
final char fExitCharacter; final char fExitCharacter;
public ExitPolicy(char exitCharacter) { public ExitPolicy(char exitCharacter) {
fExitCharacter = exitCharacter; fExitCharacter = exitCharacter;
} }
/*
* @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int)
*/
@Override @Override
public ExitFlags doExit(LinkedModeModel environment, VerifyEvent event, int offset, int length) { public ExitFlags doExit(LinkedModeModel environment, VerifyEvent event, int offset, int length) {
if (event.character == fExitCharacter) { if (event.character == fExitCharacter) {
if (environment.anyPositionContains(offset)) { if (environment.anyPositionContains(offset))
return new ExitFlags(ILinkedModeListener.UPDATE_CARET, false); return new ExitFlags(ILinkedModeListener.UPDATE_CARET, false);
} else { else
return new ExitFlags(ILinkedModeListener.UPDATE_CARET, true); return new ExitFlags(ILinkedModeListener.UPDATE_CARET, true);
}
} }
switch (event.character) { switch (event.character) {
@ -124,8 +127,8 @@ public class FunctionCompletionProposal extends CCompletionProposal {
ui.setExitPosition(fTextViewer, exit, 0, Integer.MAX_VALUE); ui.setExitPosition(fTextViewer, exit, 0, Integer.MAX_VALUE);
ui.setCyclingMode(LinkedModeUI.CYCLE_NEVER); ui.setCyclingMode(LinkedModeUI.CYCLE_NEVER);
ui.enter(); ui.enter();
} catch (BadLocationException e) { } catch (BadLocationException x) {
CUIPlugin.log(e); CUIPlugin.log(x);
} }
} }
} }

View file

@ -12,16 +12,16 @@
package org.eclipse.cdt.internal.ui.text.contentassist; package org.eclipse.cdt.internal.ui.text.contentassist;
/** /**
* This class represents a field or variable which shall be initialized lazily when accessed * This class represents a field or variable which shall be initialized lazily when accessed the
* the first time. It's value is computed once by the {@code calculateValue()} method. The value is * first time. It's value is computed once by the <code>calculateValue()</code> method. The value is
* accessed by {@code value()}. * accessed by <code>value()</code>.
* *
* This implementation is NOT thread-safe! * This implementation is NOT thread-safe!
* *
* @param <E> The type of the lazy initialized variable. * @param <E> The type of the lazy initialized variable.
*/ */
public abstract class Lazy<E> { public abstract class Lazy<E> {
private static final Object NOT_INITIALIZED = new Object(); private final static Object NOT_INITIALIZED = new Object();
private Object value = NOT_INITIALIZED; private Object value = NOT_INITIALIZED;
/** /**

View file

@ -26,7 +26,6 @@ import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Image;
import org.eclipse.cdt.core.dom.ast.DOMException; import org.eclipse.cdt.core.dom.ast.DOMException;
import org.eclipse.cdt.core.dom.ast.IASTExpression.ValueCategory;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.IBinding; import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.ICompositeType; import org.eclipse.cdt.core.dom.ast.ICompositeType;
@ -37,6 +36,7 @@ import org.eclipse.cdt.core.dom.ast.IPointerType;
import org.eclipse.cdt.core.dom.ast.IType; import org.eclipse.cdt.core.dom.ast.IType;
import org.eclipse.cdt.core.dom.ast.ITypedef; import org.eclipse.cdt.core.dom.ast.ITypedef;
import org.eclipse.cdt.core.dom.ast.IVariable; import org.eclipse.cdt.core.dom.ast.IVariable;
import org.eclipse.cdt.core.dom.ast.IASTExpression.ValueCategory;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPBase; import org.eclipse.cdt.core.dom.ast.cpp.ICPPBase;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPBinding; import org.eclipse.cdt.core.dom.ast.cpp.ICPPBinding;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassTemplate; import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassTemplate;
@ -61,10 +61,10 @@ import org.eclipse.cdt.internal.ui.util.StringMatcher;
import org.eclipse.cdt.internal.ui.viewsupport.CElementImageProvider; import org.eclipse.cdt.internal.ui.viewsupport.CElementImageProvider;
/** /**
* This class is based on org.eclipse.jdt.internal.ui.text.java.ParameterGuesser * This iAPI layout is copied from org.eclipse.jdt.internal.ui.text.java.ParameterGuesser
* *
* This class triggers a code-completion that will track all global, local and member variables and * This class triggers a code-completion that will track all global, local and member variables and order them logically for later
* order them logically for later use as a parameter guessing proposal. * use as a parameter guessing proposal.
*/ */
public class ParameterGuesser { public class ParameterGuesser {
private IASTTranslationUnit fTranslationUnit; private IASTTranslationUnit fTranslationUnit;
@ -72,9 +72,9 @@ public class ParameterGuesser {
private final Set<String> fAlreadyMatchedNames; private final Set<String> fAlreadyMatchedNames;
private final static class Variable { private final static class Variable {
/** /**
* Variable type. Used to choose the best guess based on scope * Variable type. Used to choose the best guess based on scope (Local beats instance beats inherited beats global).
* (Local beats instance beats inherited beats global).
*/ */
public static final int LOCAL = 0; public static final int LOCAL = 0;
public static final int FIELD = 1; public static final int FIELD = 1;
@ -92,8 +92,7 @@ public class ParameterGuesser {
public boolean alreadyMatched; public boolean alreadyMatched;
public Variable(IType qualifiedTypeName, String name, int variableType, public Variable(IType qualifiedTypeName, String name, int variableType, boolean isAutoboxMatch, int positionScore, char[] triggerChars, ImageDescriptor descriptor) {
boolean isAutoboxMatch, int positionScore, char[] triggerChars, ImageDescriptor descriptor) {
this.qualifiedTypeName= qualifiedTypeName; this.qualifiedTypeName= qualifiedTypeName;
this.name= name; this.name= name;
this.variableType= variableType; this.variableType= variableType;
@ -104,15 +103,20 @@ public class ParameterGuesser {
this.alreadyMatched= false; this.alreadyMatched= false;
} }
/*
* @see Object#toString()
*/
@Override @Override
public String toString() { public String toString() {
StringBuilder buffer= new StringBuilder();
StringBuffer buffer= new StringBuffer();
buffer.append(qualifiedTypeName); buffer.append(qualifiedTypeName);
buffer.append(' '); buffer.append(' ');
buffer.append(name); buffer.append(name);
buffer.append(" ("); //$NON-NLS-1$ buffer.append(" ("); //$NON-NLS-1$
buffer.append(variableType); buffer.append(variableType);
buffer.append(')'); buffer.append(')');
return buffer.toString(); return buffer.toString();
} }
} }
@ -125,9 +129,8 @@ public class ParameterGuesser {
fTranslationUnit = translationUnit; fTranslationUnit = translationUnit;
} }
private List<Variable> evaluateVisibleMatches(IType expectedType, List<IBinding> suggestions) private List<Variable> evaluateVisibleMatches(IType expectedType, ArrayList<IBinding> suggestions) throws CModelException {
throws CModelException { ArrayList<Variable> res= new ArrayList<Variable>();
ArrayList<Variable> res= new ArrayList<>();
int size = suggestions.size(); int size = suggestions.size();
for (int i= 0; i < size; i++) { for (int i= 0; i < size; i++) {
Variable variable= createVariable(suggestions.get(i), expectedType, i); Variable variable= createVariable(suggestions.get(i), expectedType, i);
@ -169,6 +172,7 @@ public class ParameterGuesser {
int variableType = Variable.GLOBAL; int variableType = Variable.GLOBAL;
if (element instanceof ICPPField) { if (element instanceof ICPPField) {
variableType = Variable.FIELD; variableType = Variable.FIELD;
} else if (element instanceof IVariable) { } else if (element instanceof IVariable) {
try { try {
if (element instanceof ICPPBinding && ((ICPPBinding) element).isGloballyQualified()) { if (element instanceof ICPPBinding && ((ICPPBinding) element).isGloballyQualified()) {
@ -181,13 +185,11 @@ public class ParameterGuesser {
} }
// Handle reference case // Handle reference case
if (isReferenceTo(enclosingType, elementType)) { if (isReferenceTo(enclosingType, elementType))
elementName = "&" + elementName; //$NON-NLS-1$ elementName = "&" + elementName; //$NON-NLS-1$
} else if (isReferenceTo(elementType, enclosingType)) { else if (isReferenceTo(elementType, enclosingType))
elementName = "*" + elementName; //$NON-NLS-1$ elementName = "*" + elementName; //$NON-NLS-1$
} return new Variable(elementType, elementName, variableType, false, positionScore, NO_TRIGGERS, getImageDescriptor(element));
return new Variable(elementType, elementName, variableType, false, positionScore,
NO_TRIGGERS, getImageDescriptor(element));
} }
return null; return null;
} }
@ -292,6 +294,9 @@ public class ParameterGuesser {
} }
/** /**
*
* Copied from JDT
*
* Returns the matches for the type and name argument, ordered by match quality. * Returns the matches for the type and name argument, ordered by match quality.
* *
* @param expectedType - the qualified type of the parameter we are trying to match * @param expectedType - the qualified type of the parameter we are trying to match
@ -302,7 +307,7 @@ public class ParameterGuesser {
* @param isLastParameter <code>true</code> iff this proposal is for the last parameter of a method * @param isLastParameter <code>true</code> iff this proposal is for the last parameter of a method
* @return returns the name of the best match, or <code>null</code> if no match found * @return returns the name of the best match, or <code>null</code> if no match found
*/ */
public ICompletionProposal[] parameterProposals(IType expectedType, String paramName, Position pos, List<IBinding> suggestions, boolean fillBestGuess, boolean isLastParameter) throws CModelException { public ICompletionProposal[] parameterProposals(IType expectedType, String paramName, Position pos, ArrayList<IBinding> suggestions, boolean fillBestGuess, boolean isLastParameter) throws CModelException {
List<Variable> typeMatches= evaluateVisibleMatches(expectedType, suggestions); List<Variable> typeMatches= evaluateVisibleMatches(expectedType, suggestions);
typeMatches = removeDuplicates(typeMatches); typeMatches = removeDuplicates(typeMatches);
orderMatches(typeMatches, paramName); orderMatches(typeMatches, paramName);
@ -340,7 +345,11 @@ public class ParameterGuesser {
return ret; return ret;
} }
/**
* Copied from JDT
*/
private static class MatchComparator implements Comparator<Variable> { private static class MatchComparator implements Comparator<Variable> {
private String fParamName; private String fParamName;
MatchComparator(String paramName) { MatchComparator(String paramName) {
@ -380,7 +389,10 @@ public class ParameterGuesser {
} }
/** /**
* Determines the best match of all possible type matches. The input into this method is all *
* Copied from JDT
*
* Determine the best match of all possible type matches. The input into this method is all
* possible completions that match the type of the argument. The purpose of this method is to * possible completions that match the type of the argument. The purpose of this method is to
* choose among them based on the following simple rules: * choose among them based on the following simple rules:
* *
@ -403,7 +415,10 @@ public class ParameterGuesser {
} }
/** /**
* Removes the duplicates from the list if any. *
* Copied from JDT
*
* Remove the duplicates from the list if any.
*/ */
private static List<Variable> removeDuplicates(List<Variable> typeMatches) { private static List<Variable> removeDuplicates(List<Variable> typeMatches) {
HashSet<Variable> set = new HashSet<Variable>(); HashSet<Variable> set = new HashSet<Variable>();
@ -412,6 +427,9 @@ public class ParameterGuesser {
} }
/** /**
*
* Copied from JDT
*
* Returns the longest common substring of two strings. * Returns the longest common substring of two strings.
* *
* @param first the first string * @param first the first string
@ -419,12 +437,13 @@ public class ParameterGuesser {
* @return the longest common substring * @return the longest common substring
*/ */
private static String getLongestCommonSubstring(String first, String second) { private static String getLongestCommonSubstring(String first, String second) {
String shorter= first.length() <= second.length() ? first : second;
String shorter= (first.length() <= second.length()) ? first : second;
String longer= shorter == first ? second : first; String longer= shorter == first ? second : first;
int minLength= shorter.length(); int minLength= shorter.length();
StringBuilder pattern= new StringBuilder(shorter.length() + 2); StringBuffer pattern= new StringBuffer(shorter.length() + 2);
String longestCommonSubstring= ""; //$NON-NLS-1$ String longestCommonSubstring= ""; //$NON-NLS-1$
for (int i= 0; i < minLength; i++) { for (int i= 0; i < minLength; i++) {
@ -447,7 +466,11 @@ public class ParameterGuesser {
return longestCommonSubstring; return longestCommonSubstring;
} }
/**
* Copied from JDT
*/
private Image getImage(ImageDescriptor descriptor) { private Image getImage(ImageDescriptor descriptor) {
return descriptor == null ? null : CUIPlugin.getImageDescriptorRegistry().get(descriptor); return (descriptor == null) ? null : CUIPlugin.getImageDescriptorRegistry().get(descriptor);
} }
} }

View file

@ -14,7 +14,6 @@ package org.eclipse.cdt.internal.ui.text.contentassist;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List;
import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.BadPositionCategoryException;
@ -55,7 +54,7 @@ import org.eclipse.cdt.internal.ui.editor.CEditor;
import org.eclipse.cdt.internal.ui.editor.EditorHighlightingSynchronizer; import org.eclipse.cdt.internal.ui.editor.EditorHighlightingSynchronizer;
/** /**
* This class is based on org.eclipse.jdt.internal.ui.text.java.ParameterGuessingProposal * This API layout is copied from org.eclipse.jdt.internal.ui.text.java.ParameterGuessingProposal
* *
* Extents the basic Function Compilation Proposal to add a linked mode for each of * Extents the basic Function Compilation Proposal to add a linked mode for each of
* the function parameters with a list of suggestions for each parameter. * the function parameters with a list of suggestions for each parameter.
@ -63,16 +62,15 @@ import org.eclipse.cdt.internal.ui.editor.EditorHighlightingSynchronizer;
public class ParameterGuessingProposal extends FunctionCompletionProposal { public class ParameterGuessingProposal extends FunctionCompletionProposal {
private ICompletionProposal[][] fChoices; // initialized by guessParameters() private ICompletionProposal[][] fChoices; // initialized by guessParameters()
private Position[] fPositions; // initialized by guessParameters() private Position[] fPositions; // initialized by guessParameters()
private boolean fReplacementStringComputed; private boolean fReplacementStringComputed = false;
private IRegion fSelectedRegion; // initialized by apply() private IRegion fSelectedRegion; // initialized by apply()
private IPositionUpdater fUpdater; private IPositionUpdater fUpdater;
private String fPrefix; // The string from the start of the statement to the parse offset. private String fPrefix; // The string from the start of the statement to the parse offset.
private String fFullPrefix; // The string from the start of the statement to the invocation offset. private String fFullPrefix; // The string from the start of the statement to the invocation offset.
private char[][] fParametersNames; private char[][] fParametersNames;
private IType[] fParametersTypes; private IType [] fParametersTypes;
public static ParameterGuessingProposal createProposal(CContentAssistInvocationContext context, public static ParameterGuessingProposal createProposal(CContentAssistInvocationContext context, CCompletionProposal proposal, IFunction function, String prefix) {
CCompletionProposal proposal, IFunction function, String prefix) {
String replacement = getParametersList(function); String replacement = getParametersList(function);
String fullPrefix = function.getName() + "("; //$NON-NLS-1$ String fullPrefix = function.getName() + "("; //$NON-NLS-1$
int replacementOffset = proposal.getReplacementOffset(); int replacementOffset = proposal.getReplacementOffset();
@ -91,10 +89,10 @@ public class ParameterGuessingProposal extends FunctionCompletionProposal {
try { try {
fullPrefix = context.getDocument().get(replacementOffset, context.getInvocationOffset() - replacementOffset); fullPrefix = context.getDocument().get(replacementOffset, context.getInvocationOffset() - replacementOffset);
replacement = fullPrefix + replacement + ")"; //$NON-NLS-1$ replacement = fullPrefix + replacement + ")"; //$NON-NLS-1$
} catch (BadLocationException e) { } catch (BadLocationException e1) {
} }
try { try {
// Remove ')' from the replacement string if it is auto appended. // remove ')' from the replacement string if it is auto appended.
if (context.getDocument().getChar(context.getInvocationOffset()) == ')') if (context.getDocument().getChar(context.getInvocationOffset()) == ')')
replacement = replacement.substring(0, replacement.length() - 1); replacement = replacement.substring(0, replacement.length() - 1);
} catch (BadLocationException e) { } catch (BadLocationException e) {
@ -105,9 +103,7 @@ public class ParameterGuessingProposal extends FunctionCompletionProposal {
} }
replacementLength = replacement.length(); replacementLength = replacement.length();
ParameterGuessingProposal ret = new ParameterGuessingProposal(replacement, replacementOffset, ParameterGuessingProposal ret = new ParameterGuessingProposal(replacement, replacementOffset, replacementLength, proposal.getImage(), proposal.getDisplayString(), proposal.getIdString(), proposal.getRelevance(), context.getViewer(), function, context);
replacementLength, proposal.getImage(), proposal.getDisplayString(),
proposal.getIdString(), proposal.getRelevance(), context.getViewer(), function, context);
ret.setContextInformation(proposal.getContextInformation()); ret.setContextInformation(proposal.getContextInformation());
ret.fPrefix = prefix; ret.fPrefix = prefix;
ret.fFullPrefix = fullPrefix; ret.fFullPrefix = fullPrefix;
@ -159,6 +155,9 @@ public class ParameterGuessingProposal extends FunctionCompletionProposal {
return super.getPrefixCompletionText(document, completionOffset); return super.getPrefixCompletionText(document, completionOffset);
} }
/**
* Copied from JDT
*/
@Override @Override
public void apply(final IDocument document, char trigger, int offset) { public void apply(final IDocument document, char trigger, int offset) {
try { try {
@ -236,6 +235,9 @@ public class ParameterGuessingProposal extends FunctionCompletionProposal {
} }
} }
/**
* Copied from JDT
*/
@Override @Override
public Point getSelection(IDocument document) { public Point getSelection(IDocument document) {
if (fSelectedRegion == null) if (fSelectedRegion == null)
@ -244,6 +246,9 @@ public class ParameterGuessingProposal extends FunctionCompletionProposal {
return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength()); return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength());
} }
/**
* Copied from JDT
*/
@Override @Override
public String getReplacementString() { public String getReplacementString() {
if (!fReplacementStringComputed) { if (!fReplacementStringComputed) {
@ -254,6 +259,9 @@ public class ParameterGuessingProposal extends FunctionCompletionProposal {
return super.getReplacementString(); return super.getReplacementString();
} }
/**
* Copied from JDT
*/
private String computeReplacementString() { private String computeReplacementString() {
if (!hasParameters()) if (!hasParameters())
return super.getReplacementString(); return super.getReplacementString();
@ -261,18 +269,21 @@ public class ParameterGuessingProposal extends FunctionCompletionProposal {
String replacement; String replacement;
try { try {
replacement = computeGuessingCompletion(); replacement = computeGuessingCompletion();
} catch (Exception e) { } catch (Exception x) {
fPositions = null; fPositions = null;
fChoices = null; fChoices = null;
CUIPlugin.log(e); CUIPlugin.log(x);
return super.getReplacementString(); return super.getReplacementString();
} }
return replacement; return replacement;
} }
/**
* Copied from JDT with replacing JDT types with CDT types
*/
private String computeGuessingCompletion() throws Exception { private String computeGuessingCompletion() throws Exception {
StringBuilder buffer = new StringBuilder(); StringBuffer buffer = new StringBuffer();
buffer.append(fFullPrefix); buffer.append(fFullPrefix);
setCursorPosition(buffer.length()); setCursorPosition(buffer.length());
@ -305,26 +316,28 @@ public class ParameterGuessingProposal extends FunctionCompletionProposal {
return buffer.toString(); return buffer.toString();
} }
/**
* Copied from JDT with replacing JDT types with CDT types
*/
private ICompletionProposal[][] guessParameters(char[][] parameterNames) throws Exception { private ICompletionProposal[][] guessParameters(char[][] parameterNames) throws Exception {
int count= parameterNames.length; int count= parameterNames.length;
fPositions= new Position[count]; fPositions= new Position[count];
fChoices= new ICompletionProposal[count][]; fChoices= new ICompletionProposal[count][];
ParameterGuesser guesser= new ParameterGuesser(fContext.getCompletionNode().getTranslationUnit()); ParameterGuesser guesser= new ParameterGuesser(fContext.getCompletionNode().getTranslationUnit());
List<IBinding> assignableElements = getAssignableElements(); ArrayList<IBinding> assignableElements = getAssignableElements();
for (int i= count - 1; i >= 0; i--) { for (int i= count - 1; i >= 0; i--) {
String paramName= new String(parameterNames[i]); String paramName= new String(parameterNames[i]);
Position position= new Position(0, 0); Position position= new Position(0,0);
boolean isLastParameter= i == count - 1; boolean isLastParameter= i == count - 1;
List<ICompletionProposal> allProposals = new ArrayList<>(); ArrayList<ICompletionProposal> allProposals = new ArrayList<ICompletionProposal>();
CCompletionProposal proposal= new CCompletionProposal(paramName, 0, paramName.length(), null, paramName, 0); CCompletionProposal proposal= new CCompletionProposal(paramName, 0, paramName.length(), null, paramName, 0);
if (isLastParameter) if (isLastParameter)
proposal.setTriggerCharacters(new char[] { ',' }); proposal.setTriggerCharacters(new char[] { ',' });
allProposals.add(proposal); allProposals.add(proposal);
ICompletionProposal[] argumentProposals= ICompletionProposal[] argumentProposals= guesser.parameterProposals(fParametersTypes[i], paramName, position, assignableElements, true, isLastParameter);
guesser.parameterProposals(fParametersTypes[i], paramName, position, assignableElements, true, isLastParameter);
allProposals.addAll(Arrays.asList(argumentProposals)); allProposals.addAll(Arrays.asList(argumentProposals));
fPositions[i]= position; fPositions[i]= position;
fChoices[i]= allProposals.toArray(new ICompletionProposal[allProposals.size()]); fChoices[i]= allProposals.toArray(new ICompletionProposal[allProposals.size()]);
@ -333,8 +346,8 @@ public class ParameterGuessingProposal extends FunctionCompletionProposal {
return fChoices; return fChoices;
} }
private static IType[] getFunctionParametersTypes(IParameter[] functionParameters) { private static IType[] getFunctionParametersTypes(IParameter [] functionParameters) {
IType[] ret = new IType[functionParameters.length]; IType [] ret = new IType[functionParameters.length];
for (int i = 0; i < functionParameters.length; i++) { for (int i = 0; i < functionParameters.length; i++) {
ret[i] = functionParameters[i].getType(); ret[i] = functionParameters[i].getType();
} }
@ -342,7 +355,7 @@ public class ParameterGuessingProposal extends FunctionCompletionProposal {
} }
private static char[][] getFunctionParametersNames(IParameter[] functionParameters) { private static char[][] getFunctionParametersNames(IParameter [] functionParameters) {
char[][] parameterNames = new char[functionParameters.length][]; char[][] parameterNames = new char[functionParameters.length][];
for (int i = 0; i < functionParameters.length; i++) { for (int i = 0; i < functionParameters.length; i++) {
parameterNames[i] = functionParameters[i].getNameCharArray(); parameterNames[i] = functionParameters[i].getNameCharArray();
@ -361,12 +374,12 @@ public class ParameterGuessingProposal extends FunctionCompletionProposal {
* Returns a list of functions and variables that are defined in current context. * Returns a list of functions and variables that are defined in current context.
* @return a list of assignable elements. * @return a list of assignable elements.
*/ */
private List<IBinding> getAssignableElements() { private ArrayList<IBinding> getAssignableElements() {
int i = getStatementStartOffset(fContext.getDocument(), getStatementStartOffset()); int i = getStatementStartOffset(fContext.getDocument(), getStatementStartOffset());
CContentAssistInvocationContext c = new CContentAssistInvocationContext(fTextViewer, i, getCEditor(), true, false); CContentAssistInvocationContext c = new CContentAssistInvocationContext(fTextViewer, i, getCEditor(), true, false);
IASTCompletionNode node = c.getCompletionNode(); IASTCompletionNode node = c.getCompletionNode();
IASTName[] names = node.getNames(); IASTName [] names = node.getNames();
List<IBinding> allBindings = new ArrayList<>(); ArrayList<IBinding> allBindings = new ArrayList<IBinding>();
for (IASTName name : names) { for (IASTName name : names) {
IASTCompletionContext astContext = name.getCompletionContext(); IASTCompletionContext astContext = name.getCompletionContext();
if (astContext != null) { if (astContext != null) {
@ -408,6 +421,9 @@ public class ParameterGuessingProposal extends FunctionCompletionProposal {
return offset; return offset;
} }
/**
* Copied from JDT
*/
private void ensurePositionCategoryInstalled(final IDocument document, LinkedModeModel model) { private void ensurePositionCategoryInstalled(final IDocument document, LinkedModeModel model) {
if (!document.containsPositionCategory(getCategory())) { if (!document.containsPositionCategory(getCategory())) {
document.addPositionCategory(getCategory()); document.addPositionCategory(getCategory());
@ -429,6 +445,9 @@ public class ParameterGuessingProposal extends FunctionCompletionProposal {
} }
} }
/**
* Copied from JDT
*/
private void ensurePositionCategoryRemoved(IDocument document) { private void ensurePositionCategoryRemoved(IDocument document) {
if (document.containsPositionCategory(getCategory())) { if (document.containsPositionCategory(getCategory())) {
try { try {
@ -440,11 +459,16 @@ public class ParameterGuessingProposal extends FunctionCompletionProposal {
} }
} }
/**
* Copied from JDT
*/
private String getCategory() { private String getCategory() {
return "ParameterGuessingProposal_" + toString(); //$NON-NLS-1$ return "ParameterGuessingProposal_" + toString(); //$NON-NLS-1$
} }
/** /**
* Copied from JDT with replacing JDT types with CDT types.
*
* Returns the currently active C/C++ editor, or <code>null</code> if it * Returns the currently active C/C++ editor, or <code>null</code> if it
* cannot be determined. * cannot be determined.
* *

View file

@ -6,10 +6,11 @@
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* Contributors: * Contributors:
* QNX - Initial API and implementation * QNX - Initial API and implementation
* Anton Leherbauer (Wind River Systems) * Anton Leherbauer (Wind River Systems)
* Mentor Graphics (Mohamed Azab) - added the API to CDT * Mentor Graphics (Mohamed Azab) - added the API to CDT
*******************************************************************************/ *******************************************************************************/
package org.eclipse.cdt.internal.ui.text.contentassist; package org.eclipse.cdt.internal.ui.text.contentassist;
import java.util.ArrayList; import java.util.ArrayList;
@ -35,7 +36,8 @@ import org.eclipse.cdt.ui.text.contentassist.ICompletionProposalComputer;
* @author Bryan Wilkinson * @author Bryan Wilkinson
*/ */
public abstract class ParsingBasedProposalComputer implements ICompletionProposalComputer { public abstract class ParsingBasedProposalComputer implements ICompletionProposalComputer {
private String fErrorMessage;
private String fErrorMessage = null;
@Override @Override
public List<ICompletionProposal> computeCompletionProposals( public List<ICompletionProposal> computeCompletionProposals(
@ -71,7 +73,8 @@ public abstract class ParsingBasedProposalComputer implements ICompletionProposa
public List<IContextInformation> computeContextInformation( public List<IContextInformation> computeContextInformation(
ContentAssistInvocationContext context, IProgressMonitor monitor) { ContentAssistInvocationContext context, IProgressMonitor monitor) {
Collection<ICompletionProposal> proposals= computeCompletionProposals(context, monitor); Collection<ICompletionProposal> proposals= computeCompletionProposals(context, monitor);
// Remove duplicates // remove duplicates
proposals= (new LinkedHashSet<ICompletionProposal>(proposals)); proposals= (new LinkedHashSet<ICompletionProposal>(proposals));
List<IContextInformation> result= new ArrayList<IContextInformation>(); List<IContextInformation> result= new ArrayList<IContextInformation>();
for (ICompletionProposal proposal : proposals) { for (ICompletionProposal proposal : proposals) {
@ -99,11 +102,11 @@ public abstract class ParsingBasedProposalComputer implements ICompletionProposa
} }
/** /**
* Computes base relevance depending on quality of name / prefix match. * Compute base relevance depending on quality of name / prefix match.
* *
* @param prefix the completion prefix * @param prefix the completion pefix
* @param match the matching identifier * @param match the matching identifier
* @return a relevance value indicating the quality of the name match * @return a relevance value inidicating the quality of the name match
*/ */
protected int computeBaseRelevance(String prefix, String match) { protected int computeBaseRelevance(String prefix, String match) {
boolean caseMatch= prefix.length() > 0 && match.startsWith(prefix); boolean caseMatch= prefix.length() > 0 && match.startsWith(prefix);