added index manager to the new builder;
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpeclipse / builder / IdentifierIndexManager.java
1 package net.sourceforge.phpeclipse.builder;
2 import java.io.BufferedInputStream;
3 import java.io.BufferedReader;
4 import java.io.FileNotFoundException;
5 import java.io.FileReader;
6 import java.io.FileWriter;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.util.ArrayList;
10 import java.util.Collection;
11 import java.util.Comparator;
12 import java.util.HashMap;
13 import java.util.Iterator;
14 import java.util.List;
15 import java.util.SortedMap;
16 import java.util.StringTokenizer;
17 import java.util.TreeMap;
18 import net.sourceforge.phpdt.core.compiler.ITerminalSymbols;
19 import net.sourceforge.phpdt.core.compiler.InvalidInputException;
20 import net.sourceforge.phpdt.internal.compiler.parser.Scanner;
21 import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError;
22 import net.sourceforge.phpdt.internal.compiler.util.Util;
23 import net.sourceforge.phpeclipse.obfuscator.PHPIdentifier;
24 import org.eclipse.core.resources.IFile;
25 import org.eclipse.core.runtime.CoreException;
26 /**
27  * Manages the identifer index information for a specific project
28  *  
29  */
30 public class IdentifierIndexManager {
31   public class LineCreator implements ITerminalSymbols {
32     private Scanner fScanner;
33     private int fToken;
34     public LineCreator() {
35       fScanner = new Scanner(true, false);
36     }
37     /**
38      * Add the information of the current identifier to the line
39      * 
40      * @param typeOfIdentifier
41      *            the type of the identifier ('c'lass, 'd'efine, 'f'unction,
42      *            'm'ethod, 'v'ariable)
43      * @param identifier
44      *            current identifier
45      * @param line
46      *            Buffer for the current index line
47      * @param phpdocOffset
48      *            the offset of the PHPdoc comment if available
49      * @param phpdocLength
50      *            the length of the PHPdoc comment if available
51      */
52     private void addIdentifierInformation(char typeOfIdentifier,
53         char[] identifier, StringBuffer line, int phpdocOffset, int phpdocLength) {
54       line.append('\t');
55       line.append(typeOfIdentifier);
56       line.append(identifier);
57       line.append("\to"); // Offset
58       line.append(fScanner.getCurrentTokenStartPosition());
59       if (phpdocOffset >= 0) {
60         line.append("\tp"); // phpdoc offset
61         line.append(phpdocOffset);
62         line.append("\tl"); // phpdoc length
63         line.append(phpdocLength);
64       }
65     }
66     /**
67      * Get the next token from input
68      */
69     private void getNextToken() {
70       try {
71         fToken = fScanner.getNextToken();
72         if (Scanner.DEBUG) {
73           int currentEndPosition = fScanner.getCurrentTokenEndPosition();
74           int currentStartPosition = fScanner.getCurrentTokenStartPosition();
75           System.out.print(currentStartPosition + "," + currentEndPosition
76               + ": ");
77           System.out.println(fScanner.toStringAction(fToken));
78         }
79         return;
80       } catch (InvalidInputException e) {
81         // ignore errors
82       }
83       fToken = TokenNameERROR;
84     }
85     private void parseDeclarations(char[] parent, StringBuffer buf,
86         boolean goBack) {
87       char[] ident;
88       char[] classVariable;
89       int counter = 0;
90       int phpdocOffset = -1;
91       int phpdocLength = -1;
92       try {
93         while (fToken != TokenNameEOF && fToken != TokenNameERROR) {
94           phpdocOffset = -1;
95           if (fToken == TokenNameCOMMENT_PHPDOC) {
96             phpdocOffset = fScanner.getCurrentTokenStartPosition();
97             phpdocLength = fScanner.getCurrentTokenEndPosition()
98                 - fScanner.getCurrentTokenStartPosition() + 1;
99             getNextToken();
100             if (fToken == TokenNameEOF || fToken == TokenNameERROR) {
101               break;
102             }
103           }
104           if (fToken == TokenNamevar || fToken == TokenNamepublic
105               || fToken == TokenNameprotected || fToken == TokenNameprivate) {
106             getNextToken();
107             if (fToken == TokenNameVariable) {
108               ident = fScanner.getCurrentIdentifierSource();
109               classVariable = new char[ident.length - 1];
110               System.arraycopy(ident, 1, classVariable, 0, ident.length - 1);
111               addIdentifierInformation('v', classVariable, buf, phpdocOffset,
112                   phpdocLength);
113               getNextToken();
114             }
115           } else if (fToken == TokenNamefunction) {
116             getNextToken();
117             if (fToken == TokenNameAND) {
118               getNextToken();
119             }
120             if (fToken == TokenNameIdentifier) {
121               ident = fScanner.getCurrentIdentifierSource();
122               if (parent != null && equalCharArrays(parent, ident)) {
123                 // constructor function
124                 addIdentifierInformation('k', ident, buf, phpdocOffset,
125                     phpdocLength);
126               } else {
127                 if (parent != null) {
128                   // class method function
129                   addIdentifierInformation('m', ident, buf, phpdocOffset,
130                       phpdocLength);
131                 } else {
132                   // nested function ?!
133                   addIdentifierInformation('f', ident, buf, phpdocOffset,
134                       phpdocLength);
135                 }
136               }
137               getNextToken();
138               parseDeclarations(null, buf, true);
139             }
140           } else if (fToken == TokenNameclass) {
141             getNextToken();
142             if (fToken == TokenNameIdentifier) {
143               ident = fScanner.getCurrentIdentifierSource();
144               addIdentifierInformation('c', ident, buf, phpdocOffset,
145                   phpdocLength);
146               getNextToken();
147               //skip tokens for classname, extends and others until we have
148               // the opening '{'
149               while (fToken != TokenNameLBRACE && fToken != TokenNameEOF
150                   && fToken != TokenNameERROR) {
151                 getNextToken();
152               }
153               parseDeclarations(ident, buf, true);
154             }
155           } else if (fToken == TokenNameIdentifier) {
156             ident = fScanner.getCurrentIdentifierSource();
157             getNextToken();
158             if (ident.length==6 && 
159                 ident[0]=='d' && 
160                 ident[1]=='e' && 
161                 ident[2]=='f' && 
162                 ident[3]=='i' && 
163                 ident[4]=='n' && 
164                 ident[5]=='e') {
165               if (fToken == TokenNameLPAREN) {
166                 getNextToken();
167                 if (fToken == TokenNameStringLiteral) {
168                   ident = fScanner.getCurrentStringLiteralSource();
169                   addIdentifierInformation('d', ident, buf, phpdocOffset,
170                       phpdocLength);
171                   getNextToken();
172                 }
173               }
174             }
175           } else if ((fToken == TokenNameLBRACE)
176               || (fToken == TokenNameDOLLAR_LBRACE)) {
177             getNextToken();
178             counter++;
179           } else if (fToken == TokenNameRBRACE) {
180             getNextToken();
181             --counter;
182             if (counter == 0 && goBack) {
183               return;
184             }
185           } else {
186             getNextToken();
187           }
188         }
189       } catch (SyntaxError e) {
190         // TODO Auto-generated catch block
191         e.printStackTrace();
192       }
193     }
194     public void parseIdentifiers(char[] charArray, StringBuffer buf) {
195       char[] ident;
196       String identifier;
197       int counter = 0;
198       int phpdocOffset = -1;
199       int phpdocLength = -1;
200       fScanner.setSource(charArray);
201       fScanner.setPHPMode(false);
202       fToken = TokenNameEOF;
203       getNextToken();
204       try {
205         while (fToken != TokenNameEOF && fToken != TokenNameERROR) {
206           phpdocOffset = -1;
207           if (fToken == TokenNameCOMMENT_PHPDOC) {
208             phpdocOffset = fScanner.getCurrentTokenStartPosition();
209             phpdocLength = fScanner.getCurrentTokenEndPosition()
210                 - fScanner.getCurrentTokenStartPosition() + 1;
211             getNextToken();
212             if (fToken == TokenNameEOF || fToken == TokenNameERROR) {
213               break;
214             }
215           }
216           if (fToken == TokenNamefunction) {
217             getNextToken();
218             if (fToken == TokenNameAND) {
219               getNextToken();
220             }
221             if (fToken == TokenNameIdentifier) {
222               ident = fScanner.getCurrentIdentifierSource();
223               addIdentifierInformation('f', ident, buf, phpdocOffset,
224                   phpdocLength);
225               getNextToken();
226               parseDeclarations(null, buf, true);
227             }
228           } else if (fToken == TokenNameclass) {
229             getNextToken();
230             if (fToken == TokenNameIdentifier) {
231               ident = fScanner.getCurrentIdentifierSource();
232               addIdentifierInformation('c', ident, buf, phpdocOffset,
233                   phpdocLength);
234               getNextToken();
235               //skip fTokens for classname, extends and others until we have
236               // the opening '{'
237               while (fToken != TokenNameLBRACE && fToken != TokenNameEOF
238                   && fToken != TokenNameERROR) {
239                 getNextToken();
240               }
241               parseDeclarations(ident, buf, true);
242             }
243           } else if (fToken == TokenNameIdentifier) {
244             ident = fScanner.getCurrentIdentifierSource();
245             getNextToken();
246             if (ident.length==6 && 
247                 ident[0]=='d' && 
248                 ident[1]=='e' && 
249                 ident[2]=='f' && 
250                 ident[3]=='i' && 
251                 ident[4]=='n' && 
252                 ident[5]=='e') {
253               if (fToken == TokenNameLPAREN) {
254                 getNextToken();
255                 if (fToken == TokenNameStringLiteral) {
256                   ident = fScanner.getCurrentStringLiteralSource();
257                   addIdentifierInformation('d', ident, buf, phpdocOffset,
258                       phpdocLength);
259                   getNextToken();
260                 }
261               }
262             }
263           } else {
264             getNextToken();
265           }
266         }
267       } catch (SyntaxError e) {
268         // TODO Auto-generated catch block
269         e.printStackTrace();
270       }
271     }
272   }
273   class StringComparator implements Comparator {
274     public int compare(Object o1, Object o2) {
275       String s1 = (String) o1;
276       String s2 = (String) o2;
277       return s1.compareTo(s2);
278       //        return s1.toUpperCase().compareTo(s2.toUpperCase());
279     }
280     public boolean equals(Object o) {
281       String s = (String) o;
282       return compare(this, o) == 0;
283     }
284   }
285   private HashMap fFileMap;
286   private String fFilename;
287   private TreeMap fIndentifierMap;
288   public IdentifierIndexManager(String filename) {
289     fFilename = filename;
290     initialize();
291     readFile();
292   }
293   /**
294    * Check if 2 char arrays are equal
295    * 
296    * @param a
297    * @param b
298    * @return
299    */
300   private static boolean equalCharArrays(char[] a, char[] b) {
301     if (a.length != b.length) {
302       return false;
303     }
304     for (int i = 0; i < b.length; i++) {
305       if (a[i] != b[i]) {
306         return false;
307       }
308     }
309     return true;
310   }
311   /**
312    * Add the information for a given IFile resource
313    *  
314    */
315   public void addFile(IFile fileToParse) {
316     //    InputStream iStream;
317     LineCreator lineCreator = new LineCreator();
318     try {
319       //      iStream = fileToParse.getContents();
320       //
321       //      StringBuffer buf = new StringBuffer();
322       //      int c0;
323       //      try {
324       //        while ((c0 = iStream.read()) != (-1)) {
325       //          buf.append((char) c0);
326       //        }
327       //      } catch (IOException e) {
328       //        return;
329       //      }
330       InputStream stream = null;
331       try {
332         stream = new BufferedInputStream(fileToParse.getContents());
333         StringBuffer lineBuffer = new StringBuffer();
334         lineBuffer.append(fileToParse.getFullPath().toString());
335         int lineLength = lineBuffer.length();
336         // lineCreator.parseIdentifiers(buf.toString().toCharArray(),
337         // lineBuffer);
338         lineCreator.parseIdentifiers(Util.getInputStreamAsCharArray(stream, -1,
339             null), lineBuffer);
340         if (lineLength != lineBuffer.length()) {
341           addLine(lineBuffer.toString());
342         }
343       } catch (IOException e) {
344         return;
345       } finally {
346         try {
347           if (stream != null) {
348             stream.close();
349           }
350         } catch (IOException e) {
351         }
352       }
353     } catch (CoreException e1) {
354       // TODO Auto-generated catch block
355       e1.printStackTrace();
356     }
357   }
358   /**
359    * Adds a line of the index file for function, class, class-method and
360    * class-variable names
361    * 
362    * @param line
363    */
364   private void addLine(String line) {
365     StringTokenizer tokenizer;
366     String phpFileName = null;
367     String token;
368     String identifier = null;
369     String classname = null;
370     String offset = null;
371     PHPIdentifierLocation phpIdentifier = null;
372     boolean tokenExists = false;
373     tokenizer = new StringTokenizer(line, "\t");
374     // first token contains the filename:
375     if (tokenizer.hasMoreTokens()) {
376       phpFileName = tokenizer.nextToken();
377       //System.out.println(token);
378     } else {
379       return;
380     }
381     // all the other tokens are identifiers:
382     while (tokenizer.hasMoreTokens()) {
383       token = tokenizer.nextToken();
384       //System.out.println(token);
385       switch (token.charAt(0)) {
386         case 'c' :
387           // class name
388           identifier = token.substring(1);
389           classname = identifier;
390           phpIdentifier = new PHPIdentifierLocation(identifier,
391               PHPIdentifier.CLASS, phpFileName);
392           break;
393         case 'd' :
394           // define
395           identifier = token.substring(1);
396           phpIdentifier = new PHPIdentifierLocation(identifier,
397               PHPIdentifier.DEFINE, phpFileName);
398           break;
399         case 'f' :
400           // function name
401           identifier = token.substring(1);
402           phpIdentifier = new PHPIdentifierLocation(identifier,
403               PHPIdentifier.FUNCTION, phpFileName);
404           break;
405         case 'k' :
406           // constructor function name
407           identifier = token.substring(1);
408           phpIdentifier = new PHPIdentifierLocation(identifier,
409               PHPIdentifier.CONSTRUCTOR, phpFileName);
410           break;
411         case 'm' :
412           //method inside a class
413           identifier = token.substring(1);
414           phpIdentifier = new PHPIdentifierLocation(identifier,
415               PHPIdentifier.METHOD, phpFileName, classname);
416           break;
417         case 'v' :
418           // variable inside a class
419           identifier = token.substring(1);
420           phpIdentifier = new PHPIdentifierLocation(identifier,
421               PHPIdentifier.VARIABLE, phpFileName, classname);
422           break;
423         case 'o' :
424           // offset information
425           identifier = null;
426           if (phpIdentifier != null) {
427             offset = token.substring(1);
428             phpIdentifier.setOffset(Integer.parseInt(offset));
429           }
430           break;
431         case 'p' :
432           // PHPdoc offset information
433           identifier = null;
434           if (phpIdentifier != null) {
435             offset = token.substring(1);
436             phpIdentifier.setPHPDocOffset(Integer.parseInt(offset));
437           }
438           break;
439         case 'l' :
440           // PHPdoc length information
441           identifier = null;
442           if (phpIdentifier != null) {
443             offset = token.substring(1);
444             phpIdentifier.setPHPDocLength(Integer.parseInt(offset));
445           }
446           break;
447         default :
448           identifier = null;
449           phpIdentifier = null;
450           classname = null;
451       }
452       if (identifier != null && phpIdentifier != null) {
453         tokenExists = true;
454         ArrayList list = (ArrayList) fIndentifierMap.get(identifier);
455         if (list == null) {
456           list = new ArrayList();
457           list.add(phpIdentifier);
458           fIndentifierMap.put(identifier, list);
459         } else {
460           boolean flag = false;
461           for (int i = 0; i < list.size(); i++) {
462             if (list.get(i).equals(phpIdentifier)) {
463               flag = true;
464               break;
465             }
466           }
467           if (flag == false) {
468             list.add(phpIdentifier);
469           }
470         }
471       }
472     }
473     if (tokenExists) {
474       fFileMap.put(phpFileName, line);
475     }
476   }
477   /**
478    * Change the information for a given IFile resource
479    *  
480    */
481   public void changeFile(IFile fileToParse) {
482     removeFile(fileToParse);
483     addFile(fileToParse);
484   }
485   /**
486    * Get a list of all PHPIdentifierLocation object's associated with an
487    * identifier
488    * 
489    * @param identifier
490    * @return
491    */
492   public List getLocations(String identifier) {
493     return (List) fIndentifierMap.get(identifier);
494   }
495   /**
496    * Initialize (i.e. clear) the current index information
497    *  
498    */
499   public void initialize() {
500     fIndentifierMap = new TreeMap(new StringComparator());
501     fFileMap = new HashMap();
502   }
503   private void readFile() {
504     FileReader fileReader;
505     try {
506       fileReader = new FileReader(fFilename);
507       BufferedReader bufferedReader = new BufferedReader(fileReader);
508       String line;
509       while (bufferedReader.ready()) {
510         // all entries for one file are in a line
511         // separated by tabs !
512         line = bufferedReader.readLine();
513         addLine(line);
514       }
515       fileReader.close();
516     } catch (FileNotFoundException e) {
517       // ignore this
518       // TODO DialogBox which asks the user if she/he likes to build new index?
519     } catch (IOException e) {
520       // TODO Auto-generated catch block
521       e.printStackTrace();
522     }
523   }
524   /**
525    * Remove the information for a given IFile resource
526    *  
527    */
528   public void removeFile(IFile fileToParse) {
529     //    String line = (String)
530     // fFileMap.get(fileToParse.getLocation().toString());
531     String line = (String) fFileMap.get(fileToParse.getFullPath().toString());
532     if (line != null) {
533       removeLine(line);
534     }
535   }
536   /**
537    * Removes a line of the index file for function, class, class-method and
538    * class-variable names
539    * 
540    * @param line
541    */
542   private void removeLine(String line) {
543     StringTokenizer tokenizer;
544     String phpFileName = null;
545     String token;
546     String identifier = null;
547     String classname = null;
548     PHPIdentifier phpIdentifier = null;
549     boolean tokenExists = false;
550     tokenizer = new StringTokenizer(line, "\t");
551     // first token contains the filename:
552     if (tokenizer.hasMoreTokens()) {
553       phpFileName = tokenizer.nextToken();
554       //System.out.println(token);
555     } else {
556       return;
557     }
558     // all the other tokens are identifiers:
559     while (tokenizer.hasMoreTokens()) {
560       token = tokenizer.nextToken();
561       //System.out.println(token);
562       switch (token.charAt(0)) {
563         case 'c' :
564           // class name
565           identifier = token.substring(1);
566           classname = identifier;
567           phpIdentifier = new PHPIdentifierLocation(identifier,
568               PHPIdentifier.CLASS, phpFileName);
569           break;
570         case 'd' :
571           // define
572           identifier = token.substring(1);
573           phpIdentifier = new PHPIdentifierLocation(identifier,
574               PHPIdentifier.DEFINE, phpFileName);
575           break;
576         case 'f' :
577           // function name
578           identifier = token.substring(1);
579           phpIdentifier = new PHPIdentifierLocation(identifier,
580               PHPIdentifier.FUNCTION, phpFileName);
581           break;
582         case 'k' :
583           // constructor function name
584           identifier = token.substring(1);
585           phpIdentifier = new PHPIdentifierLocation(identifier,
586               PHPIdentifier.CONSTRUCTOR, phpFileName);
587           break;
588         case 'm' :
589           //method inside a class
590           identifier = token.substring(1);
591           phpIdentifier = new PHPIdentifierLocation(identifier,
592               PHPIdentifier.METHOD, phpFileName, classname);
593           break;
594         case 'v' :
595           // variable inside a class
596           identifier = token.substring(1);
597           phpIdentifier = new PHPIdentifierLocation(identifier,
598               PHPIdentifier.VARIABLE, phpFileName, classname);
599           break;
600         default :
601           identifier = null;
602           phpIdentifier = null;
603           classname = null;
604       }
605       if (identifier != null && phpIdentifier != null) {
606         ArrayList list = (ArrayList) fIndentifierMap.get(identifier);
607         if (list == null) {
608         } else {
609           for (int i = 0; i < list.size(); i++) {
610             if (list.get(i).equals(phpIdentifier)) {
611               list.remove(i);
612               break;
613             }
614           }
615           if (list.size() == 0) {
616             fIndentifierMap.remove(identifier);
617           }
618         }
619       }
620     }
621     fFileMap.remove(phpFileName);
622   }
623   /**
624    * Save the current index information in the projects index file
625    *  
626    */
627   public void writeFile() {
628     FileWriter fileWriter;
629     try {
630       fileWriter = new FileWriter(fFilename);
631       String line;
632       Collection collection = fFileMap.values();
633       Iterator iterator = collection.iterator();
634       while (iterator.hasNext()) {
635         line = (String) iterator.next();
636         fileWriter.write(line + '\n');
637       }
638       fileWriter.close();
639     } catch (FileNotFoundException e) {
640       // ignore exception; project is deleted by user
641     } catch (IOException e) {
642       // TODO Auto-generated catch block
643       e.printStackTrace();
644     }
645   }
646   /**
647    * @param fromKey
648    * @param toKey
649    * @return
650    */
651   public SortedMap getIdentifierMap() {
652     return fIndentifierMap;
653   }
654 }