Skip to main content
summaryrefslogtreecommitdiffstats
blob: 02590fa3572fd5ef3713d21373b08fb7b3358ec9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/*******************************************************************************
 * Copyright (c) 2005, 2015 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
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *     Anton Leherbauer (Wind River Systems)
 *     Bryan Wilkinson (QNX)
 *     Thomas Corbat (IFS)
 *     Sergey Prigogin (Google)
 *******************************************************************************/
package org.eclipse.cdt.internal.ui.text.contentassist;

import java.util.Map;

import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.ui.IEditorPart;

import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.dom.ast.IASTCompletionNode;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.index.IIndexManager;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.PreferenceConstants;
import org.eclipse.cdt.ui.text.contentassist.ContentAssistInvocationContext;
import org.eclipse.cdt.ui.text.contentassist.ICEditorContentAssistInvocationContext;

import org.eclipse.cdt.internal.ui.editor.CEditor;
import org.eclipse.cdt.internal.ui.text.CHeuristicScanner;
import org.eclipse.cdt.internal.ui.text.Symbols;


/**
 * Describes the context of a content assist invocation in a C/C++ editor.
 * <p>
 * Clients may instantiate. A client that created a context is responsible for its disposal.
 * </p>
 * 
 * @since 4.0
 */
public class CContentAssistInvocationContext extends ContentAssistInvocationContext
		implements ICEditorContentAssistInvocationContext {
	private final IEditorPart fEditor;
	private final boolean fIsCompletion;
	private final boolean fIsAutoActivated;
	private IIndex fIndex;

	private Lazy<Integer> fContextInfoPosition = new Lazy<Integer>() {
		@Override
		protected Integer calculateValue() {
			return guessContextInformationPosition();
		}
	};

	private final Lazy<ITranslationUnit> fTU;

	private final Lazy<Integer> fParseOffset = new Lazy<Integer>() {
		@Override
		protected Integer calculateValue() {
			if (fIsCompletion) {
				return guessCompletionPosition(getInvocationOffset());
			}
			int contextInfoPosition = fContextInfoPosition.value();
			if (contextInfoPosition > 0) {
				return guessCompletionPosition(contextInfoPosition);
			}
			return -1;
		}
	};

	private final Lazy<IASTCompletionNode> fCN = new Lazy<IASTCompletionNode>() {
		@Override
		protected IASTCompletionNode calculateValue() {
			int offset = getParseOffset();
			if (offset < 0)
				return null;

			ICProject proj= getProject();
			if (proj == null)
				return null;

			try {
				if (fIndex != null)
					throw new IllegalStateException("The method should not be called multiple times."); //$NON-NLS-1$

				IIndexManager manager= CCorePlugin.getIndexManager();
				fIndex = manager.getIndex(proj, IIndexManager.ADD_DEPENDENCIES | IIndexManager.ADD_EXTENSION_FRAGMENTS_CONTENT_ASSIST);

				try {
					fIndex.acquireReadLock();
				} catch (InterruptedException e) {
					fIndex = null;
				}

				boolean parseNonIndexed= CUIPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.PREF_USE_STRUCTURAL_PARSE_MODE);
				int flags = parseNonIndexed ? ITranslationUnit.AST_SKIP_INDEXED_HEADERS : ITranslationUnit.AST_SKIP_ALL_HEADERS;
				flags |= ITranslationUnit.AST_CONFIGURE_USING_SOURCE_CONTEXT;

				return fTU.value().getCompletionNode(fIndex, flags, offset);
			} catch (CoreException e) {
				CUIPlugin.log(e);
			}
			return null;
		}
	};

	private final Lazy<Boolean> afterOpeningAngleBracket = new Lazy<Boolean>() {
		@Override
		protected Boolean calculateValue() {
			final int parseOffset = getParseOffset();
			final int invocationOffset = getInvocationOffset();
			final CHeuristicScanner scanner = new CHeuristicScanner(getDocument());
			final int parenthesisOffset = scanner.findOpeningPeer(invocationOffset, parseOffset, '<', '>');
			return parenthesisOffset != CHeuristicScanner.NOT_FOUND;
		}
	};

	private final Lazy<Boolean> afterOpeningParenthesis = new Lazy<Boolean>() {
		@Override
		protected Boolean calculateValue() {
			final int invocationOffset = getInvocationOffset();
			final int parseOffset = getParseOffset();
			final int bound = Math.max(-1, parseOffset - 1);
			final IDocument document = getDocument();
			final CHeuristicScanner scanner = new CHeuristicScanner(document);
			int start = invocationOffset;
			try {
				// The documentation of CHeuristicScanner.findOpeningPeer() says
				// "Note that <code>start</code> must not point to the closing peer, but to the first
				//  character being searched."
				// If we are completing in between two empty parentheses with no space between them,
				// this condition won't be satisfied, so we start the search one character earlier.
				if (document.getChar(start) == ')')
					start -= 1;
			} catch (BadLocationException e) {
			}
			final int parenthesisOffset = scanner.findOpeningPeer(start, bound, '(', ')');
			return parenthesisOffset != CHeuristicScanner.NOT_FOUND;
		}
	};

	private final Lazy<Boolean> inUsingDeclaration = new Lazy<Boolean>() {
		/**
		 * Checks whether the invocation offset is inside a using-declaration.
		 *
		 * @return {@code true} if the invocation offset is inside a using-declaration
		 */
		@Override
		protected Boolean calculateValue() {
			IDocument doc = getDocument();
			int offset = Math.max(0, getInvocationOffset() - 1);

			// Look at the tokens preceding the invocation offset.
			CHeuristicScanner.TokenStream tokenStream = new CHeuristicScanner.TokenStream(doc, offset);
			int token = tokenStream.previousToken();

			// There may be a partially typed identifier which is being completed.
			if (token == Symbols.TokenIDENT)
				token = tokenStream.previousToken();

			// Before that, there may be any number of "namespace::" token pairs.
			while (token == Symbols.TokenDOUBLECOLON) {
				token = tokenStream.previousToken();
				if (token == Symbols.TokenUSING) {  // there could also be a leading "::" for global namespace
					return true;
				} else if (token != Symbols.TokenIDENT) {
					return false;
				} else {
					token = tokenStream.previousToken();
				}
			}

			// Before that, there must be a "using" token.
			return token == Symbols.TokenUSING;
		}
	};

	private final Lazy<Boolean> followedBySemicolon = new Lazy<Boolean>() {
		@Override
		protected Boolean calculateValue() {
			final IDocument doc = getDocument();
			final int offset = getInvocationOffset();
			final CHeuristicScanner.TokenStream tokenStream = new CHeuristicScanner.TokenStream(doc, offset);
			final int token = tokenStream.nextToken();
			return token == Symbols.TokenSEMICOLON;
		}
	};
	
	private final Lazy<Boolean> followedByOpeningParen = new Lazy<Boolean>() {		
		@Override
		protected Boolean calculateValue() {
			final IDocument doc = getDocument();
			final int offset = getInvocationOffset();
			final CHeuristicScanner.TokenStream tokenStream = new CHeuristicScanner.TokenStream(doc, offset);
			final int token = tokenStream.nextToken();
			return token == Symbols.TokenLPAREN;
		}
	};

	private final Lazy<String> functionParameterDelimiter = new Lazy<String>() {
		@Override
		protected String calculateValue() {
			String propertyKey = DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_DECLARATION_PARAMETERS;
			Map<String, String> options = getProject().getOptions(true);
			return options.get(propertyKey).equals(CCorePlugin.INSERT) ? ", " : ","; //$NON-NLS-1$ //$NON-NLS-2$
		}
	};

	private final Lazy<String> templateParameterDelimiter = new Lazy<String>() {
		@Override
		protected String calculateValue() {
			String propertyKey = DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_TEMPLATE_PARAMETERS;
			Map<String, String> options = getProject().getOptions(true);
			return options.get(propertyKey).equals(CCorePlugin.INSERT) ? ", " : ","; //$NON-NLS-1$ //$NON-NLS-2$
		}
	};

	/**
	 * Creates a new context.
	 * 
	 * @param viewer the viewer used by the editor
	 * @param offset the invocation offset
	 * @param editor the editor that content assist is invoked in
	 * @param isAutoActivated indicates whether content assist was auto-activated
	 */
	public CContentAssistInvocationContext(ITextViewer viewer, int offset, IEditorPart editor,
			boolean isCompletion, boolean isAutoActivated) {
		super(viewer, offset);
		Assert.isNotNull(editor);
		fEditor= editor;
		fIsCompletion= isCompletion;
		fIsAutoActivated= isAutoActivated;
		fTU = new Lazy<ITranslationUnit>() {
			@Override
			protected ITranslationUnit calculateValue() {
				return CUIPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(fEditor.getEditorInput());
			}
		};
	}
	
	/**
	 * Creates a new context.
	 * 
	 * @param unit the translation unit in <code>document</code>
	 */
	public CContentAssistInvocationContext(final ITranslationUnit unit, boolean isCompletion) {
		super();
		fTU= new Lazy<ITranslationUnit>() {
			@Override
			protected ITranslationUnit calculateValue() {
				return unit;
			}
		};
		fEditor= null;
		fIsCompletion= isCompletion;
		fIsAutoActivated= false;
	}
	
	/**
	 * Returns the translation unit that content assist is invoked in, <code>null</code> if there
	 * is none.
	 * 
	 * @return the translation unit that content assist is invoked in, possibly <code>null</code>
	 */
	@Override
	public ITranslationUnit getTranslationUnit() {
		assertNotDisposed();
		return fTU.value();
	}
	
	/**
	 * Returns the project of the translation unit that content assist is invoked in,
	 * <code>null</code> if none.
	 * 
	 * @return the current C project, possibly <code>null</code>
	 */
	@Override
	public ICProject getProject() {
		assertNotDisposed();
		ITranslationUnit unit= getTranslationUnit();
		return unit == null ? null : unit.getCProject();
	}
		
	@Override
	public IASTCompletionNode getCompletionNode() {
		assertNotDisposed();
		// For scalability.
		if (fEditor != null && fEditor instanceof CEditor) {
			CEditor editor = (CEditor) fEditor;
			
			// Check to make sure we should attempt local parsing completions... for remote projects
			// we should not do this.
			if (!editor.shouldProcessLocalParsingCompletions()) {
				return null;
			}
			if (editor.isEnableScalablilityMode()) {
				if (editor.isParserBasedContentAssistDisabled()) {
					return null;
				}
				if (isAutoActivated() && editor.isContentAssistAutoActivartionDisabled()) {
					return null;
				}
			}
		}
		return fCN.value();
	}
	
	@Override
	public int getParseOffset() {
		assertNotDisposed();
		return fParseOffset.value();
	}

	/**
	 * @return the offset where context information (parameter hints) starts.
	 */
	@Override
	public int getContextInformationOffset() {
		assertNotDisposed();
		return fContextInfoPosition.value();
	}
	
	/**
	 * Try to find a sensible completion position backwards in case the given offset
	 * is inside a function call argument list or in template arguments.
	 * 
	 * @param contextPosition  the starting position
	 * @return a sensible completion offset
	 */
	protected int guessCompletionPosition(int contextPosition) {
		assertNotDisposed();
		CHeuristicScanner scanner= new CHeuristicScanner(getDocument());
		int bound= Math.max(-1, contextPosition - 200);
		
		int pos= scanner.findNonWhitespaceBackward(contextPosition - 1, bound);
		if (pos == CHeuristicScanner.NOT_FOUND) return contextPosition;
		
		int token= scanner.previousToken(pos, bound);
		
		if (token == Symbols.TokenCOMMA) {
			int openingParenthesisPos = scanner.findOpeningPeer(pos, bound, '(', ')');
			int openingAngleBracketPos = scanner.findOpeningPeer(pos, bound, '<', '>');
			pos = Math.max(openingParenthesisPos, openingAngleBracketPos);
			if (pos == CHeuristicScanner.NOT_FOUND) return contextPosition;
			
			token = scanner.previousToken(pos, bound);
		}
		
		if (token == Symbols.TokenLPAREN || token == Symbols.TokenLESSTHAN) {
			pos= scanner.findNonWhitespaceBackward(pos - 1, bound);
			if (pos == CHeuristicScanner.NOT_FOUND) return contextPosition;
			
			token= scanner.previousToken(pos, bound);
			
			if (token == Symbols.TokenGREATERTHAN) {
				// skip template arguments
				pos= scanner.findOpeningPeer(pos - 1, '<', '>');
				if (pos == CHeuristicScanner.NOT_FOUND) return contextPosition;
				pos= scanner.findNonWhitespaceBackward(pos - 1, bound);
				if (pos == CHeuristicScanner.NOT_FOUND) return contextPosition;
				token= scanner.previousToken(pos, bound);
			}
			
			if (token == Symbols.TokenIDENT) {
				return pos + 1;
			}
		}
		
		return contextPosition;
	}
	
	/**
	 * Try to find the smallest offset inside the opening parenthesis of a function call
	 * argument list.
	 * 
	 * @return the offset of the function call parenthesis plus 1 or -1 if the invocation
	 *     offset is not inside a function call (or similar)
	 */
	protected int guessContextInformationPosition() {
		assertNotDisposed();
		final int contextPosition= getInvocationOffset();
		
		CHeuristicScanner scanner= new CHeuristicScanner(getDocument());
		int bound= Math.max(-1, contextPosition - 200);
		
		// try the innermost scope of parentheses that looks like a method call
		int pos= contextPosition - 1;
		do {
			int paren= scanner.findOpeningPeer(pos, bound, '(', ')');
			int angle= scanner.findOpeningPeer(pos, bound, '<', '>');
			int nearestPeer = Math.max(paren, angle);
			if (nearestPeer == CHeuristicScanner.NOT_FOUND)
				break;
			int token= scanner.previousToken(nearestPeer - 1, bound);
			// next token must be a method name (identifier) or the closing angle of a
			// constructor call of a template type.
			if (token == Symbols.TokenIDENT || token == Symbols.TokenGREATERTHAN) {
				return nearestPeer + 1;
			}
			pos= nearestPeer - 1;
		} while (true);
		
		return -1;
	}
	
	/**
	 * Get the editor content assist is invoked in.
	 * 
	 * @return the editor, may be <code>null</code>
	 */
	@Override
	public IEditorPart getEditor() {
		assertNotDisposed();
		return fEditor;
	}

	@Override
	public boolean isContextInformationStyle() {
		assertNotDisposed();
		return !fIsCompletion || (getParseOffset() != getInvocationOffset());
	}
	
	public boolean isAutoActivated() {
		assertNotDisposed();
		return fIsAutoActivated;
	}

	@Override
	public void dispose() {
		if (fIndex != null) {
			fIndex.releaseReadLock();
			fIndex = null;
		}
		super.dispose();
	}

	public boolean isAfterOpeningParenthesis() {
		assertNotDisposed();
		return afterOpeningParenthesis.value();
	}

	public boolean isAfterOpeningAngleBracket() {
		assertNotDisposed();
		return afterOpeningAngleBracket.value();
	}

	public boolean isInUsingDirective() {
		assertNotDisposed();
		return inUsingDeclaration.value();
	}

	public boolean isFollowedBySemicolon() {
		assertNotDisposed();
		return followedBySemicolon.value();
	}
	
	public boolean isFollowedByOpeningParen() {		
		assertNotDisposed();
		return followedByOpeningParen.value();
	}

	public String getFunctionParameterDelimiter() {
		assertNotDisposed();
		return functionParameterDelimiter.value();
	}

	public String getTemplateParameterDelimiter() {
		assertNotDisposed();
		return templateParameterDelimiter.value();
	}
}

Back to the top