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.core.CompilationUnit;
41 import net.sourceforge.phpdt.internal.core.SourceMethod;
42 import net.sourceforge.phpdt.internal.core.SourceType;
43 import net.sourceforge.phpdt.internal.corext.template.php.JavaContext;
44 import net.sourceforge.phpdt.internal.corext.template.php.JavaContextType;
45 import net.sourceforge.phpdt.internal.ui.PHPUiImages;
46 import net.sourceforge.phpdt.internal.ui.text.PHPCodeReader;
47 import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal;
48 import net.sourceforge.phpdt.internal.ui.text.java.PHPCompletionProposalComparator;
49 import net.sourceforge.phpdt.internal.ui.text.template.BuiltInEngine;
50 import net.sourceforge.phpdt.internal.ui.text.template.DeclarationEngine;
51 import net.sourceforge.phpdt.internal.ui.text.template.LocalVariableProposal;
52 import net.sourceforge.phpdt.internal.ui.text.template.SQLProposal;
53 import net.sourceforge.phpdt.internal.ui.text.template.contentassist.TemplateEngine;
54 import net.sourceforge.phpdt.ui.IWorkingCopyManager;
55 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
56 import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
57 import net.sourceforge.phpeclipse.internal.compiler.ast.CompilationUnitDeclaration;
58 import net.sourceforge.phpeclipse.phpeditor.PHPEditor;
59 import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr;
60 import net.sourceforge.phpeclipse.ui.IPreferenceConstants;
61 import net.sourceforge.phpeclipse.ui.overlaypages.ProjectPrefUtil;
63 import org.eclipse.core.resources.IFile;
64 import org.eclipse.core.resources.IProject;
65 import org.eclipse.jface.text.BadLocationException;
66 import org.eclipse.jface.text.IDocument;
67 import org.eclipse.jface.text.IRegion;
68 import org.eclipse.jface.text.ITextViewer;
69 import org.eclipse.jface.text.Region;
70 import org.eclipse.jface.text.TextPresentation;
71 import org.eclipse.jface.text.contentassist.ICompletionProposal;
72 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
73 import org.eclipse.jface.text.contentassist.IContextInformation;
74 import org.eclipse.jface.text.contentassist.IContextInformationExtension;
75 import org.eclipse.jface.text.contentassist.IContextInformationPresenter;
76 import org.eclipse.jface.text.contentassist.IContextInformationValidator;
77 import org.eclipse.jface.text.templates.DocumentTemplateContext;
78 import org.eclipse.jface.text.templates.TemplateContextType;
79 import org.eclipse.swt.graphics.Image;
80 import org.eclipse.swt.graphics.Point;
81 import org.eclipse.ui.IEditorPart;
82 import org.eclipse.ui.IFileEditorInput;
84 import com.quantum.ExternalInterface;
85 import com.quantum.model.NotConnectedException;
88 * Example PHP completion processor.
90 public class PHPCompletionProcessor implements IContentAssistProcessor {
92 * Simple content assist tip closer. The tip is valid in a range of 5 characters around its popup location.
94 protected static class Validator implements IContextInformationValidator, IContextInformationPresenter {
95 protected int fInstallOffset;
98 * @see IContextInformationValidator#isContextInformationValid(int)
100 public boolean isContextInformationValid(int offset) {
101 return Math.abs(fInstallOffset - offset) < 5;
105 * @see IContextInformationValidator#install(IContextInformation, ITextViewer, int)
107 public void install(IContextInformation info, ITextViewer viewer, int offset) {
108 fInstallOffset = offset;
112 * @see org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int, TextPresentation)
114 public boolean updatePresentation(int documentPosition, TextPresentation presentation) {
119 private static class ContextInformationWrapper implements IContextInformation, IContextInformationExtension {
120 private final IContextInformation fContextInformation;
122 private int fPosition;
124 public ContextInformationWrapper(IContextInformation contextInformation) {
125 fContextInformation = contextInformation;
129 * @see IContextInformation#getContextDisplayString()
131 public String getContextDisplayString() {
132 return fContextInformation.getContextDisplayString();
136 * @see IContextInformation#getImage()
138 public Image getImage() {
139 return fContextInformation.getImage();
143 * @see IContextInformation#getInformationDisplayString()
145 public String getInformationDisplayString() {
146 return fContextInformation.getInformationDisplayString();
150 * @see IContextInformationExtension#getContextInformationPosition()
152 public int getContextInformationPosition() {
156 public void setContextInformationPosition(int position) {
157 fPosition = position;
161 private class TableName {
169 * @return Returns the tableName.
171 public String getTableName() {
172 if (fTableName == null) {
173 return "<!--no-table-->";
180 * The tableName to set.
182 public void setTableName(String tableName) {
183 fTableName = tableName;
187 private char[] fProposalAutoActivationSet;
189 protected IContextInformationValidator fValidator = new Validator();
191 private TemplateEngine fTemplateEngine;
193 private PHPCompletionProposalComparator fComparator;
195 private int fNumberOfComputedResults = 0;
197 private IEditorPart fEditor;
199 protected IWorkingCopyManager fManager;
201 public PHPCompletionProcessor(IEditorPart editor) {
203 fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager();
204 TemplateContextType contextType = PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType("php"); //$NON-NLS-1$
205 if (contextType != null)
206 fTemplateEngine = new TemplateEngine(contextType);
207 fComparator = new PHPCompletionProposalComparator();
211 * Tells this processor to order the proposals alphabetically.
214 * <code>true</code> if proposals should be ordered.
216 public void orderProposalsAlphabetically(boolean order) {
217 fComparator.setOrderAlphabetically(order);
221 * Sets this processor's set of characters triggering the activation of the completion proposal computation.
223 * @param activationSet
226 public void setCompletionProposalAutoActivationCharacters(char[] activationSet) {
227 fProposalAutoActivationSet = activationSet;
231 * (non-Javadoc) Method declared on IContentAssistProcessor
233 public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
234 int contextInformationPosition = guessContextInformationPosition(viewer, documentOffset);
235 return internalComputeCompletionProposals(viewer, documentOffset, contextInformationPosition);
238 private int getLastToken(List list, ITextViewer viewer, int completionPosition, JavaContext context, TableName tableName) {
239 IDocument document = viewer.getDocument();
240 int start = context.getStart();
241 int end = context.getEnd();
243 int lastSignificantToken = ITerminalSymbols.TokenNameEOF;
245 // begin search 2 lines behind of this
250 ch = document.getChar(j);
256 ch = document.getChar(j);
263 // scan the line for the dereferencing operator '->'
264 startText = document.get(j, start - j);
266 System.out.println(startText);
268 int token = ITerminalSymbols.TokenNameEOF;
269 // token = getLastSQLToken(startText);
270 tableName.setTableName(getLastSQLTableName(startText));
271 Scanner scanner = ToolFactory.createScanner(false, false, false);
272 scanner.setSource(startText.toCharArray());
273 scanner.setPHPMode(true);
274 int beforeLastToken = ITerminalSymbols.TokenNameEOF;
275 int lastToken = ITerminalSymbols.TokenNameEOF;
278 token = scanner.getNextToken();
280 while (token != ITerminalSymbols.TokenNameERROR && token != ITerminalSymbols.TokenNameEOF) {
281 beforeLastToken = lastToken;
282 if (token == ITerminalSymbols.TokenNameVariable) {
283 ident = scanner.getCurrentTokenSource();
284 if (ident.length == 5 && ident[0] == '$' && ident[1] == 't' && ident[2] == 'h' && ident[3] == 'i' && ident[4] == 's') {
285 token = ITerminalSymbols.TokenNamethis_PHP_COMPLETION;
289 // System.out.println(scanner.toStringAction(lastToken));
290 token = scanner.getNextToken();
292 } catch (InvalidInputException e1) {
293 } catch (SyntaxError e) {
296 case ITerminalSymbols.TokenNameMINUS_GREATER:
297 // dereferencing operator '->' found
298 lastSignificantToken = ITerminalSymbols.TokenNameMINUS_GREATER;
299 if (beforeLastToken == ITerminalSymbols.TokenNameVariable) {
300 lastSignificantToken = ITerminalSymbols.TokenNameVariable;
302 } else if (beforeLastToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION) {
303 lastSignificantToken = ITerminalSymbols.TokenNamethis_PHP_COMPLETION;
307 case ITerminalSymbols.TokenNamenew:
308 lastSignificantToken = ITerminalSymbols.TokenNamenew;
312 } catch (BadLocationException e) {
314 return lastSignificantToken;
317 String getSQLTableName(String sqlText, int start) {
318 int tableNameStart = -1;
319 int currentCharacterPosition = start + 1;
323 ch = sqlText.charAt(currentCharacterPosition++);
324 if (tableNameStart == -1 && Scanner.isPHPIdentifierStart(ch)) {
325 tableNameStart = currentCharacterPosition - 1;
327 if (!Scanner.isPHPIdentifierPart(ch)) {
328 return sqlText.substring(tableNameStart, currentCharacterPosition - 1);
332 } catch (IndexOutOfBoundsException e) {
333 if (tableNameStart >= 0) {
334 return sqlText.substring(tableNameStart, currentCharacterPosition - 1);
340 private String getLastSQLTableName(String startText) {
342 // scan for sql identifiers
344 int currentSQLPosition = startText.length();
347 boolean whiteSpace = true;
350 ch = startText.charAt(--currentSQLPosition);
351 if (ch >= 'A' && ch <= 'Z') {
353 identEnd = currentSQLPosition + 1;
355 } else if (ch >= 'a' && ch <= 'z') {
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;
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 JavaContextType phpContextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType(
543 "php"); //$NON-NLS-1$
544 JavaContext context = (JavaContext) phpContextType.createContext(document, offset, selection.y, unit);
545 context.setVariable("selection", selectedText); //$NON-NLS-1$
546 String prefix = context.getKey();
548 HashMap methodVariables = null;
549 HashMap typeVariables = null;
550 HashMap unitVariables = null;
551 ICompilationUnit compilationUnit = (ICompilationUnit) context.findEnclosingElement(IJavaElement.COMPILATION_UNIT);
552 // if (compilationUnit != null) {
553 // unitVariables = ((CompilationUnit) compilationUnit).variables;
555 IType type = (IType) context.findEnclosingElement(IJavaElement.TYPE);
556 // if (type != null) {
557 // typeVariables = ((SourceType) type).variables;
559 IMethod method = (IMethod) context.findEnclosingElement(IJavaElement.METHOD);
560 // if (method != null) {
561 // methodVariables = ((SourceMethod) method).variables;
564 boolean emptyPrefix = prefix == null || prefix.equals("");
565 IPHPCompletionProposal[] localVariableResults = new IPHPCompletionProposal[0];
567 if (!emptyPrefix && prefix.length() >= 1 && prefix.charAt(0) == '$') { // php Variable ?
568 String lowerCasePrefix = prefix.toLowerCase();
569 HashSet localVariables = new HashSet();
570 if (compilationUnit != null) {
571 unitVariables = getUnitVariables(unitVariables, compilationUnit);
572 getVariableProposals(localVariables, viewer, project, context, unitVariables, lowerCasePrefix, 94);
574 if (method != null) {
575 methodVariables = getMethodVariables(methodVariables, method);
576 getVariableProposals(localVariables, viewer, project, context, methodVariables, lowerCasePrefix, 99);
578 if (!localVariables.isEmpty()) {
579 localVariableResults = (IPHPCompletionProposal[]) localVariables.toArray(new IPHPCompletionProposal[localVariables.size()]);
583 TableName sqlTable = new TableName();
584 ArrayList list = new ArrayList();
586 int lastSignificantToken = getLastToken(list, viewer, offset, context, sqlTable);
587 boolean useClassMembers = (lastSignificantToken == ITerminalSymbols.TokenNameMINUS_GREATER)
588 || (lastSignificantToken == ITerminalSymbols.TokenNameVariable) || (lastSignificantToken == ITerminalSymbols.TokenNamenew)
589 || (lastSignificantToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION);
591 if (fTemplateEngine != null) {
592 IPHPCompletionProposal[] templateResults = new IPHPCompletionProposal[0];
593 ICompletionProposal[] results;
595 fTemplateEngine.reset();
596 fTemplateEngine.complete(viewer, offset, unit);
597 templateResults = fTemplateEngine.getResults();
600 IPHPCompletionProposal[] identifierResults = new IPHPCompletionProposal[0];
602 // declarations stored in file project.index on project level
603 IPHPCompletionProposal[] declarationResults = new IPHPCompletionProposal[0];
604 if (project != null) {
605 DeclarationEngine declarationEngine;
606 JavaContextType contextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType(
607 "php"); //$NON-NLS-1$
608 if (contextType != null) {
609 IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault().getIndexManager(project);
611 declarationEngine = new DeclarationEngine(project, contextType, lastSignificantToken, file);
612 if (lastSignificantToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION) {
613 // complete '$this->'
614 sortedMap = indexManager.getIdentifiers(file);
615 declarationEngine.completeObject(viewer, offset, sortedMap, unit);
617 String typeRef = null;
618 char[] varName = (char[]) list.get(0);
619 if (varName != null) {
620 if (method != null) {
621 methodVariables = getMethodVariables(methodVariables, method);
622 VariableInfo info = (VariableInfo) methodVariables.get(new String(varName));
623 if (info != null && info.typeIdentifier != null) {
624 typeRef = new String(info.typeIdentifier);
629 if (typeRef != null) {
630 // complete '$variable->' with type information
631 sortedMap = indexManager.getIdentifiers(typeRef);
632 declarationEngine.completeObject(viewer, offset, sortedMap, unit);
634 // complete '$variable->' without type information
635 sortedMap = indexManager.getIdentifierMap();
636 declarationEngine.complete(viewer, offset, sortedMap, unit);
639 declarationResults = declarationEngine.getResults();
642 // built in function names from phpsyntax.xml
643 ArrayList syntaxbuffer = PHPSyntaxRdr.getSyntaxData();
644 IPHPCompletionProposal[] builtinResults = new IPHPCompletionProposal[0];
645 if ((!useClassMembers) && syntaxbuffer != null) {
646 BuiltInEngine builtinEngine;
648 JavaContextType contextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType(
649 "php"); //$NON-NLS-1$
650 if (contextType != null) {
651 builtinEngine = new BuiltInEngine(contextType);
652 builtinEngine.complete(viewer, offset, syntaxbuffer, unit);
653 builtinResults = builtinEngine.getResults();
656 ICompletionProposal[] sqlResults = new ICompletionProposal[0];
657 if (project != null) {
658 sqlResults = getSQLProposals(viewer, project, context, prefix, sqlTable);
660 // concatenate the result arrays
661 IPHPCompletionProposal[] total;
662 total = new IPHPCompletionProposal[localVariableResults.length + templateResults.length + identifierResults.length
663 + builtinResults.length + declarationResults.length + sqlResults.length];
664 System.arraycopy(templateResults, 0, total, 0, templateResults.length);
665 System.arraycopy(identifierResults, 0, total, templateResults.length, identifierResults.length);
666 System.arraycopy(builtinResults, 0, total, templateResults.length + identifierResults.length, builtinResults.length);
667 System.arraycopy(declarationResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length,
668 declarationResults.length);
669 System.arraycopy(sqlResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length
670 + declarationResults.length, sqlResults.length);
671 System.arraycopy(localVariableResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length
672 + declarationResults.length + sqlResults.length, localVariableResults.length);
674 fNumberOfComputedResults = (results == null ? 0 : results.length);
676 * Order here and not in result collector to make sure that the order applies to all proposals and not just those of the
679 return order(results);
681 return new IPHPCompletionProposal[0];
685 * @param unitVariables
688 private HashMap getUnitVariables(HashMap unitVariables, ICompilationUnit unit) {
689 if (unitVariables == null) {
691 String unitText = unit.getSource();
692 unitVariables = new HashMap();
694 ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.exitAfterAllProblems(),
695 new CompilerOptions(JavaCore.getOptions()), new DefaultProblemFactory());
696 UnitParser parser = new UnitParser(problemReporter);
697 parser.compilationUnit = new CompilationUnitDeclaration(problemReporter, null, unitText.length());
698 parser.parse(unitText, unitVariables);
700 } catch (Exception e) {
701 // TODO Auto-generated catch block
703 PHPeclipsePlugin.log(e);
706 return unitVariables;
710 * @param methodVariables
713 private HashMap getMethodVariables(HashMap methodVariables, IMethod method) {
714 if (methodVariables == null) {
716 String methodText = method.getSource();
717 methodVariables = new HashMap();
718 ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.exitAfterAllProblems(),
719 new CompilerOptions(JavaCore.getOptions()), new DefaultProblemFactory());
720 UnitParser parser = new UnitParser(problemReporter);
721 parser.compilationUnit = new CompilationUnitDeclaration(problemReporter, null, methodText.length());
722 parser.parseFunction(methodText, methodVariables);
723 } catch (Exception e) {
724 // TODO Auto-generated catch block
726 PHPeclipsePlugin.log(e);
729 return methodVariables;
739 private void getVariableProposals(HashSet localVariables, ITextViewer viewer, IProject project, JavaContext context,
740 HashMap variables, String prefix, int relevance) {
742 int start = context.getStart();
743 int end = context.getEnd();
744 IRegion region = new Region(start, end - start);
745 // IMethod method = (IMethod) context.findEnclosingElement(IJavaElement.METHOD);
746 // if (method != null && (method instanceof SourceMethod) && ((SourceMethod) method).variables != null) {
747 // HashMap map = ((SourceMethod) method).variables;
748 Set set = variables.keySet();
749 Iterator iter = set.iterator();
751 boolean matchesVarName;
752 while (iter.hasNext()) {
753 varName = (String) iter.next();
754 if (varName.length() >= prefix.length()) {
755 matchesVarName = true;
756 for (int i = 0; i < prefix.length(); i++) {
757 if (prefix.charAt(i) != Character.toLowerCase(varName.charAt(i))) {
758 matchesVarName = false;
762 if (matchesVarName) {
763 LocalVariableProposal prop;
764 // if (varName.length == prefix.length()) {
765 // prop = new LocalVariableProposal(new String(varName), region, viewer, relevance-10);
767 prop = new LocalVariableProposal(new String(varName), region, viewer, relevance);
769 localVariables.add(prop);
776 // boolean matchesVarName;
777 // if (method != null) {
778 // ISourceRange range = method.getSourceRange();
779 // char[] source = method.getSource().toCharArray();
780 // Scanner scanner = new Scanner();
781 // scanner.setSource(source);
782 // scanner.phpMode = true;
783 // int token = Scanner.TokenNameWHITESPACE;
784 // while ((token = scanner.getNextToken()) != Scanner.TokenNameEOF) {
785 // if (token == Scanner.TokenNameVariable) {
786 // varName = scanner.getCurrentTokenSource();
787 // if (varName.length >= prefix.length()) {
788 // matchesVarName = true;
789 // for (int i = 0; i < prefix.length(); i++) {
790 // if (prefix.charAt(i) != varName[i]) {
791 // matchesVarName = false;
795 // if (matchesVarName) {
796 // LocalVariableProposal prop = new LocalVariableProposal(new String(varName), region, viewer);
797 // if (varName.length == prefix.length()) {
798 // prop.setRelevance(98);
800 // localVariables.add(prop);
806 // } catch (Throwable e) {
807 // // ignore - Syntax exceptions could occur, if there are syntax errors !
820 private ICompletionProposal[] getSQLProposals(ITextViewer viewer, IProject project, DocumentTemplateContext context,
821 String prefix, TableName sqlTable) {
822 ICompletionProposal[] sqlResults = new ICompletionProposal[0];
823 // Get The Database bookmark from the Quantum SQL plugin:
824 // BookmarkCollection sqlBookMarks = BookmarkCollection.getInstance();
825 // if (sqlBookMarks != null) {
826 String bookmarkString = ProjectPrefUtil.getMiscProjectsPreferenceValue(project, IPreferenceConstants.PHP_BOOKMARK_DEFAULT);
827 if (bookmarkString != null && !bookmarkString.equals("")) {
828 String[] bookmarks = ExternalInterface.getBookmarkNames();
829 boolean foundBookmark = false;
830 for (int i = 0; i < bookmarks.length; i++) {
831 if (bookmarks[i].equals(bookmarkString)) {
832 foundBookmark = true;
835 if (!foundBookmark) {
838 // Bookmark bookmark = sqlBookMarks.find(bookmarkString);
839 ArrayList sqlList = new ArrayList();
840 if (!ExternalInterface.isBookmarkConnected(bookmarkString)) {
841 ExternalInterface.connectBookmark(bookmarkString, null);
842 if (!ExternalInterface.isBookmarkConnected(bookmarkString)) {
846 // if (ExternalInterface.isBookmarkConnected(bookmarkString)) {
848 // Connection connection = bookmark.getConnection();
849 // DatabaseMetaData metaData = connection.getMetaData();
851 // if (metaData != null) {
852 int start = context.getStart();
853 int end = context.getEnd();
854 String foundSQLTableName = sqlTable.getTableName();
857 String prefixWithoutDollar = prefix;
858 boolean isDollarPrefix = false;
859 if (prefix.length() > 0 && prefix.charAt(0) == '$') {
860 prefixWithoutDollar = prefix.substring(1);
861 isDollarPrefix = true;
863 IRegion region = new Region(start, end - start);
865 if (!isDollarPrefix) {
866 String[] tableNames = ExternalInterface.getMatchingTableNames(null, bookmarkString, prefixWithoutDollar, null, false);
867 for (int i = 0; i < tableNames.length; i++) {
868 sqlList.add(new SQLProposal(tableNames[i], context, region, viewer, PHPUiImages.get(PHPUiImages.IMG_TABLE)));
871 // set = metaData.getTables(null, null, prefixWithoutDollar + "%", null);
872 // while (set.next()) {
873 // tableName = set.getString("TABLE_NAME");
874 // tableName = (tableName == null) ? "" : tableName.trim();
875 // if (tableName != null && tableName.length() > 0) {
876 // sqlList.add(new SQLProposal(tableName, context, region, viewer, PHPUiImages.get(PHPUiImages.IMG_TABLE)));
882 String[] columnNames = ExternalInterface.getMatchingColumnNames(null, bookmarkString, prefixWithoutDollar, null, false);
883 for (int i = 0; i < columnNames.length; i++) {
884 sqlList.add(new SQLProposal(columnNames[i], context, region, viewer, PHPUiImages.get(PHPUiImages.IMG_TABLE)));
886 // set = metaData.getColumns(null, null, "%", prefixWithoutDollar + "%");
887 // SQLProposal sqlProposal;
888 // while (set.next()) {
889 // columnName = set.getString("COLUMN_NAME");
890 // columnName = (columnName == null) ? "" : columnName.trim();
891 // tableName = set.getString("TABLE_NAME");
892 // tableName = (tableName == null) ? "" : tableName.trim();
893 // if (tableName != null && tableName.length() > 0 && columnName != null && columnName.length() > 0) {
894 // if (isDollarPrefix) {
895 // sqlProposal = new SQLProposal(tableName, "$" + columnName, context, region, viewer, PHPUiImages
896 // .get(PHPUiImages.IMG_COLUMN));
898 // sqlProposal = new SQLProposal(tableName, columnName, context, region, viewer, PHPUiImages
899 // .get(PHPUiImages.IMG_COLUMN));
901 // if (tableName.equals(foundSQLTableName)) {
902 // sqlProposal.setRelevance(90);
903 // } else if (tableName.indexOf(foundSQLTableName) >= 0) {
904 // sqlProposal.setRelevance(75);
906 // sqlList.add(sqlProposal);
910 sqlResults = new IPHPCompletionProposal[sqlList.size()];
911 for (int i = 0; i < sqlList.size(); i++) {
912 sqlResults[i] = (SQLProposal) sqlList.get(i);
915 } catch (NotConnectedException e) {
916 // ignore this - not mission critical
917 // } catch (SQLException e) {
918 // e.printStackTrace();
926 private boolean looksLikeMethod(PHPCodeReader reader) throws IOException {
927 int curr = reader.read();
928 while (curr != PHPCodeReader.EOF && Character.isWhitespace((char) curr))
929 curr = reader.read();
931 if (curr == PHPCodeReader.EOF)
934 return Scanner.isPHPIdentifierPart((char) curr) || Scanner.isPHPIdentifierStart((char) curr);
937 private int guessContextInformationPosition(ITextViewer viewer, int offset) {
938 int contextPosition = offset;
939 IDocument document = viewer.getDocument();
942 PHPCodeReader reader = new PHPCodeReader();
943 reader.configureBackwardReader(document, offset, true, true);
945 int nestingLevel = 0;
947 int curr = reader.read();
948 while (curr != PHPCodeReader.EOF) {
950 if (')' == (char) curr)
953 else if ('(' == (char) curr) {
956 if (nestingLevel < 0) {
957 int start = reader.getOffset();
958 if (looksLikeMethod(reader))
963 curr = reader.read();
965 } catch (IOException e) {
967 return contextPosition;
971 * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
973 public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
974 int contextInformationPosition = guessContextInformationPosition(viewer, offset);
975 List result = addContextInformations(viewer, contextInformationPosition);
976 return (IContextInformation[]) result.toArray(new IContextInformation[result.size()]);
979 private List addContextInformations(ITextViewer viewer, int offset) {
980 ICompletionProposal[] proposals = internalComputeCompletionProposals(viewer, offset, -1);
981 List result = new ArrayList();
982 for (int i = 0; i < proposals.length; i++) {
983 IContextInformation contextInformation = proposals[i].getContextInformation();
984 if (contextInformation != null) {
985 ContextInformationWrapper wrapper = new ContextInformationWrapper(contextInformation);
986 wrapper.setContextInformationPosition(offset);
994 * Order the given proposals.
996 private ICompletionProposal[] order(ICompletionProposal[] proposals) {
997 Arrays.sort(proposals, fComparator);
998 // int len = proposals.length;
1002 // for (int i = 0; i < len; i++) {
1003 // System.out.println(proposals[i].getDisplayString());
1009 * (non-Javadoc) Method declared on IContentAssistProcessor
1011 public char[] getCompletionProposalAutoActivationCharacters() {
1012 return fProposalAutoActivationSet;
1013 // return null; // new char[] { '$' };
1017 * (non-Javadoc) Method declared on IContentAssistProcessor
1019 public char[] getContextInformationAutoActivationCharacters() {
1020 return new char[] {};
1024 * (non-Javadoc) Method declared on IContentAssistProcessor
1026 public IContextInformationValidator getContextInformationValidator() {
1031 * (non-Javadoc) Method declared on IContentAssistProcessor
1033 public String getErrorMessage() {