Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 7f74b541c5a029203f73ebf7585848a208368464 (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
/*******************************************************************************
 * Copyright (c) 2003 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials 
 * are made available under the terms of the Common Public License v0.5 
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors:
 *     IBM Corp. - Rational Software - initial implementation
 ******************************************************************************/
/*
 * Created on Jun 13, 2003
 */
package org.eclipse.cdt.internal.core.search.matching;

import java.io.CharArrayReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;

import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.parser.IParser;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.core.parser.IScanner;
import org.eclipse.cdt.core.parser.IScannerInfo;
import org.eclipse.cdt.core.parser.IScannerInfoProvider;
import org.eclipse.cdt.core.parser.ISourceElementCallbackDelegate;
import org.eclipse.cdt.core.parser.ISourceElementRequestor;
import org.eclipse.cdt.core.parser.ParserFactory;
import org.eclipse.cdt.core.parser.ParserLanguage;
import org.eclipse.cdt.core.parser.ParserMode;
import org.eclipse.cdt.core.parser.ast.IASTASMDefinition;
import org.eclipse.cdt.core.parser.ast.IASTAbstractTypeSpecifierDeclaration;
import org.eclipse.cdt.core.parser.ast.IASTClassReference;
import org.eclipse.cdt.core.parser.ast.IASTClassSpecifier;
import org.eclipse.cdt.core.parser.ast.IASTCodeScope;
import org.eclipse.cdt.core.parser.ast.IASTCompilationUnit;
import org.eclipse.cdt.core.parser.ast.IASTElaboratedTypeSpecifier;
import org.eclipse.cdt.core.parser.ast.IASTEnumerationReference;
import org.eclipse.cdt.core.parser.ast.IASTEnumerationSpecifier;
import org.eclipse.cdt.core.parser.ast.IASTEnumerator;
import org.eclipse.cdt.core.parser.ast.IASTEnumeratorReference;
import org.eclipse.cdt.core.parser.ast.IASTField;
import org.eclipse.cdt.core.parser.ast.IASTFieldReference;
import org.eclipse.cdt.core.parser.ast.IASTFunction;
import org.eclipse.cdt.core.parser.ast.IASTFunctionReference;
import org.eclipse.cdt.core.parser.ast.IASTInclusion;
import org.eclipse.cdt.core.parser.ast.IASTLinkageSpecification;
import org.eclipse.cdt.core.parser.ast.IASTMacro;
import org.eclipse.cdt.core.parser.ast.IASTMethod;
import org.eclipse.cdt.core.parser.ast.IASTMethodReference;
import org.eclipse.cdt.core.parser.ast.IASTNamespaceDefinition;
import org.eclipse.cdt.core.parser.ast.IASTNamespaceReference;
import org.eclipse.cdt.core.parser.ast.IASTOffsetableNamedElement;
import org.eclipse.cdt.core.parser.ast.IASTParameterReference;
import org.eclipse.cdt.core.parser.ast.IASTReference;
import org.eclipse.cdt.core.parser.ast.IASTScope;
import org.eclipse.cdt.core.parser.ast.IASTTemplateDeclaration;
import org.eclipse.cdt.core.parser.ast.IASTTemplateInstantiation;
import org.eclipse.cdt.core.parser.ast.IASTTemplateSpecialization;
import org.eclipse.cdt.core.parser.ast.IASTTypedefDeclaration;
import org.eclipse.cdt.core.parser.ast.IASTTypedefReference;
import org.eclipse.cdt.core.parser.ast.IASTUsingDeclaration;
import org.eclipse.cdt.core.parser.ast.IASTUsingDirective;
import org.eclipse.cdt.core.parser.ast.IASTVariable;
import org.eclipse.cdt.core.parser.ast.IASTVariableReference;
import org.eclipse.cdt.core.search.ICSearchConstants;
import org.eclipse.cdt.core.search.ICSearchPattern;
import org.eclipse.cdt.core.search.ICSearchResultCollector;
import org.eclipse.cdt.core.search.ICSearchScope;
import org.eclipse.cdt.core.search.IMatch;
import org.eclipse.cdt.internal.core.model.IWorkingCopy;
import org.eclipse.cdt.internal.core.parser.ScannerInfo;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;


/**
 * @author aniefer
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
public class MatchLocator implements ISourceElementRequestor, ICSearchConstants {

	
	public static boolean VERBOSE = false;
	/**
	 * 
	 */
	public MatchLocator( ICSearchPattern pattern, ICSearchResultCollector collector, ICSearchScope scope, IProgressMonitor monitor) {
		super();
		searchPattern = pattern;
		resultCollector = collector;
		searchScope = scope;
		progressMonitor = monitor;		
	}

	public void acceptProblem(IProblem problem) 								{	}
	public void acceptUsingDirective(IASTUsingDirective usageDirective) 		{	}
	public void acceptUsingDeclaration(IASTUsingDeclaration usageDeclaration) 	{	}
	public void acceptASMDefinition(IASTASMDefinition asmDefinition) 			{	}
	public void acceptAbstractTypeSpecDeclaration(IASTAbstractTypeSpecifierDeclaration abstractDeclaration) {}

	public void enterLinkageSpecification(IASTLinkageSpecification linkageSpec) {	}
	public void enterTemplateDeclaration(IASTTemplateDeclaration declaration) 	{	}
	public void enterTemplateSpecialization(IASTTemplateSpecialization specialization) 		{	}
	public void enterTemplateInstantiation(IASTTemplateInstantiation instantiation) {	}

	public void exitTemplateDeclaration(IASTTemplateDeclaration declaration) 	{}
	public void exitTemplateSpecialization(IASTTemplateSpecialization specialization) 		{	}
	public void exitTemplateExplicitInstantiation(IASTTemplateInstantiation instantiation) 	{	}
	public void exitLinkageSpecification(IASTLinkageSpecification linkageSpec) 	{	}

	public void enterCodeBlock(IASTCodeScope scope) {	}
	public void exitCodeBlock(IASTCodeScope scope) 	{	}
	
	
	public void acceptTypedefDeclaration(IASTTypedefDeclaration typedef){
		lastDeclaration = typedef;
		check( DECLARATIONS, typedef );
	}
	
	public void acceptTypedefReference( IASTTypedefReference reference ){
		check( REFERENCES, reference );
	}
	
	public void acceptEnumeratorReference(IASTEnumeratorReference reference){
		check( REFERENCES, reference );	
	}
		
	public void acceptMacro(IASTMacro macro){
		check( DECLARATIONS, macro );	
	}
	
	public void acceptVariable(IASTVariable variable){
		lastDeclaration = variable;
		check( DECLARATIONS, variable );   
	}
	
	public void acceptField(IASTField field){
		lastDeclaration = field; 
		check( DECLARATIONS, field ); 	   
	}
	
	public void acceptEnumerationSpecifier(IASTEnumerationSpecifier enumeration){
		lastDeclaration = enumeration; 
		check( DECLARATIONS, enumeration );
		Iterator iter = enumeration.getEnumerators();
		while( iter.hasNext() ){
			IASTEnumerator enumerator = (IASTEnumerator) iter.next();
			lastDeclaration = enumerator;
			check ( DECLARATIONS, enumerator );
		}  
	}
		
	public void acceptFunctionDeclaration(IASTFunction function){
		lastDeclaration = function;
		check( DECLARATIONS, function );
	}
	
	public void acceptMethodDeclaration(IASTMethod method){
		lastDeclaration = method;
		check( DECLARATIONS, method );
	}
		
	public void acceptClassReference(IASTClassReference reference) {
		check( REFERENCES, reference );
	}
	
	public void acceptNamespaceReference( IASTNamespaceReference reference ){
		check( REFERENCES, reference );
	}
	
	public void acceptVariableReference( IASTVariableReference reference ){
		check( REFERENCES, reference );		
	}
	
	public void acceptFieldReference( IASTFieldReference reference ){
		check( REFERENCES, reference );
	}
	
	public void acceptEnumerationReference( IASTEnumerationReference reference ){
		check( REFERENCES, reference );
	}
	
	public void acceptFunctionReference( IASTFunctionReference reference ){
		check( REFERENCES, reference );
	}
	
	public void acceptMethodReference( IASTMethodReference reference ){
		check( REFERENCES, reference );	
	}
	
	public void enterFunctionBody(IASTFunction function){
		lastDeclaration = function;
		check( DECLARATIONS, function );
		check( DEFINITIONS, function );
		pushScope( function );
	}
	
	public void enterMethodBody(IASTMethod method) {
		lastDeclaration = method;
		check( DEFINITIONS, method );
		pushScope( method );
	}
	
	public void enterCompilationUnit(IASTCompilationUnit compilationUnit) {
		pushScope( compilationUnit );
	}
	
	public void enterNamespaceDefinition(IASTNamespaceDefinition namespaceDefinition) {
		lastDeclaration = namespaceDefinition;
		check( DECLARATIONS, namespaceDefinition );
		pushScope( namespaceDefinition );			
	}

	public void enterClassSpecifier(IASTClassSpecifier classSpecification) {
		lastDeclaration = classSpecification;
		check( DECLARATIONS, classSpecification );
		pushScope( classSpecification );		
	}
	
	public void exitFunctionBody(IASTFunction function) {
		popScope();	
	}

	public void exitMethodBody(IASTMethod method) {
		popScope();	
	}

	public void exitClassSpecifier(IASTClassSpecifier classSpecification) {
		popScope();
	}

	public void exitNamespaceDefinition(IASTNamespaceDefinition namespaceDefinition) {
		popScope();
	}

	public void exitCompilationUnit(IASTCompilationUnit compilationUnit){
		popScope();
	}
	
	public void enterInclusion(IASTInclusion inclusion) {
		String includePath = inclusion.getFullFileName();

		IPath path = new Path( includePath );
		IResource resource = null;
		
		if( workspaceRoot != null ){
			resource = workspaceRoot.getFileForLocation( path );
			if( resource == null ){
				IFile file = workspaceRoot.getFile( path );
				try{
					file.createLink( path, 0, null );
				} catch ( CoreException e ){
					file = null;
				}
				resource = file;
			}
		}
		
		resourceStack.addFirst( ( currentResource != null ) ? (Object)currentResource : (Object)currentPath );
		
		currentResource = resource;
		currentPath = ( resource == null ) ? path : null;
	}

	public void exitInclusion(IASTInclusion inclusion) {
		Object obj = resourceStack.removeFirst();
		if( obj instanceof IResource ){
			currentResource = (IResource)obj;
			currentPath = null;
		} else {
			currentPath = (IPath) obj;
			currentResource = null;
		}
	}
		

	public void locateMatches( String [] paths, IWorkspace workspace, IWorkingCopy[] workingCopies ){
		workspaceRoot = (workspace != null) ? workspace.getRoot() : null;
		
		HashMap wcPaths = new HashMap();
		int wcLength = (workingCopies == null) ? 0 : workingCopies.length;
		if( wcLength > 0 ){
			String [] newPaths = new String[ wcLength ];
			
			for( int i = 0; i < wcLength; i++ ){
				IWorkingCopy workingCopy = workingCopies[ i ];
				String path = workingCopy.getOriginalElement().getPath().toString();
				wcPaths.put( path, workingCopy );
				newPaths[ i ] = path;
			}
			
			int len = paths.length;
			String [] tempArray = new String[ len + wcLength ];
			System.arraycopy( paths, 0, tempArray, 0, len );
			System.arraycopy( newPaths, 0, tempArray, len, wcLength );
			paths = tempArray;
		}
		
		Arrays.sort( paths );
		
		int length = paths.length;
		if( progressMonitor != null ){
			progressMonitor.beginTask( "", length );
		}
		
		for( int i = 0; i < length; i++ ){
			if( progressMonitor != null ) {
				if( progressMonitor.isCanceled() ){
					throw new OperationCanceledException();
				} else {
					progressMonitor.worked( 1 );
				}
			}
			
			String pathString = paths[ i ];
			
			//skip duplicates
			if( i > 0 && pathString.equals( paths[ i - 1 ] ) ) continue;
			
			if  (!searchScope.encloses(pathString)) continue;
			
			Reader reader = null;
			
			IPath realPath = null; 
			IProject project = null;
			
			if( workspaceRoot != null ){
				IWorkingCopy workingCopy = (IWorkingCopy)wcPaths.get( pathString );
				
				if( workingCopy != null ){
					reader = new CharArrayReader( workingCopy.getContents() );
					currentResource = workingCopy.getResource();
					realPath = currentResource.getLocation();
					project = currentResource.getProject();
				} else {
					currentResource = workspaceRoot.findMember( pathString, true );
					
					try{
						if( currentResource == null ){
							IPath path = new Path( pathString );
							IFile file = workspaceRoot.getFile( path );
							file.createLink( path, 0, null );
							project = file.getProject();
						}
						if( currentResource != null && currentResource instanceof IFile ){
							IFile file = (IFile) currentResource;
							reader = new InputStreamReader( file.getContents() );
							realPath = currentResource.getLocation();
							project = file.getProject();
						} else continue;
					} catch ( CoreException e ){
						continue;
					}
				}
			} else {
				IPath path = new Path( pathString );
				try {
					currentPath = path;
					reader = new FileReader( path.toFile() );
					realPath = currentPath; 
				} catch (FileNotFoundException e) {
					continue;
				}
			}
			
			//Get the scanner info
			IScannerInfo scanInfo = new ScannerInfo();
			IScannerInfoProvider provider = CCorePlugin.getDefault().getScannerInfoProvider(project);
			if (provider != null){
				IScannerInfo buildScanInfo = provider.getScannerInformation(project);
				scanInfo = new ScannerInfo(buildScanInfo.getDefinedSymbols(), buildScanInfo.getIncludePaths());
			}
			
			ParserLanguage language = null;
			if( project != null ){
				language = CoreModel.getDefault().hasCCNature( project ) ? ParserLanguage.CPP : ParserLanguage.C;
			} else {
				//TODO no probject, what language do we use?
				language = ParserLanguage.CPP;
			}
			IScanner scanner = ParserFactory.createScanner( reader, realPath.toOSString(), scanInfo, ParserMode.COMPLETE_PARSE, language, this );
			IParser  parser  = ParserFactory.createParser( scanner, this, ParserMode.COMPLETE_PARSE, language );
			
			if (VERBOSE)
			  MatchLocator.verbose("*** New Search for path: " + pathString);
			  
			parser.parse();
		}
	}
	
	protected void report( ISourceElementCallbackDelegate node, int accuracyLevel ){
		try {
			int offset = 0;
			int length = 0;
			
			if( node instanceof IASTReference ){
				IASTReference reference = (IASTReference) node;
				offset = reference.getOffset();
				length = reference.getName().length();
				if (VERBOSE)
					MatchLocator.verbose("Report Match: " + reference.getName());
			} else if( node instanceof IASTOffsetableNamedElement ){
				IASTOffsetableNamedElement offsetableElement = (IASTOffsetableNamedElement) node;
				offset = offsetableElement.getNameOffset() != 0 ? offsetableElement.getNameOffset() 
															    : offsetableElement.getStartingOffset();
				length = offsetableElement.getName().length();															  
				if (VERBOSE)
					MatchLocator.verbose("Report Match: " + offsetableElement.getName());
			}
		
			IMatch match = null;
			ISourceElementCallbackDelegate object = null;
			
			if( node instanceof IASTReference ){
				if( currentScope instanceof IASTFunction || currentScope instanceof IASTMethod ){
					object = (ISourceElementCallbackDelegate) currentScope;
				} else {
					object = lastDeclaration;
				}
			} else {
				if( currentScope instanceof IASTFunction || currentScope instanceof IASTMethod ){
					object = (ISourceElementCallbackDelegate) currentScope;
				} else {
					object = node;
				}
			}
		
			if( currentResource != null ){
				match = resultCollector.createMatch( currentResource, offset, offset + length, object );
			} else if( currentPath != null ){
				match = resultCollector.createMatch( currentPath, offset, offset + length, object );
			}
			if( match != null ){
				resultCollector.acceptMatch( match );
			}
		
		} catch (CoreException e) {
		}
	}

	private void check( LimitTo limit, ISourceElementCallbackDelegate node ){
		if( !searchPattern.canAccept( limit ) )
			return;
			
		int level = ICSearchPattern.IMPOSSIBLE_MATCH;
		
		if( node instanceof IASTReference ){
			level = searchPattern.matchLevel( ((IASTReference)node).getReferencedElement(), limit );
		} else  {
			level = searchPattern.matchLevel(  node, limit );
		} 
		
		if( level != ICSearchPattern.IMPOSSIBLE_MATCH )
		{
			report( node, level );
		}
	}
	
	private void pushScope( IASTScope scope ){
		scopeStack.addFirst( currentScope );
		currentScope = scope;
	}
	
	private IASTScope popScope(){
		IASTScope oldScope = currentScope;
		currentScope = (scopeStack.size() > 0 ) ? (IASTScope) scopeStack.removeFirst() : null;
		return oldScope;
	}
	
	private ISourceElementCallbackDelegate lastDeclaration;
	
	private ICSearchPattern 		searchPattern;
	private ICSearchResultCollector resultCollector;
	private IProgressMonitor 		progressMonitor;
	private IPath					currentPath 	= null;
	private ICSearchScope 			searchScope;
	private IWorkspaceRoot 			workspaceRoot;
	
	private IResource 				currentResource = null;
	private LinkedList 				resourceStack = new LinkedList();
	
	private IASTScope				currentScope = null;
	private LinkedList				scopeStack = new LinkedList();
    /* (non-Javadoc)
     * @see org.eclipse.cdt.core.parser.ISourceElementRequestor#acceptElaboratedForewardDeclaration(org.eclipse.cdt.core.parser.ast.IASTElaboratedTypeSpecifier)
     */
    public void acceptElaboratedForewardDeclaration(IASTElaboratedTypeSpecifier elaboratedType){
		check( DECLARATIONS, elaboratedType );	
    }

	public static void verbose(String log) {
	  System.out.println("(" + Thread.currentThread() + ") " + log); 
	}

    /* (non-Javadoc)
     * @see org.eclipse.cdt.core.parser.ISourceElementRequestor#acceptParameterReference(org.eclipse.cdt.internal.core.parser.ast.complete.ASTParameterReference)
     */
    public void acceptParameterReference(IASTParameterReference reference)
    {
        // TODO Auto-generated method stub
        
    }


}

Back to the top