Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: f9991fca26cfb92116c808631c0c6831882cfbf3 (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
482
483
484
485
486
487
488
489
490
491
/*******************************************************************************
 * Copyright (c) 2007, 2008 Wind River Systems, Inc. and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Markus Schorn - initial API and implementation
 *******************************************************************************/ 

package org.eclipse.cdt.internal.core.pdom;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier;
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.IASTPreprocessorIncludeStatement;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorMacroDefinition;
import org.eclipse.cdt.core.dom.ast.IASTProblem;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.ICompositeType;
import org.eclipse.cdt.core.dom.ast.IEnumeration;
import org.eclipse.cdt.core.dom.ast.IProblemBinding;
import org.eclipse.cdt.core.dom.ast.ITypedef;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTUsingDirective;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassTemplate;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespace;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespaceAlias;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTCompositeTypeSpecifier.ICPPASTBaseSpecifier;
import org.eclipse.cdt.core.index.IIndexFile;
import org.eclipse.cdt.core.index.IIndexFileLocation;
import org.eclipse.cdt.internal.core.dom.parser.ASTInternal;
import org.eclipse.cdt.internal.core.index.IIndexFragmentFile;
import org.eclipse.cdt.internal.core.index.IWritableIndex;
import org.eclipse.cdt.internal.core.index.IWritableIndex.IncludeInformation;
import org.eclipse.cdt.internal.core.pdom.dom.PDOMASTAdapter;
import org.eclipse.cdt.internal.core.pdom.dom.PDOMNotImplementedError;
import org.eclipse.cdt.internal.core.pdom.indexer.IndexerASTVisitor;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.osgi.util.NLS;

/**
 * Abstract class to write information from AST 
 * @since 4.0
 */
abstract public class PDOMWriter {
	public static int SKIP_ALL_REFERENCES= -1;
	public static int SKIP_TYPE_REFERENCES= 1;
	public static int SKIP_NO_REFERENCES= 0;
	
	private static class Symbols {
		ArrayList<IASTName[]> fNames= new ArrayList<IASTName[]>();
		ArrayList<IASTPreprocessorMacroDefinition> fMacros= new ArrayList<IASTPreprocessorMacroDefinition>();
		ArrayList<IASTPreprocessorIncludeStatement> fIncludes= new ArrayList<IASTPreprocessorIncludeStatement>();
	}
	private boolean fShowProblems;
	private boolean fShowInclusionProblems;
	private boolean fShowScannerProblems;
	private boolean fShowSyntaxProblems;
	protected boolean fShowActivity;
	protected final IndexerStatistics fStatistics;
	protected final IndexerInputAdapter fResolver;
	
	private IndexerProgress fInfo= new IndexerProgress();
	private int fSkipReferences= SKIP_NO_REFERENCES;
	
	public PDOMWriter(IndexerInputAdapter resolver) {
		fStatistics= new IndexerStatistics();
		fResolver= resolver;
	}
	
	public void setShowActivity(boolean val) {
		fShowActivity= val;
	}
	
	public void setShowInclusionProblems(boolean val) {
		fShowInclusionProblems= val;
	}

	public void setShowScannerProblems(boolean val) {
		fShowScannerProblems= val;
	}

	public void setShowSyntaxProblems(boolean val) {
		fShowSyntaxProblems= val;
	}

	public void setShowProblems(boolean val) {
		fShowProblems= val;
	}
	
	/**
	 * Determines whether references are skipped or not. Provide one of 
	 * {@link #SKIP_ALL_REFERENCES}, {@link #SKIP_TYPE_REFERENCES} or {@link #SKIP_NO_REFERENCES}.
	 */
	public void setSkipReferences(int options) {
		fSkipReferences= options;
	}
	
	public int getSkipReferences() {
		return fSkipReferences;
	}
			
	/**
	 * Extracts symbols from the given ast and adds them to the index. It will
	 * make calls to 	  
	 * {@link #needToUpdate(IIndexFileLocation)},
	 * {@link #postAddToIndex(IIndexFileLocation, IIndexFile)},
	 * {@link #getLastModified(IIndexFileLocation)} and
	 * {@link #findLocation(String)} to obtain further information.
	 * 
	 * When flushIndex is set to <code>false</code>, you must make sure to flush the 
	 * index after your last write operation.
	 * @since 4.0
	 */
	public void addSymbols(IASTTranslationUnit ast, IIndexFileLocation[] ifls, IWritableIndex index, 
			int readlockCount, boolean flushIndex, int configHash, ITodoTaskUpdater taskUpdater, IProgressMonitor pm) 
			throws InterruptedException, CoreException {
		if (fShowProblems) {
			fShowInclusionProblems= true;
			fShowScannerProblems= true;
			fShowSyntaxProblems= true;
		}
		final Map<IIndexFileLocation, Symbols> symbolMap= new HashMap<IIndexFileLocation, Symbols>();
		for (int i = 0; i < ifls.length; i++) {
			prepareInMap(symbolMap, ifls[i]);
		}
		ArrayList<IStatus> stati= new ArrayList<IStatus>();

		HashSet<IASTPreprocessorIncludeStatement> contextIncludes= new HashSet<IASTPreprocessorIncludeStatement>();
		extractSymbols(ast, symbolMap, contextIncludes);
			
		// name resolution
		resolveNames(symbolMap, ifls, stati, pm);

		// index update
		storeSymbolsInIndex(symbolMap, ifls, ast.getLinkage().getLinkageID(), configHash, contextIncludes, index, readlockCount, flushIndex,	stati, pm);

		if (taskUpdater != null) {
			taskUpdater.updateTasks(ast.getComments(), ifls);
		}
		if (!stati.isEmpty()) {
			String path= null;
			if (ifls != null && ifls.length > 0) {
				path= ifls[ifls.length-1].getURI().getPath();
			}
			else {
				path= ast.getFilePath().toString();
			}
			String msg= NLS.bind(Messages.PDOMWriter_errorWhileParsing, path);
			if (stati.size() == 1) {
				IStatus status= stati.get(0);
				if (msg.equals(status.getMessage())) {
					throw new CoreException(status);
				}
				throw new CoreException(new Status(status.getSeverity(), status.getPlugin(), status.getCode(), 
						msg + ':' + status.getMessage(), status.getException()));
			}
			throw new CoreException(new MultiStatus(CCorePlugin.PLUGIN_ID, 0, 
					stati.toArray(new IStatus[stati.size()]), msg, null));
		}
	}

	private void storeSymbolsInIndex(final Map<IIndexFileLocation, Symbols> symbolMap, IIndexFileLocation[] ifls, int linkageID, int configHash,
			HashSet<IASTPreprocessorIncludeStatement> contextIncludes, IWritableIndex index, int readlockCount, boolean flushIndex,
			ArrayList<IStatus> stati, IProgressMonitor pm) throws InterruptedException, CoreException {
		index.acquireWriteLock(readlockCount);
		long start= System.currentTimeMillis();
		try {
			for (int i=0; i<ifls.length; i++) {
				if (pm.isCanceled()) 
					return;

				final IIndexFileLocation ifl= ifls[i];
				if (ifl != null) {
					if (fShowActivity) {
						System.out.println("Indexer: adding " + ifl.getURI());  //$NON-NLS-1$
					}
					try {
						storeFileInIndex(index, ifl, symbolMap, linkageID, configHash, contextIncludes);
					} catch (RuntimeException e) {
						stati.add(CCorePlugin.createStatus(
								NLS.bind(Messages.PDOMWriter_errorWhileParsing, ifl.getURI().getPath()), e));
						break;
					} catch (PDOMNotImplementedError e) {
						stati.add(CCorePlugin.createStatus(
								NLS.bind(Messages.PDOMWriter_errorWhileParsing, ifl.getURI().getPath()), e));
						break;
					}
					if (i<ifls.length-1) {
						updateInfo(0, 1, 0); // update header count
					}
				}
			}
		} finally {
			index.releaseWriteLock(readlockCount, flushIndex);
		}
		fStatistics.fAddToIndexTime+= System.currentTimeMillis()-start;
	}

	private void resolveNames(final Map<IIndexFileLocation, Symbols> symbolMap, IIndexFileLocation[] ifls, ArrayList<IStatus> stati, IProgressMonitor pm) {
		long start= System.currentTimeMillis();
		for (int i=0; i<ifls.length; i++) {
			if (pm.isCanceled()) {
				return;
			}
			IIndexFileLocation path= ifls[i];
			Symbols symbols= symbolMap.get(path);

			final ArrayList<IASTName[]> names= symbols.fNames;
			boolean reported= false;
			for (Iterator<IASTName[]> j = names.iterator(); j.hasNext();) {
				final IASTName[] na= j.next();
				final IASTName name = na[0];
				if (name != null) { // should not be null, just be defensive.
					try {
						final IBinding binding = name.resolveBinding();
						if (binding instanceof IProblemBinding) {
							fStatistics.fProblemBindingCount++;
							if (fShowProblems) {
								reportProblem((IProblemBinding) binding);
							}
						}
						else if (name.isReference()) {
							if (fSkipReferences == SKIP_TYPE_REFERENCES) {
								if (isTypeReferenceBinding(binding) && !isRequiredReference(name)) {
									na[0]= null;
									fStatistics.fReferenceCount--;
								}
							}
							fStatistics.fReferenceCount++;
						}
						else {
							fStatistics.fDeclarationCount++;
						}
					} catch (RuntimeException e) {
						if (!reported) {
							stati.add(CCorePlugin.createStatus(
									NLS.bind(Messages.PDOMWriter_errorResolvingName, name.toString(), path.getURI().getPath()), e));
						}
						reported= true;
						j.remove();
					} catch (PDOMNotImplementedError e) {
						if (!reported) {
							stati.add(CCorePlugin.createStatus(
									NLS.bind(Messages.PDOMWriter_errorResolvingName, name.toString(), path.getURI().getPath()), e));
						}
						reported= true;
						j.remove();
					}
				}
			}
		}
		fStatistics.fResolutionTime += System.currentTimeMillis()-start;
	}

	private void extractSymbols(IASTTranslationUnit ast, final Map<IIndexFileLocation, Symbols> symbolMap, Collection<IASTPreprocessorIncludeStatement> contextIncludes) throws CoreException {
		
		final HashSet<IIndexFileLocation> contextIFLs= new HashSet<IIndexFileLocation>();
		final IIndexFileLocation astIFL = fResolver.resolveASTPath(ast.getFilePath());
		
		// includes
		int unresolvedIncludes= 0;
		IASTPreprocessorIncludeStatement[] includes = ast.getIncludeDirectives();
		for (int i= 0; i < includes.length; i++) {
			final IASTPreprocessorIncludeStatement include = includes[i];
			final IASTFileLocation astLoc= include.getFileLocation();
			final IIndexFileLocation sourceIFL= astLoc != null ? fResolver.resolveASTPath(astLoc.getFileName()) : astIFL; // command-line includes
			final boolean updateSource= symbolMap.containsKey(sourceIFL);
			if (updateSource) {
				addToMap(symbolMap, sourceIFL, include);
			}
			if (include.isActive()) {
				if (!include.isResolved()) {
					unresolvedIncludes++;
				}
				else if (updateSource) {
					// the include was parsed, check if we want to update the included file in the index
					final IIndexFileLocation targetIFL= fResolver.resolveASTPath(include.getPath());
					if (symbolMap.containsKey(targetIFL) && contextIFLs.add(targetIFL)) {
						contextIncludes.add(include);
					}
				}
			}
		}
		
		// macros
		IASTPreprocessorMacroDefinition[] macros = ast.getMacroDefinitions();
		for (int i2 = 0; i2 < macros.length; ++i2) {
			IASTPreprocessorMacroDefinition macro = macros[i2];
			IASTFileLocation sourceLoc = macro.getFileLocation();
			if (sourceLoc != null) { // skip built-ins and command line macros
				IIndexFileLocation path2 = fResolver.resolveASTPath(sourceLoc.getFileName());
				addToMap(symbolMap, path2, macro);
			}
		}
		
		// names
		final IndexerASTVisitor visitor = new IndexerASTVisitor() {
			@Override
			public void visit(IASTName name, IASTName caller) {
				if (fSkipReferences == SKIP_ALL_REFERENCES) {
					if (name.isReference()) {
						if (!isRequiredReference(name)) {
							return;
						}
					}
				}
					
				// assign a location to anonymous types.
				name= PDOMASTAdapter.getAdapterIfAnonymous(name);
				if (name != null) {
					IASTFileLocation nameLoc = name.getFileLocation();
					if (nameLoc != null) {
						IIndexFileLocation location = fResolver.resolveASTPath(nameLoc.getFileName());
						addToMap(symbolMap, location, new IASTName[]{name, caller});
					}
				}
			}
		};
		ast.accept(visitor);
		
		fStatistics.fUnresolvedIncludesCount += unresolvedIncludes;
		fStatistics.fPreprocessorProblemCount+= ast.getPreprocessorProblemsCount() - unresolvedIncludes;
		if (fShowScannerProblems || fShowInclusionProblems) {
			final boolean reportAll= fShowScannerProblems && fShowInclusionProblems;
			IASTProblem[] scannerProblems= ast.getPreprocessorProblems();
			for (IASTProblem problem : scannerProblems) {
				if (reportAll || (problem.getID() == IASTProblem.PREPROCESSOR_INCLUSION_NOT_FOUND) == fShowInclusionProblems) {
					reportProblem(problem);
				}
			}
		}

		final List<IASTProblem> problems= visitor.getProblems();
		fStatistics.fSyntaxProblemsCount+= problems.size();
		if (fShowSyntaxProblems) {
			for (IASTProblem problem : problems) {
				reportProblem(problem); 
			}
		}
	}
	
	protected final boolean isRequiredReference(IASTName name) {
		IASTNode parentNode= name.getParent();
		if (parentNode instanceof ICPPASTBaseSpecifier) {
			return true;
		}
		else if (parentNode instanceof IASTDeclSpecifier) {
			IASTDeclSpecifier ds= (IASTDeclSpecifier) parentNode;
			return ds.getStorageClass() == IASTDeclSpecifier.sc_typedef;
		}
		else if (parentNode instanceof ICPPASTUsingDirective) {
			return true;
		}
		return false;
	}

	private boolean isTypeReferenceBinding(IBinding binding) {
		if (binding instanceof ICompositeType ||
				binding instanceof IEnumeration ||
				binding instanceof ITypedef ||
				binding instanceof ICPPNamespace ||
				binding instanceof ICPPNamespaceAlias ||
				binding instanceof ICPPClassTemplate) {
			return true;
		}
		return false;
	}

	private void addToMap(Map<IIndexFileLocation, Symbols> map, IIndexFileLocation location, IASTName[] thing) {
		Symbols lists= map.get(location);
		if (lists != null) 
			lists.fNames.add(thing);
	}		

	private void addToMap(Map<IIndexFileLocation, Symbols> map, IIndexFileLocation location, IASTPreprocessorIncludeStatement thing) {
		Symbols lists= map.get(location);
		if (lists != null) 
			lists.fIncludes.add(thing);
	}		

	private void addToMap(Map<IIndexFileLocation, Symbols> map, IIndexFileLocation location, IASTPreprocessorMacroDefinition thing) {
		Symbols lists= map.get(location);
		if (lists != null) 
			lists.fMacros.add(thing);
	}		
	
	private boolean prepareInMap(Map<IIndexFileLocation, Symbols> map, IIndexFileLocation location) {
		if (map.get(location) == null) {
			map.put(location, new Symbols());
		}
		return false;
	}

	private IIndexFragmentFile storeFileInIndex(IWritableIndex index, IIndexFileLocation location, Map<IIndexFileLocation, Symbols> symbolMap, 
			int linkageID, int configHash, Set<IASTPreprocessorIncludeStatement> contextIncludes) throws CoreException {
		Set<IIndexFileLocation> clearedContexts= Collections.emptySet();
		IIndexFragmentFile file= index.getWritableFile(linkageID, location);
		if (file != null) {
			clearedContexts= new HashSet<IIndexFileLocation>();
			index.clearFile(file, clearedContexts);
		} else {
			file= index.addFile(linkageID, location);
		}
		file.setTimestamp(fResolver.getLastModified(location));
		file.setScannerConfigurationHashcode(configHash);
		Symbols lists= symbolMap.get(location);
		if (lists != null) {
			IASTPreprocessorMacroDefinition[] macros= lists.fMacros.toArray(new IASTPreprocessorMacroDefinition[lists.fMacros.size()]);
			IASTName[][] names= lists.fNames.toArray(new IASTName[lists.fNames.size()][]);
			for (int j= 0; j<names.length; j++) {
				final IASTName name= names[j][0];
				if (name != null) {
					ASTInternal.setFullyResolved(name.getBinding(), true);
				}
			}

			IncludeInformation[] includeInfos= new IncludeInformation[lists.fIncludes.size()];
			for (int i=0; i<lists.fIncludes.size(); i++) {
				final IASTPreprocessorIncludeStatement include = lists.fIncludes.get(i);
				final IncludeInformation info= includeInfos[i]= new IncludeInformation();
				info.fStatement= include;
				if (include.isResolved()) {
					info.fLocation= fResolver.resolveASTPath(include.getPath());
					info.fIsContext= include.isActive() && 
						(contextIncludes.contains(include) || clearedContexts.contains(info.fLocation));
				}
			}
			index.setFileContent(file, linkageID, includeInfos, macros, names, fResolver);
		}
		return file;
	}
	
	/**
	 * Makes a copy of the current progress information and returns it.
	 * @since 4.0
	 */
	public IndexerProgress getProgressInformation() {
		synchronized (fInfo) {
			return new IndexerProgress(fInfo);
		}
	}

	/**
	 * Updates current progress information with the provided delta.
	 * @since 4.0
	 */
	protected final void updateInfo(int completedSources, int completedHeaders, int totalEstimate) {
		synchronized(fInfo) {
			fInfo.fCompletedHeaders+= completedHeaders;
			fInfo.fCompletedSources+= completedSources;
			fInfo.fTotalSourcesEstimate+= totalEstimate;
		}
	}
		
	private String getLocationInfo(String filename, int lineNumber) {
		return " at " + filename + "(" + lineNumber + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
	}

	private void reportProblem(IProblemBinding problem) {
		String msg= "Indexer: unresolved name" + getLocationInfo(problem.getFileName(), problem.getLineNumber()); //$NON-NLS-1$
		String pmsg= problem.getMessage();
		if (pmsg != null && pmsg.length() > 0) 
			msg+= "; " + problem.getMessage(); //$NON-NLS-1$
		System.out.println(msg);
	}
	
	private void reportProblem(IASTProblem problem) {
		String msg= "Indexer: " + problem.getMessage(); //$NON-NLS-1$
		System.out.println(msg);
	}

}

Back to the top