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.ast.CompilationUnitDeclaration;
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.text.PHPCodeReader;
43 import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal;
44 import net.sourceforge.phpdt.internal.ui.text.java.JavaParameterListValidator;
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.contentassist.TemplateEngine;
50 import net.sourceforge.phpdt.ui.IWorkingCopyManager;
51 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
52 import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
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.IEditorInput;
72 import org.eclipse.ui.IEditorPart;
73 import org.eclipse.ui.IFileEditorInput;
76 * Example PHP completion processor.
78 public class PHPCompletionProcessor implements IContentAssistProcessor {
80 * Simple content assist tip closer. The tip is valid in a range of 5
81 * characters around its popup location.
83 // protected static class Validator implements IContextInformationValidator,
84 // IContextInformationPresenter {
85 // protected int fInstallOffset;
88 // * @see IContextInformationValidator#isContextInformationValid(int)
90 // public boolean isContextInformationValid(int offset) {
91 // return Math.abs(fInstallOffset - offset) < 5;
95 // * @see IContextInformationValidator#install(IContextInformation,
98 // public void install(IContextInformation info, ITextViewer viewer, int
100 // fInstallOffset = offset;
105 // org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int,
108 // public boolean updatePresentation(int documentPosition, TextPresentation
113 private static class ContextInformationWrapper implements IContextInformation, IContextInformationExtension {
114 private final IContextInformation fContextInformation;
116 private int fPosition;
118 public ContextInformationWrapper(IContextInformation contextInformation) {
119 fContextInformation = contextInformation;
123 * @see IContextInformation#getContextDisplayString()
125 public String getContextDisplayString() {
126 return fContextInformation.getContextDisplayString();
130 * @see IContextInformation#getImage()
132 public Image getImage() {
133 return fContextInformation.getImage();
137 * @see IContextInformation#getInformationDisplayString()
139 public String getInformationDisplayString() {
140 return fContextInformation.getInformationDisplayString();
144 * @see IContextInformationExtension#getContextInformationPosition()
146 public int getContextInformationPosition() {
150 public void setContextInformationPosition(int position) {
151 fPosition = position;
155 // private class TableName {
156 // String fTableName;
159 // fTableName = null;
163 // * @return Returns the tableName.
165 // public String getTableName() {
166 // if (fTableName == null) {
167 // return "<!--no-table-->";
169 // return fTableName;
173 // * @param tableName
174 // * The tableName to set.
176 // public void setTableName(String tableName) {
177 // fTableName = tableName;
181 private char[] fProposalAutoActivationSet;
183 protected IContextInformationValidator fValidator = null;
185 private TemplateEngine fTemplateEngine;
187 private PHPCompletionProposalComparator fComparator;
189 private IEditorPart fEditor;
191 protected IWorkingCopyManager fManager;
193 public PHPCompletionProcessor(IEditorPart editor) {
195 fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager();
196 TemplateContextType contextType = PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType("php"); //$NON-NLS-1$
197 if (contextType != null)
198 fTemplateEngine = new TemplateEngine(contextType);
199 fComparator = new PHPCompletionProposalComparator();
203 * Tells this processor to order the proposals alphabetically.
206 * <code>true</code> if proposals should be ordered.
208 public void orderProposalsAlphabetically(boolean order) {
209 fComparator.setOrderAlphabetically(order);
213 * Sets this processor's set of characters triggering the activation of the
214 * completion proposal computation.
216 * @param activationSet
219 public void setCompletionProposalAutoActivationCharacters(char[] activationSet) {
220 fProposalAutoActivationSet = activationSet;
224 * (non-Javadoc) Method declared on IContentAssistProcessor
226 public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
227 int contextInformationPosition = guessContextInformationPosition(viewer, documentOffset);
228 return internalComputeCompletionProposals(viewer, documentOffset, contextInformationPosition);
231 private int getLastToken(List list, ITextViewer viewer, int completionPosition, JavaContext context) {
232 // TableName tableName) {
233 IDocument document = viewer.getDocument();
234 int start = context.getStart();
235 // int end = context.getEnd();
237 int lastSignificantToken = ITerminalSymbols.TokenNameEOF;
239 // begin search 2 lines behind of this
244 ch = document.getChar(j);
250 ch = document.getChar(j);
257 // scan the line for the dereferencing operator '->'
258 startText = document.get(j, start - j);
260 System.out.println(startText);
262 int token = ITerminalSymbols.TokenNameEOF;
263 // token = getLastSQLToken(startText);
264 // tableName.setTableName(getLastSQLTableName(startText));
265 Scanner scanner = ToolFactory.createScanner(false, false, false);
266 scanner.setSource(startText.toCharArray());
267 scanner.setPHPMode(true);
268 int beforeLastToken = ITerminalSymbols.TokenNameEOF;
269 int lastToken = ITerminalSymbols.TokenNameEOF;
272 token = scanner.getNextToken();
274 while (token != ITerminalSymbols.TokenNameERROR && token != ITerminalSymbols.TokenNameEOF) {
275 beforeLastToken = lastToken;
276 if (token == ITerminalSymbols.TokenNameVariable) {
277 ident = scanner.getCurrentTokenSource();
278 if (ident.length == 5 && ident[0] == '$' && ident[1] == 't' && ident[2] == 'h' && ident[3] == 'i' && ident[4] == 's') {
279 token = ITerminalSymbols.TokenNamethis_PHP_COMPLETION;
283 // System.out.println(scanner.toStringAction(lastToken));
284 token = scanner.getNextToken();
286 } catch (InvalidInputException e1) {
287 } catch (SyntaxError e) {
290 case ITerminalSymbols.TokenNameMINUS_GREATER:
291 // dereferencing operator '->' found
292 lastSignificantToken = ITerminalSymbols.TokenNameMINUS_GREATER;
293 if (beforeLastToken == ITerminalSymbols.TokenNameVariable) {
294 lastSignificantToken = ITerminalSymbols.TokenNameVariable;
296 } else if (beforeLastToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION) {
297 lastSignificantToken = ITerminalSymbols.TokenNamethis_PHP_COMPLETION;
301 case ITerminalSymbols.TokenNamenew:
302 lastSignificantToken = ITerminalSymbols.TokenNamenew;
306 } catch (BadLocationException e) {
308 return lastSignificantToken;
311 String getSQLTableName(String sqlText, int start) {
312 int tableNameStart = -1;
313 int currentCharacterPosition = start + 1;
317 ch = sqlText.charAt(currentCharacterPosition++);
318 if (tableNameStart == -1 && Scanner.isPHPIdentifierStart(ch)) {
319 tableNameStart = currentCharacterPosition - 1;
321 if (!Scanner.isPHPIdentifierPart(ch)) {
322 return sqlText.substring(tableNameStart, currentCharacterPosition - 1);
326 } catch (IndexOutOfBoundsException e) {
327 if (tableNameStart >= 0) {
328 return sqlText.substring(tableNameStart, currentCharacterPosition - 1);
334 // private String getLastSQLTableName(String startText) {
335 // // scan for sql identifiers
337 // int currentSQLPosition = startText.length();
338 // int identEnd = -1;
339 // String ident = null;
342 // ch = startText.charAt(--currentSQLPosition);
343 // if (Scanner.isSQLIdentifierPart(ch)) {
344 // // if (ch >= 'A' && ch <= 'Z') {
345 // if (identEnd < 0) {
346 // identEnd = currentSQLPosition + 1;
348 // // } else if (ch >= 'a' && ch <= 'z') {
349 // // if (identEnd < 0) {
350 // // identEnd = currentSQLPosition + 1;
352 // } else if (identEnd >= 0) {
353 // ident = startText.substring(currentSQLPosition + 1, identEnd);
354 // // select -- from -- where --
355 // // update -- set -- where --
356 // // insert into -- ( -- ) values ( -- )
357 // if (ident.length() >= 4 && ident.length() <= 6) {
358 // ident = ident.toLowerCase();
359 // switch (ident.length()) {
361 // // if (ident.equals("set")) {
362 // // // System.out.println("set");
363 // // token = ITerminalSymbols.TokenNameSQLset;
368 // if (ident.equals("from")) {
369 // // System.out.println("from");
370 // return getSQLTableName(startText, identEnd);
371 // } else if (ident.equals("into")) {
372 // // System.out.println("into");
373 // return getSQLTableName(startText, identEnd);
377 // if (ident.equals("update")) {
378 // // System.out.println("update");
379 // return getSQLTableName(startText, identEnd);
385 // } else if (Character.isWhitespace(ch)) {
388 // } catch (IndexOutOfBoundsException e) {
390 // return "<!--no-table-->";
394 * Detect the last significant SQL token in the text before the completion
398 // private int getLastSQLToken(String startText) {
400 // // scan for sql identifiers
402 // int currentSQLPosition = startText.length();
403 // int identEnd = -1;
404 // String ident = null;
407 // ch = startText.charAt(--currentSQLPosition);
408 // if (ch >= 'A' && ch <= 'Z') {
409 // if (identEnd < 0) {
410 // identEnd = currentSQLPosition + 1;
412 // } else if (ch >= 'a' && ch <= 'z') {
413 // if (identEnd < 0) {
414 // identEnd = currentSQLPosition + 1;
416 // } else if (identEnd >= 0) {
417 // ident = startText.substring(currentSQLPosition + 1, identEnd);
418 // // select -- from -- where --
419 // // update -- set -- where --
420 // // insert into -- ( -- ) values ( -- )
421 // if (ident.length() >= 3 && ident.length() <= 6) {
422 // ident = ident.toLowerCase();
423 // switch (ident.length()) {
425 // if (ident.equals("set")) {
426 // // System.out.println("set");
427 // token = ITerminalSymbols.TokenNameSQLset;
432 // if (ident.equals("from")) {
433 // // System.out.println("from");
434 // token = ITerminalSymbols.TokenNameSQLfrom;
435 // // getSQLTableName();
437 // } else if (ident.equals("into")) {
438 // // System.out.println("into");
439 // token = ITerminalSymbols.TokenNameSQLinto;
444 // if (ident.equals("where")) {
445 // // System.out.println("where");
446 // token = ITerminalSymbols.TokenNameSQLwhere;
451 // if (ident.equals("select")) {
452 // // System.out.println("select");
453 // token = ITerminalSymbols.TokenNameSQLselect;
455 // } else if (ident.equals("insert")) {
456 // // System.out.println("insert");
457 // token = ITerminalSymbols.TokenNameSQLinsert;
459 // } else if (ident.equals("update")) {
460 // // System.out.println("update");
461 // token = ITerminalSymbols.TokenNameSQLupdate;
463 // } else if (ident.equals("values")) {
464 // // System.out.println("values");
465 // token = ITerminalSymbols.TokenNameSQLvalues;
474 // } catch (IndexOutOfBoundsException e) {
476 // return ITerminalSymbols.TokenNameEOF;
479 private ICompletionProposal[] internalComputeCompletionProposals(ITextViewer viewer, int offset, int contextOffset) {
480 ICompilationUnit unit = fManager.getWorkingCopy(fEditor.getEditorInput());
481 IDocument document = viewer.getDocument();
483 IProject project = null;
485 PHPEditor editor = null;
486 if (fEditor != null && (fEditor instanceof PHPEditor)) {
487 editor = (PHPEditor) fEditor;
488 IEditorInput editorInput=editor.getEditorInput();
489 if (editorInput instanceof IFileEditorInput) {
490 file = ((IFileEditorInput) editorInput).getFile();
491 project = file.getProject();
494 return new ICompletionProposal[0];
499 Point selection = viewer.getSelectedRange();
500 // remember selected text
501 String selectedText = null;
502 if (selection.y != 0) {
504 selectedText = document.get(selection.x, selection.y);
505 } catch (BadLocationException e) {
509 if (offset > 2 && fProposalAutoActivationSet != null) {
510 // restrict auto activation for '>' character to '->' token
513 char ch = document.getChar(offset-1);
515 for (int i = 0; i < fProposalAutoActivationSet.length; i++) {
516 ch = fProposalAutoActivationSet[i];
517 if (ch == '>') { // auto activation enabled
518 ch = document.getChar(offset - 2);
520 return new IPHPCompletionProposal[0];
526 } catch (BadLocationException e) {
531 JavaContextType phpContextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType(
532 "php"); //$NON-NLS-1$
533 JavaContext context = (JavaContext) phpContextType.createContext(document, offset, selection.y, unit);
534 context.setVariable("selection", selectedText); //$NON-NLS-1$
535 String prefix = context.getKey();
537 HashMap methodVariables = null;
538 // HashMap typeVariables = null;
539 HashMap unitVariables = null;
540 ICompilationUnit compilationUnit = (ICompilationUnit) context.findEnclosingElement(IJavaElement.COMPILATION_UNIT);
541 // if (compilationUnit != null) {
542 // unitVariables = ((CompilationUnit) compilationUnit).variables;
544 IType type = (IType) context.findEnclosingElement(IJavaElement.TYPE);
546 // typeVariables = ((SourceType) type).variables;
548 IMethod method = (IMethod) context.findEnclosingElement(IJavaElement.METHOD);
549 // if (method != null) {
550 // methodVariables = ((SourceMethod) method).variables;
553 boolean emptyPrefix = prefix == null || prefix.equals("");
554 IPHPCompletionProposal[] localVariableResults = new IPHPCompletionProposal[0];
556 if (!emptyPrefix && prefix.length() >= 1 && prefix.charAt(0) == '$') {
558 String lowerCasePrefix = prefix.toLowerCase();
559 HashSet localVariables = new HashSet();
560 if (compilationUnit != null) {
561 unitVariables = getUnitVariables(unitVariables, compilationUnit);
562 getVariableProposals(localVariables, viewer, project, context, unitVariables, lowerCasePrefix, 94);
564 if (method != null) {
565 methodVariables = getMethodVariables(methodVariables, method);
566 getVariableProposals(localVariables, viewer, project, context, methodVariables, lowerCasePrefix, 99);
568 if (!localVariables.isEmpty()) {
569 localVariableResults = (IPHPCompletionProposal[]) localVariables.toArray(new IPHPCompletionProposal[localVariables.size()]);
573 // TableName sqlTable = new TableName();
574 ArrayList list = new ArrayList();
576 int lastSignificantToken = getLastToken(list, viewer, offset, context); //, sqlTable);
577 boolean useClassMembers = (lastSignificantToken == ITerminalSymbols.TokenNameMINUS_GREATER)
578 || (lastSignificantToken == ITerminalSymbols.TokenNameVariable) || (lastSignificantToken == ITerminalSymbols.TokenNamenew)
579 || (lastSignificantToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION);
581 if (fTemplateEngine != null) {
582 IPHPCompletionProposal[] templateResults = new IPHPCompletionProposal[0];
583 ICompletionProposal[] results;
585 fTemplateEngine.reset();
586 fTemplateEngine.complete(viewer, offset, unit);
587 templateResults = fTemplateEngine.getResults();
590 IPHPCompletionProposal[] identifierResults = new IPHPCompletionProposal[0];
592 // declarations stored in file project.index on project level
593 IPHPCompletionProposal[] declarationResults = new IPHPCompletionProposal[0];
594 if (project != null) {
595 DeclarationEngine declarationEngine;
596 JavaContextType contextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType(
597 "php"); //$NON-NLS-1$
598 if (contextType != null) {
599 IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault().getIndexManager(project);
601 declarationEngine = new DeclarationEngine(project, contextType, lastSignificantToken, file);
602 if (lastSignificantToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION) {
603 // complete '$this->'
604 sortedMap = indexManager.getIdentifiers(file);
605 declarationEngine.completeObject(viewer, offset, sortedMap, unit);
607 String typeRef = null;
608 char[] varName = (char[]) list.get(0);
609 if (varName != null) {
610 if (method != null) {
611 methodVariables = getMethodVariables(methodVariables, method);
612 VariableInfo info = (VariableInfo) methodVariables.get(new String(varName));
613 if (info != null && info.typeIdentifier != null) {
614 typeRef = new String(info.typeIdentifier);
618 if (typeRef != null) {
619 // complete '$variable->' with type information
620 sortedMap = indexManager.getIdentifiers(typeRef);
621 declarationEngine.completeObject(viewer, offset, sortedMap, unit);
623 // complete '$variable->' without type information
624 sortedMap = indexManager.getIdentifierMap();
625 declarationEngine.complete(viewer, offset, sortedMap, unit);
628 declarationResults = declarationEngine.getResults();
631 // built in function names from phpsyntax.xml
632 ArrayList syntaxbuffer = PHPSyntaxRdr.getSyntaxData();
633 IPHPCompletionProposal[] builtinResults = new IPHPCompletionProposal[0];
634 if ((!useClassMembers) && syntaxbuffer != null) {
635 BuiltInEngine builtinEngine;
636 JavaContextType contextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType(
637 "php"); //$NON-NLS-1$
638 if (contextType != null) {
639 builtinEngine = new BuiltInEngine(contextType);
640 builtinEngine.complete(viewer, offset, syntaxbuffer, unit);
641 builtinResults = builtinEngine.getResults();
644 // ICompletionProposal[] sqlResults = new ICompletionProposal[0];
645 // if (project != null) {
646 // sqlResults = getSQLProposals(viewer, project, context, prefix,
649 // concatenate the result arrays
650 IPHPCompletionProposal[] total;
651 total = new IPHPCompletionProposal[localVariableResults.length + templateResults.length + identifierResults.length
652 + builtinResults.length + declarationResults.length];// +
653 // sqlResults.length];
654 System.arraycopy(templateResults, 0, total, 0, templateResults.length);
655 System.arraycopy(identifierResults, 0, total, templateResults.length, identifierResults.length);
656 System.arraycopy(builtinResults, 0, total, templateResults.length + identifierResults.length, builtinResults.length);
657 System.arraycopy(declarationResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length,
658 declarationResults.length);
659 // System.arraycopy(sqlResults, 0, total, templateResults.length +
660 // identifierResults.length + builtinResults.length
661 // + declarationResults.length, sqlResults.length);
662 // System.arraycopy(localVariableResults, 0, total, templateResults.length
663 // + identifierResults.length + builtinResults.length
664 // + declarationResults.length + sqlResults.length,
665 // localVariableResults.length);
666 System.arraycopy(localVariableResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length
667 + declarationResults.length, localVariableResults.length);
669 // fNumberOfComputedResults = (results == null ? 0 : results.length);
671 * Order here and not in result collector to make sure that the order
672 * applies to all proposals and not just those of the compilation unit.
674 return order(results);
676 return new IPHPCompletionProposal[0];
680 * @param unitVariables
683 private HashMap getUnitVariables(HashMap unitVariables, ICompilationUnit unit) {
684 if (unitVariables == null) {
686 String unitText = unit.getSource();
687 unitVariables = new HashMap();
689 ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.exitAfterAllProblems(),
690 new CompilerOptions(JavaCore.getOptions()), new DefaultProblemFactory());
691 UnitParser parser = new UnitParser(problemReporter);
692 parser.compilationUnit = new CompilationUnitDeclaration(problemReporter, null, unitText.length());
693 parser.parse(unitText, unitVariables);
695 } catch (Exception e) {
696 // TODO Auto-generated catch block
698 PHPeclipsePlugin.log(e);
701 return unitVariables;
705 * @param methodVariables
708 private HashMap getMethodVariables(HashMap methodVariables, IMethod method) {
709 if (methodVariables == null) {
711 String methodText = method.getSource();
712 methodVariables = new HashMap();
713 ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.exitAfterAllProblems(),
714 new CompilerOptions(JavaCore.getOptions()), new DefaultProblemFactory());
715 UnitParser parser = new UnitParser(problemReporter);
716 parser.compilationUnit = new CompilationUnitDeclaration(problemReporter, null, methodText.length());
717 parser.parseFunction(methodText, methodVariables);
718 } catch (Exception e) {
719 // TODO Auto-generated catch block
721 PHPeclipsePlugin.log(e);
724 return methodVariables;
734 private void getVariableProposals(HashSet localVariables, ITextViewer viewer, IProject project, JavaContext context,
735 HashMap variables, String prefix, int relevance) {
737 int start = context.getStart();
738 int end = context.getEnd();
739 IRegion region = new Region(start, end - start);
740 // IMethod method = (IMethod)
741 // context.findEnclosingElement(IJavaElement.METHOD);
742 // if (method != null && (method instanceof SourceMethod) && ((SourceMethod)
743 // method).variables != null) {
744 // HashMap map = ((SourceMethod) method).variables;
745 Set set = variables.keySet();
746 Iterator iter = set.iterator();
748 boolean matchesVarName;
749 while (iter.hasNext()) {
750 varName = (String) iter.next();
751 if (varName.length() >= prefix.length()) {
752 matchesVarName = true;
753 for (int i = 0; i < prefix.length(); i++) {
754 if (prefix.charAt(i) != Character.toLowerCase(varName.charAt(i))) {
755 matchesVarName = false;
759 if (matchesVarName) {
760 LocalVariableProposal prop;
761 // if (varName.length == prefix.length()) {
762 // prop = new LocalVariableProposal(new String(varName), region,
763 // viewer, relevance-10);
765 prop = new LocalVariableProposal(new String(varName), region, viewer, relevance);
767 localVariables.add(prop);
774 // boolean matchesVarName;
775 // if (method != null) {
776 // ISourceRange range = method.getSourceRange();
777 // char[] source = method.getSource().toCharArray();
778 // Scanner scanner = new Scanner();
779 // scanner.setSource(source);
780 // scanner.phpMode = true;
781 // int token = Scanner.TokenNameWHITESPACE;
782 // while ((token = scanner.getNextToken()) != Scanner.TokenNameEOF) {
783 // if (token == Scanner.TokenNameVariable) {
784 // varName = scanner.getCurrentTokenSource();
785 // if (varName.length >= prefix.length()) {
786 // matchesVarName = true;
787 // for (int i = 0; i < prefix.length(); i++) {
788 // if (prefix.charAt(i) != varName[i]) {
789 // matchesVarName = false;
793 // if (matchesVarName) {
794 // LocalVariableProposal prop = new LocalVariableProposal(new
795 // 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
820 // 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 =
827 // ProjectPrefUtil.getMiscProjectsPreferenceValue(project,
828 // IPreferenceConstants.PHP_BOOKMARK_DEFAULT);
829 // if (bookmarkString != null && !bookmarkString.equals("")) {
830 // String[] bookmarks = ExternalInterface.getBookmarkNames();
831 // boolean foundBookmark = false;
832 // for (int i = 0; i < bookmarks.length; i++) {
833 // if (bookmarks[i].equals(bookmarkString)) {
834 // foundBookmark = true;
837 // if (!foundBookmark) {
838 // return sqlResults;
840 // // Bookmark bookmark = sqlBookMarks.find(bookmarkString);
841 // ArrayList sqlList = new ArrayList();
842 // if (!ExternalInterface.isBookmarkConnected(bookmarkString)) {
843 // ExternalInterface.connectBookmark(bookmarkString, null);
844 // if (!ExternalInterface.isBookmarkConnected(bookmarkString)) {
845 // return sqlResults;
848 // // if (ExternalInterface.isBookmarkConnected(bookmarkString)) {
850 // int start = context.getStart();
851 // int end = context.getEnd();
852 // String foundSQLTableName = sqlTable.getTableName();
854 // String columnName;
855 // String prefixWithoutDollar = prefix;
856 // boolean isDollarPrefix = false;
857 // if (prefix.length() > 0 && prefix.charAt(0) == '$') {
858 // prefixWithoutDollar = prefix.substring(1);
859 // isDollarPrefix = true;
861 // IRegion region = new Region(start, end - start);
863 // if (!isDollarPrefix) {
864 // String[] tableNames = ExternalInterface.getMatchingTableNames(null,
865 // bookmarkString, prefixWithoutDollar, null, false);
866 // for (int i = 0; i < tableNames.length; i++) {
867 // sqlList.add(new SQLProposal(tableNames[i], context, region, viewer,
868 // PHPUiImages.get(PHPUiImages.IMG_TABLE)));
872 // String[] columnNames = ExternalInterface.getMatchingColumnNames(null,
873 // bookmarkString, prefixWithoutDollar, null, false);
874 // for (int i = 0; i < columnNames.length; i++) {
875 // sqlList.add(new SQLProposal(columnNames[i], context, region, viewer,
876 // PHPUiImages.get(PHPUiImages.IMG_TABLE)));
879 // sqlResults = new IPHPCompletionProposal[sqlList.size()];
880 // for (int i = 0; i < sqlList.size(); i++) {
881 // sqlResults[i] = (SQLProposal) sqlList.get(i);
883 // } catch (Exception /* NotConnectedException */ e) {
889 // return sqlResults;
891 private boolean looksLikeMethod(PHPCodeReader reader) throws IOException {
892 int curr = reader.read();
893 while (curr != PHPCodeReader.EOF && Character.isWhitespace((char) curr))
894 curr = reader.read();
896 if (curr == PHPCodeReader.EOF)
899 return Scanner.isPHPIdentifierPart((char) curr);
902 private int guessContextInformationPosition(ITextViewer viewer, int offset) {
903 int contextPosition = offset;
904 IDocument document = viewer.getDocument();
907 PHPCodeReader reader = new PHPCodeReader();
908 reader.configureBackwardReader(document, offset, true, true);
910 int nestingLevel = 0;
912 int curr = reader.read();
913 while (curr != PHPCodeReader.EOF) {
915 if (')' == (char) curr)
918 else if ('(' == (char) curr) {
921 if (nestingLevel < 0) {
922 int start = reader.getOffset();
923 if (looksLikeMethod(reader))
928 curr = reader.read();
930 } catch (IOException e) {
932 return contextPosition;
936 * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
938 public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
939 int contextInformationPosition = guessContextInformationPosition(viewer, offset);
940 List result = addContextInformations(viewer, contextInformationPosition);
941 return (IContextInformation[]) result.toArray(new IContextInformation[result.size()]);
944 private List addContextInformations(ITextViewer viewer, int offset) {
945 ICompletionProposal[] proposals = internalComputeCompletionProposals(viewer, offset, -1);
946 List result = new ArrayList();
947 for (int i = 0; i < proposals.length; i++) {
948 IContextInformation contextInformation = proposals[i].getContextInformation();
949 if (contextInformation != null) {
950 ContextInformationWrapper wrapper = new ContextInformationWrapper(contextInformation);
951 wrapper.setContextInformationPosition(offset);
959 * Order the given proposals.
961 private ICompletionProposal[] order(ICompletionProposal[] proposals) {
962 Arrays.sort(proposals, fComparator);
963 // int len = proposals.length;
967 // for (int i = 0; i < len; i++) {
968 // System.out.println(proposals[i].getDisplayString());
974 * (non-Javadoc) Method declared on IContentAssistProcessor
976 public char[] getCompletionProposalAutoActivationCharacters() {
977 return fProposalAutoActivationSet;
978 // return null; // new char[] { '$' };
982 * (non-Javadoc) Method declared on IContentAssistProcessor
984 public char[] getContextInformationAutoActivationCharacters() {
989 * (non-Javadoc) Method declared on IContentAssistProcessor
991 public IContextInformationValidator getContextInformationValidator() {
992 if (fValidator == null)
993 fValidator = new JavaParameterListValidator();
998 * (non-Javadoc) Method declared on IContentAssistProcessor
1000 public String getErrorMessage() {