1 /**********************************************************************
2 Copyright (c) 2000, 2002 IBM Corp. and others.
3 All rights reserved. This program and the accompanying materials
4 are made available under the terms of the Common Public License v1.0
5 which accompanies this distribution, and is available at
6 http://www.eclipse.org/legal/cpl-v10.html
9 IBM Corporation - Initial implementation
10 **********************************************************************/
11 package net.sourceforge.phpeclipse.phpeditor.php;
13 import java.io.IOException;
14 import java.util.ArrayList;
15 import java.util.Arrays;
16 import java.util.HashMap;
17 import java.util.HashSet;
18 import java.util.Iterator;
19 import java.util.List;
21 import java.util.SortedMap;
23 import net.sourceforge.phpdt.core.ICompilationUnit;
24 import net.sourceforge.phpdt.core.IJavaElement;
25 import net.sourceforge.phpdt.core.IMethod;
26 import net.sourceforge.phpdt.core.IType;
27 import net.sourceforge.phpdt.core.JavaCore;
28 import net.sourceforge.phpdt.core.ToolFactory;
29 import net.sourceforge.phpdt.core.compiler.ITerminalSymbols;
30 import net.sourceforge.phpdt.core.compiler.InvalidInputException;
31 import net.sourceforge.phpdt.internal.compiler.DefaultErrorHandlingPolicies;
32 import net.sourceforge.phpdt.internal.compiler.impl.CompilerOptions;
33 import net.sourceforge.phpdt.internal.compiler.parser.Scanner;
34 import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError;
35 import net.sourceforge.phpdt.internal.compiler.parser.UnitParser;
36 import net.sourceforge.phpdt.internal.compiler.parser.VariableInfo;
37 import net.sourceforge.phpdt.internal.compiler.problem.DefaultProblemFactory;
38 import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter;
39 import net.sourceforge.phpdt.internal.corext.template.php.JavaContext;
40 import net.sourceforge.phpdt.internal.corext.template.php.JavaContextType;
41 import net.sourceforge.phpdt.internal.ui.text.PHPCodeReader;
42 import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal;
43 import net.sourceforge.phpdt.internal.ui.text.java.JavaParameterListValidator;
44 import net.sourceforge.phpdt.internal.ui.text.java.PHPCompletionProposalComparator;
45 import net.sourceforge.phpdt.internal.ui.text.template.BuiltInEngine;
46 import net.sourceforge.phpdt.internal.ui.text.template.DeclarationEngine;
47 import net.sourceforge.phpdt.internal.ui.text.template.LocalVariableProposal;
48 import net.sourceforge.phpdt.internal.ui.text.template.contentassist.TemplateEngine;
49 import net.sourceforge.phpdt.ui.IWorkingCopyManager;
50 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
51 import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
52 import net.sourceforge.phpeclipse.internal.compiler.ast.CompilationUnitDeclaration;
53 import net.sourceforge.phpeclipse.phpeditor.PHPEditor;
54 import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr;
56 import org.eclipse.core.resources.IFile;
57 import org.eclipse.core.resources.IProject;
58 import org.eclipse.jface.text.BadLocationException;
59 import org.eclipse.jface.text.IDocument;
60 import org.eclipse.jface.text.IRegion;
61 import org.eclipse.jface.text.ITextViewer;
62 import org.eclipse.jface.text.Region;
63 import org.eclipse.jface.text.contentassist.ICompletionProposal;
64 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
65 import org.eclipse.jface.text.contentassist.IContextInformation;
66 import org.eclipse.jface.text.contentassist.IContextInformationExtension;
67 import org.eclipse.jface.text.contentassist.IContextInformationValidator;
68 import org.eclipse.jface.text.templates.TemplateContextType;
69 import org.eclipse.swt.graphics.Image;
70 import org.eclipse.swt.graphics.Point;
71 import org.eclipse.ui.IEditorPart;
72 import org.eclipse.ui.IFileEditorInput;
74 // import com.quantum.ExternalInterface;
75 // import com.quantum.util.connection.NotConnectedException;
78 * Example PHP completion processor.
80 public class PHPCompletionProcessor implements IContentAssistProcessor {
82 * Simple content assist tip closer. The tip is valid in a range of 5
83 * characters around its popup location.
85 // protected static class Validator implements IContextInformationValidator,
86 // IContextInformationPresenter {
87 // protected int fInstallOffset;
90 // * @see IContextInformationValidator#isContextInformationValid(int)
92 // public boolean isContextInformationValid(int offset) {
93 // return Math.abs(fInstallOffset - offset) < 5;
97 // * @see IContextInformationValidator#install(IContextInformation,
100 // public void install(IContextInformation info, ITextViewer viewer, int
102 // fInstallOffset = offset;
107 // org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int,
110 // public boolean updatePresentation(int documentPosition, TextPresentation
115 private static class ContextInformationWrapper implements IContextInformation, IContextInformationExtension {
116 private final IContextInformation fContextInformation;
118 private int fPosition;
120 public ContextInformationWrapper(IContextInformation contextInformation) {
121 fContextInformation = contextInformation;
125 * @see IContextInformation#getContextDisplayString()
127 public String getContextDisplayString() {
128 return fContextInformation.getContextDisplayString();
132 * @see IContextInformation#getImage()
134 public Image getImage() {
135 return fContextInformation.getImage();
139 * @see IContextInformation#getInformationDisplayString()
141 public String getInformationDisplayString() {
142 return fContextInformation.getInformationDisplayString();
146 * @see IContextInformationExtension#getContextInformationPosition()
148 public int getContextInformationPosition() {
152 public void setContextInformationPosition(int position) {
153 fPosition = position;
157 private class TableName {
165 * @return Returns the tableName.
167 public String getTableName() {
168 if (fTableName == null) {
169 return "<!--no-table-->";
176 * The tableName to set.
178 public void setTableName(String tableName) {
179 fTableName = tableName;
183 private char[] fProposalAutoActivationSet;
185 protected IContextInformationValidator fValidator = null;// = new
189 private TemplateEngine fTemplateEngine;
191 private PHPCompletionProposalComparator fComparator;
193 private int fNumberOfComputedResults = 0;
195 private IEditorPart fEditor;
197 protected IWorkingCopyManager fManager;
199 public PHPCompletionProcessor(IEditorPart editor) {
201 fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager();
202 TemplateContextType contextType = PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType("php"); //$NON-NLS-1$
203 if (contextType != null)
204 fTemplateEngine = new TemplateEngine(contextType);
205 fComparator = new PHPCompletionProposalComparator();
209 * Tells this processor to order the proposals alphabetically.
212 * <code>true</code> if proposals should be ordered.
214 public void orderProposalsAlphabetically(boolean order) {
215 fComparator.setOrderAlphabetically(order);
219 * Sets this processor's set of characters triggering the activation of the
220 * completion proposal computation.
222 * @param activationSet
225 public void setCompletionProposalAutoActivationCharacters(char[] activationSet) {
226 fProposalAutoActivationSet = activationSet;
230 * (non-Javadoc) Method declared on IContentAssistProcessor
232 public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
233 int contextInformationPosition = guessContextInformationPosition(viewer, documentOffset);
234 return internalComputeCompletionProposals(viewer, documentOffset, contextInformationPosition);
237 private int getLastToken(List list, ITextViewer viewer, int completionPosition, JavaContext context, TableName tableName) {
238 IDocument document = viewer.getDocument();
239 int start = context.getStart();
240 int end = context.getEnd();
242 int lastSignificantToken = ITerminalSymbols.TokenNameEOF;
244 // begin search 2 lines behind of this
249 ch = document.getChar(j);
255 ch = document.getChar(j);
262 // scan the line for the dereferencing operator '->'
263 startText = document.get(j, start - j);
265 System.out.println(startText);
267 int token = ITerminalSymbols.TokenNameEOF;
268 // token = getLastSQLToken(startText);
269 tableName.setTableName(getLastSQLTableName(startText));
270 Scanner scanner = ToolFactory.createScanner(false, false, false);
271 scanner.setSource(startText.toCharArray());
272 scanner.setPHPMode(true);
273 int beforeLastToken = ITerminalSymbols.TokenNameEOF;
274 int lastToken = ITerminalSymbols.TokenNameEOF;
277 token = scanner.getNextToken();
279 while (token != ITerminalSymbols.TokenNameERROR && token != ITerminalSymbols.TokenNameEOF) {
280 beforeLastToken = lastToken;
281 if (token == ITerminalSymbols.TokenNameVariable) {
282 ident = scanner.getCurrentTokenSource();
283 if (ident.length == 5 && ident[0] == '$' && ident[1] == 't' && ident[2] == 'h' && ident[3] == 'i' && ident[4] == 's') {
284 token = ITerminalSymbols.TokenNamethis_PHP_COMPLETION;
288 // System.out.println(scanner.toStringAction(lastToken));
289 token = scanner.getNextToken();
291 } catch (InvalidInputException e1) {
292 } catch (SyntaxError e) {
295 case ITerminalSymbols.TokenNameMINUS_GREATER:
296 // dereferencing operator '->' found
297 lastSignificantToken = ITerminalSymbols.TokenNameMINUS_GREATER;
298 if (beforeLastToken == ITerminalSymbols.TokenNameVariable) {
299 lastSignificantToken = ITerminalSymbols.TokenNameVariable;
301 } else if (beforeLastToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION) {
302 lastSignificantToken = ITerminalSymbols.TokenNamethis_PHP_COMPLETION;
306 case ITerminalSymbols.TokenNamenew:
307 lastSignificantToken = ITerminalSymbols.TokenNamenew;
311 } catch (BadLocationException e) {
313 return lastSignificantToken;
316 String getSQLTableName(String sqlText, int start) {
317 int tableNameStart = -1;
318 int currentCharacterPosition = start + 1;
322 ch = sqlText.charAt(currentCharacterPosition++);
323 if (tableNameStart == -1 && Scanner.isPHPIdentifierStart(ch)) {
324 tableNameStart = currentCharacterPosition - 1;
326 if (!Scanner.isPHPIdentifierPart(ch)) {
327 return sqlText.substring(tableNameStart, currentCharacterPosition - 1);
331 } catch (IndexOutOfBoundsException e) {
332 if (tableNameStart >= 0) {
333 return sqlText.substring(tableNameStart, currentCharacterPosition - 1);
339 private String getLastSQLTableName(String startText) {
341 // scan for sql identifiers
343 int currentSQLPosition = startText.length();
346 boolean whiteSpace = true;
349 ch = startText.charAt(--currentSQLPosition);
350 if (Scanner.isSQLIdentifierPart(ch)) {
351 // if (ch >= 'A' && ch <= 'Z') {
353 identEnd = currentSQLPosition + 1;
355 // } else if (ch >= 'a' && ch <= 'z') {
356 // if (identEnd < 0) {
357 // identEnd = currentSQLPosition + 1;
359 } else if (identEnd >= 0) {
360 ident = startText.substring(currentSQLPosition + 1, identEnd);
361 // select -- from -- where --
362 // update -- set -- where --
363 // insert into -- ( -- ) values ( -- )
364 if (ident.length() >= 4 && ident.length() <= 6) {
365 ident = ident.toLowerCase();
366 switch (ident.length()) {
368 // if (ident.equals("set")) {
369 // // System.out.println("set");
370 // token = ITerminalSymbols.TokenNameSQLset;
375 if (ident.equals("from")) {
376 // System.out.println("from");
377 token = ITerminalSymbols.TokenNameSQLfrom;
378 return getSQLTableName(startText, identEnd);
379 } else if (ident.equals("into")) {
380 // System.out.println("into");
381 token = ITerminalSymbols.TokenNameSQLinto;
382 return getSQLTableName(startText, identEnd);
386 // if (ident.equals("where")) {
387 // // System.out.println("where");
388 // token = ITerminalSymbols.TokenNameSQLwhere;
393 // if (ident.equals("select")) {
394 // // System.out.println("select");
395 // token = ITerminalSymbols.TokenNameSQLselect;
397 // } else if (ident.equals("insert")) {
398 // // System.out.println("insert");
399 // token = ITerminalSymbols.TokenNameSQLinsert;
402 if (ident.equals("update")) {
403 // System.out.println("update");
404 token = ITerminalSymbols.TokenNameSQLupdate;
405 return getSQLTableName(startText, identEnd);
407 // else if (ident.equals("values")) {
408 // // System.out.println("values");
409 // token = ITerminalSymbols.TokenNameSQLvalues;
417 } else if (Character.isWhitespace(ch)) {
422 } catch (IndexOutOfBoundsException e) {
424 return "<!--no-table-->";
428 * Detect the last significant SQL token in the text before the completion
432 private int getLastSQLToken(String startText) {
434 // scan for sql identifiers
436 int currentSQLPosition = startText.length();
439 boolean whiteSpace = true;
442 ch = startText.charAt(--currentSQLPosition);
443 if (ch >= 'A' && ch <= 'Z') {
445 identEnd = currentSQLPosition + 1;
447 } else if (ch >= 'a' && ch <= 'z') {
449 identEnd = currentSQLPosition + 1;
451 } else if (identEnd >= 0) {
452 ident = startText.substring(currentSQLPosition + 1, identEnd);
453 // select -- from -- where --
454 // update -- set -- where --
455 // insert into -- ( -- ) values ( -- )
456 if (ident.length() >= 3 && ident.length() <= 6) {
457 ident = ident.toLowerCase();
458 switch (ident.length()) {
460 if (ident.equals("set")) {
461 // System.out.println("set");
462 token = ITerminalSymbols.TokenNameSQLset;
467 if (ident.equals("from")) {
468 // System.out.println("from");
469 token = ITerminalSymbols.TokenNameSQLfrom;
470 // getSQLTableName();
472 } else if (ident.equals("into")) {
473 // System.out.println("into");
474 token = ITerminalSymbols.TokenNameSQLinto;
479 if (ident.equals("where")) {
480 // System.out.println("where");
481 token = ITerminalSymbols.TokenNameSQLwhere;
486 if (ident.equals("select")) {
487 // System.out.println("select");
488 token = ITerminalSymbols.TokenNameSQLselect;
490 } else if (ident.equals("insert")) {
491 // System.out.println("insert");
492 token = ITerminalSymbols.TokenNameSQLinsert;
494 } else if (ident.equals("update")) {
495 // System.out.println("update");
496 token = ITerminalSymbols.TokenNameSQLupdate;
498 } else if (ident.equals("values")) {
499 // System.out.println("values");
500 token = ITerminalSymbols.TokenNameSQLvalues;
508 } else if (Character.isWhitespace(ch)) {
513 } catch (IndexOutOfBoundsException e) {
515 return ITerminalSymbols.TokenNameEOF;
518 private ICompletionProposal[] internalComputeCompletionProposals(ITextViewer viewer, int offset, int contextOffset) {
519 ICompilationUnit unit = fManager.getWorkingCopy(fEditor.getEditorInput());
520 IDocument document = viewer.getDocument();
522 IProject project = null;
524 PHPEditor editor = null;
525 if (fEditor != null && (fEditor instanceof PHPEditor)) {
526 editor = (PHPEditor) fEditor;
527 file = ((IFileEditorInput) editor.getEditorInput()).getFile();
528 project = file.getProject();
532 Point selection = viewer.getSelectedRange();
533 // remember selected text
534 String selectedText = null;
535 if (selection.y != 0) {
537 selectedText = document.get(selection.x, selection.y);
538 } catch (BadLocationException e) {
542 if (offset > 2 && fProposalAutoActivationSet != null) {
543 // restrict auto activation for '>' character to '->' token
546 char ch = document.getChar(offset-1);
548 for (int i = 0; i < fProposalAutoActivationSet.length; i++) {
549 ch = fProposalAutoActivationSet[i];
550 if (ch == '>') { // auto activation enabled
551 ch = document.getChar(offset - 2);
553 return new IPHPCompletionProposal[0];
559 } catch (BadLocationException e) {
564 JavaContextType phpContextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType(
565 "php"); //$NON-NLS-1$
566 JavaContext context = (JavaContext) phpContextType.createContext(document, offset, selection.y, unit);
567 context.setVariable("selection", selectedText); //$NON-NLS-1$
568 String prefix = context.getKey();
570 HashMap methodVariables = null;
571 // HashMap typeVariables = null;
572 HashMap unitVariables = null;
573 ICompilationUnit compilationUnit = (ICompilationUnit) context.findEnclosingElement(IJavaElement.COMPILATION_UNIT);
574 // if (compilationUnit != null) {
575 // unitVariables = ((CompilationUnit) compilationUnit).variables;
577 // IType type = (IType) context.findEnclosingElement(IJavaElement.TYPE);
578 // if (type != null) {
579 // typeVariables = ((SourceType) type).variables;
581 IMethod method = (IMethod) context.findEnclosingElement(IJavaElement.METHOD);
582 // if (method != null) {
583 // methodVariables = ((SourceMethod) method).variables;
586 boolean emptyPrefix = prefix == null || prefix.equals("");
587 IPHPCompletionProposal[] localVariableResults = new IPHPCompletionProposal[0];
589 if (!emptyPrefix && prefix.length() >= 1 && prefix.charAt(0) == '$') { // php
592 String lowerCasePrefix = prefix.toLowerCase();
593 HashSet localVariables = new HashSet();
594 if (compilationUnit != null) {
595 unitVariables = getUnitVariables(unitVariables, compilationUnit);
596 getVariableProposals(localVariables, viewer, project, context, unitVariables, lowerCasePrefix, 94);
598 if (method != null) {
599 methodVariables = getMethodVariables(methodVariables, method);
600 getVariableProposals(localVariables, viewer, project, context, methodVariables, lowerCasePrefix, 99);
602 if (!localVariables.isEmpty()) {
603 localVariableResults = (IPHPCompletionProposal[]) localVariables.toArray(new IPHPCompletionProposal[localVariables.size()]);
607 TableName sqlTable = new TableName();
608 ArrayList list = new ArrayList();
610 int lastSignificantToken = getLastToken(list, viewer, offset, context, sqlTable);
611 boolean useClassMembers = (lastSignificantToken == ITerminalSymbols.TokenNameMINUS_GREATER)
612 || (lastSignificantToken == ITerminalSymbols.TokenNameVariable) || (lastSignificantToken == ITerminalSymbols.TokenNamenew)
613 || (lastSignificantToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION);
615 if (fTemplateEngine != null) {
616 IPHPCompletionProposal[] templateResults = new IPHPCompletionProposal[0];
617 ICompletionProposal[] results;
619 fTemplateEngine.reset();
620 fTemplateEngine.complete(viewer, offset, unit);
621 templateResults = fTemplateEngine.getResults();
624 IPHPCompletionProposal[] identifierResults = new IPHPCompletionProposal[0];
626 // declarations stored in file project.index on project level
627 IPHPCompletionProposal[] declarationResults = new IPHPCompletionProposal[0];
628 if (project != null) {
629 DeclarationEngine declarationEngine;
630 JavaContextType contextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType(
631 "php"); //$NON-NLS-1$
632 if (contextType != null) {
633 IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault().getIndexManager(project);
635 declarationEngine = new DeclarationEngine(project, contextType, lastSignificantToken, file);
636 if (lastSignificantToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION) {
637 // complete '$this->'
638 sortedMap = indexManager.getIdentifiers(file);
639 declarationEngine.completeObject(viewer, offset, sortedMap, unit);
641 String typeRef = null;
642 char[] varName = (char[]) list.get(0);
643 if (varName != null) {
644 if (method != null) {
645 methodVariables = getMethodVariables(methodVariables, method);
646 VariableInfo info = (VariableInfo) methodVariables.get(new String(varName));
647 if (info != null && info.typeIdentifier != null) {
648 typeRef = new String(info.typeIdentifier);
653 if (typeRef != null) {
654 // complete '$variable->' with type information
655 sortedMap = indexManager.getIdentifiers(typeRef);
656 declarationEngine.completeObject(viewer, offset, sortedMap, unit);
658 // complete '$variable->' without type information
659 sortedMap = indexManager.getIdentifierMap();
660 declarationEngine.complete(viewer, offset, sortedMap, unit);
663 declarationResults = declarationEngine.getResults();
666 // built in function names from phpsyntax.xml
667 ArrayList syntaxbuffer = PHPSyntaxRdr.getSyntaxData();
668 IPHPCompletionProposal[] builtinResults = new IPHPCompletionProposal[0];
669 if ((!useClassMembers) && syntaxbuffer != null) {
670 BuiltInEngine builtinEngine;
672 JavaContextType contextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType(
673 "php"); //$NON-NLS-1$
674 if (contextType != null) {
675 builtinEngine = new BuiltInEngine(contextType);
676 builtinEngine.complete(viewer, offset, syntaxbuffer, unit);
677 builtinResults = builtinEngine.getResults();
680 // ICompletionProposal[] sqlResults = new ICompletionProposal[0];
681 // if (project != null) {
682 // sqlResults = getSQLProposals(viewer, project, context, prefix,
685 // concatenate the result arrays
686 IPHPCompletionProposal[] total;
687 total = new IPHPCompletionProposal[localVariableResults.length + templateResults.length + identifierResults.length
688 + builtinResults.length + declarationResults.length];// +
689 // sqlResults.length];
690 System.arraycopy(templateResults, 0, total, 0, templateResults.length);
691 System.arraycopy(identifierResults, 0, total, templateResults.length, identifierResults.length);
692 System.arraycopy(builtinResults, 0, total, templateResults.length + identifierResults.length, builtinResults.length);
693 System.arraycopy(declarationResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length,
694 declarationResults.length);
695 // System.arraycopy(sqlResults, 0, total, templateResults.length +
696 // identifierResults.length + builtinResults.length
697 // + declarationResults.length, sqlResults.length);
698 // System.arraycopy(localVariableResults, 0, total, templateResults.length
699 // + identifierResults.length + builtinResults.length
700 // + declarationResults.length + sqlResults.length,
701 // localVariableResults.length);
702 System.arraycopy(localVariableResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length
703 + declarationResults.length, localVariableResults.length);
705 fNumberOfComputedResults = (results == null ? 0 : results.length);
707 * Order here and not in result collector to make sure that the order
708 * applies to all proposals and not just those of the compilation unit.
710 return order(results);
712 return new IPHPCompletionProposal[0];
716 * @param unitVariables
719 private HashMap getUnitVariables(HashMap unitVariables, ICompilationUnit unit) {
720 if (unitVariables == null) {
722 String unitText = unit.getSource();
723 unitVariables = new HashMap();
725 ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.exitAfterAllProblems(),
726 new CompilerOptions(JavaCore.getOptions()), new DefaultProblemFactory());
727 UnitParser parser = new UnitParser(problemReporter);
728 parser.compilationUnit = new CompilationUnitDeclaration(problemReporter, null, unitText.length());
729 parser.parse(unitText, unitVariables);
731 } catch (Exception e) {
732 // TODO Auto-generated catch block
734 PHPeclipsePlugin.log(e);
737 return unitVariables;
741 * @param methodVariables
744 private HashMap getMethodVariables(HashMap methodVariables, IMethod method) {
745 if (methodVariables == null) {
747 String methodText = method.getSource();
748 methodVariables = new HashMap();
749 ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.exitAfterAllProblems(),
750 new CompilerOptions(JavaCore.getOptions()), new DefaultProblemFactory());
751 UnitParser parser = new UnitParser(problemReporter);
752 parser.compilationUnit = new CompilationUnitDeclaration(problemReporter, null, methodText.length());
753 parser.parseFunction(methodText, methodVariables);
754 } catch (Exception e) {
755 // TODO Auto-generated catch block
757 PHPeclipsePlugin.log(e);
760 return methodVariables;
770 private void getVariableProposals(HashSet localVariables, ITextViewer viewer, IProject project, JavaContext context,
771 HashMap variables, String prefix, int relevance) {
773 int start = context.getStart();
774 int end = context.getEnd();
775 IRegion region = new Region(start, end - start);
776 // IMethod method = (IMethod)
777 // context.findEnclosingElement(IJavaElement.METHOD);
778 // if (method != null && (method instanceof SourceMethod) && ((SourceMethod)
779 // method).variables != null) {
780 // HashMap map = ((SourceMethod) method).variables;
781 Set set = variables.keySet();
782 Iterator iter = set.iterator();
784 boolean matchesVarName;
785 while (iter.hasNext()) {
786 varName = (String) iter.next();
787 if (varName.length() >= prefix.length()) {
788 matchesVarName = true;
789 for (int i = 0; i < prefix.length(); i++) {
790 if (prefix.charAt(i) != Character.toLowerCase(varName.charAt(i))) {
791 matchesVarName = false;
795 if (matchesVarName) {
796 LocalVariableProposal prop;
797 // if (varName.length == prefix.length()) {
798 // prop = new LocalVariableProposal(new String(varName), region,
799 // viewer, relevance-10);
801 prop = new LocalVariableProposal(new String(varName), region, viewer, relevance);
803 localVariables.add(prop);
810 // boolean matchesVarName;
811 // if (method != null) {
812 // ISourceRange range = method.getSourceRange();
813 // char[] source = method.getSource().toCharArray();
814 // Scanner scanner = new Scanner();
815 // scanner.setSource(source);
816 // scanner.phpMode = true;
817 // int token = Scanner.TokenNameWHITESPACE;
818 // while ((token = scanner.getNextToken()) != Scanner.TokenNameEOF) {
819 // if (token == Scanner.TokenNameVariable) {
820 // varName = scanner.getCurrentTokenSource();
821 // if (varName.length >= prefix.length()) {
822 // matchesVarName = true;
823 // for (int i = 0; i < prefix.length(); i++) {
824 // if (prefix.charAt(i) != varName[i]) {
825 // matchesVarName = false;
829 // if (matchesVarName) {
830 // LocalVariableProposal prop = new LocalVariableProposal(new
831 // String(varName), region, viewer);
832 // if (varName.length == prefix.length()) {
833 // prop.setRelevance(98);
835 // localVariables.add(prop);
841 // } catch (Throwable e) {
842 // // ignore - Syntax exceptions could occur, if there are syntax errors !
855 // private ICompletionProposal[] getSQLProposals(ITextViewer viewer, IProject
856 // project, DocumentTemplateContext context,
857 // String prefix, TableName sqlTable) {
858 // ICompletionProposal[] sqlResults = new ICompletionProposal[0];
859 // // Get The Database bookmark from the Quantum SQL plugin:
860 // // BookmarkCollection sqlBookMarks = BookmarkCollection.getInstance();
861 // // if (sqlBookMarks != null) {
862 // String bookmarkString =
863 // ProjectPrefUtil.getMiscProjectsPreferenceValue(project,
864 // IPreferenceConstants.PHP_BOOKMARK_DEFAULT);
865 // if (bookmarkString != null && !bookmarkString.equals("")) {
866 // String[] bookmarks = ExternalInterface.getBookmarkNames();
867 // boolean foundBookmark = false;
868 // for (int i = 0; i < bookmarks.length; i++) {
869 // if (bookmarks[i].equals(bookmarkString)) {
870 // foundBookmark = true;
873 // if (!foundBookmark) {
874 // return sqlResults;
876 // // Bookmark bookmark = sqlBookMarks.find(bookmarkString);
877 // ArrayList sqlList = new ArrayList();
878 // if (!ExternalInterface.isBookmarkConnected(bookmarkString)) {
879 // ExternalInterface.connectBookmark(bookmarkString, null);
880 // if (!ExternalInterface.isBookmarkConnected(bookmarkString)) {
881 // return sqlResults;
884 // // if (ExternalInterface.isBookmarkConnected(bookmarkString)) {
886 // int start = context.getStart();
887 // int end = context.getEnd();
888 // String foundSQLTableName = sqlTable.getTableName();
890 // String columnName;
891 // String prefixWithoutDollar = prefix;
892 // boolean isDollarPrefix = false;
893 // if (prefix.length() > 0 && prefix.charAt(0) == '$') {
894 // prefixWithoutDollar = prefix.substring(1);
895 // isDollarPrefix = true;
897 // IRegion region = new Region(start, end - start);
899 // if (!isDollarPrefix) {
900 // String[] tableNames = ExternalInterface.getMatchingTableNames(null,
901 // bookmarkString, prefixWithoutDollar, null, false);
902 // for (int i = 0; i < tableNames.length; i++) {
903 // sqlList.add(new SQLProposal(tableNames[i], context, region, viewer,
904 // PHPUiImages.get(PHPUiImages.IMG_TABLE)));
908 // String[] columnNames = ExternalInterface.getMatchingColumnNames(null,
909 // bookmarkString, prefixWithoutDollar, null, false);
910 // for (int i = 0; i < columnNames.length; i++) {
911 // sqlList.add(new SQLProposal(columnNames[i], context, region, viewer,
912 // PHPUiImages.get(PHPUiImages.IMG_TABLE)));
915 // sqlResults = new IPHPCompletionProposal[sqlList.size()];
916 // for (int i = 0; i < sqlList.size(); i++) {
917 // sqlResults[i] = (SQLProposal) sqlList.get(i);
919 // } catch (Exception /* NotConnectedException */ e) {
925 // return sqlResults;
927 private boolean looksLikeMethod(PHPCodeReader reader) throws IOException {
928 int curr = reader.read();
929 while (curr != PHPCodeReader.EOF && Character.isWhitespace((char) curr))
930 curr = reader.read();
932 if (curr == PHPCodeReader.EOF)
935 return Scanner.isPHPIdentifierPart((char) curr);
938 private int guessContextInformationPosition(ITextViewer viewer, int offset) {
939 int contextPosition = offset;
940 IDocument document = viewer.getDocument();
943 PHPCodeReader reader = new PHPCodeReader();
944 reader.configureBackwardReader(document, offset, true, true);
946 int nestingLevel = 0;
948 int curr = reader.read();
949 while (curr != PHPCodeReader.EOF) {
951 if (')' == (char) curr)
954 else if ('(' == (char) curr) {
957 if (nestingLevel < 0) {
958 int start = reader.getOffset();
959 if (looksLikeMethod(reader))
964 curr = reader.read();
966 } catch (IOException e) {
968 return contextPosition;
972 * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
974 public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
975 int contextInformationPosition = guessContextInformationPosition(viewer, offset);
976 List result = addContextInformations(viewer, contextInformationPosition);
977 return (IContextInformation[]) result.toArray(new IContextInformation[result.size()]);
980 private List addContextInformations(ITextViewer viewer, int offset) {
981 ICompletionProposal[] proposals = internalComputeCompletionProposals(viewer, offset, -1);
982 List result = new ArrayList();
983 for (int i = 0; i < proposals.length; i++) {
984 IContextInformation contextInformation = proposals[i].getContextInformation();
985 if (contextInformation != null) {
986 ContextInformationWrapper wrapper = new ContextInformationWrapper(contextInformation);
987 wrapper.setContextInformationPosition(offset);
995 * Order the given proposals.
997 private ICompletionProposal[] order(ICompletionProposal[] proposals) {
998 Arrays.sort(proposals, fComparator);
999 // int len = proposals.length;
1003 // for (int i = 0; i < len; i++) {
1004 // System.out.println(proposals[i].getDisplayString());
1010 * (non-Javadoc) Method declared on IContentAssistProcessor
1012 public char[] getCompletionProposalAutoActivationCharacters() {
1013 return fProposalAutoActivationSet;
1014 // return null; // new char[] { '$' };
1018 * (non-Javadoc) Method declared on IContentAssistProcessor
1020 public char[] getContextInformationAutoActivationCharacters() {
1025 * (non-Javadoc) Method declared on IContentAssistProcessor
1027 public IContextInformationValidator getContextInformationValidator() {
1028 if (fValidator == null)
1029 fValidator = new JavaParameterListValidator();
1034 * (non-Javadoc) Method declared on IContentAssistProcessor
1036 public String getErrorMessage() {