Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 3d14dc3c98a3cbc3925f956b293bd1c3d315a428 (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
/*******************************************************************************
 * Copyright (c) 2008, 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
 *     Sergey Prigogin (Google)
 *     Thomas Corbat (IFS)
 *******************************************************************************/ 
package org.eclipse.cdt.internal.core.dom.parser;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Semaphore;

import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.dom.IName;
import org.eclipse.cdt.core.dom.ast.ASTGenericVisitor;
import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTComment;
import org.eclipse.cdt.core.dom.ast.IASTDeclaration;
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.IASTNodeLocation;
import org.eclipse.cdt.core.dom.ast.IASTNodeSelector;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorIncludeStatement;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorMacroDefinition;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorMacroExpansion;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorStatement;
import org.eclipse.cdt.core.dom.ast.IASTProblem;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.IASTTypeId;
import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.IMacroBinding;
import org.eclipse.cdt.core.dom.ast.INodeFactory;
import org.eclipse.cdt.core.dom.ast.IType;
import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.index.IIndexFile;
import org.eclipse.cdt.core.index.IIndexFileSet;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.parser.ISignificantMacros;
import org.eclipse.cdt.core.parser.util.ArrayUtil;
import org.eclipse.cdt.internal.core.index.IndexBasedFileContentProvider;
import org.eclipse.cdt.internal.core.parser.scanner.ILocationResolver;
import org.eclipse.cdt.internal.core.parser.scanner.ISkippedIndexedFilesListener;
import org.eclipse.cdt.internal.core.parser.scanner.InternalFileContent;
import org.eclipse.cdt.internal.core.parser.scanner.InternalFileContentProvider;
import org.eclipse.cdt.internal.core.parser.scanner.Lexer.LexerOptions;
import org.eclipse.core.runtime.CoreException;

/**
 * Abstract base class for all translation units.
 *
 * This class and other ASTNode subclasses are not thread safe.
 * Even 'get' methods may cause changes to the underlying object.
 */
public abstract class ASTTranslationUnit extends ASTNode implements IASTTranslationUnit, ISkippedIndexedFilesListener {
	private static final IASTPreprocessorStatement[] EMPTY_PREPROCESSOR_STATEMENT_ARRAY = {};
	private static final IASTPreprocessorMacroDefinition[] EMPTY_PREPROCESSOR_MACRODEF_ARRAY = {};
	private static final IASTPreprocessorIncludeStatement[] EMPTY_PREPROCESSOR_INCLUSION_ARRAY = {};
	private static final IASTProblem[] EMPTY_PROBLEM_ARRAY = {};
	private static final String EMPTY_STRING = ""; //$NON-NLS-1$

    private IASTDeclaration[] fAllDeclarations;
    private IASTDeclaration[] fActiveDeclarations;
	private int fLastDeclaration= -1;

	protected ILocationResolver fLocationResolver;
	private IIndex fIndex;
	private boolean fIsHeader= true;
	private IIndexFileSet fIndexFileSet;
	private IIndexFileSet fASTFileSet;
	private INodeFactory fNodeFactory;
	private boolean fForContentAssist;
	private ITranslationUnit fOriginatingTranslationUnit;
	private ISignificantMacros fSignificantMacros= ISignificantMacros.NONE;
	private boolean fPragmaOnceSemantics;
	private SizeofCalculator fSizeofCalculator;
	/** The semaphore controlling exclusive access to the AST. */
	private final Semaphore fSemaphore= new Semaphore(1);
	private boolean fBasedOnIncompleteIndex;
	private boolean fNodesOmitted;

	@Override
	public final IASTTranslationUnit getTranslationUnit() {
    	return this;
    }
    
	@Override
	public final void addDeclaration(IASTDeclaration d) {
		if (d != null) {
			d.setParent(this);
			d.setPropertyInParent(OWNED_DECLARATION);
			fAllDeclarations = ArrayUtil.appendAt(IASTDeclaration.class,
					fAllDeclarations, ++fLastDeclaration, d);
			fActiveDeclarations= null;
		}
	}

	@Override
	public final IASTDeclaration[] getDeclarations() {
		IASTDeclaration[] active= fActiveDeclarations;
		if (active == null) {
			active = ASTQueries.extractActiveDeclarations(fAllDeclarations, fLastDeclaration+1);
			fActiveDeclarations= active;
		}
		return active;
	}

	@Override
	public final IASTDeclaration[] getDeclarations(boolean includeInactive) {
		if (includeInactive) {
			fAllDeclarations= ArrayUtil.trimAt(IASTDeclaration.class,
					fAllDeclarations, fLastDeclaration);
			return fAllDeclarations;
		}
		return getDeclarations();
	}

	public final void replace(IASTNode child, IASTNode other) {
		assert child.isActive() == other.isActive();
		for (int i = 0; i <= fLastDeclaration; ++i) {
			if (fAllDeclarations[i] == child) {
				other.setParent(child.getParent());
				other.setPropertyInParent(child.getPropertyInParent());
				fAllDeclarations[i] = (IASTDeclaration) other;
				fActiveDeclarations= null;
				return;
			}
		}
	}
    
	@Override
	public final IName[] getDeclarations(IBinding binding) {
    	IName[] names= getDeclarationsInAST(binding);
        if (names.length == 0 && fIndex != null) {
        	try {
        		names = fIndex.findDeclarations(binding);
        	} catch (CoreException e) {
        		CCorePlugin.log(e);
        		return names;
        	}
        }

		return names;
	}
	
	protected final IASTName[] getMacroDefinitionsInAST(IMacroBinding binding) {
		if (fLocationResolver == null)
			return IASTName.EMPTY_NAME_ARRAY;
		
		IASTName[] declarations = fLocationResolver.getDeclarations(binding);
		int j = 0;
		for (int i = 0; i < declarations.length; i++) {
			IASTName name = declarations[i];
			if (name.isPartOfTranslationUnitFile()) {
				declarations[j++] = name;
			}
		}
		if (j < declarations.length)
			return j > 0 ? Arrays.copyOf(declarations, j) : IASTName.EMPTY_NAME_ARRAY;
		return declarations;
	}

	protected final IASTName[] getMacroReferencesInAST(IMacroBinding binding) {
		if (fLocationResolver == null)
			return IASTName.EMPTY_NAME_ARRAY;
        return fLocationResolver.getReferences(binding);
    }

    @Override
	public final IName[] getDefinitions(IBinding binding) {
    	IName[] names= getDefinitionsInAST(binding);
        if (names.length == 0 && fIndex != null) {
        	try {
        		names= fIndex.findDefinitions(binding);
        	} catch (CoreException e) {
        		CCorePlugin.log(e);
        		return names;
        	}
        }
        return names;
    }
    
	@Override
	public final IASTPreprocessorMacroDefinition[] getMacroDefinitions() {
		if (fLocationResolver == null)
			return EMPTY_PREPROCESSOR_MACRODEF_ARRAY;
		return fLocationResolver.getMacroDefinitions();
	}
	
	@Override
	public IASTPreprocessorMacroExpansion[] getMacroExpansions() {
		if (fLocationResolver == null)
			return IASTPreprocessorMacroExpansion.EMPTY_ARRAY;
		return fLocationResolver.getMacroExpansions(getFileLocation());
	}
	
	@Override
	public final IASTPreprocessorMacroDefinition[] getBuiltinMacroDefinitions() {
		if (fLocationResolver == null)
			return EMPTY_PREPROCESSOR_MACRODEF_ARRAY;
		return fLocationResolver.getBuiltinMacroDefinitions();
	}

	@Override
	public final IASTPreprocessorIncludeStatement[] getIncludeDirectives() {
		if (fLocationResolver == null)
			return EMPTY_PREPROCESSOR_INCLUSION_ARRAY;
		return fLocationResolver.getIncludeDirectives();
	}

	@Override
	public final IASTPreprocessorStatement[] getAllPreprocessorStatements() {
		if (fLocationResolver == null)
			return EMPTY_PREPROCESSOR_STATEMENT_ARRAY;
		return fLocationResolver.getAllPreprocessorStatements();
	}

	public final void setLocationResolver(ILocationResolver resolver) {
		fLocationResolver= resolver;
        resolver.setRootNode(this);
	}

	@Override
	public final IASTProblem[] getPreprocessorProblems() {
		if (fLocationResolver == null)
			return EMPTY_PROBLEM_ARRAY;
		IASTProblem[] result = fLocationResolver.getScannerProblems();
		for (int i = 0; i < result.length; ++i) {
			IASTProblem p = result[i];
			p.setParent(this);
			p.setPropertyInParent(IASTTranslationUnit.SCANNER_PROBLEM);
		}
		return result;
	}

	@Override
	public final int getPreprocessorProblemsCount() {
		return fLocationResolver == null ? 0 : fLocationResolver.getScannerProblemsCount();
	}

	@Override
	public final String getFilePath() {
		if (fLocationResolver == null)
			return EMPTY_STRING;
		return new String(fLocationResolver.getTranslationUnitPath());
	}

	@Override
	public final boolean accept(ASTVisitor action) {
		if (action.shouldVisitTranslationUnit) {
			switch (action.visit(this)) {
	            case ASTVisitor.PROCESS_ABORT: return false;
	            case ASTVisitor.PROCESS_SKIP: return true;
	            default: break;
	        }
		}
		IASTDeclaration[] decls = getDeclarations(action.includeInactiveNodes);
		for (IASTDeclaration decl : decls) {
			if (!decl.accept(action)) return false;
		}
        
        if (action.shouldVisitTranslationUnit && action.leave(this) == ASTVisitor.PROCESS_ABORT)
        	return false;

        return true;
    }

	@Override
	public final IASTFileLocation flattenLocationsToFile(IASTNodeLocation[] nodeLocations) {
        if (fLocationResolver == null)
            return null;
        return fLocationResolver.flattenLocations(nodeLocations);
    }

    @Override
	public final IDependencyTree getDependencyTree() {
        if (fLocationResolver == null)
            return null;
        return fLocationResolver.getDependencyTree();
    }

	@Override
	public final String getContainingFilename(int offset) {
		if (fLocationResolver == null)
			return EMPTY_STRING;
		return fLocationResolver.getContainingFilePath(offset);
	}

    @Override
	public final IIndex getIndex() {
    	return fIndex;
    }
    
    @Override
	public final void setIndex(IIndex index) {
    	this.fIndex = index;
    	if (index != null) {
    		fIndexFileSet= index.createFileSet();
    		fASTFileSet= index.createFileSet();
    	}
    }

    @Override
	public final INodeFactory getASTNodeFactory() {
    	return fNodeFactory;
    }
    
    public final void setASTNodeFactory(INodeFactory nodeFactory) {
    	this.fNodeFactory = nodeFactory;
    }
    
	@Override
	public final IASTComment[] getComments() {
		if (fLocationResolver != null) {
			return fLocationResolver.getComments();
		}
		return new IASTComment[0];
	}

	@Override
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public final Object getAdapter(Class adapter) {
		if (adapter.isAssignableFrom(fLocationResolver.getClass())) {
			return fLocationResolver;
		}
		if (adapter.isAssignableFrom(IIndexFileSet.class)) {
			return fIndexFileSet;
		}
		if (adapter.isAssignableFrom(LexerOptions.class)) {
			return fLocationResolver.getLexerOptions();
		}
		return null;
	}

	@Override
	public final boolean isHeaderUnit() {
		return fIsHeader;
	}

	@Override
	public final void setIsHeaderUnit(boolean headerUnit) {
		fIsHeader= headerUnit;
	}
	
	public boolean isForContentAssist() {
		return fForContentAssist;
	}

	public final void setIsForContentAssist(boolean forContentAssist) {
		fForContentAssist= forContentAssist;
	}

	@Override
	public boolean isBasedOnIncompleteIndex() {
		return fBasedOnIncompleteIndex;
	}

	public void setBasedOnIncompleteIndex(boolean basedOnIncompleteIndex) {
		fBasedOnIncompleteIndex = basedOnIncompleteIndex;
	}

	@Override
	public void skippedFile(int offset, InternalFileContent fileContent) {
		if (fIndexFileSet != null) {
			List<IIndexFile> files= fileContent.getFilesIncluded();
			for (IIndexFile indexFile : files) {
				fASTFileSet.remove(indexFile);
				fIndexFileSet.add(indexFile);
			}
		}
	}	
	
	@Override
	public final IIndexFileSet getIndexFileSet() {
		return fIndexFileSet;
	}
	
	@Override
	public void parsingFile(InternalFileContentProvider provider, InternalFileContent fc) {
		if (fASTFileSet != null) {
			if (provider instanceof IndexBasedFileContentProvider) {
				try {
					for (IIndexFile file : ((IndexBasedFileContentProvider) provider).findIndexFiles(fc)) {
						if (!fIndexFileSet.contains(file)) {
							fASTFileSet.add(file);
						}
					}
				} catch (CoreException e) {
					// Ignore, tracking of replaced files fails.
				}
			}
		}
	}	
	
	@Override
	public final IIndexFileSet getASTFileSet() {
		return fASTFileSet;
	}

	@Override
	public final IASTNode selectNodeForLocation(String path, int realOffset, int realLength) {
		return getNodeSelector(path).findNode(realOffset, realLength);
	}
	
	@Override
	public final IASTNodeSelector getNodeSelector(String filePath) {
		return new ASTNodeSelector(this, fLocationResolver, filePath);
	}

	/**
	 * Must be called by the parser, before the ast is passed to the clients.
	 */
	public abstract void resolveAmbiguities();

	/**
	 * Can be called to create a type for a type-id.
	 */
	abstract protected IType createType(IASTTypeId typeid);

	protected <T extends ASTTranslationUnit> T copy(T copy, CopyStyle style) {
		copy.setIndex(fIndex);
		copy.fIsHeader = fIsHeader;
		copy.fNodeFactory = fNodeFactory;
		copy.setLocationResolver(fLocationResolver);
		copy.fForContentAssist = fForContentAssist;
		copy.fOriginatingTranslationUnit = fOriginatingTranslationUnit;
		copy.fNodesOmitted = fNodesOmitted;
		
		for (IASTDeclaration declaration : getDeclarations()) {
			copy.addDeclaration(declaration == null ? null : declaration.copy(style));
		}

		return super.copy(copy, style);
	}
	
	@Override
	public final void freeze() {
		accept(new ASTGenericVisitor(true) {
			@Override
			protected int genericVisit(IASTNode node) {
				((ASTNode) node).setIsFrozen();
				return PROCESS_CONTINUE;
			}
		});
	}

	@Override
	public ITranslationUnit getOriginatingTranslationUnit() {
		return fOriginatingTranslationUnit;
	}

	public void setOriginatingTranslationUnit(ITranslationUnit tu) {
		this.fOriginatingTranslationUnit = tu;
	}

	@Override
	public ISignificantMacros getSignificantMacros() {
		return fSignificantMacros;
	}

	@Override
	public void setSignificantMacros(ISignificantMacros sigMacros) {
		assertNotFrozen();
		if (sigMacros != null)
			fSignificantMacros= sigMacros;
	}
	
	@Override
	public boolean hasPragmaOnceSemantics() {
		return fPragmaOnceSemantics;
	}
	
	@Override
	public void setPragmaOnceSemantics(boolean value) {
		assertNotFrozen();
		fPragmaOnceSemantics= value;
	}

	/**
	 * Starts exclusive access 
	 * @throws InterruptedException
	 */
	public void beginExclusiveAccess() throws InterruptedException {
		fSemaphore.acquire();
	}

	public void endExclusiveAccess() {
		fSemaphore.release();
	}

	public SizeofCalculator getSizeofCalculator() {
		if (fSizeofCalculator == null) {
			fSizeofCalculator = new SizeofCalculator(this);
		}
		return fSizeofCalculator;
	}

	/**
	 * Returns the offset of the given node, or -1 if the node is not part of the translation
	 * unit file or doesn't have a file-location.
	 * @see IASTNode#getFileLocation()
	 */
	public static int getNodeOffset(IASTNode node) {
		if (!node.isPartOfTranslationUnitFile())
			return -1;
		IASTFileLocation nodeLocation = node.getFileLocation();
		return nodeLocation != null ? nodeLocation.getNodeOffset() : -1;
	}

	/**
	 * Returns the end offset of the given node, or -1 if the node is not part of the translation
	 * unit file or doesn't have a file-location.
	 * @see IASTNode#getFileLocation()
	 */
	public static int getNodeEndOffset(IASTNode node) {
		if (!node.isPartOfTranslationUnitFile())
			return -1;
		IASTFileLocation nodeLocation = node.getFileLocation();
		return nodeLocation != null ? nodeLocation.getNodeOffset() + nodeLocation.getNodeLength() : -1;
	}

    /**
     * Returns the 1-based starting line number of the given node, or 0 if the node is not part of
     * the translation unit file or doesn't have a file-location.
	 * @see IASTNode#getFileLocation()
	 */
	public static int getStartingLineNumber(IASTNode node) {
		if (!node.isPartOfTranslationUnitFile())
			return 0;
		IASTFileLocation nodeLocation = node.getFileLocation();
		return nodeLocation != null ? nodeLocation.getStartingLineNumber() : 0;
	}

    /**
     * Returns the 1-based ending line number of the given node, or 0 if the node is not part of
     * the translation unit file or doesn't have a file-location.
	 * @see IASTNode#getFileLocation()
	 */
	public static int getEndingLineNumber(IASTNode node) {
		if (!node.isPartOfTranslationUnitFile())
			return 0;
		IASTFileLocation nodeLocation = node.getFileLocation();
		return nodeLocation != null ? nodeLocation.getEndingLineNumber() : 0;
	}

	@Override
	public boolean hasNodesOmitted() {
		return fNodesOmitted;
	}

	@Override
	public void setHasNodesOmitted(boolean hasNodesOmitted) {
		assertNotFrozen();
		fNodesOmitted = hasNodesOmitted;
	}
}

Back to the top