Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 2f78c6eaa0c98cc9ae3bce86f900aaeef18c15c5 (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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
/*******************************************************************************
 * Copyright (c) 2007, 2013 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
 *     IBM Corporation
 *     Sergey Prigogin (Google)
 *******************************************************************************/
package org.eclipse.cdt.internal.core.pdom;

import java.util.ArrayList;
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.IASTPreprocessorStatement;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorUndefStatement;
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.ICPPASTCompositeTypeSpecifier.ICPPASTBaseSpecifier;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTQualifiedName;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateId;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTUsingDirective;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassTemplate;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPFunctionTemplate;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespace;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespaceAlias;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPTemplateParameter;
import org.eclipse.cdt.core.index.IIndexFile;
import org.eclipse.cdt.core.index.IIndexFileLocation;
import org.eclipse.cdt.core.index.IIndexInclude;
import org.eclipse.cdt.core.parser.FileContent;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.core.parser.ISignificantMacros;
import org.eclipse.cdt.core.parser.util.CharArrayUtils;
import org.eclipse.cdt.internal.core.dom.parser.ASTInternal;
import org.eclipse.cdt.internal.core.dom.parser.cpp.ICPPUnknownBinding;
import org.eclipse.cdt.internal.core.index.FileContentKey;
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.parser.scanner.LocationMap;
import org.eclipse.cdt.internal.core.pdom.dom.PDOMASTAdapter;
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 {
	private static final boolean REPORT_UNKNOWN_BUILTINS = false;

	public static class FileInAST {
		final IASTPreprocessorIncludeStatement includeStatement;
		final FileContentKey fileContentKey;
		final long timestamp;
		final long fileSize;
		final long contentsHash;
		final long sourceReadTime;
		final boolean hasError;

		public FileInAST(IASTPreprocessorIncludeStatement includeStmt, FileContentKey key) {
			includeStatement= includeStmt;
			fileContentKey= key;
			timestamp= includeStmt.getIncludedFileTimestamp();
			fileSize = includeStmt.getIncludedFileSize();
			contentsHash= includeStmt.getIncludedFileContentsHash();
			sourceReadTime= includeStmt.getIncludedFileReadTime();
			hasError= includeStmt.isErrorInIncludedFile();
		}

		public FileInAST(FileContentKey key, FileContent codeReader) {
			includeStatement= null;
			fileContentKey= key;
			timestamp= codeReader.getTimestamp();
			fileSize= codeReader.getFileSize();
			contentsHash= codeReader.getContentsHash();
			sourceReadTime= codeReader.getReadTime();
			hasError= codeReader.hasError();
		}

		@Override
		public String toString() {
			return fileContentKey.toString();
		}
	}

	public static class FileContext {
		final IIndexFragmentFile fContext;
		final IIndexFragmentFile fOldFile;
		IIndexFragmentFile fNewFile;
		public boolean fLostPragmaOnceSemantics;

		public FileContext(IIndexFragmentFile context, IIndexFragmentFile oldFile) {
			fContext= context;
			fOldFile= oldFile;
			fNewFile= null;
		}
	}

	public static int SKIP_ALL_REFERENCES= -1;
	public static int SKIP_TYPE_REFERENCES= 1;
	public static int SKIP_MACRO_REFERENCES= 2;
	public static int SKIP_IMPLICIT_REFERENCES= 4;
	public static int SKIP_NO_REFERENCES= 0;

	private static class Symbols {
		final ArrayList<IASTName[]> fNames= new ArrayList<IASTName[]>();
		final ArrayList<IASTPreprocessorStatement> fMacros= new ArrayList<IASTPreprocessorStatement>();
		final ArrayList<IASTPreprocessorIncludeStatement> fIncludes= new ArrayList<IASTPreprocessorIncludeStatement>();
	}

	private static class Data {
		final IASTTranslationUnit fAST;
		final FileInAST[] fSelectedFiles;
		final IWritableIndex fIndex;
		final Map<IASTPreprocessorIncludeStatement, Symbols> fSymbolMap = new HashMap<IASTPreprocessorIncludeStatement, Symbols>();
		final Set<IASTPreprocessorIncludeStatement> fContextIncludes = new HashSet<IASTPreprocessorIncludeStatement>();
		final List<IStatus> fStati= new ArrayList<IStatus>();

		public Data(IASTTranslationUnit ast, FileInAST[] selectedFiles, IWritableIndex index) {
			fAST= ast;
			fSelectedFiles= selectedFiles;
			fIndex= index;
		}
	}

	private boolean fShowProblems;
	protected boolean fShowInclusionProblems;
	private boolean fShowScannerProblems;
	private boolean fShowSyntaxProblems;
	protected boolean fShowActivity;
	protected final IndexerStatistics fStatistics;
	protected final IndexerInputAdapter fResolver;

	private int fSkipReferences= SKIP_NO_REFERENCES;

	public PDOMWriter(IndexerInputAdapter resolver) {
		fStatistics= new IndexerStatistics();
		fResolver= resolver;
	}

	protected IndexerInputAdapter getInputAdapter() {
		return fResolver;
	}

	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_NO_REFERENCES} or a combination of
	 * {@link #SKIP_IMPLICIT_REFERENCES}, {@link #SKIP_TYPE_REFERENCES} and {@link #SKIP_MACRO_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.
	 *
	 * When flushIndex is set to <code>false</code>, you must make sure to flush
	 * the index after your last write operation.
	 */
	final protected void addSymbols(IASTTranslationUnit ast, FileInAST[] selectedFiles,
			IWritableIndex index, boolean flushIndex, FileContext ctx,
			ITodoTaskUpdater taskUpdater, IProgressMonitor pm) throws InterruptedException,
			CoreException {
		if (fShowProblems) {
			fShowInclusionProblems= true;
			fShowScannerProblems= true;
			fShowSyntaxProblems= true;
		}

		Data data= new Data(ast, selectedFiles, index);
		for (FileInAST file : selectedFiles) {
			data.fSymbolMap.put(file.includeStatement, new Symbols());
		}

		// Extract symbols from AST.
		extractSymbols(data);

		// Name resolution.
		resolveNames(data, pm);

		// Index update.
		storeSymbolsInIndex(data, ctx, flushIndex, pm);

		// Tasks update.
		if (taskUpdater != null) {
			Set<IIndexFileLocation> locations= new HashSet<IIndexFileLocation>();
			for (FileInAST file : selectedFiles) {
				locations.add(file.fileContentKey.getLocation());
			}
			taskUpdater.updateTasks(ast.getComments(), locations.toArray(new IIndexFileLocation[locations.size()]));
		}
		if (!data.fStati.isEmpty()) {
			List<IStatus> stati = data.fStati;
			String path= null;
			if (selectedFiles.length > 0) {
				path= selectedFiles[selectedFiles.length - 1].fileContentKey.getLocation().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 Data data, FileContext ctx, boolean flushIndex, IProgressMonitor pm)
			throws InterruptedException, CoreException {
		final IIndexFragmentFile newFile= ctx == null ? null : ctx.fNewFile;
		final int linkageID= data.fAST.getLinkage().getLinkageID();
		for (int i= 0; i < data.fSelectedFiles.length; i++) {
			if (pm.isCanceled())
				return;

			final FileInAST fileInAST= data.fSelectedFiles[i];
			if (fileInAST != null) {
				if (fShowActivity) {
					trace("Indexer: adding " + fileInAST.fileContentKey.getLocation().getURI());  //$NON-NLS-1$
				}
				Throwable th= null;
				YieldableIndexLock lock = new YieldableIndexLock(data.fIndex, flushIndex);
				lock.acquire();
				try {
					final boolean isReplacement= ctx != null && fileInAST.includeStatement == null;
					IIndexFragmentFile ifile= null;
					if (!isReplacement || newFile == null) {
						ifile= storeFileInIndex(data, fileInAST, linkageID, lock);
						reportFileWrittenToIndex(fileInAST, ifile);
					}

					if (isReplacement) {
						if (ifile == null)
							ifile= newFile;
						if (ctx != null && !ctx.fOldFile.equals(ifile) && ifile != null) {
							if (ctx.fOldFile.hasPragmaOnceSemantics() &&
									!ifile.hasPragmaOnceSemantics()) {
								data.fIndex.transferContext(ctx.fOldFile, ifile);
								ctx.fLostPragmaOnceSemantics= true;
							} else {
								data.fIndex.transferIncluders(ctx.fOldFile, ifile);
							}
						}
					}
				} catch (RuntimeException e) {
					th= e;
				} catch (StackOverflowError e) {
					th= e;
				} catch (AssertionError e) {
					th= e;
				} finally {
					// Because the caller holds a read-lock, the result cache of the index is never
					// cleared. Before releasing the lock for the last time in this AST, we clear
					// the result cache.
					if (i == data.fSelectedFiles.length - 1) {
						data.fIndex.clearResultCache();
					}
					lock.release();
				}
				if (th != null) {
					data.fStati.add(createStatus(NLS.bind(Messages.PDOMWriter_errorWhileParsing,
							fileInAST.fileContentKey.getLocation().getURI().getPath()), th));
				}
				fStatistics.fAddToIndexTime += lock.getCumulativeLockTime();
			}
		}
	}

	private void resolveNames(Data data, IProgressMonitor pm) {
		long start= System.currentTimeMillis();
		for (FileInAST file : data.fSelectedFiles) {
			if (pm.isCanceled()) {
				return;
			}
			Symbols symbols= data.fSymbolMap.get(file.includeStatement);

			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.
					Throwable th= null;
					try {
						final IBinding binding = name.resolveBinding();
						if (name.getPropertyInParent() == ICPPASTTemplateId.TEMPLATE_NAME &&
								(((IASTName) name.getParent()).getBinding() == binding ||
								binding instanceof ICPPFunctionTemplate)) {
								na[0]= null;
						} else if (binding instanceof IProblemBinding) {
							IProblemBinding problemBinding = (IProblemBinding) binding;
							if (REPORT_UNKNOWN_BUILTINS ||
									problemBinding.getID() != IProblemBinding.BINDING_NOT_FOUND ||
									!CharArrayUtils.startsWith(problemBinding.getNameCharArray(), "__builtin_")) { //$NON-NLS-1$
								fStatistics.fProblemBindingCount++;
								if (fShowProblems) {
									reportProblem(problemBinding);
								}
							}
						} else if (name.isReference()) {
							if (binding instanceof ICPPTemplateParameter ||
									binding instanceof ICPPUnknownBinding ||
									((fSkipReferences & SKIP_TYPE_REFERENCES) != 0 &&
											isTypeReferenceBinding(binding))) {
								if (!isRequiredReference(name)) {
									na[0]= null;
								} else {
									fStatistics.fReferenceCount++;
								}
							} else {
								fStatistics.fReferenceCount++;
							}
						} else {
							fStatistics.fDeclarationCount++;
						}
					} catch (RuntimeException e) {
						th= e;
					} catch (StackOverflowError e) {
						th= e;
					}
					if (th != null) {
						if (!reported) {
							data.fStati.add(CCorePlugin.createStatus(NLS.bind(Messages.PDOMWriter_errorResolvingName,
									name.toString(), file.fileContentKey.getLocation().getURI().getPath()), th));
						}
						reported= true;
						j.remove();
					}
				}
			}
		}
		fStatistics.fResolutionTime += System.currentTimeMillis() - start;
	}

	private void extractSymbols(Data data) throws CoreException {
		int unresolvedIncludes= 0;
		final IASTTranslationUnit ast = data.fAST;
		final Map<IASTPreprocessorIncludeStatement, Symbols> symbolMap = data.fSymbolMap;

		IASTPreprocessorStatement[] stmts = ast.getAllPreprocessorStatements();
		for (final IASTPreprocessorStatement stmt : stmts) {
			// Includes.
			if (stmt instanceof IASTPreprocessorIncludeStatement) {
				IASTPreprocessorIncludeStatement include= (IASTPreprocessorIncludeStatement) stmt;

				final IASTFileLocation astLoc= include.getFileLocation();
				IASTPreprocessorIncludeStatement owner = astLoc.getContextInclusionStatement();
				final boolean updateSource= symbolMap.containsKey(owner);
				if (updateSource) {
					addToMap(symbolMap, owner, 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.
						if (symbolMap.containsKey(include)) {
							data.fContextIncludes.add(include);
						}
					}
				}
			} else if (stmt.isActive() &&
					(stmt instanceof IASTPreprocessorUndefStatement || stmt instanceof IASTPreprocessorMacroDefinition)) {
				IASTFileLocation sourceLoc = stmt.getFileLocation();
				if (sourceLoc != null) { // skip built-ins and command line macros
					IASTPreprocessorIncludeStatement owner = sourceLoc.getContextInclusionStatement();
					addToMap(symbolMap, owner, stmt);
				}
			}
		}

		// Names.
		final IndexerASTVisitor visitor = new IndexerASTVisitor((fSkipReferences & SKIP_IMPLICIT_REFERENCES) == 0) {
			@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) {
						IASTPreprocessorIncludeStatement owner= nameLoc.getContextInclusionStatement();
						addToMap(symbolMap, owner, new IASTName[] { name, caller });
					}
				}
			}
		};
		ast.accept(visitor);

		if ((fSkipReferences & SKIP_MACRO_REFERENCES) == 0) {
			LocationMap lm= (LocationMap) ast.getAdapter(LocationMap.class);
			if (lm != null) {
				IASTName[] refs= lm.getMacroReferences();
				for (IASTName name : refs) {
					IASTFileLocation nameLoc = name.getFileLocation();
					if (nameLoc != null) {
						IASTPreprocessorIncludeStatement owner= nameLoc.getContextInclusionStatement();
						addToMap(symbolMap, owner, new IASTName[] { name, null });
					}
				}
			}
		}

		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() == IProblem.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 ICPPASTQualifiedName) {
			if (name != ((ICPPASTQualifiedName) parentNode).getLastName())
				return false;
			parentNode= parentNode.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<IASTPreprocessorIncludeStatement, Symbols> symbolMap, IASTPreprocessorIncludeStatement owner, IASTName[] thing) {
		Symbols lists= symbolMap.get(owner);
		if (lists != null)
			lists.fNames.add(thing);
	}

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

	private void addToMap(Map<IASTPreprocessorIncludeStatement, Symbols> symbolMap,
			IASTPreprocessorIncludeStatement owner, IASTPreprocessorStatement thing) {
		Symbols lists= symbolMap.get(owner);
		if (lists != null)
			lists.fMacros.add(thing);
	}

	private IIndexFragmentFile storeFileInIndex(Data data, FileInAST astFile, int linkageID,
			YieldableIndexLock lock) throws CoreException, InterruptedException {
		final IWritableIndex index = data.fIndex;
		IIndexFragmentFile file;
		// We create a temporary PDOMFile with zero timestamp, add names to it, then replace
		// contents of the old file from the temporary one, then delete the temporary file.
		// The write lock on the index can be yielded between adding names to the temporary file,
		// if another thread is waiting for a read lock.
		final FileContentKey fileKey = astFile.fileContentKey;
		final IASTPreprocessorIncludeStatement owner= astFile.includeStatement;

		IIndexFileLocation location = fileKey.getLocation();
		ISignificantMacros significantMacros = fileKey.getSignificantMacros();
		IIndexFragmentFile oldFile = index.getWritableFile(linkageID, location, significantMacros);
		file= index.addUncommittedFile(linkageID, location, significantMacros);
		try {
			boolean pragmaOnce= owner != null ? owner.hasPragmaOnceSemantics() : data.fAST.hasPragmaOnceSemantics();
			file.setPragmaOnceSemantics(pragmaOnce);

			Symbols lists= data.fSymbolMap.get(owner);
			if (lists != null) {
				IASTPreprocessorStatement[] macros= lists.fMacros.toArray(new IASTPreprocessorStatement[lists.fMacros.size()]);
				IASTName[][] names= lists.fNames.toArray(new IASTName[lists.fNames.size()][]);
				for (IASTName[] name2 : names) {
					final IASTName name= name2[0];
					if (name != null) {
						ASTInternal.setFullyResolved(name.getBinding(), true);
					}
				}

				List<IncludeInformation> includeInfos= new ArrayList<IncludeInformation>();
				for (int i= 0; i < lists.fIncludes.size(); i++) {
					final IASTPreprocessorIncludeStatement stmt = lists.fIncludes.get(i);
					if (!stmt.isResolved()) {
						includeInfos.add(new IncludeInformation(stmt, null, ISignificantMacros.NONE, false));
					} else {
						IIndexFileLocation targetLoc = fResolver.resolveASTPath(stmt.getPath());
						ISignificantMacros mainSig= stmt.getSignificantMacros();
						for (ISignificantMacros sig : stmt.getLoadedVersions()) {
							if (!sig.equals(mainSig)) {
								includeInfos.add(new IncludeInformation(stmt, targetLoc, sig, false));
							}
						}
						final boolean isContext = stmt.isActive() && stmt.isResolved() &&
								(data.fContextIncludes.contains(stmt) || isContextFor(oldFile, stmt));
						includeInfos.add(new IncludeInformation(stmt, targetLoc, mainSig, isContext));
					}
				}
				IncludeInformation[] includeInfoArray= includeInfos.toArray(new IncludeInformation[includeInfos.size()]);
				index.setFileContent(file, linkageID, includeInfoArray, macros, names, fResolver, lock);
			}
			file.setTimestamp(astFile.hasError ? 0 : astFile.timestamp);
			file.setSourceReadTime(astFile.sourceReadTime);
			file.setSizeAndEncodingHashcode(computeFileSizeAndEncodingHashcode(astFile.fileSize, location));
			file.setContentsHash(astFile.contentsHash);
			file = index.commitUncommittedFile();
		} finally {
			index.clearUncommittedFile();
		}
		return file;
	}

	protected int computeFileSizeAndEncodingHashcode(IIndexFileLocation location) {
		return computeFileSizeAndEncodingHashcode((int) fResolver.getFileSize(location), location);
	}

	private int computeFileSizeAndEncodingHashcode(long size, IIndexFileLocation location) {
		return (int) size + 31 * fResolver.getEncoding(location).hashCode();
	}

	private boolean isContextFor(IIndexFragmentFile oldFile, IASTPreprocessorIncludeStatement stmt)
			throws CoreException {
		IIndexFile target= stmt.getImportedIndexFile();
		if (oldFile != null && target != null) {
			IIndexInclude ctxInclude = target.getParsedInContext();
			if (ctxInclude != null && oldFile.equals(ctxInclude.getIncludedBy()))
				return true;
		}
		return false;
	}

	/**
	 * Informs the subclass that a file has been stored in the index.
	 */
	protected abstract void reportFileWrittenToIndex(FileInAST file, IIndexFragmentFile iFile) throws CoreException;

	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$
		trace(msg);
	}

	private void reportProblem(IASTProblem problem) {
		String msg= "Indexer: " + problem.getMessageWithLocation(); //$NON-NLS-1$
		trace(msg);
	}

	protected void trace(String message) {
		System.out.println(message);
	}

	protected IStatus createStatus(String msg) {
		return CCorePlugin.createStatus(msg);
	}

	protected IStatus createStatus(String msg, Throwable e) {
		return CCorePlugin.createStatus(msg, e);
	}
}

Back to the top