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.sql.ResultSet;
15 import java.util.ArrayList;
16 import java.util.Arrays;
17 import java.util.HashMap;
18 import java.util.HashSet;
19 import java.util.Iterator;
20 import java.util.List;
22 import java.util.SortedMap;
24 import net.sourceforge.phpdt.core.ICompilationUnit;
25 import net.sourceforge.phpdt.core.IJavaElement;
26 import net.sourceforge.phpdt.core.IMethod;
27 import net.sourceforge.phpdt.core.IType;
28 import net.sourceforge.phpdt.core.JavaCore;
29 import net.sourceforge.phpdt.core.ToolFactory;
30 import net.sourceforge.phpdt.core.compiler.ITerminalSymbols;
31 import net.sourceforge.phpdt.core.compiler.InvalidInputException;
32 import net.sourceforge.phpdt.internal.compiler.DefaultErrorHandlingPolicies;
33 import net.sourceforge.phpdt.internal.compiler.impl.CompilerOptions;
34 import net.sourceforge.phpdt.internal.compiler.parser.Scanner;
35 import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError;
36 import net.sourceforge.phpdt.internal.compiler.parser.UnitParser;
37 import net.sourceforge.phpdt.internal.compiler.parser.VariableInfo;
38 import net.sourceforge.phpdt.internal.compiler.problem.DefaultProblemFactory;
39 import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter;
40 import net.sourceforge.phpdt.internal.corext.template.php.JavaContext;
41 import net.sourceforge.phpdt.internal.corext.template.php.JavaContextType;
42 import net.sourceforge.phpdt.internal.ui.PHPUiImages;
43 import net.sourceforge.phpdt.internal.ui.text.PHPCodeReader;
44 import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal;
45 import net.sourceforge.phpdt.internal.ui.text.java.PHPCompletionProposalComparator;
46 import net.sourceforge.phpdt.internal.ui.text.template.BuiltInEngine;
47 import net.sourceforge.phpdt.internal.ui.text.template.DeclarationEngine;
48 import net.sourceforge.phpdt.internal.ui.text.template.LocalVariableProposal;
49 import net.sourceforge.phpdt.internal.ui.text.template.SQLProposal;
50 import net.sourceforge.phpdt.internal.ui.text.template.contentassist.TemplateEngine;
51 import net.sourceforge.phpdt.ui.IWorkingCopyManager;
52 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
53 import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
54 import net.sourceforge.phpeclipse.internal.compiler.ast.CompilationUnitDeclaration;
55 import net.sourceforge.phpeclipse.phpeditor.PHPEditor;
56 import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr;
57 import net.sourceforge.phpeclipse.ui.IPreferenceConstants;
58 import net.sourceforge.phpeclipse.ui.overlaypages.ProjectPrefUtil;
60 import org.eclipse.core.resources.IFile;
61 import org.eclipse.core.resources.IProject;
62 import org.eclipse.jface.text.BadLocationException;
63 import org.eclipse.jface.text.IDocument;
64 import org.eclipse.jface.text.IRegion;
65 import org.eclipse.jface.text.ITextViewer;
66 import org.eclipse.jface.text.Region;
67 import org.eclipse.jface.text.TextPresentation;
68 import org.eclipse.jface.text.contentassist.ICompletionProposal;
69 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
70 import org.eclipse.jface.text.contentassist.IContextInformation;
71 import org.eclipse.jface.text.contentassist.IContextInformationExtension;
72 import org.eclipse.jface.text.contentassist.IContextInformationPresenter;
73 import org.eclipse.jface.text.contentassist.IContextInformationValidator;
74 import org.eclipse.jface.text.templates.DocumentTemplateContext;
75 import org.eclipse.jface.text.templates.TemplateContextType;
76 import org.eclipse.swt.graphics.Image;
77 import org.eclipse.swt.graphics.Point;
78 import org.eclipse.ui.IEditorPart;
79 import org.eclipse.ui.IFileEditorInput;
81 //import com.quantum.ExternalInterface;
82 // import com.quantum.util.connection.NotConnectedException;
85 * Example PHP completion processor.
87 public class PHPCompletionProcessor implements IContentAssistProcessor {
89 * Simple content assist tip closer. The tip is valid in a range of 5 characters around its popup location.
91 protected static class Validator implements IContextInformationValidator, IContextInformationPresenter {
92 protected int fInstallOffset;
95 * @see IContextInformationValidator#isContextInformationValid(int)
97 public boolean isContextInformationValid(int offset) {
98 return Math.abs(fInstallOffset - offset) < 5;
102 * @see IContextInformationValidator#install(IContextInformation, ITextViewer, int)
104 public void install(IContextInformation info, ITextViewer viewer, int offset) {
105 fInstallOffset = offset;
109 * @see org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int, TextPresentation)
111 public boolean updatePresentation(int documentPosition, TextPresentation presentation) {
116 private static class ContextInformationWrapper implements IContextInformation, IContextInformationExtension {
117 private final IContextInformation fContextInformation;
119 private int fPosition;
121 public ContextInformationWrapper(IContextInformation contextInformation) {
122 fContextInformation = contextInformation;
126 * @see IContextInformation#getContextDisplayString()
128 public String getContextDisplayString() {
129 return fContextInformation.getContextDisplayString();
133 * @see IContextInformation#getImage()
135 public Image getImage() {
136 return fContextInformation.getImage();
140 * @see IContextInformation#getInformationDisplayString()
142 public String getInformationDisplayString() {
143 return fContextInformation.getInformationDisplayString();
147 * @see IContextInformationExtension#getContextInformationPosition()
149 public int getContextInformationPosition() {
153 public void setContextInformationPosition(int position) {
154 fPosition = position;
158 private class TableName {
166 * @return Returns the tableName.
168 public String getTableName() {
169 if (fTableName == null) {
170 return "<!--no-table-->";
177 * The tableName to set.
179 public void setTableName(String tableName) {
180 fTableName = tableName;
184 private char[] fProposalAutoActivationSet;
186 protected IContextInformationValidator fValidator = new Validator();
188 private TemplateEngine fTemplateEngine;
190 private PHPCompletionProposalComparator fComparator;
192 private int fNumberOfComputedResults = 0;
194 private IEditorPart fEditor;
196 protected IWorkingCopyManager fManager;
198 public PHPCompletionProcessor(IEditorPart editor) {
200 fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager();
201 TemplateContextType contextType = PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType("php"); //$NON-NLS-1$
202 if (contextType != null)
203 fTemplateEngine = new TemplateEngine(contextType);
204 fComparator = new PHPCompletionProposalComparator();
208 * Tells this processor to order the proposals alphabetically.
211 * <code>true</code> if proposals should be ordered.
213 public void orderProposalsAlphabetically(boolean order) {
214 fComparator.setOrderAlphabetically(order);
218 * Sets this processor's set of characters triggering the activation of the completion proposal computation.
220 * @param activationSet
223 public void setCompletionProposalAutoActivationCharacters(char[] activationSet) {
224 fProposalAutoActivationSet = activationSet;
228 * (non-Javadoc) Method declared on IContentAssistProcessor
230 public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
231 int contextInformationPosition = guessContextInformationPosition(viewer, documentOffset);
232 return internalComputeCompletionProposals(viewer, documentOffset, contextInformationPosition);
235 private int getLastToken(List list, ITextViewer viewer, int completionPosition, JavaContext context, TableName tableName) {
236 IDocument document = viewer.getDocument();
237 int start = context.getStart();
238 int end = context.getEnd();
240 int lastSignificantToken = ITerminalSymbols.TokenNameEOF;
242 // begin search 2 lines behind of this
247 ch = document.getChar(j);
253 ch = document.getChar(j);
260 // scan the line for the dereferencing operator '->'
261 startText = document.get(j, start - j);
263 System.out.println(startText);
265 int token = ITerminalSymbols.TokenNameEOF;
266 // token = getLastSQLToken(startText);
267 tableName.setTableName(getLastSQLTableName(startText));
268 Scanner scanner = ToolFactory.createScanner(false, false, false);
269 scanner.setSource(startText.toCharArray());
270 scanner.setPHPMode(true);
271 int beforeLastToken = ITerminalSymbols.TokenNameEOF;
272 int lastToken = ITerminalSymbols.TokenNameEOF;
275 token = scanner.getNextToken();
277 while (token != ITerminalSymbols.TokenNameERROR && token != ITerminalSymbols.TokenNameEOF) {
278 beforeLastToken = lastToken;
279 if (token == ITerminalSymbols.TokenNameVariable) {
280 ident = scanner.getCurrentTokenSource();
281 if (ident.length == 5 && ident[0] == '$' && ident[1] == 't' && ident[2] == 'h' && ident[3] == 'i' && ident[4] == 's') {
282 token = ITerminalSymbols.TokenNamethis_PHP_COMPLETION;
286 // System.out.println(scanner.toStringAction(lastToken));
287 token = scanner.getNextToken();
289 } catch (InvalidInputException e1) {
290 } catch (SyntaxError e) {
293 case ITerminalSymbols.TokenNameMINUS_GREATER:
294 // dereferencing operator '->' found
295 lastSignificantToken = ITerminalSymbols.TokenNameMINUS_GREATER;
296 if (beforeLastToken == ITerminalSymbols.TokenNameVariable) {
297 lastSignificantToken = ITerminalSymbols.TokenNameVariable;
299 } else if (beforeLastToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION) {
300 lastSignificantToken = ITerminalSymbols.TokenNamethis_PHP_COMPLETION;
304 case ITerminalSymbols.TokenNamenew:
305 lastSignificantToken = ITerminalSymbols.TokenNamenew;
309 } catch (BadLocationException e) {
311 return lastSignificantToken;
314 String getSQLTableName(String sqlText, int start) {
315 int tableNameStart = -1;
316 int currentCharacterPosition = start + 1;
320 ch = sqlText.charAt(currentCharacterPosition++);
321 if (tableNameStart == -1 && Scanner.isPHPIdentifierStart(ch)) {
322 tableNameStart = currentCharacterPosition - 1;
324 if (!Scanner.isPHPIdentifierPart(ch)) {
325 return sqlText.substring(tableNameStart, currentCharacterPosition - 1);
329 } catch (IndexOutOfBoundsException e) {
330 if (tableNameStart >= 0) {
331 return sqlText.substring(tableNameStart, currentCharacterPosition - 1);
337 private String getLastSQLTableName(String startText) {
339 // scan for sql identifiers
341 int currentSQLPosition = startText.length();
344 boolean whiteSpace = true;
347 ch = startText.charAt(--currentSQLPosition);
348 if (ch >= 'A' && ch <= 'Z') {
350 identEnd = currentSQLPosition + 1;
352 } else if (ch >= 'a' && ch <= 'z') {
354 identEnd = currentSQLPosition + 1;
356 } else if (identEnd >= 0) {
357 ident = startText.substring(currentSQLPosition + 1, identEnd);
358 // select -- from -- where --
359 // update -- set -- where --
360 // insert into -- ( -- ) values ( -- )
361 if (ident.length() >= 4 && ident.length() <= 6) {
362 ident = ident.toLowerCase();
363 switch (ident.length()) {
365 // if (ident.equals("set")) {
366 // // System.out.println("set");
367 // token = ITerminalSymbols.TokenNameSQLset;
372 if (ident.equals("from")) {
373 // System.out.println("from");
374 token = ITerminalSymbols.TokenNameSQLfrom;
375 return getSQLTableName(startText, identEnd);
376 } else if (ident.equals("into")) {
377 // System.out.println("into");
378 token = ITerminalSymbols.TokenNameSQLinto;
379 return getSQLTableName(startText, identEnd);
383 // if (ident.equals("where")) {
384 // // System.out.println("where");
385 // token = ITerminalSymbols.TokenNameSQLwhere;
390 // if (ident.equals("select")) {
391 // // System.out.println("select");
392 // token = ITerminalSymbols.TokenNameSQLselect;
394 // } else if (ident.equals("insert")) {
395 // // System.out.println("insert");
396 // token = ITerminalSymbols.TokenNameSQLinsert;
399 if (ident.equals("update")) {
400 // System.out.println("update");
401 token = ITerminalSymbols.TokenNameSQLupdate;
402 return getSQLTableName(startText, identEnd);
404 // else if (ident.equals("values")) {
405 // // System.out.println("values");
406 // token = ITerminalSymbols.TokenNameSQLvalues;
414 } else if (Character.isWhitespace(ch)) {
419 } catch (IndexOutOfBoundsException e) {
421 return "<!--no-table-->";
425 * Detect the last significant SQL token in the text before the completion
429 private int getLastSQLToken(String startText) {
431 // scan for sql identifiers
433 int currentSQLPosition = startText.length();
436 boolean whiteSpace = true;
439 ch = startText.charAt(--currentSQLPosition);
440 if (ch >= 'A' && ch <= 'Z') {
442 identEnd = currentSQLPosition + 1;
444 } else if (ch >= 'a' && ch <= 'z') {
446 identEnd = currentSQLPosition + 1;
448 } else if (identEnd >= 0) {
449 ident = startText.substring(currentSQLPosition + 1, identEnd);
450 // select -- from -- where --
451 // update -- set -- where --
452 // insert into -- ( -- ) values ( -- )
453 if (ident.length() >= 3 && ident.length() <= 6) {
454 ident = ident.toLowerCase();
455 switch (ident.length()) {
457 if (ident.equals("set")) {
458 // System.out.println("set");
459 token = ITerminalSymbols.TokenNameSQLset;
464 if (ident.equals("from")) {
465 // System.out.println("from");
466 token = ITerminalSymbols.TokenNameSQLfrom;
469 } else if (ident.equals("into")) {
470 // System.out.println("into");
471 token = ITerminalSymbols.TokenNameSQLinto;
476 if (ident.equals("where")) {
477 // System.out.println("where");
478 token = ITerminalSymbols.TokenNameSQLwhere;
483 if (ident.equals("select")) {
484 // System.out.println("select");
485 token = ITerminalSymbols.TokenNameSQLselect;
487 } else if (ident.equals("insert")) {
488 // System.out.println("insert");
489 token = ITerminalSymbols.TokenNameSQLinsert;
491 } else if (ident.equals("update")) {
492 // System.out.println("update");
493 token = ITerminalSymbols.TokenNameSQLupdate;
495 } else if (ident.equals("values")) {
496 // System.out.println("values");
497 token = ITerminalSymbols.TokenNameSQLvalues;
505 } else if (Character.isWhitespace(ch)) {
510 } catch (IndexOutOfBoundsException e) {
512 return ITerminalSymbols.TokenNameEOF;
515 private ICompletionProposal[] internalComputeCompletionProposals(ITextViewer viewer, int offset, int contextOffset) {
516 ICompilationUnit unit = fManager.getWorkingCopy(fEditor.getEditorInput());
517 IDocument document = viewer.getDocument();
519 IProject project = null;
521 PHPEditor editor = null;
522 if (fEditor != null && (fEditor instanceof PHPEditor)) {
523 editor = (PHPEditor) fEditor;
524 file = ((IFileEditorInput) editor.getEditorInput()).getFile();
525 project = file.getProject();
529 Point selection = viewer.getSelectedRange();
530 // remember selected text
531 String selectedText = null;
532 if (selection.y != 0) {
534 selectedText = document.get(selection.x, selection.y);
535 } catch (BadLocationException e) {
539 JavaContextType phpContextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType(
540 "php"); //$NON-NLS-1$
541 JavaContext context = (JavaContext) phpContextType.createContext(document, offset, selection.y, unit);
542 context.setVariable("selection", selectedText); //$NON-NLS-1$
543 String prefix = context.getKey();
545 HashMap methodVariables = null;
546 HashMap typeVariables = null;
547 HashMap unitVariables = null;
548 ICompilationUnit compilationUnit = (ICompilationUnit) context.findEnclosingElement(IJavaElement.COMPILATION_UNIT);
549 // if (compilationUnit != null) {
550 // unitVariables = ((CompilationUnit) compilationUnit).variables;
552 IType type = (IType) context.findEnclosingElement(IJavaElement.TYPE);
553 // if (type != null) {
554 // typeVariables = ((SourceType) type).variables;
556 IMethod method = (IMethod) context.findEnclosingElement(IJavaElement.METHOD);
557 // if (method != null) {
558 // methodVariables = ((SourceMethod) method).variables;
561 boolean emptyPrefix = prefix == null || prefix.equals("");
562 IPHPCompletionProposal[] localVariableResults = new IPHPCompletionProposal[0];
564 if (!emptyPrefix && prefix.length() >= 1 && prefix.charAt(0) == '$') { // php Variable ?
565 String lowerCasePrefix = prefix.toLowerCase();
566 HashSet localVariables = new HashSet();
567 if (compilationUnit != null) {
568 unitVariables = getUnitVariables(unitVariables, compilationUnit);
569 getVariableProposals(localVariables, viewer, project, context, unitVariables, lowerCasePrefix, 94);
571 if (method != null) {
572 methodVariables = getMethodVariables(methodVariables, method);
573 getVariableProposals(localVariables, viewer, project, context, methodVariables, lowerCasePrefix, 99);
575 if (!localVariables.isEmpty()) {
576 localVariableResults = (IPHPCompletionProposal[]) localVariables.toArray(new IPHPCompletionProposal[localVariables.size()]);
580 TableName sqlTable = new TableName();
581 ArrayList list = new ArrayList();
583 int lastSignificantToken = getLastToken(list, viewer, offset, context, sqlTable);
584 boolean useClassMembers = (lastSignificantToken == ITerminalSymbols.TokenNameMINUS_GREATER)
585 || (lastSignificantToken == ITerminalSymbols.TokenNameVariable) || (lastSignificantToken == ITerminalSymbols.TokenNamenew)
586 || (lastSignificantToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION);
588 if (fTemplateEngine != null) {
589 IPHPCompletionProposal[] templateResults = new IPHPCompletionProposal[0];
590 ICompletionProposal[] results;
592 fTemplateEngine.reset();
593 fTemplateEngine.complete(viewer, offset, unit);
594 templateResults = fTemplateEngine.getResults();
597 IPHPCompletionProposal[] identifierResults = new IPHPCompletionProposal[0];
599 // declarations stored in file project.index on project level
600 IPHPCompletionProposal[] declarationResults = new IPHPCompletionProposal[0];
601 if (project != null) {
602 DeclarationEngine declarationEngine;
603 JavaContextType contextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType(
604 "php"); //$NON-NLS-1$
605 if (contextType != null) {
606 IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault().getIndexManager(project);
608 declarationEngine = new DeclarationEngine(project, contextType, lastSignificantToken, file);
609 if (lastSignificantToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION) {
610 // complete '$this->'
611 sortedMap = indexManager.getIdentifiers(file);
612 declarationEngine.completeObject(viewer, offset, sortedMap, unit);
614 String typeRef = null;
615 char[] varName = (char[]) list.get(0);
616 if (varName != null) {
617 if (method != null) {
618 methodVariables = getMethodVariables(methodVariables, method);
619 VariableInfo info = (VariableInfo) methodVariables.get(new String(varName));
620 if (info != null && info.typeIdentifier != null) {
621 typeRef = new String(info.typeIdentifier);
626 if (typeRef != null) {
627 // complete '$variable->' with type information
628 sortedMap = indexManager.getIdentifiers(typeRef);
629 declarationEngine.completeObject(viewer, offset, sortedMap, unit);
631 // complete '$variable->' without type information
632 sortedMap = indexManager.getIdentifierMap();
633 declarationEngine.complete(viewer, offset, sortedMap, unit);
636 declarationResults = declarationEngine.getResults();
639 // built in function names from phpsyntax.xml
640 ArrayList syntaxbuffer = PHPSyntaxRdr.getSyntaxData();
641 IPHPCompletionProposal[] builtinResults = new IPHPCompletionProposal[0];
642 if ((!useClassMembers) && syntaxbuffer != null) {
643 BuiltInEngine builtinEngine;
645 JavaContextType contextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType(
646 "php"); //$NON-NLS-1$
647 if (contextType != null) {
648 builtinEngine = new BuiltInEngine(contextType);
649 builtinEngine.complete(viewer, offset, syntaxbuffer, unit);
650 builtinResults = builtinEngine.getResults();
653 // ICompletionProposal[] sqlResults = new ICompletionProposal[0];
654 // if (project != null) {
655 // sqlResults = getSQLProposals(viewer, project, context, prefix, sqlTable);
657 // concatenate the result arrays
658 IPHPCompletionProposal[] total;
659 total = new IPHPCompletionProposal[localVariableResults.length + templateResults.length + identifierResults.length
660 + builtinResults.length + declarationResults.length];// + sqlResults.length];
661 System.arraycopy(templateResults, 0, total, 0, templateResults.length);
662 System.arraycopy(identifierResults, 0, total, templateResults.length, identifierResults.length);
663 System.arraycopy(builtinResults, 0, total, templateResults.length + identifierResults.length, builtinResults.length);
664 System.arraycopy(declarationResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length,
665 declarationResults.length);
666 // System.arraycopy(sqlResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length
667 // + declarationResults.length, sqlResults.length);
668 // System.arraycopy(localVariableResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length
669 // + declarationResults.length + sqlResults.length, localVariableResults.length);
670 System.arraycopy(localVariableResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length
671 + declarationResults.length, localVariableResults.length);
673 fNumberOfComputedResults = (results == null ? 0 : results.length);
675 * Order here and not in result collector to make sure that the order applies to all proposals and not just those of the
678 return order(results);
680 return new IPHPCompletionProposal[0];
684 * @param unitVariables
687 private HashMap getUnitVariables(HashMap unitVariables, ICompilationUnit unit) {
688 if (unitVariables == null) {
690 String unitText = unit.getSource();
691 unitVariables = new HashMap();
693 ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.exitAfterAllProblems(),
694 new CompilerOptions(JavaCore.getOptions()), new DefaultProblemFactory());
695 UnitParser parser = new UnitParser(problemReporter);
696 parser.compilationUnit = new CompilationUnitDeclaration(problemReporter, null, unitText.length());
697 parser.parse(unitText, unitVariables);
699 } catch (Exception e) {
700 // TODO Auto-generated catch block
702 PHPeclipsePlugin.log(e);
705 return unitVariables;
709 * @param methodVariables
712 private HashMap getMethodVariables(HashMap methodVariables, IMethod method) {
713 if (methodVariables == null) {
715 String methodText = method.getSource();
716 methodVariables = new HashMap();
717 ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.exitAfterAllProblems(),
718 new CompilerOptions(JavaCore.getOptions()), new DefaultProblemFactory());
719 UnitParser parser = new UnitParser(problemReporter);
720 parser.compilationUnit = new CompilationUnitDeclaration(problemReporter, null, methodText.length());
721 parser.parseFunction(methodText, methodVariables);
722 } catch (Exception e) {
723 // TODO Auto-generated catch block
725 PHPeclipsePlugin.log(e);
728 return methodVariables;
738 private void getVariableProposals(HashSet localVariables, ITextViewer viewer, IProject project, JavaContext context,
739 HashMap variables, String prefix, int relevance) {
741 int start = context.getStart();
742 int end = context.getEnd();
743 IRegion region = new Region(start, end - start);
744 // IMethod method = (IMethod) context.findEnclosingElement(IJavaElement.METHOD);
745 // if (method != null && (method instanceof SourceMethod) && ((SourceMethod) method).variables != null) {
746 // HashMap map = ((SourceMethod) method).variables;
747 Set set = variables.keySet();
748 Iterator iter = set.iterator();
750 boolean matchesVarName;
751 while (iter.hasNext()) {
752 varName = (String) iter.next();
753 if (varName.length() >= prefix.length()) {
754 matchesVarName = true;
755 for (int i = 0; i < prefix.length(); i++) {
756 if (prefix.charAt(i) != Character.toLowerCase(varName.charAt(i))) {
757 matchesVarName = false;
761 if (matchesVarName) {
762 LocalVariableProposal prop;
763 // if (varName.length == prefix.length()) {
764 // prop = new LocalVariableProposal(new String(varName), region, viewer, relevance-10);
766 prop = new LocalVariableProposal(new String(varName), region, viewer, relevance);
768 localVariables.add(prop);
775 // boolean matchesVarName;
776 // if (method != null) {
777 // ISourceRange range = method.getSourceRange();
778 // char[] source = method.getSource().toCharArray();
779 // Scanner scanner = new Scanner();
780 // scanner.setSource(source);
781 // scanner.phpMode = true;
782 // int token = Scanner.TokenNameWHITESPACE;
783 // while ((token = scanner.getNextToken()) != Scanner.TokenNameEOF) {
784 // if (token == Scanner.TokenNameVariable) {
785 // varName = scanner.getCurrentTokenSource();
786 // if (varName.length >= prefix.length()) {
787 // matchesVarName = true;
788 // for (int i = 0; i < prefix.length(); i++) {
789 // if (prefix.charAt(i) != varName[i]) {
790 // matchesVarName = false;
794 // if (matchesVarName) {
795 // LocalVariableProposal prop = new LocalVariableProposal(new String(varName), region, viewer);
796 // if (varName.length == prefix.length()) {
797 // prop.setRelevance(98);
799 // localVariables.add(prop);
805 // } catch (Throwable e) {
806 // // ignore - Syntax exceptions could occur, if there are syntax errors !
819 // private ICompletionProposal[] getSQLProposals(ITextViewer viewer, IProject project, DocumentTemplateContext context,
820 // String prefix, TableName sqlTable) {
821 // ICompletionProposal[] sqlResults = new ICompletionProposal[0];
822 // // Get The Database bookmark from the Quantum SQL plugin:
823 // // BookmarkCollection sqlBookMarks = BookmarkCollection.getInstance();
824 // // if (sqlBookMarks != null) {
825 // String bookmarkString = ProjectPrefUtil.getMiscProjectsPreferenceValue(project, IPreferenceConstants.PHP_BOOKMARK_DEFAULT);
826 // if (bookmarkString != null && !bookmarkString.equals("")) {
827 // String[] bookmarks = ExternalInterface.getBookmarkNames();
828 // boolean foundBookmark = false;
829 // for (int i = 0; i < bookmarks.length; i++) {
830 // if (bookmarks[i].equals(bookmarkString)) {
831 // foundBookmark = true;
834 // if (!foundBookmark) {
835 // return sqlResults;
837 // // Bookmark bookmark = sqlBookMarks.find(bookmarkString);
838 // ArrayList sqlList = new ArrayList();
839 // if (!ExternalInterface.isBookmarkConnected(bookmarkString)) {
840 // ExternalInterface.connectBookmark(bookmarkString, null);
841 // if (!ExternalInterface.isBookmarkConnected(bookmarkString)) {
842 // return sqlResults;
845 // // if (ExternalInterface.isBookmarkConnected(bookmarkString)) {
847 // int start = context.getStart();
848 // int end = context.getEnd();
849 // String foundSQLTableName = sqlTable.getTableName();
851 // String columnName;
852 // String prefixWithoutDollar = prefix;
853 // boolean isDollarPrefix = false;
854 // if (prefix.length() > 0 && prefix.charAt(0) == '$') {
855 // prefixWithoutDollar = prefix.substring(1);
856 // isDollarPrefix = true;
858 // IRegion region = new Region(start, end - start);
860 // if (!isDollarPrefix) {
861 // String[] tableNames = ExternalInterface.getMatchingTableNames(null, bookmarkString, prefixWithoutDollar, null, false);
862 // for (int i = 0; i < tableNames.length; i++) {
863 // sqlList.add(new SQLProposal(tableNames[i], context, region, viewer, PHPUiImages.get(PHPUiImages.IMG_TABLE)));
867 // String[] columnNames = ExternalInterface.getMatchingColumnNames(null, bookmarkString, prefixWithoutDollar, null, false);
868 // for (int i = 0; i < columnNames.length; i++) {
869 // sqlList.add(new SQLProposal(columnNames[i], context, region, viewer, PHPUiImages.get(PHPUiImages.IMG_TABLE)));
872 // sqlResults = new IPHPCompletionProposal[sqlList.size()];
873 // for (int i = 0; i < sqlList.size(); i++) {
874 // sqlResults[i] = (SQLProposal) sqlList.get(i);
876 // } catch (Exception /* NotConnectedException */ e) {
882 // return sqlResults;
885 private boolean looksLikeMethod(PHPCodeReader reader) throws IOException {
886 int curr = reader.read();
887 while (curr != PHPCodeReader.EOF && Character.isWhitespace((char) curr))
888 curr = reader.read();
890 if (curr == PHPCodeReader.EOF)
893 return Scanner.isPHPIdentifierPart((char) curr) || Scanner.isPHPIdentifierStart((char) curr);
896 private int guessContextInformationPosition(ITextViewer viewer, int offset) {
897 int contextPosition = offset;
898 IDocument document = viewer.getDocument();
901 PHPCodeReader reader = new PHPCodeReader();
902 reader.configureBackwardReader(document, offset, true, true);
904 int nestingLevel = 0;
906 int curr = reader.read();
907 while (curr != PHPCodeReader.EOF) {
909 if (')' == (char) curr)
912 else if ('(' == (char) curr) {
915 if (nestingLevel < 0) {
916 int start = reader.getOffset();
917 if (looksLikeMethod(reader))
922 curr = reader.read();
924 } catch (IOException e) {
926 return contextPosition;
930 * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
932 public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
933 int contextInformationPosition = guessContextInformationPosition(viewer, offset);
934 List result = addContextInformations(viewer, contextInformationPosition);
935 return (IContextInformation[]) result.toArray(new IContextInformation[result.size()]);
938 private List addContextInformations(ITextViewer viewer, int offset) {
939 ICompletionProposal[] proposals = internalComputeCompletionProposals(viewer, offset, -1);
940 List result = new ArrayList();
941 for (int i = 0; i < proposals.length; i++) {
942 IContextInformation contextInformation = proposals[i].getContextInformation();
943 if (contextInformation != null) {
944 ContextInformationWrapper wrapper = new ContextInformationWrapper(contextInformation);
945 wrapper.setContextInformationPosition(offset);
953 * Order the given proposals.
955 private ICompletionProposal[] order(ICompletionProposal[] proposals) {
956 Arrays.sort(proposals, fComparator);
957 // int len = proposals.length;
961 // for (int i = 0; i < len; i++) {
962 // System.out.println(proposals[i].getDisplayString());
968 * (non-Javadoc) Method declared on IContentAssistProcessor
970 public char[] getCompletionProposalAutoActivationCharacters() {
971 return fProposalAutoActivationSet;
972 // return null; // new char[] { '$' };
976 * (non-Javadoc) Method declared on IContentAssistProcessor
978 public char[] getContextInformationAutoActivationCharacters() {
979 return new char[] {};
983 * (non-Javadoc) Method declared on IContentAssistProcessor
985 public IContextInformationValidator getContextInformationValidator() {
990 * (non-Javadoc) Method declared on IContentAssistProcessor
992 public String getErrorMessage() {