You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@uima.apache.org by pk...@apache.org on 2013/07/17 10:23:19 UTC

svn commit: r1504044 [7/12] - in /uima/sandbox/ruta/trunk/ruta-ep-ide: ./ schema/ src/ src/main/ src/main/antlr3/ src/main/antlr3/org/ src/main/antlr3/org/apache/ src/main/antlr3/org/apache/uima/ src/main/antlr3/org/apache/uima/ruta/ src/main/antlr3/or...

Added: uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaCompletionEngine.java
URL: http://svn.apache.org/viewvc/uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaCompletionEngine.java?rev=1504044&view=auto
==============================================================================
--- uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaCompletionEngine.java (added)
+++ uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaCompletionEngine.java Wed Jul 17 08:23:15 2013
@@ -0,0 +1,640 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.uima.ruta.ide.core.codeassist;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.uima.UIMAFramework;
+import org.apache.uima.resource.ResourceManager;
+import org.apache.uima.resource.metadata.TypeDescription;
+import org.apache.uima.resource.metadata.TypeSystemDescription;
+import org.apache.uima.ruta.ide.RutaIdeCorePlugin;
+import org.apache.uima.ruta.ide.core.IRutaKeywords;
+import org.apache.uima.ruta.ide.core.RutaExtensionManager;
+import org.apache.uima.ruta.ide.core.RutaKeywordsManager;
+import org.apache.uima.ruta.ide.core.builder.RutaProjectUtils;
+import org.apache.uima.ruta.ide.core.extensions.ICompletionExtension;
+import org.apache.uima.ruta.ide.core.parser.RutaParseUtils;
+import org.apache.uima.ruta.ide.parser.ast.ComponentDeclaration;
+import org.apache.uima.ruta.ide.parser.ast.ComponentReference;
+import org.apache.uima.ruta.ide.parser.ast.RutaAction;
+import org.apache.uima.ruta.ide.parser.ast.RutaCondition;
+import org.apache.uima.ruta.ide.parser.ast.RutaModuleDeclaration;
+import org.apache.uima.ruta.ide.parser.ast.RutaTypeConstants;
+import org.apache.uima.ruta.ide.parser.ast.RutaVariableReference;
+import org.apache.uima.util.InvalidXMLException;
+import org.apache.uima.util.XMLInputSource;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.dltk.ast.ASTNode;
+import org.eclipse.dltk.codeassist.RelevanceConstants;
+import org.eclipse.dltk.codeassist.ScriptCompletionEngine;
+import org.eclipse.dltk.compiler.CharOperation;
+import org.eclipse.dltk.compiler.env.IModuleSource;
+import org.eclipse.dltk.core.CompletionProposal;
+import org.eclipse.dltk.core.IField;
+import org.eclipse.dltk.core.IMethod;
+import org.eclipse.dltk.core.IModelElement;
+import org.eclipse.dltk.core.IScriptProject;
+import org.eclipse.dltk.core.IType;
+import org.eclipse.dltk.core.ModelException;
+import org.eclipse.dltk.internal.core.SourceField;
+import org.eclipse.dltk.internal.core.SourceMethod;
+import org.eclipse.dltk.internal.core.SourceModule;
+
+public class RutaCompletionEngine extends ScriptCompletionEngine {
+
+  protected RutaCompletionParser parser;
+
+  protected IModuleSource sourceModule;
+
+  protected final static boolean TRACE_COMPLETION_TIME = false;
+
+  private ICompletionExtension[] extensions;
+
+  private URLClassLoader classloader = null;
+
+  public RutaCompletionEngine() {
+    extensions = RutaExtensionManager.getDefault().getCompletionExtensions();
+    this.parser = new RutaCompletionParser(extensions);
+  }
+
+  @Override
+  protected int getEndOfEmptyToken() {
+    return actualCompletionPosition;
+  }
+
+  @Override
+  protected String processMethodName(IMethod method, String token) {
+    return RutaParseUtils.processMethodName(method, token);
+  }
+
+  @Override
+  protected String processTypeName(IType type, String token) {
+    return RutaParseUtils.processTypeName(type, token);
+  }
+
+  public void complete(IModuleSource module, int position, int i) {
+    this.sourceModule = module;
+    this.actualCompletionPosition = position;
+    this.offset = i;
+    this.requestor.beginReporting();
+    String content = module.getSourceContents();
+    if (position < 0 || position > content.length()) {
+      return;
+    }
+
+    TMAutoCompletionToolkit tk = new TMAutoCompletionToolkit(content, position);
+
+    String startPart = tk.getWordPrefix();
+    this.setSourceRange(position - startPart.length(), position);
+
+    // 090813:
+    RutaModuleDeclaration parsed = (RutaModuleDeclaration) this.parser.parse(module);
+
+    // types = getShortNames(types);
+    if (classloader == null) {
+      IScriptProject scriptProject = sourceModule.getModelElement().getScriptProject();
+      try {
+        Collection<String> dependencies = new ArrayList<String>();
+        // TODO UIMA-3077
+//        Collection<String> dependencies = RutaLaunchConfigurationDelegate
+//                .getClassPath(scriptProject);
+        URL[] urls = new URL[dependencies.size()];
+        int counter = 0;
+        for (String dep : dependencies) {
+          urls[counter] = new File(dep).toURL();
+          counter++;
+        }
+        classloader = new URLClassLoader(urls);
+//      } catch (CoreException e) {
+//        RutaIdeCorePlugin.error(e);
+      } catch (MalformedURLException e) {
+        RutaIdeCorePlugin.error(e);
+      }
+    }
+
+    ASTNode node;
+    if (parsed != null) {
+      try {
+        RutaReferenceVisitor referenceVisitor = new RutaReferenceVisitor(actualCompletionPosition);
+        parsed.traverse(referenceVisitor);
+        node = referenceVisitor.getResult();
+
+        if (node == null) {
+          doCompletionOnEmptyStatement(module, position, i);
+          doCompletionOnDeclaration(module, startPart);
+        } else if (node instanceof RutaVariableReference) {
+          int type = ((RutaVariableReference) node).getType();
+          doCompletionOnVarRef(module, parsed, startPart, type,
+                  ((RutaVariableReference) node).getName());
+          if (RutaParseUtils.isAtLineStart(node, content)) {
+            doCompletionOnDeclaration(module, startPart);
+          }
+        } else if (node instanceof ComponentDeclaration) {
+          doCompletionOnComponentDeclaration(module, parsed, startPart,
+                  ((ComponentDeclaration) node).getType(), startPart);
+        } else if (node instanceof ComponentReference) {
+          doCompletionOnComponentReference(module, parsed, startPart,
+                  ((ComponentReference) node).getType(), startPart);
+        } else if (node instanceof RutaAction) {
+          doCompletionOnAction(module, parsed, startPart, RutaTypeConstants.RUTA_TYPE_A, startPart);
+        } else if (node instanceof RutaCondition) {
+          doCompletionOnCondition(module, parsed, startPart, RutaTypeConstants.RUTA_TYPE_C,
+                  startPart);
+        }
+        // if(requestor.)
+        // doCompletionOnKeyword(position, i, startPart);
+
+        // }
+      } catch (Exception e) {
+        System.out.println("no completion node found");
+      } finally {
+        this.requestor.endReporting();
+      }
+    }
+  }
+
+  private void doCompletionOnComponentReference(IModuleSource cu, RutaModuleDeclaration parsed,
+          String startPart, int type, String complString) {
+    Collection<String> importedEngines = parsed.descriptorInfo.getImportedEngines();
+    for (String string : importedEngines) {
+      if (match(complString, string)) {
+        addProposal(complString, string, CompletionProposal.PACKAGE_REF);
+      }
+    }
+    Collection<String> importedScripts = parsed.descriptorInfo.getImportedScripts();
+    for (String each : importedScripts) {
+      String[] split = each.split("\\.");
+      String string = split[split.length - 1];
+      if (match(complString, string)) {
+        addProposal(complString, string, CompletionProposal.PACKAGE_REF);
+      }
+    }
+    List<IMethod> blocks = new ArrayList<IMethod>();
+    try {
+      IModelElement[] children = sourceModule.getModelElement().getModel().getChildren();
+      for (IModelElement iModelElement : children) {
+        if (iModelElement instanceof SourceMethod) {
+          collectBlocks((SourceMethod) iModelElement, blocks);
+        }
+      }
+    } catch (ModelException e) {
+    }
+    for (IMethod m : blocks) {
+      String string = m.getElementName();
+      if (match(complString, string)) {
+        addProposal(complString, string, CompletionProposal.PACKAGE_REF);
+      }
+    }
+  }
+
+  private void doCompletionOnComponentDeclaration(IModuleSource cu, RutaModuleDeclaration parsed,
+          String startPart, int type, String complString) throws Exception {
+    if (type == ComponentDeclaration.SCRIPT) {
+      List<IFolder> scriptFolders = RutaProjectUtils.getAllScriptFolders(sourceModule
+              .getModelElement().getScriptProject());
+
+      List<String> scripts = new ArrayList<String>();
+      for (IFolder folder : scriptFolders) {
+        try {
+          scripts.addAll(collectScripts(folder, ""));
+        } catch (CoreException e) {
+        }
+      }
+      for (String string : scripts) {
+        if (match(complString, string)) {
+          addProposal(complString, string, CompletionProposal.PACKAGE_REF);
+        }
+      }
+    } else if (type == ComponentDeclaration.UIMAFIT_ENGINE) {
+      List<String> engines = new ArrayList<String>();
+      // TODO: collect engines
+      for (String string : engines) {
+        if (match(complString, string)) {
+          addProposal(complString, string, CompletionProposal.PACKAGE_REF);
+        }
+      }
+    } else if (type == ComponentDeclaration.ENGINE) {
+      List<IFolder> descriptorFolders = RutaProjectUtils.getAllDescriptorFolders(sourceModule
+              .getModelElement().getScriptProject().getProject());
+      List<String> engines = new ArrayList<String>();
+      for (IFolder folder : descriptorFolders) {
+        try {
+          engines.addAll(collectEngines(folder, ""));
+        } catch (CoreException e) {
+        }
+      }
+      for (String string : engines) {
+        if (match(complString, string)) {
+          addProposal(complString, string, CompletionProposal.PACKAGE_REF);
+        }
+      }
+    } else {
+      List<IFolder> descriptorFolders = RutaProjectUtils.getAllDescriptorFolders(sourceModule
+              .getModelElement().getScriptProject().getProject());
+      List<String> tss = new ArrayList<String>();
+      for (IFolder folder : descriptorFolders) {
+        try {
+          tss.addAll(collectTypeSystems(folder, ""));
+        } catch (CoreException e) {
+        }
+      }
+      for (String string : tss) {
+        if (match(complString, string)) {
+          addProposal(complString, string, CompletionProposal.PACKAGE_REF);
+        }
+      }
+    }
+  }
+
+  private List<String> collectEngines(IFolder folder, String prefix) throws CoreException {
+    List<String> result = new ArrayList<String>();
+    IResource[] members = folder.members();
+    for (IResource iResource : members) {
+      if (iResource instanceof IFolder) {
+        IFolder folder2 = (IFolder) iResource;
+        String newPrefix = prefix + folder2.getProjectRelativePath().lastSegment() + ".";
+        result.addAll(collectEngines(folder2, newPrefix));
+      } else if (iResource instanceof IFile) {
+        IFile file = (IFile) iResource;
+        if (file.getFileExtension().equals("xml")) {
+          File f = new File(file.getLocation().toPortableString());
+          if (f.exists()) {
+            try {
+              UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(f));
+              result.add(prefix + file.getName().substring(0, file.getName().length() - 4));
+            } catch (Exception e) {
+            }
+          }
+        }
+      }
+    }
+    return result;
+  }
+
+  private List<String> collectTypeSystems(IFolder folder, String prefix) throws CoreException {
+    List<String> result = new ArrayList<String>();
+    IResource[] members = folder.members();
+    for (IResource iResource : members) {
+      if (iResource instanceof IFolder) {
+        IFolder folder2 = (IFolder) iResource;
+        String newPrefix = prefix + folder2.getProjectRelativePath().lastSegment() + ".";
+        result.addAll(collectTypeSystems(folder2, newPrefix));
+      } else if (iResource instanceof IFile) {
+        IFile file = (IFile) iResource;
+        String fileExtension = file.getFileExtension();
+        if (fileExtension != null && fileExtension.equals("xml")) {
+          File f = new File(file.getLocation().toPortableString());
+          if (f.exists()) {
+            try {
+              UIMAFramework.getXMLParser().parseTypeSystemDescription(new XMLInputSource(f));
+              result.add(prefix + file.getName().substring(0, file.getName().length() - 4));
+            } catch (Exception e) {
+            }
+          }
+        }
+      }
+    }
+    return result;
+  }
+
+  private List<String> collectScripts(IFolder folder, String prefix) throws CoreException {
+    List<String> result = new ArrayList<String>();
+    IResource[] members = folder.members();
+    for (IResource iResource : members) {
+      if (iResource instanceof IFolder) {
+        IFolder folder2 = (IFolder) iResource;
+        String newPrefix = prefix + folder2.getProjectRelativePath().lastSegment() + ".";
+        result.addAll(collectScripts(folder2, newPrefix));
+      } else if (iResource instanceof IFile) {
+        IFile file = (IFile) iResource;
+        if (file.getFileExtension().equals("tm")) {
+          result.add(prefix + file.getName().substring(0, file.getName().length() - 5));
+        }
+      }
+    }
+    return result;
+  }
+
+  private void doCompletionOnDeclaration(IModuleSource cu, String startPart) {
+    String[] keywords = RutaKeywordsManager.getKeywords(IRutaKeywords.DECLARATION);
+    for (String string : keywords) {
+      if (match(startPart, string)) {
+        addProposal(startPart, string, CompletionProposal.KEYWORD);
+      }
+    }
+  }
+
+  private Set<String> importTypeSystem(String xmlFilePath, IProject project)
+          throws InvalidXMLException, IOException {
+    IFolder folder = project.getProject()
+            .getFolder(RutaProjectUtils.getDefaultDescriptorLocation());
+    xmlFilePath = xmlFilePath.substring(0, xmlFilePath.length() - 5) + "TypeSystem.xml";
+    return getTypes(folder, xmlFilePath);
+  }
+
+  private Set<String> getTypes(IFolder folder, String filePath) throws InvalidXMLException,
+          IOException {
+    Set<String> types = new HashSet<String>();
+    IFile iFile = getFile(folder, filePath);
+    URL url;
+    try {
+      url = iFile.getLocationURI().toURL();
+      ResourceManager resMgr = UIMAFramework.newDefaultResourceManager();
+      resMgr.setDataPath(folder.getLocation().toPortableString());
+      types = getTypes(url, resMgr);
+    } catch (MalformedURLException e) {
+      e.printStackTrace();
+    }
+    return types;
+  }
+
+  private Set<String> getTypes(URL resource, ResourceManager resMgr) throws IOException,
+          InvalidXMLException {
+    Set<String> types = new HashSet<String>();
+    TypeSystemDescription typeSysDescr = null;
+    typeSysDescr = UIMAFramework.getXMLParser().parseTypeSystemDescription(
+            new XMLInputSource(resource));
+    typeSysDescr.resolveImports(resMgr);
+    for (TypeDescription each : typeSysDescr.getTypes()) {
+      String name = each.getName();
+      String[] nameSpace = name.split("[.]");
+      types.add(nameSpace[nameSpace.length - 1]);
+      types.add(name);
+    }
+    return types;
+  }
+
+  private IFile getFile(IFolder folder, String filePath) {
+    int lastDot = filePath.lastIndexOf('.');
+    int sndLastDot = filePath.lastIndexOf('.', lastDot - 1);
+    String fName = filePath;
+    if (sndLastDot >= 0) {
+      String subFolder = filePath.substring(0, sndLastDot);
+      folder = folder.getFolder(subFolder);
+      fName = filePath.substring(sndLastDot + 1);
+    }
+    return folder.getFile(fName);
+  }
+
+  private void doCompletionOnAction(IModuleSource cu, RutaModuleDeclaration parsed,
+          String startPart, int type, String complString) {
+    String[] keywords = RutaKeywordsManager.getKeywords(IRutaKeywords.ACTION);
+    for (String string : keywords) {
+      if (match(complString, string)) {
+        addProposal(complString, string + "()", string, CompletionProposal.METHOD_NAME_REFERENCE);
+      }
+    }
+  }
+
+  private void doCompletionOnCondition(IModuleSource cu, RutaModuleDeclaration parsed,
+          String startPart, int type, String complString) {
+    if (complString.startsWith("-")) {
+      complString = complString.substring(1, complString.length());
+    }
+    String[] keywords = RutaKeywordsManager.getKeywords(IRutaKeywords.CONDITION);
+    for (String string : keywords) {
+      if (match(complString, string)) {
+        addProposal(complString, string + "()", string, CompletionProposal.METHOD_NAME_REFERENCE);
+      }
+    }
+  }
+
+  private void doCompletionOnVarRef(IModuleSource cu, RutaModuleDeclaration parsed,
+          String startPart, int type, String complString) {
+    Collection<String> types = new HashSet<String>();
+    if (type == RutaTypeConstants.RUTA_TYPE_AT) {
+      try {
+        IPath path = sourceModule.getModelElement().getPath();
+        path = path.removeFirstSegments(2);
+        types = importTypeSystem(path.toPortableString(), sourceModule.getModelElement()
+                .getScriptProject().getProject());
+      } catch (Exception e) {
+      }
+      for (String string : types) {
+        if (match(startPart, string)) {
+          addProposal(startPart, string, CompletionProposal.TYPE_REF);
+        }
+      }
+    } else {
+      IModelElement modelElement = sourceModule.getModelElement();
+      if (modelElement instanceof SourceModule) {
+        SourceModule sm = (SourceModule) modelElement;
+        try {
+          IField[] fields = sm.getFields();
+          for (IField iField : fields) {
+            SourceField f = (SourceField) iField;
+            int fieldType = RutaParseUtils.getTypeOfIModelElement(f);
+            if (RutaTypeConstants.RUTA_TYPE_N == type) {
+              if (fieldType == RutaTypeConstants.RUTA_TYPE_N
+                      || fieldType == RutaTypeConstants.RUTA_TYPE_I
+                      || fieldType == RutaTypeConstants.RUTA_TYPE_D
+                      || fieldType == RutaTypeConstants.RUTA_TYPE_F) {
+                addProposal(startPart, f.getElementName(), CompletionProposal.LOCAL_VARIABLE_REF);
+              }
+            } else if (type == fieldType) {
+              addProposal(startPart, f.getElementName(), CompletionProposal.LOCAL_VARIABLE_REF);
+            }
+
+          }
+        } catch (ModelException e) {
+        }
+
+      }
+    }
+  }
+
+  private boolean match(String complString, String string) {
+    return string.toLowerCase().startsWith(complString.toLowerCase())
+            || removeLowerCase(string).startsWith(complString);
+  }
+
+  private void collectFields(SourceMethod sm, List<IField> fields) throws ModelException {
+    IModelElement[] children = sm.getChildren();
+    for (IModelElement me : children) {
+      if (me instanceof SourceMethod) {
+        collectFields((SourceMethod) me, fields);
+      } else if (me instanceof SourceField) {
+        fields.add((IField) me);
+      }
+    }
+  }
+
+  private void collectBlocks(SourceMethod sm, List<IMethod> blocks) throws ModelException {
+    blocks.add(sm);
+    IModelElement[] children = sm.getChildren();
+    for (IModelElement me : children) {
+      if (me instanceof SourceMethod) {
+        collectBlocks((SourceMethod) me, blocks);
+      }
+    }
+  }
+
+  private String removeLowerCase(String string) {
+    String replaceAll = string.replaceAll("\\p{Lower}|[.]", "");
+    return replaceAll;
+  }
+
+  @SuppressWarnings({ "unchecked" })
+  private void doCompletionOnEmptyStatement(IModuleSource cu, int position, int i) {
+    int kind = CompletionProposal.LOCAL_VARIABLE_REF;
+    // doCompletionOnKeyword(position, i, "");
+    if (!super.requestor.isIgnored(kind)) {
+      suggestFields(cu);
+    }
+  }
+
+  /**
+   * @param cu
+   */
+  private void suggestFields(IModuleSource cu) {
+    // try {
+    // if (cu != null) {
+    // IField[] fieldsArray = sourceModule.getFields();
+    // for (IField field : fieldsArray) {
+    // int relevance = RelevanceConstants.R_EXACT_EXPECTED_TYPE;
+    // // accept result
+    // super.noProposal = false;
+    // int kind = CompletionProposal.LOCAL_VARIABLE_REF;
+    // if (!super.requestor.isIgnored(kind)) {
+    // CompletionProposal proposal = super.createProposal(kind, actualCompletionPosition);
+    // proposal.setRelevance(relevance);
+    // proposal.setModelElement(field);
+    // proposal.setName(field.getElementName());
+    // proposal.setCompletion(field.getElementName());
+    // proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition
+    // - this.offset);
+    // try {
+    // proposal.setFlags(field.getFlags());
+    // } catch (ModelException e) {
+    // }
+    // this.requestor.accept(proposal);
+    // if (DEBUG) {
+    // this.printDebug(proposal);
+    // }
+    // }
+    // }
+    // }
+    // } catch (ModelException e) {
+    // }
+  }
+
+  /**
+   * @param complString
+   * @param names
+   * @param field
+   */
+  private void addProposal(String complString, List names, IField field) {
+    char[] fieldName = field.getElementName().toCharArray();
+    char[] complFragment = complString.toCharArray();
+
+    if (CharOperation.camelCaseMatch(complString.toCharArray(), fieldName)
+            || match(complString, field.getElementName())) {
+
+      int relevance = RelevanceConstants.R_DEFAULT + 1;
+      relevance += computeRelevanceForCaseMatching(complFragment, field.getElementName());
+
+      // accept result
+      super.noProposal = false;
+      int kind = CompletionProposal.LOCAL_VARIABLE_REF;
+      if (!super.requestor.isIgnored(kind)) {
+        CompletionProposal proposal = super.createProposal(kind, actualCompletionPosition);
+        proposal.setRelevance(relevance);
+        proposal.setModelElement(field);
+        proposal.setName(field.getElementName());
+        proposal.setCompletion(field.getElementName());
+        proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset);
+        try {
+          proposal.setFlags(field.getFlags());
+        } catch (ModelException e) {
+        }
+        this.requestor.accept(proposal);
+        if (DEBUG) {
+          this.printDebug(proposal);
+        }
+      }
+    }
+  }
+
+  private void addProposal(String complString, String string, int kind) {
+    addProposal(complString, string, string, kind);
+  }
+
+  private void addProposal(String complString, String string, String name, int kind) {
+    char[] fieldName = string.toCharArray();
+    char[] complFragment = complString.toCharArray();
+
+    char[] pattern = null;
+    if (complString.length() > 0) {
+      pattern = complString.toCharArray();
+    }
+    if (CharOperation.camelCaseMatch(pattern, fieldName) || match(complString, string)) {
+
+      int relevance = RelevanceConstants.R_DEFAULT + 1;
+      relevance += computeRelevanceForCaseMatching(complFragment, string);
+
+      // accept result
+      super.noProposal = false;
+      if (!super.requestor.isIgnored(kind)) {
+        CompletionProposal proposal = super.createProposal(kind, actualCompletionPosition);
+        proposal.setRelevance(relevance);
+        proposal.setName(name);
+        proposal.setCompletion(string);
+        proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset);
+        // try {
+        // proposal.setFlags(field.getFlags());
+        // } catch (ModelException e) {
+        // }
+        this.requestor.accept(proposal);
+        if (DEBUG) {
+          this.printDebug(proposal);
+        }
+      }
+    }
+  }
+
+  private void doCompletionOnKeyword(int position, int pos, String startPart) {
+    List<String> keywords = new ArrayList<String>();
+    for (int i = 0; i < IRutaKeywords.END_INDEX; i++) {
+      keywords.addAll(Arrays.asList(RutaKeywordsManager.getKeywords(i)));
+    }
+    char[][] keyWordsArray = new char[keywords.size()][];
+    for (int a = 0; a < keywords.size(); a++) {
+      keyWordsArray[a] = keywords.get(a).toCharArray();
+    }
+    findKeywords(startPart.toCharArray(), keywords.toArray(new String[0]), true);
+  }
+
+}

Added: uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaCompletionParser.java
URL: http://svn.apache.org/viewvc/uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaCompletionParser.java?rev=1504044&view=auto
==============================================================================
--- uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaCompletionParser.java (added)
+++ uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaCompletionParser.java Wed Jul 17 08:23:15 2013
@@ -0,0 +1,396 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.uima.ruta.ide.core.codeassist;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.uima.ruta.ide.core.extensions.ICompletionExtension;
+import org.apache.uima.ruta.ide.core.parser.RutaParseUtils;
+import org.apache.uima.ruta.ide.parser.ast.RutaStatement;
+import org.eclipse.dltk.ast.ASTNode;
+import org.eclipse.dltk.ast.ASTVisitor;
+import org.eclipse.dltk.ast.declarations.MethodDeclaration;
+import org.eclipse.dltk.ast.declarations.ModuleDeclaration;
+import org.eclipse.dltk.ast.declarations.TypeDeclaration;
+import org.eclipse.dltk.ast.expressions.Expression;
+import org.eclipse.dltk.ast.references.SimpleReference;
+import org.eclipse.dltk.ast.statements.Block;
+import org.eclipse.dltk.ast.statements.Statement;
+import org.eclipse.dltk.codeassist.complete.CompletionNodeFound;
+import org.eclipse.dltk.compiler.env.IModuleSource;
+
+public class RutaCompletionParser extends RutaAssistParser {
+  private static class RutaEmptyCompleteStatement extends RutaStatement {
+    public RutaEmptyCompleteStatement(List expressions) {
+      super(expressions);
+    }
+  }
+
+  private ICompletionExtension[] extensions;
+
+  public RutaCompletionParser(ICompletionExtension[] extensions) {
+    this.extensions = extensions;
+  }
+
+  /**
+   * Called then element could not be found.
+   */
+  public void handleNotInElement(ASTNode node, int position) {
+    if (node != null && node.sourceStart() <= position && position <= node.sourceEnd()) {
+      // this is empty module case
+      if (node instanceof ModuleDeclaration) {
+        ModuleDeclaration unit = (ModuleDeclaration) node;
+        List exprs = new ArrayList();
+        exprs.add(new SimpleReference(position, position, ""));
+        RutaEmptyCompleteStatement statement = new RutaEmptyCompleteStatement(exprs);
+        unit.addStatement(statement);
+        this.parseBlockStatements(statement, unit, position);
+      } else if (node instanceof MethodDeclaration) {
+        // empty keyword like completion.
+        MethodDeclaration method = (MethodDeclaration) node;
+        List exprs = new ArrayList();
+        exprs.add(new SimpleReference(position, position, ""));
+        RutaEmptyCompleteStatement statement = new RutaEmptyCompleteStatement(exprs);
+        method.getStatements().add(statement);
+        this.parseBlockStatements(statement, method, position);
+      } else if (node instanceof TypeDeclaration) {
+        // empty keyword like completion.
+        TypeDeclaration type = (TypeDeclaration) node;
+        List exprs = new ArrayList();
+        exprs.add(new SimpleReference(position, position, ""));
+        RutaEmptyCompleteStatement statement = new RutaEmptyCompleteStatement(exprs);
+        type.getStatements().add(statement);
+        // this.assistNodeParent = node;
+        this.parseBlockStatements(statement, type, position);
+        // } else if (node instanceof RutaExecuteExpression) {
+        // // empty keyword like completion.
+        // List exprs = new ArrayList();
+        // exprs.add(new SimpleReference(position, position, ""));
+        // RutaEmptyCompleteStatement statement = new
+        // RutaEmptyCompleteStatement(
+        // exprs);
+        // this.parseBlockStatements(statement, node, position);
+      }
+    }
+  }
+
+  /*
+   * (non-Javadoc)
+   * 
+   * @see
+   * org.eclipse.dltk.codeassist.IAssistParser#parseBlockStatements(org.eclipse.dltk.ast.ASTNode,
+   * org.eclipse.dltk.ast.ASTNode, int)
+   */
+  public void parseBlockStatements(ASTNode node, ASTNode inNode, int position) {
+    // if (node instanceof RutaStatement) {
+    // RutaStatement statement = (RutaStatement) node;
+    // List expressions = statement.getExpressions();
+    // int len = expressions.size();
+    // boolean first = false;
+    // String completionToken = null;
+    // ASTNode completionNode = null;
+    // for (int i = 0; i < len; ++i) {
+    // ASTNode n = (ASTNode) expressions.get(i);
+    // if (n.sourceStart() <= position && n.sourceEnd() >= position
+    // || (node instanceof RutaEmptyCompleteStatement)) {
+    // if (i == 0) {
+    // first = true;
+    // }
+    // completionNode = n;
+    // }
+    // }
+    // if (completionNode == null) {
+    // // TODO: Add inner completion here.
+    // if (len > 0) {
+    // // ASTNode firstNode = (ASTNode) expressions.get(0);
+    // // if (position > firstNode.sourceEnd()) {
+    // // // This could be variable completion.
+    // // boolean provideDollar =
+    // // !checkVariableWithoutDollarCompletion(
+    // // statement, position);
+    // // this.assistNodeParent = inNode;
+    // // SimpleReference ref = new SimpleReference(position,
+    // // position, "");
+    // // ASTNode nde = new CompletionOnVariable("", ref, node,
+    // // inNode, true, provideDollar);
+    // // throw new CompletionNodeFound(nde, null);
+    // // }
+    // String[] keywords = checkKeywords(completionToken, MODULE);
+    // ASTNode nde = new CompletionOnKeywordArgumentOrFunctionArgument("",
+    // (RutaStatement) node, keywords, position);
+    // this.assistNodeParent = inNode;
+    // throw new CompletionNodeFound(nde, null/* ((TypeDeclaration)inNode).scope */);
+    //
+    // } else {
+    // completionToken = "";
+    // }
+    // } else if (completionNode instanceof SimpleReference) {
+    // int maxLen = position - completionNode.sourceStart();
+    // completionToken = ((SimpleReference) completionNode).getName();
+    // // We need to cut some sumbols if node is begger then position.
+    // if (completionToken.length() > maxLen && maxLen > 0) {
+    // completionToken = completionToken.substring(0, maxLen);
+    // }
+    // } /*
+    // * else if (completionNode instanceof RutaBlockExpression) { RutaBlockExpression
+    // * block = (RutaBlockExpression) completionNode;
+    // *
+    // * List s = block.parseBlock(); if (s != null) { int slen = s.size(); for (int u = 0; u <
+    // * slen; ++u) { ASTNode n = (ASTNode) s.get(u); n.setStart(n.sourceStart() -
+    // * block.sourceStart()); n.setEnd(n.sourceEnd() - block.sourceStart());
+    // * RutaASTUtil.extendStatement(n, block.getBlock()); n.setStart(n.sourceStart() +
+    // * block.sourceStart()); n.setEnd(n.sourceEnd() + block.sourceStart()); if (n != null &&
+    // * n.sourceStart() <= position && n.sourceEnd() >= position) { parseBlockStatements(n,
+    // * inNode, position); } } } handleNotInElement(inNode, position); }
+    // */
+    // if (completionNode instanceof StringLiteral) {
+    // int maxLen = position - completionNode.sourceStart();
+    // int pos = maxLen;
+    // SimpleReference tok = RutaParseUtils.extractVariableFromString(
+    // (StringLiteral) completionNode, pos);
+    // if (tok != null) {
+    // this.assistNodeParent = inNode;
+    // ASTNode nde = new CompletionOnVariable(tok.getName(), tok, node, inNode, false);
+    // throw new CompletionNodeFound(nde, null);
+    // } else {
+    // this.assistNodeParent = inNode;
+    // SimpleReference ref = new SimpleReference(position, position, "");
+    // ASTNode nde = new CompletionOnVariable("", ref, node, inNode, true);
+    // throw new CompletionNodeFound(nde, null);
+    // }
+    // }
+    // // if (completionNode instanceof RutaExecuteExpression) {
+    // // RutaExecuteExpression expr = (RutaExecuteExpression)
+    // // completionNode;
+    // // List exprs = expr.parseExpression();
+    // // for (int i = 0; i < exprs.size(); ++i) {
+    // // ASTNode n = (ASTNode) exprs.get(i);
+    // // if (n.sourceStart() <= position
+    // // && n.sourceEnd() >= position) {
+    // // parseBlockStatements(n, expr, position);
+    // // }
+    // // }
+    // // handleNotInElement(expr, position);
+    // // }
+    // if (completionToken != null && completionToken.startsWith("$")) {
+    // // Argument name completion...
+    // this.assistNodeParent = inNode;
+    // ASTNode nde = new CompletionOnVariable(completionToken, completionNode, node, inNode, false);
+    // throw new CompletionNodeFound(nde, null);
+    // } else {
+    // // This is keyword or function completion.
+    // if (inNode instanceof ModuleDeclaration && completionNode != null && first) {
+    // String[] keywords = checkKeywords(completionToken, MODULE);
+    // ASTNode nde = new CompletionOnKeywordOrFunction(completionToken, completionNode, node,
+    // keywords);
+    // this.assistNodeParent = inNode;
+    // throw new CompletionNodeFound(nde, ((ModuleDeclaration) inNode).scope);
+    // } else if (inNode instanceof MethodDeclaration && completionNode != null && first) {
+    // String[] keywords = checkKeywords(completionToken, FUNCTION);
+    // ASTNode nde = new CompletionOnKeywordOrFunction(completionToken, completionNode, node,
+    // keywords);
+    // this.assistNodeParent = inNode;
+    // throw new CompletionNodeFound(nde, ((MethodDeclaration) inNode).scope);
+    // } else if (inNode instanceof TypeDeclaration && completionNode != null && first) {
+    // String[] keywords = checkKeywords(completionToken, NAMESPACE);
+    // ASTNode nde = new CompletionOnKeywordOrFunction(completionToken, completionNode, node,
+    // keywords);
+    // this.assistNodeParent = inNode;
+    // throw new CompletionNodeFound(nde, null/* ((TypeDeclaration)inNode).scope */);
+    // // } else if (inNode instanceof RutaExecuteExpression
+    // // && completionNode != null && first) {
+    // // String[] keywords = checkKeywords(completionToken,
+    // // EXEC_EXPRESSION);
+    // // ASTNode nde = new CompletionOnKeywordOrFunction(
+    // // completionToken, completionNode, node, keywords);
+    // // this.assistNodeParent = inNode;
+    // // throw new CompletionNodeFound(nde, null/*
+    // // ((TypeDeclaration)inNode).scope */);
+    // } else {
+    // if (completionNode != null) {
+    // String[] keywords = checkKeywords(completionToken, MODULE);
+    //
+    // ASTNode nde = new CompletionOnKeywordArgumentOrFunctionArgument(completionToken,
+    // completionNode, (RutaStatement) node, keywords);
+    // this.assistNodeParent = inNode;
+    // throw new CompletionNodeFound(nde, null/* ((TypeDeclaration)inNode).scope */);
+    // } else {
+    // String[] keywords = checkKeywords(completionToken, MODULE);
+    // if (completionToken == null) {
+    // completionToken = "";
+    // }
+    // ASTNode nde = new CompletionOnKeywordArgumentOrFunctionArgument(completionToken,
+    // (RutaStatement) node, keywords, position);
+    // this.assistNodeParent = inNode;
+    // throw new CompletionNodeFound(nde, null/* ((TypeDeclaration)inNode).scope */);
+    // }
+    // }
+    // }
+    // // if (checkVariableWithoutDollarCompletion(statement, position)
+    // // && completionToken != null) {
+    // // this.assistNodeParent = inNode;
+    // // SimpleReference ref = new SimpleReference(completionNode
+    // // .sourceStart(), completionNode.sourceEnd(),
+    // // completionToken);
+    // // ASTNode nde = new CompletionOnVariable(completionToken, ref,
+    // // node, inNode, true);
+    // // throw new CompletionNodeFound(nde, null);
+    // // }
+    //
+    // } else if (node instanceof MethodDeclaration) {
+    // MethodDeclaration method = (MethodDeclaration) node;
+    // List statements = method.getStatements();
+    // boolean inStatement = false;
+    // if (statements != null) {
+    // int length = statements.size();
+    // for (int i = 0; i < length; i++) {
+    // ASTNode nde = (ASTNode) statements.get(i);
+    // if (nde.sourceStart() <= position && nde.sourceEnd() >= position) {
+    // inStatement = true;
+    // parseBlockStatements(nde, method, position);
+    // }
+    // }
+    // }
+    // if (!inStatement) {
+    // this.handleNotInElement(method, position);
+    // }
+    // } else {
+    // visitElements(node, position);
+    // }
+  }
+
+  public class CompletionVisitor extends ASTVisitor {
+    protected int position;
+
+    protected ModuleDeclaration module;
+
+    public CompletionVisitor(int position, ModuleDeclaration module) {
+      this.position = position;
+      this.module = module;
+    }
+
+    @Override
+    public boolean visit(Statement s) throws Exception {
+      // if (s.sourceStart() <= position && s.sourceEnd() >= position) {
+      // for (int i = 0; i < extensions.length; i++) {
+      // extensions[i].visit(s, RutaCompletionParser.this,
+      // position);
+      // }
+      // if (s instanceof RutaStatement) {
+      // ASTNode inNode = RutaParseUtil.getScopeParent(module, s);
+      // RutaCompletionParser.this.parseBlockStatements(s, inNode,
+      // position);
+      // }
+      // if (s instanceof RutaPackageDeclaration) {
+      // RutaPackageDeclaration decl =
+      // (RutaPackageDeclaration) s;
+      // if (decl.getNameStart() <= position
+      // && position <= decl.getNameEnd()) {
+      // ASTNode inNode = RutaParseUtil.getScopeParent(module, s);
+      // assistNodeParent = inNode;
+      // throw new CompletionNodeFound(decl, null/*
+      // ((TypeDeclaration)inNode).scope */);
+      // }
+      // }
+      // }
+      return super.visit(s);
+    }
+
+    @Override
+    public boolean visit(Expression s) throws Exception {
+      if (s.sourceStart() <= position && s.sourceEnd() >= position) {
+        for (int i = 0; i < extensions.length; i++) {
+          extensions[i].visit(s, RutaCompletionParser.this, position);
+        }
+      }
+      return super.visit(s);
+    }
+
+    @Override
+    public boolean endvisit(Expression s) throws Exception {
+      if (s instanceof Block && s.sourceStart() <= position && s.sourceEnd() >= position) {
+        // We are in block, and no in node completion are done.
+        String[] keywords = checkKeywords("", MODULE);
+        ASTNode inNode = RutaParseUtils.getScopeParent(module, s);
+        ASTNode nde = new CompletionOnKeywordOrFunction("", inNode, s, keywords);
+        assistNodeParent = inNode;
+        throw new CompletionNodeFound(nde, null);
+      }
+      return super.endvisit(s);
+    }
+  };
+
+  protected CompletionVisitor createCompletionVisitor(int position) {
+    return new CompletionVisitor(position, this.getModule());
+  }
+
+  private void visitElements(ASTNode node, int position) {
+    if (!(node instanceof RutaStatement)) {
+      CompletionVisitor visitor = createCompletionVisitor(position);
+      try {
+        node.traverse(visitor);
+      } catch (CompletionNodeFound e) {
+        throw e;
+      } catch (Exception e) {
+        e.printStackTrace();
+      }
+    }
+  }
+
+  private boolean checkVariableWithoutDollarCompletion(RutaStatement statement, int position) {
+    // TODO: Add more compecated check.
+    Expression e = statement.getAt(0);
+    if (e instanceof SimpleReference) {
+      SimpleReference ref = (SimpleReference) e;
+      String name = ref.getName();
+      if (name.equals("set")) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  public String[] checkKeywords(String completionToken, int type) {
+    // String[] keywords = RutaKeywordsManager.getKeywords(type);
+    // // TODO: Possible require cases.
+    // if (type == MODULE || type == FUNCTION || type == NAMESPACE
+    // || type == EXEC_EXPRESSION) {
+    // // Suppose we can handle all keywords.
+    // String[] kw = new String[keywords.length];
+    // for (int i = 0; i < keywords.length; ++i) {
+    // kw[i] = keywords[i];
+    // }
+    // return kw;
+    // }
+    return null;
+  }
+
+  public void setAssistNodeParent(ASTNode prevParent) {
+    this.assistNodeParent = prevParent;
+  }
+
+  public ModuleDeclaration parse(IModuleSource sourceModule) {
+    ModuleDeclaration module = (ModuleDeclaration) this.parser.parse(sourceModule, null);
+    module.rebuild();
+    return module;
+  }
+
+}

Added: uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaModelElementView.java
URL: http://svn.apache.org/viewvc/uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaModelElementView.java?rev=1504044&view=auto
==============================================================================
--- uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaModelElementView.java (added)
+++ uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaModelElementView.java Wed Jul 17 08:23:15 2013
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.uima.ruta.ide.core.codeassist;
+
+public interface RutaModelElementView {
+
+  void setModelElement(Object element);
+
+}

Added: uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaReferenceDeclarationVisitor.java
URL: http://svn.apache.org/viewvc/uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaReferenceDeclarationVisitor.java?rev=1504044&view=auto
==============================================================================
--- uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaReferenceDeclarationVisitor.java (added)
+++ uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaReferenceDeclarationVisitor.java Wed Jul 17 08:23:15 2013
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.uima.ruta.ide.core.codeassist;
+
+import org.apache.uima.ruta.ide.parser.ast.RutaDeclarationsStatement;
+import org.apache.uima.ruta.ide.parser.ast.RutaVariableReference;
+import org.eclipse.dltk.ast.ASTNode;
+import org.eclipse.dltk.ast.ASTVisitor;
+import org.eclipse.dltk.ast.declarations.FieldDeclaration;
+import org.eclipse.dltk.ast.expressions.Expression;
+import org.eclipse.dltk.ast.statements.Statement;
+
+public class RutaReferenceDeclarationVisitor extends ASTVisitor {
+  private ASTNode result = null;
+
+  private int start = 0;
+
+  public RutaReferenceDeclarationVisitor(int start) {
+    this.start = start;
+  }
+
+  @Override
+  public boolean visitGeneral(ASTNode node) throws Exception {
+    if (node.sourceStart() <= start && start <= node.sourceEnd()) {
+      return true;
+    }
+    return false;
+  }
+
+  @Override
+  public boolean visit(Statement s) throws Exception {
+    if (s instanceof RutaDeclarationsStatement || s instanceof FieldDeclaration) {
+      return true && super.visit(s);
+    }
+    return false;
+  }
+
+  @Override
+  public boolean visit(Expression s) throws Exception {
+    if (s instanceof RutaVariableReference) {
+      result = s;
+    }
+    return super.visit(s);
+  }
+
+  public ASTNode getResult() {
+    return result;
+  }
+}

Added: uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaReferenceVisitor.java
URL: http://svn.apache.org/viewvc/uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaReferenceVisitor.java?rev=1504044&view=auto
==============================================================================
--- uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaReferenceVisitor.java (added)
+++ uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaReferenceVisitor.java Wed Jul 17 08:23:15 2013
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.uima.ruta.ide.core.codeassist;
+
+import org.apache.uima.ruta.ide.parser.ast.ComponentDeclaration;
+import org.apache.uima.ruta.ide.parser.ast.ComponentReference;
+import org.apache.uima.ruta.ide.parser.ast.RutaAction;
+import org.apache.uima.ruta.ide.parser.ast.RutaCondition;
+import org.apache.uima.ruta.ide.parser.ast.RutaExpression;
+import org.apache.uima.ruta.ide.parser.ast.RutaVariableReference;
+import org.eclipse.dltk.ast.ASTNode;
+import org.eclipse.dltk.ast.ASTVisitor;
+import org.eclipse.dltk.ast.expressions.Expression;
+
+public class RutaReferenceVisitor extends ASTVisitor {
+  private ASTNode result = null;
+
+  private int start = 0;
+
+  public RutaReferenceVisitor(int start) {
+    this.start = start;
+  }
+
+  @Override
+  public boolean visitGeneral(ASTNode node) throws Exception {
+    if (result == null && node.sourceStart() <= start && start <= node.sourceEnd()) {
+      return true;
+    }
+    return false;
+  }
+
+  @Override
+  public boolean visit(Expression s) throws Exception {
+    if (result != null) {
+      return false;
+    }
+    if (s instanceof RutaVariableReference || s instanceof ComponentDeclaration
+            || s instanceof ComponentReference) {
+      result = s;
+    } else if (s instanceof RutaAction && ((RutaAction) s).getNameStart() <= start
+            && start <= ((RutaAction) s).getNameEnd()) {
+      result = s;
+    } else if (s instanceof RutaAction && ((RutaAction) s).getNameStart() - 1 == start
+            && start == ((RutaAction) s).getNameEnd() - 1) {
+      result = s;
+    } else if (s instanceof RutaCondition && ((RutaCondition) s).getNameStart() <= start
+            && start <= ((RutaCondition) s).getNameEnd()) {
+      result = s;
+    } else if (s instanceof RutaCondition && ((RutaCondition) s).getNameStart() - 1 == start
+            && start == ((RutaCondition) s).getNameEnd() - 1) {
+      result = s;
+    } else if (s instanceof RutaExpression && s.sourceStart() == start && s.sourceEnd() == start) {
+      result = s;
+    }
+    return super.visit(s);
+  }
+
+  public ASTNode getResult() {
+    return result;
+  }
+}

Added: uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaResolver.java
URL: http://svn.apache.org/viewvc/uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaResolver.java?rev=1504044&view=auto
==============================================================================
--- uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaResolver.java (added)
+++ uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaResolver.java Wed Jul 17 08:23:15 2013
@@ -0,0 +1,326 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.uima.ruta.ide.core.codeassist;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.apache.uima.ruta.ide.core.parser.RutaParseUtils;
+import org.eclipse.dltk.ast.ASTNode;
+import org.eclipse.dltk.ast.ASTVisitor;
+import org.eclipse.dltk.ast.Modifiers;
+import org.eclipse.dltk.ast.declarations.FieldDeclaration;
+import org.eclipse.dltk.ast.declarations.MethodDeclaration;
+import org.eclipse.dltk.ast.declarations.ModuleDeclaration;
+import org.eclipse.dltk.ast.declarations.TypeDeclaration;
+import org.eclipse.dltk.ast.expressions.Expression;
+import org.eclipse.dltk.ast.statements.Block;
+import org.eclipse.dltk.ast.statements.Statement;
+import org.eclipse.dltk.core.DLTKCore;
+import org.eclipse.dltk.core.IField;
+import org.eclipse.dltk.core.IModelElement;
+import org.eclipse.dltk.core.IParent;
+import org.eclipse.dltk.core.ISourceModule;
+import org.eclipse.dltk.core.IType;
+import org.eclipse.dltk.core.ModelException;
+
+public class RutaResolver {
+  private IResolveElementParent resolver;
+
+  private ModuleDeclaration moduleDeclaration;
+
+  private ISourceModule sourceModule;
+
+  public RutaResolver(ISourceModule sourceModule, ModuleDeclaration moduleDeclaration,
+          IResolveElementParent resolver) {
+    this(sourceModule, moduleDeclaration);
+    this.resolver = resolver;
+  }
+
+  public RutaResolver(ISourceModule sourceModule, ModuleDeclaration moduleDeclaration) {
+    this.sourceModule = sourceModule;
+    this.moduleDeclaration = moduleDeclaration;
+  }
+
+  public IModelElement findModelElementFrom(ASTNode node) {
+    List statements = moduleDeclaration.getStatements();
+    List elements = new ArrayList();
+    searchAddElementsTo(statements, node, sourceModule, elements);
+    if (elements.size() == 1) {
+      return (IModelElement) elements.get(0);
+    }
+    return null;
+  }
+
+  public interface IResolveElementParent {
+    IModelElement findElementParent(ASTNode node, String name, IParent parent);
+  }
+
+  public void searchAddElementsTo(List statements, final ASTNode node, IParent element,
+          List selectionElements) {
+    if (statements == null || element == null) {
+      return;
+    }
+    Iterator i = statements.iterator();
+    while (i.hasNext()) {
+      ASTNode nde = (ASTNode) i.next();
+      if (nde.equals(node)) {
+        if (node instanceof MethodDeclaration) {
+          String oName = ((MethodDeclaration) node).getName();
+          if (oName.indexOf("::") != -1) {
+            String pName = oName.substring(0, oName.lastIndexOf("::"));
+            pName = pName.replaceAll("::", "\\$");
+
+            if (pName.startsWith("$")) {
+              if (pName.equals("$")) {
+                element = sourceModule;
+              } else {
+                try {
+                  element = findTypeFrom(sourceModule.getChildren(), "", pName, '$');
+                } catch (ModelException e) {
+                  if (DLTKCore.DEBUG) {
+                    e.printStackTrace();
+                  }
+                }
+              }
+            } else {
+              pName = "$" + pName;
+              try {
+                element = findTypeFrom(element.getChildren(), "", pName, '$');
+                if (element == null) {
+                  return;
+                }
+              } catch (ModelException e) {
+                e.printStackTrace();
+                return;
+              }
+            }
+          }
+        }
+        String nodeName = getNodeChildName(node);
+        if (nodeName != null) {
+          IModelElement e = null;
+          if (nodeName.startsWith("::")) {
+            nodeName = nodeName.substring(2);
+            e = findChildrenByName(nodeName, sourceModule);
+          } else {
+            e = findChildrenByName(nodeName, element);
+          }
+          if (e == null && resolver != null) {
+            e = resolver.findElementParent(node, nodeName, element);
+
+          }
+          if (e != null) {
+            List toRemove = new ArrayList();
+            for (int k = 0; k < selectionElements.size(); ++k) {
+              IModelElement ke = (IModelElement) selectionElements.get(k);
+              String keName = ke.getElementName();
+              if (keName.equals(nodeName)) {
+                toRemove.add(ke);
+              }
+            }
+            for (int k = 0; k < toRemove.size(); ++k) {
+              selectionElements.remove(toRemove.get(k));
+            }
+            selectionElements.add(e);
+          }
+        }
+        return;
+      }
+      if (nde.sourceStart() <= node.sourceStart() && node.sourceEnd() <= nde.sourceEnd()) {
+        if (element instanceof IParent) {
+          if (nde instanceof TypeDeclaration) {
+            TypeDeclaration type = (TypeDeclaration) nde;
+            String typeName = getNodeChildName(type);
+            IModelElement e = findChildrenByName(typeName, element);
+            if (e == null && type.getName().startsWith("::")) {
+              try {
+                e = (IModelElement) findTypeFrom(sourceModule.getChildren(), "", type.getName()
+                        .replaceAll("::", "\\$"), '$');
+              } catch (ModelException e1) {
+                // TODO Auto-generated catch block
+                e1.printStackTrace();
+              }
+            }
+            if (e instanceof IParent) {
+              // was: if (e != null || e instanceof IParent)
+              List stats = ((TypeDeclaration) nde).getStatements();
+              searchAddElementsTo(stats, node, (IParent) e, selectionElements);
+            }
+          } else if (nde instanceof MethodDeclaration) {
+            searchInMethod(node, element, nde, selectionElements);
+          } /*
+             * else if (nde instanceof RutaStatement) { RutaStatement s = (RutaStatement) nde;
+             * Expression commandId = s.getAt(0); final IParent e = element; if (commandId != null
+             * && commandId instanceof SimpleReference) { String qname = ((SimpleReference)
+             * commandId) .getName(); } }
+             */
+          else {
+            final IParent e = element;
+            List statements2 = findExtractBlocks(nde);
+            if (statements2.size() > 0) {
+              searchAddElementsTo(statements2, node, e, selectionElements);
+            }
+          }
+        }
+        return;
+      }
+    }
+  }
+
+  public static IModelElement findChildrenByName(String childName, IParent element) {
+    try {
+      if (element == null) {
+        return null;
+      }
+      String nextName = null;
+      int pos;
+      if ((pos = childName.indexOf("::")) != -1) {
+        nextName = childName.substring(pos + 2);
+        childName = childName.split("::")[0];
+      }
+      IModelElement[] children = element.getChildren();
+      if (children != null) {
+        for (int i = 0; i < children.length; ++i) {
+          String name = children[i].getElementName();
+          if (children[i] instanceof IField && name.indexOf('(') != -1) {
+            name = name.substring(0, name.indexOf('('));
+          }
+          if (name.equals(childName)) {
+            if (nextName == null) {
+              return children[i];
+            } else if (children[i] instanceof IParent) {
+              return findChildrenByName(nextName, (IParent) children[i]);
+            }
+          }
+        }
+      }
+    } catch (ModelException e) {
+      if (DLTKCore.DEBUG) {
+        e.printStackTrace();
+      }
+    }
+    return null;
+  }
+
+  public static IParent findTypeFrom(IModelElement[] childs, String name, String parentName,
+          char delimiter) {
+    try {
+      for (int i = 0; i < childs.length; ++i) {
+        if (childs[i] instanceof IType) {
+          if ((((IType) childs[i]).getFlags() & Modifiers.AccNameSpace) == 0) {
+            continue;
+          }
+          IType type = (IType) childs[i];
+          String qname = name + delimiter + type.getElementName();
+          if (qname.equals(parentName)) {
+            return type;
+          }
+          IParent val = findTypeFrom(type.getChildren(), qname, parentName, delimiter);
+          if (val != null) {
+            return val;
+          }
+        }
+      }
+    } catch (ModelException e) {
+      if (DLTKCore.DEBUG) {
+        e.printStackTrace();
+      }
+    }
+    return null;
+  }
+
+  public static String getNodeChildName(ASTNode node) {
+    if (node instanceof MethodDeclaration) {
+      MethodDeclaration method = (MethodDeclaration) node;
+      String name = method.getName();
+      if (name.indexOf("::") != -1) {
+        return name.substring(name.lastIndexOf("::") + 2);
+      }
+      return name;
+    } else if (node instanceof TypeDeclaration) {
+      TypeDeclaration type = (TypeDeclaration) node;
+      String name = type.getName();
+      /*
+       * if (name.startsWith("::")) { return name.substring(2); }
+       */
+      return name;
+    } else if (node instanceof Statement) {
+      String[] var = RutaParseUtils.returnVariable((Statement) node);
+      if (var != null) {
+        return var[0];
+      }
+    } else if (node instanceof FieldDeclaration) {
+      return ((FieldDeclaration) node).getName();
+    }
+    return null;
+  }
+
+  public void searchInMethod(final ASTNode node, IParent element, ASTNode nde,
+          List selectionElements) {
+    MethodDeclaration method = (MethodDeclaration) nde;
+    String methodName = method.getName();
+    if (methodName.indexOf("::") != -1) {
+      String pName = methodName.substring(0, methodName.lastIndexOf("::"));
+      pName = pName.replaceAll("::", "\\$");
+      if (pName.equals("$")) {
+        element = sourceModule;
+      } else {
+        try {
+          element = RutaResolver.findTypeFrom(sourceModule.getChildren(), "", pName, '$');
+          if (element == null) {
+            return;
+          }
+        } catch (ModelException e) {
+          e.printStackTrace();
+          return;
+        }
+      }
+      methodName = RutaResolver.getNodeChildName(nde);
+    }
+    IModelElement e = RutaResolver.findChildrenByName(methodName, element);
+    if (e != null && e instanceof IParent) {
+      List stats = ((MethodDeclaration) nde).getStatements();
+      searchAddElementsTo(stats, node, (IParent) e, selectionElements);
+    }
+  }
+
+  public static List findExtractBlocks(ASTNode node) {
+    final List statements2 = new ArrayList();
+    ASTVisitor visitor = new ASTVisitor() {
+      @Override
+      public boolean visit(Expression s) throws Exception {
+        if (s instanceof Block) {
+          statements2.addAll(((Block) s).getStatements());
+        }
+        return super.visit(s);
+      }
+    };
+    try {
+      node.traverse(visitor);
+    } catch (Exception e) {
+      if (DLTKCore.DEBUG) {
+        e.printStackTrace();
+      }
+    }
+    return statements2;
+  }
+}

Added: uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaRuleIdVisitor.java
URL: http://svn.apache.org/viewvc/uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaRuleIdVisitor.java?rev=1504044&view=auto
==============================================================================
--- uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaRuleIdVisitor.java (added)
+++ uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaRuleIdVisitor.java Wed Jul 17 08:23:15 2013
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.uima.ruta.ide.core.codeassist;
+
+import org.apache.uima.ruta.ide.parser.ast.RutaRule;
+import org.eclipse.dltk.ast.ASTVisitor;
+import org.eclipse.dltk.ast.statements.Statement;
+
+public class RutaRuleIdVisitor extends ASTVisitor {
+
+  private int id;
+
+  private RutaRule result;
+
+  public RutaRuleIdVisitor(int id) {
+    super();
+    this.id = id;
+  }
+
+  @Override
+  public boolean visit(Statement s) throws Exception {
+    if (result != null) {
+      return false;
+    }
+    if (s instanceof RutaRule) {
+      RutaRule rule = (RutaRule) s;
+      if (id == rule.getId()) {
+        result = rule;
+      }
+    }
+    return true;
+  }
+
+  public RutaRule getResult() {
+    return result;
+  }
+
+}

Added: uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaSelectionEngine.java
URL: http://svn.apache.org/viewvc/uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaSelectionEngine.java?rev=1504044&view=auto
==============================================================================
--- uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaSelectionEngine.java (added)
+++ uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaSelectionEngine.java Wed Jul 17 08:23:15 2013
@@ -0,0 +1,466 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.uima.ruta.ide.core.codeassist;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.uima.UIMAFramework;
+import org.apache.uima.resource.metadata.TypeDescription;
+import org.apache.uima.resource.metadata.TypeSystemDescription;
+import org.apache.uima.ruta.engine.RutaEngine;
+import org.apache.uima.ruta.ide.core.builder.RutaProjectUtils;
+import org.apache.uima.ruta.ide.core.parser.RutaParseUtils;
+import org.apache.uima.ruta.ide.parser.ast.RutaActionConstants;
+import org.apache.uima.ruta.ide.parser.ast.RutaImportStatement;
+import org.apache.uima.ruta.ide.parser.ast.RutaStatementConstants;
+import org.apache.uima.util.InvalidXMLException;
+import org.apache.uima.util.XMLInputSource;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.dltk.ast.ASTVisitor;
+import org.eclipse.dltk.ast.declarations.MethodDeclaration;
+import org.eclipse.dltk.ast.declarations.ModuleDeclaration;
+import org.eclipse.dltk.ast.declarations.TypeDeclaration;
+import org.eclipse.dltk.ast.expressions.Expression;
+import org.eclipse.dltk.ast.references.SimpleReference;
+import org.eclipse.dltk.ast.references.VariableReference;
+import org.eclipse.dltk.ast.statements.Statement;
+import org.eclipse.dltk.codeassist.ScriptSelectionEngine;
+import org.eclipse.dltk.compiler.env.IModuleSource;
+import org.eclipse.dltk.core.DLTKCore;
+import org.eclipse.dltk.core.IDLTKLanguageToolkit;
+import org.eclipse.dltk.core.IField;
+import org.eclipse.dltk.core.IMethod;
+import org.eclipse.dltk.core.IModelElement;
+import org.eclipse.dltk.core.IModelElementVisitor;
+import org.eclipse.dltk.core.IOpenable;
+import org.eclipse.dltk.core.IScriptFolder;
+import org.eclipse.dltk.core.IScriptProject;
+import org.eclipse.dltk.core.ModelException;
+
+public class RutaSelectionEngine extends ScriptSelectionEngine {
+
+  private class ModelElementFinder extends ASTVisitor {
+    private int offset;
+
+    private List results;
+
+    private Set<String> engines;
+
+    private Set<String> typesystems;
+
+    private Map<String, org.eclipse.dltk.core.ISourceModule> scripts;
+
+    private Map<String, IField> impFields;
+
+    private String curFileName;
+
+    public ModelElementFinder(int offset, List results, String curFileName) {
+      super();
+      this.offset = offset;
+      this.results = results;
+      this.engines = new HashSet<String>();
+      this.typesystems = new HashSet<String>();
+      this.scripts = new HashMap<String, org.eclipse.dltk.core.ISourceModule>();
+      this.impFields = new HashMap<String, IField>();
+      this.curFileName = curFileName;
+      try {
+        importScript(parseFileName(curFileName));
+      } catch (Exception e) {
+      }
+    }
+
+    private String parseFileName(String curFileName2) {
+      int i = curFileName2.indexOf("script");
+      String s = curFileName2.substring(i + "scripts".length() - 1);
+      s = s.replace('/', '.');
+      if (s.endsWith(RutaEngine.SCRIPT_FILE_EXTENSION)) {
+        s = s.substring(1, s.length() - 5);
+      }
+      return s;
+    }
+
+    @Override
+    public boolean visit(Statement s) throws Exception {
+      if (s instanceof RutaImportStatement) {
+        // handle engine imports
+        if (((RutaImportStatement) s).getType() == RutaStatementConstants.S_IMPORT_ENGINE) {
+          SimpleReference sRef = (SimpleReference) ((RutaImportStatement) s).getExpression();
+          importEngine(sRef.getName());
+        }
+        if (((RutaImportStatement) s).getType() == RutaStatementConstants.S_IMPORT_ENGINE) {
+          SimpleReference sRef = (SimpleReference) ((RutaImportStatement) s).getExpression();
+          importEngine(sRef.getName());
+        }
+        // handle script imports
+        if (((RutaImportStatement) s).getType() == RutaStatementConstants.S_IMPORT_SCRIPT) {
+          importScript(s);
+        }
+        // handle type system imports
+        if (((RutaImportStatement) s).getType() == RutaStatementConstants.S_IMPORT_TYPESYSTEM) {
+          importTypesystem(s);
+        }
+        return false;
+      }
+      return true;
+    }
+
+    @Override
+    public boolean visit(Expression s) throws Exception {
+      if (s.sourceStart() <= offset && offset <= s.sourceEnd()) {
+        if (s instanceof VariableReference) {
+          VariableReference ref = (VariableReference) s;
+          // TODO refactor: extern declaration always checked, even if
+          // local decl found
+          String name = ((VariableReference) s).getName();
+          findLocalDeclaration(name, results, IField.class);
+          if (impFields.containsKey(name)) {
+            results.add(impFields.get(name));
+          }
+        }
+        if (s != null && s.getKind() == RutaActionConstants.A_CALL) {
+          SimpleReference sr = (SimpleReference) s.getChilds().get(0);
+          if (sr != null) {
+            String name = sr.getName();
+            if (engines.contains(name)) {
+              // referenceEngineCall(name);
+            } else if (scripts.containsKey(name)) {
+              findImportedDeclaration(name, results, IMethod.class);
+            } else {
+              checkInnerBlockRef(name, "");
+              name = name.substring(name.lastIndexOf('.') + 1);
+              findLocalDeclaration(name, results, IMethod.class);
+            }
+          }
+        }
+      }
+      return super.visit(s);
+    }
+
+    @Override
+    public boolean visit(MethodDeclaration s) throws Exception {
+      if (s.getNameStart() <= offset && offset <= s.getNameEnd()) {
+        findLocalDeclaration(s.getName(), results, IMethod.class);
+      }
+      return super.visit(s);
+    }
+
+    @Override
+    public boolean visit(TypeDeclaration s) throws Exception {
+      if (s.getNameStart() <= offset && offset <= s.getNameEnd()) {
+        findLocalDeclaration(s.getName(), results, IField.class);
+        // TODO ??
+      }
+      return super.visit(s);
+    }
+
+    private void checkInnerBlockRef(String head, String tail) {
+      int li = head.lastIndexOf('.');
+      if (li > 0) {
+        String frontPart = head.substring(0, li);
+        if (StringUtils.isEmpty(tail)) {
+          tail = head.substring(li + 1);
+        }
+        if (scripts.containsKey(frontPart)) {
+          findDeclaration(scripts.get(frontPart), tail, results, IMethod.class);
+        } else {
+          checkInnerBlockRef(frontPart, tail);
+        }
+      }
+    }
+
+    private void importEngine(String name) {
+      engines.add(name);
+      int i = name.lastIndexOf('.');
+      if (i > 1) {
+        String lastPart = name.substring(i + 1);
+        if (lastPart != null && lastPart.length() != 0) {
+          engines.add(lastPart);
+        }
+      }
+    }
+
+    private void referenceEngineCall(String name) {
+      // name = "";
+      IScriptProject scriptProject = sourceModule.getScriptProject();
+      IFile engine = getEngine(name, scriptProject);
+      if (engine == null) {
+        return;
+      }
+      results.add(engine);
+      // IScriptProject scriptProject = sourceModule.getScriptProject();
+      // IPath path = scriptProject.g;
+      // path = path.append(name);
+      // IModelElement element;
+      // try {
+      // element = scriptProject.findElement(path);
+      // System.out.println(element.exists() + "bla");
+      // } catch (ModelException e) {
+      // e.printStackTrace();
+      // }
+      // sourceModule.
+      // scriptProject.findType(packageName, name);
+    }
+
+    public IFile getFile(IFolder folder, String filePath) {
+      int lastDot = filePath.lastIndexOf('.');
+      int sndLastDot = filePath.lastIndexOf('.', lastDot - 1);
+      String fName = filePath;
+      if (sndLastDot >= 0) {
+        String subFolder = filePath.substring(0, sndLastDot);
+        folder = folder.getFolder(subFolder);
+        fName = filePath.substring(sndLastDot + 1);
+      }
+      return folder.getFile(fName);
+    }
+
+    /**
+     * @param xmlFilePath
+     *          absolute full path. i.e.: "org.apache.uima.myengine" ".xml" will be added.
+     * @return file.exists
+     */
+    public IFile getEngine(String xmlFilePath, IScriptProject project) {
+      IFolder folder = project.getProject().getFolder(
+              RutaProjectUtils.getDefaultDescriptorLocation());
+      IFolder f = folder.getFolder("de.martin");
+      boolean b = f.exists();
+      // xmlFilePath = xmlFilePath.replace('.', '/');
+      String fileExtended = xmlFilePath + ".xml";
+      IFile file = getFile(folder, fileExtended);
+      if (file.exists()) {
+        IOpenable opena = (IOpenable) file.getAdapter(IOpenable.class);
+        return file;
+      }
+      return null;
+    }
+
+    /**
+     * @param s
+     * @throws ModelException
+     */
+    private void importScript(Statement s) throws ModelException {
+      SimpleReference sRef = (SimpleReference) ((RutaImportStatement) s).getExpression();
+      String sRefName = sRef.getName();
+      importScript(sRefName);
+    }
+
+    private void importTypesystem(Statement s) {
+      SimpleReference sRef = (SimpleReference) ((RutaImportStatement) s).getExpression();
+      String sRefName = sRef.getName();
+
+      // TODO not working yet
+      // importTypesystem(sRefName);
+
+    }
+
+    private void importTypesystem(String sRefName) {
+      typesystems.add(sRefName);
+      IFolder folder = sourceModule.getScriptProject().getProject()
+              .getFolder(RutaProjectUtils.getDefaultDescriptorLocation());
+      if (folder != null) {
+        int lastDot = sRefName.lastIndexOf('.');
+        String fileNameShort = sRefName.substring(lastDot + 1);
+        String folderName = sRefName.substring(0, lastDot);
+        String fileName = fileNameShort + ".xml";
+        IFolder tsFolder = folder.getFolder(folderName);
+        if (tsFolder != null) {
+          IFile file = tsFolder.getFile(fileName);
+          if (file != null) {
+            File tsFile = file.getLocation().toFile();
+            try {
+              TypeSystemDescription typeSystemDescription = UIMAFramework.getXMLParser()
+                      .parseTypeSystemDescription(new XMLInputSource(tsFile));
+              TypeDescription[] types = typeSystemDescription.getTypes();
+              for (TypeDescription each : types) {
+                impFields.put(each.getName(), null);
+              }
+            } catch (InvalidXMLException e) {
+              e.printStackTrace();
+            } catch (IOException e) {
+              e.printStackTrace();
+            }
+          }
+        }
+      }
+    }
+
+    /**
+     * @param sRefName
+     * @throws ModelException
+     */
+    private void importScript(String sRefName) throws ModelException {
+      int lastDot = sRefName.lastIndexOf('.');
+      String fileNameShort = sRefName.substring(lastDot + 1);
+      String fileName = fileNameShort + RutaEngine.SCRIPT_FILE_EXTENSION;
+
+      org.eclipse.dltk.core.ISourceModule sm = null;
+      IScriptFolder[] scriptFolders = sourceModule.getScriptProject().getScriptFolders();
+      for (int i = 0; i < scriptFolders.length; i++) {
+        sm = scriptFolders[i].getSourceModule(fileName);
+        if (sm.exists() && sm.getResource() != null && sm.getResource().exists()) {
+          scripts.put(sRefName, sm);
+          scripts.put(fileNameShort, sm);
+          importFields(sm.getFields());
+          break;
+        }
+      }
+    }
+
+    private void importFields(IField[] fields) {
+      if (fields == null) {
+        return;
+      }
+      for (int i = 0; i < fields.length; i++) {
+        if (fields[i] == null) {
+          continue;
+        }
+        IField iField = fields[i];
+        IPath path = iField.getPath();
+        String fullyQualifiedName = parseFileName(path.toString());
+        impFields.put(iField.getElementName(), iField);
+        impFields.put(fullyQualifiedName + "." + iField.getElementName(), iField);
+      }
+    }
+
+    @SuppressWarnings("unchecked")
+    private void findImportedDeclaration(final String name, final List results, final Class type) {
+      org.eclipse.dltk.core.ISourceModule module = this.scripts.get(name);
+      if (module != null && module.exists()) {
+        results.add(module);
+        // findDeclaration(module, name, results, type);
+      }
+    }
+
+    @SuppressWarnings("unchecked")
+    private void findDeclaration(org.eclipse.dltk.core.ISourceModule sm, final String name,
+            final List results, final Class type) {
+      try {
+        sm.accept(new IModelElementVisitor() {
+          public boolean visit(IModelElement element) {
+            Class e = element.getClass();
+            boolean classCheck = type.isAssignableFrom(e);
+            if (element.getElementName().equals(name) && classCheck) {
+              results.add(element);
+              return false;
+            }
+            return true;
+          }
+        });
+      } catch (ModelException e) {
+        if (DLTKCore.DEBUG) {
+          e.printStackTrace();
+        }
+      }
+    }
+
+    @SuppressWarnings("unchecked")
+    private void findLocalDeclaration(final String name, final List results, final Class type) {
+      try {
+        sourceModule.accept(new IModelElementVisitor() {
+          public boolean visit(IModelElement element) {
+            Class e = element.getClass();
+            boolean classCheck = type.isAssignableFrom(e);
+            if (element.getElementName().equals(name) && classCheck) {
+              results.add(element);
+            }
+            return true;
+          }
+        });
+      } catch (ModelException e) {
+        if (DLTKCore.DEBUG) {
+          e.printStackTrace();
+        }
+      }
+    }
+  }
+
+  public static boolean DEBUG = DLTKCore.DEBUG_SELECTION;
+
+  protected int actualSelectionStart;
+
+  protected int actualSelectionEnd;
+
+  protected List selectionElements = new ArrayList();
+
+  protected RutaSelectionParser parser = new RutaSelectionParser();
+
+  protected org.eclipse.dltk.core.ISourceModule sourceModule;
+
+  protected IDLTKLanguageToolkit toolkit;
+
+  public IModelElement[] select(IModuleSource module, final int offset, int i) {
+    sourceModule = (org.eclipse.dltk.core.ISourceModule) module.getModelElement();
+    ModuleDeclaration moduleDeclaration = this.parser.parse(module);
+
+    final List results = new ArrayList();
+    try {
+      moduleDeclaration.traverse(new ModelElementFinder(offset, results, module.getFileName()));
+    } catch (Exception e) {
+      if (DLTKCore.DEBUG) {
+        e.printStackTrace();
+      }
+    }
+    return (IModelElement[]) results.toArray(new IModelElement[results.size()]);
+  }
+
+  protected boolean checkSelection(String source, int selectionSourceStart, int selectionSourceEnd) {
+
+    boolean cheat = false;
+    if (selectionSourceEnd < selectionSourceStart) {
+      selectionSourceEnd = selectionSourceStart;
+      cheat = true;
+    }
+
+    int start = RutaParseUtils.startLineOrNoSymbol(selectionSourceStart, source);
+    int end = RutaParseUtils.endLineOrNoSymbol(selectionSourceEnd, source);
+    if (end <= start) {
+      if (cheat)
+        return checkSelection(source, selectionSourceEnd - 1, selectionSourceEnd - 1);
+      return false;
+    }
+    if (start > source.length() || end > source.length()) {
+      if (cheat)
+        return checkSelection(source, selectionSourceEnd - 1, selectionSourceEnd - 1);
+      return false;
+    }
+
+    String sub = source.substring(start, end);
+
+    // If contain tabs or spaces, then from start.
+    if ((sub.indexOf(' ') != -1 || sub.indexOf('\t') != -1 || sub.indexOf('\n') != -1)) {
+      if (cheat)
+        return checkSelection(source, selectionSourceEnd - 1, selectionSourceEnd - 1);
+      return false;
+    }
+    this.actualSelectionStart = start;
+    this.actualSelectionEnd = end;
+    return true;
+  }
+
+}

Added: uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaSelectionParser.java
URL: http://svn.apache.org/viewvc/uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaSelectionParser.java?rev=1504044&view=auto
==============================================================================
--- uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaSelectionParser.java (added)
+++ uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/RutaSelectionParser.java Wed Jul 17 08:23:15 2013
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.uima.ruta.ide.core.codeassist;
+
+import org.eclipse.dltk.ast.ASTNode;
+import org.eclipse.dltk.ast.declarations.ModuleDeclaration;
+import org.eclipse.dltk.compiler.env.IModuleSource;
+
+public class RutaSelectionParser extends RutaAssistParser {
+
+  public void handleNotInElement(ASTNode unit, int position) {
+
+  }
+
+  public void parseBlockStatements(ASTNode node, ASTNode unit, int position) {
+
+  }
+
+  public ModuleDeclaration parse(IModuleSource sourceModule) {
+    ModuleDeclaration module = (ModuleDeclaration) this.parser.parse(sourceModule, null);
+    module.rebuild();
+    return module;
+  }
+}

Added: uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/SelectionOnAST.java
URL: http://svn.apache.org/viewvc/uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/SelectionOnAST.java?rev=1504044&view=auto
==============================================================================
--- uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/SelectionOnAST.java (added)
+++ uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/core/codeassist/SelectionOnAST.java Wed Jul 17 08:23:15 2013
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.uima.ruta.ide.core.codeassist;
+
+import org.eclipse.dltk.ast.ASTNode;
+import org.eclipse.dltk.ast.references.SimpleReference;
+
+public class SelectionOnAST extends SimpleReference {
+
+  private ASTNode method;
+
+  public SelectionOnAST(ASTNode token) {
+    super(token.sourceStart(), token.sourceEnd(), "");
+    this.method = token;
+  }
+
+  public ASTNode getNode() {
+    return method;
+  }
+}