summaryrefslogtreecommitdiffstats
blob: d4c703db020d7e9adb0735ac9c73f355690cbaa0 (plain)
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
/*******************************************************************************
 * Copyright (c) 2006, 2011 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
 *     Andrew Ferguson (Symbian)
 *     Sergey Prigogin (Google)
 *******************************************************************************/
package org.eclipse.cdt.internal.core.pdom;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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.IASTPreprocessorStatement;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.index.IIndexFile;
import org.eclipse.cdt.core.index.IIndexFileLocation;
import org.eclipse.cdt.core.index.IIndexLocationConverter;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.parser.ISignificantMacros;
import org.eclipse.cdt.internal.core.index.FileContentKey;
import org.eclipse.cdt.internal.core.index.IIndexFragment;
import org.eclipse.cdt.internal.core.index.IIndexFragmentFile;
import org.eclipse.cdt.internal.core.index.IWritableIndex.IncludeInformation;
import org.eclipse.cdt.internal.core.index.IWritableIndexFragment;
import org.eclipse.cdt.internal.core.model.TranslationUnit;
import org.eclipse.cdt.internal.core.pdom.db.ChunkCache;
import org.eclipse.cdt.internal.core.pdom.db.DBProperties;
import org.eclipse.cdt.internal.core.pdom.db.IBTreeVisitor;
import org.eclipse.cdt.internal.core.pdom.dom.IPDOMLinkageFactory;
import org.eclipse.cdt.internal.core.pdom.dom.PDOMBinding;
import org.eclipse.cdt.internal.core.pdom.dom.PDOMFile;
import org.eclipse.cdt.internal.core.pdom.dom.PDOMLinkage;
import org.eclipse.cdt.internal.core.pdom.dom.PDOMMacro;
import org.eclipse.cdt.internal.core.pdom.dom.PDOMMacroReferenceName;
import org.eclipse.cdt.internal.core.pdom.dom.PDOMName;
import org.eclipse.core.runtime.CoreException;

public class WritablePDOM extends PDOM implements IWritableIndexFragment {
	private boolean fClearedBecauseOfVersionMismatch= false;
	private boolean fCreatedFromScratch= false;
	private ASTFilePathResolver fPathResolver;
	private PDOMFile fileBeingUpdated;
	private PDOMFile uncommittedFile;
	private FileContentKey uncommittedKey;

	public WritablePDOM(File dbPath, IIndexLocationConverter locationConverter,
			Map<String, IPDOMLinkageFactory> linkageFactoryMappings) throws CoreException {
		this(dbPath, locationConverter, ChunkCache.getSharedInstance(), linkageFactoryMappings);
	}

	public WritablePDOM(File dbPath, IIndexLocationConverter locationConverter, ChunkCache cache,
			Map<String, IPDOMLinkageFactory> linkageFactoryMappings) throws CoreException {
		super(dbPath, locationConverter, cache, linkageFactoryMappings);
	}

	public void setASTFilePathResolver(ASTFilePathResolver resolver) {
		fPathResolver= resolver;
	}

	@Override
	public IIndexFragmentFile addFile(int linkageID, IIndexFileLocation location, ISignificantMacros sigMacros) throws CoreException {
		if (uncommittedKey != null && uncommittedKey.equals(new FileContentKey(linkageID, location, sigMacros)))
			return uncommittedFile;

		return super.addFile(linkageID, location, sigMacros);
	}

	@Override
	public IIndexFragmentFile addUncommittedFile(int linkageID, IIndexFileLocation location,
			ISignificantMacros significantMacros) throws CoreException {
		uncommittedKey = new FileContentKey(linkageID, location, significantMacros);
		fileBeingUpdated = getFile(linkageID, location, significantMacros);
		PDOMLinkage linkage= createLinkage(linkageID);
		uncommittedFile = new PDOMFile(linkage, location, linkageID, significantMacros);
		return uncommittedFile;
	}

	@Override
	public IIndexFragmentFile commitUncommittedFile() throws CoreException {
		if (uncommittedFile == null)
			return null;

		int defectiveStateChange = uncommittedFile.getTimestamp() == 0 ? 1 : 0;
		int unresolvedIncludeStateChange = uncommittedFile.hasUnresolvedInclude() ? 1 : 0;

		PDOMFile file;
		if (fileBeingUpdated == null) {
			// New file, insert it into the index.
			file = uncommittedFile;
			getFileIndex().insert(file.getRecord());
		} else {
			// Existing file.
			if (fileBeingUpdated.getTimestamp() == 0)
				defectiveStateChange -= 1;
			if (fileBeingUpdated.hasUnresolvedInclude())
				unresolvedIncludeStateChange -= 1;
			fileBeingUpdated.replaceContentsFrom(uncommittedFile);
			file = fileBeingUpdated;
			fileBeingUpdated = null;
		}
		if (defectiveStateChange > 0) {
			getIndexOfDefectiveFiles().insert(file.getRecord());
		} else if (defectiveStateChange < 0) {
			getIndexOfDefectiveFiles().delete(file.getRecord());
		}
		if (unresolvedIncludeStateChange > 0) {
			getIndexOfFilesWithUnresolvedIncludes().insert(file.getRecord());
		} else if (unresolvedIncludeStateChange < 0) {
			getIndexOfFilesWithUnresolvedIncludes().delete(file.getRecord());
		}

		fEvent.fFilesWritten.add(uncommittedKey.getLocation());
		uncommittedFile = null;
		uncommittedKey = null;
		return file;
	}

	@Override
	public void clearUncommittedFile() throws CoreException {
		if (uncommittedFile != null) {
			try {
				uncommittedFile.clear();
				uncommittedFile.delete();
			} finally {
				uncommittedFile = null;
				uncommittedKey = null;
				fileBeingUpdated = null;
			}
		}
	}

	@Override
	public void addFileContent(IIndexFragmentFile sourceFile, IncludeInformation[] includes,
			IASTPreprocessorStatement[] macros, IASTName[][] names, ASTFilePathResolver pathResolver,
			YieldableIndexLock lock) throws CoreException, InterruptedException {
		assert sourceFile.getIndexFragment() == this;

		PDOMFile pdomFile = (PDOMFile) sourceFile;
		pdomFile.addMacros(macros);
		final ASTFilePathResolver origResolver= fPathResolver;
		fPathResolver= pathResolver;
		try {
			pdomFile.addNames(names, lock);
		} finally {
			fPathResolver= origResolver;
		}
		// Includes expose the temporary file in the index, we must not yield the lock beyond this point.
		pdomFile.addIncludesTo(includes);

		final IIndexFileLocation location = pdomFile.getLocation();
		if (location != null) {
			fEvent.fClearedFiles.remove(location);
			fEvent.fFilesWritten.add(location);
		}
	}

	@Override
	public void clearFile(IIndexFragmentFile file) throws CoreException {
		assert file.getIndexFragment() == this;
		IIndexFileLocation location = file.getLocation();
		PDOMFile pdomFile = (PDOMFile) file;
		pdomFile.clear();

		fEvent.fClearedFiles.add(location);
	}

	@Override
	public void clear() throws CoreException {
		super.clear();
	}

	@Override
	public void flush() throws CoreException {
		super.flush();
	}

	@Override
	public void setProperty(String propertyName, String value) throws CoreException {
		if (IIndexFragment.PROPERTY_FRAGMENT_FORMAT_ID.equals(propertyName)
				|| IIndexFragment.PROPERTY_FRAGMENT_FORMAT_VERSION.equals(propertyName)) {
			throw new IllegalArgumentException("Property " + value + " may not be written to"); //$NON-NLS-1$ //$NON-NLS-2$
		}
		new DBProperties(db, PROPERTIES).setProperty(propertyName, value);
	}

	/**
	 * Uses the specified location converter to update each internal representation of a file
	 * location. The file index is rebuilt with the new representations. Individual PDOMFile records
	 * are unmoved so as to maintain referential integrity with other PDOM records.
	 *
	 * <b>A write-lock must be obtained before calling this method</b>
	 *
	 * @param newConverter the converter to use to update internal file representations
	 * @throws CoreException
	 */
	public void rewriteLocations(final IIndexLocationConverter newConverter) throws CoreException {
		final List<PDOMFile> pdomfiles = new ArrayList<PDOMFile>();
		getFileIndex().accept(new IBTreeVisitor() {
			@Override
			public int compare(long record) throws CoreException {
				return 0;
			}
			@Override
			public boolean visit(long record) throws CoreException {
				PDOMFile file = PDOMFile.recreateFile(WritablePDOM.this, record);
				pdomfiles.add(file);
				return true;
			}
		});

		clearFileIndex();
		final List<PDOMFile> notConverted = new ArrayList<PDOMFile>();
		for (PDOMFile file : pdomfiles) {
			String internalFormat = newConverter.toInternalFormat(file.getLocation());
			if (internalFormat != null) {
				file.setInternalLocation(internalFormat);
				getFileIndex().insert(file.getRecord());
			} else {
				notConverted.add(file);
			}
		}

		// remove content where converter returns null
		for (PDOMFile file : notConverted) {
			file.convertIncludersToUnresolved();
			file.clear();
		}
	}

	boolean isClearedBecauseOfVersionMismatch() {
		return fClearedBecauseOfVersionMismatch;
	}

	void setClearedBecauseOfVersionMismatch(boolean clearedBecauseOfVersionMismatch) {
		fClearedBecauseOfVersionMismatch = clearedBecauseOfVersionMismatch;
	}

	boolean isCreatedFromScratch() {
		return fCreatedFromScratch;
	}

	void setCreatedFromScratch(boolean createdFromScratch) {
		fCreatedFromScratch = createdFromScratch;
	}

	@Override
	protected final boolean isPermanentlyReadOnly() {
		return false;
	}

	/**
	 * Returns the best file for the given location, linkage, and translation unit.
	 * May return <code>null</code>, if no such file exists.
	 *
	 * The "best" file (variant) is the one with the most content, as measured
	 * by the total number of macros defined in the file. The rationale is that
	 * often one of the variants will contain most of the code and the others
	 * just small pieces, and we are usually interested in the one with most of
	 * the code. As a tiebreaker, a variant that was parsed in the context of a
	 * source file is preferred, since a header parsed outside of the context of
	 * a code file may not represent code that a compiler actually sees.
	 *
	 * @param linkageID the id of the linkage in which the file has been parsed.
	 * @param location the IIndexFileLocation representing the location of the file
	 * @param tu the translation unit from which 'location' originates
	 * @return the best file for the location, or <code>null</code> if the file is not
	 *     present in the index
	 * @throws CoreException
	 */
	private PDOMFile getBestFile(int linkageID, IIndexFileLocation location, ITranslationUnit tu) throws CoreException {
		IIndexFile[] files = getFiles(linkageID, location);
		IIndexFile best = null;
		int bestScore = -1;
		for (IIndexFile file : files) {
			int score = file.getMacros().length * 2;
			if (tu != null && TranslationUnit.isSourceFile(TranslationUnit.getParsedInContext(file), tu.getCProject().getProject()))
				score++;
			if (score > bestScore) {
				bestScore = score;
				best = file;
			}
		}
		return (PDOMFile) best;
	}

	public PDOMFile getFileForASTNode(int linkageID, IASTNode node) throws CoreException {
		if (fPathResolver != null && node != null) {
			IASTFileLocation loc= node.getFileLocation();
			if (loc != null) {
				ISignificantMacros sigMacros= getSignificantMacros(node, loc);
				if (sigMacros != null) {
					IIndexFileLocation location = fPathResolver.resolveASTPath(loc.getFileName());
					if (uncommittedKey != null && uncommittedKey.equals(new FileContentKey(linkageID, location, sigMacros)))
						return fileBeingUpdated != null ? fileBeingUpdated : uncommittedFile;
					return getBestFile(linkageID, location, node.getTranslationUnit().getOriginatingTranslationUnit());
				}
			}
		}
		return null;
	}

	private ISignificantMacros getSignificantMacros(IASTNode node, IASTFileLocation loc) throws CoreException {
		IASTPreprocessorIncludeStatement owner= loc.getContextInclusionStatement();
		if (owner != null)
			return owner.getSignificantMacros();

		IASTTranslationUnit tu = node.getTranslationUnit();
		if (tu != null)
			return tu.getSignificantMacros();

		return null;
	}

	@Override
	public boolean hasLastingDefinition(PDOMBinding binding) throws CoreException {
		if (fileBeingUpdated == null) {
			return binding.hasDefinition();
		}
		// Definitions in fileBeingUpdated will soon go away, so look for a definition elsewhere.
		for (PDOMName name = binding.getFirstDefinition(); name != null; name = name.getNextInBinding()) {
			if (!fileBeingUpdated.getPDOM().equals(name.getPDOM()) ||
					fileBeingUpdated.getRecord() != name.getFileRecord()) {
				return true;
			}
		}
		return false;
	}

	@Override
	protected boolean isCommitted(PDOMName name) throws CoreException {
		return uncommittedFile == null || !uncommittedFile.getPDOM().equals(name.getPDOM()) ||
				uncommittedFile.getRecord() != name.getFileRecord();
	}

	@Override
	protected boolean isCommitted(PDOMMacro name) throws CoreException {
		return uncommittedFile == null || !uncommittedFile.getPDOM().equals(name.getPDOM()) ||
				uncommittedFile.getRecord() != name.getFileRecord();
	}

	@Override
	protected boolean isCommitted(PDOMMacroReferenceName name) throws CoreException {
		return uncommittedFile == null || !uncommittedFile.getPDOM().equals(name.getPDOM()) ||
				uncommittedFile.getRecord() != name.getFileRecord();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.cdt.internal.core.index.IWritableIndexFragment#getDatabaseSizeBytes()
	 */
	@Override
	public long getDatabaseSizeBytes() {
		return getDB().getSizeBytes();
	}
}