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/04/29 16:51:06 UTC
svn commit: r1477113 [17/18] - in
/uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide:
./ core/ core/builder/ core/codeassist/ core/extensions/ core/packages/
core/parser/ core/search/ debug/ debug/ui/ debug/ui/handlers/ debug/u...
Added: uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaCheckerProblemFactory.java
URL: http://svn.apache.org/viewvc/uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaCheckerProblemFactory.java?rev=1477113&view=auto
==============================================================================
--- uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaCheckerProblemFactory.java (added)
+++ uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaCheckerProblemFactory.java Mon Apr 29 14:50:56 2013
@@ -0,0 +1,189 @@
+/*
+ * 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.validator;
+
+import java.util.List;
+
+import org.apache.uima.ruta.ide.parser.ast.RutaAbstractDeclaration;
+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.RutaFeatureDeclaration;
+import org.apache.uima.ruta.ide.parser.ast.RutaVariableReference;
+import org.eclipse.dltk.ast.ASTListNode;
+import org.eclipse.dltk.ast.ASTNode;
+import org.eclipse.dltk.ast.expressions.Expression;
+import org.eclipse.dltk.ast.expressions.StringLiteral;
+import org.eclipse.dltk.compiler.problem.IProblem;
+import org.eclipse.dltk.compiler.problem.ProblemSeverity;
+import org.eclipse.dltk.core.ISourceModule;
+import org.eclipse.dltk.core.builder.ISourceLineTracker;
+
+public class RutaCheckerProblemFactory {
+ // private static final String errMsgHead = "Type \"";
+ // private static final String errMsgTailDefault =
+ // " \" not defined in this script!";
+
+ private ISourceLineTracker linetracker;
+
+ private String fileName;
+
+ public RutaCheckerProblemFactory(String fileName, ISourceLineTracker linetracker) {
+ this.fileName = fileName;
+ this.linetracker = linetracker;
+ }
+
+ public IProblem createIdConflictsWithVariableProblem(RutaAbstractDeclaration varRef) {
+ String message = generateVarAlreadyDeclaredProblemMsg(varRef);
+ return new RutaCheckerDefaultProblem(this.fileName, message, varRef, getLine(varRef));
+ }
+
+ public IProblem createIdConflictsWithTypeProblem(RutaAbstractDeclaration varRef) {
+ String message = generateVarConflictsWithTypeProblem(varRef);
+ return new RutaCheckerDefaultProblem(this.fileName, message, varRef, getLine(varRef));
+ }
+
+ public IProblem createFileNotFoundProblem(ASTNode node, String localPath) {
+ return new RutaCheckerDefaultProblem(this.fileName,
+ generateFileNotFoundProblemMsg(localPath), node, getLine(node));
+ }
+
+ public IProblem createFileNotFoundProblem(ASTNode fileNode) {
+ return createFileNotFoundProblem(fileNode, fileNode.toString());
+ // generateFileNotFoundProblemMsg(fileNode));
+ }
+
+ public IProblem createDuplicateShortNameInImported(ASTNode node, String localPath,
+ List<String> checkDuplicateShortNames, ProblemSeverity severity) {
+ StringBuilder sb = new StringBuilder();
+ for (String string : checkDuplicateShortNames) {
+ sb.append(string);
+ sb.append(", ");
+ }
+
+ return new RutaCheckerDefaultProblem(this.fileName, "Types in " + localPath
+ + " share same short name, but with different namespaces: " + sb.toString(), node,
+ getLine(node), severity);
+ }
+
+ public IProblem createDuplicateShortName(RutaAbstractDeclaration var,
+ ProblemSeverity severity) {
+ return new RutaCheckerDefaultProblem(this.fileName, "The type " + var.getName()
+ + " conflicts with other types with same short name, but different namespace.", var,
+ getLine(var), severity);
+ }
+
+ public IProblem createXMLProblem(ASTNode node, String localPath) {
+ return new RutaCheckerDefaultProblem(this.fileName, generateXMLProblemMsg(localPath),
+ node, getLine(node));
+ }
+
+ public IProblem createTypeProblem(RutaVariableReference ref, ISourceModule currentFile) {
+
+ String errMsgHead = "Type \"";
+
+ String errMsgTailDefault = " \" not defined in this script/block!";
+ String errMsg = errMsgHead + ref.getName() + errMsgTailDefault;
+ IProblem problem = new RutaCheckerDefaultProblem(currentFile.getElementName(), errMsg,
+ ref, linetracker.getLineNumberOfOffset(ref.sourceStart()));
+ return problem;
+ }
+
+ private String generateFileNotFoundProblemMsg(ASTNode node) {
+ return generateFileNotFoundProblemMsg(node.toString());
+ }
+
+ private String generateFileNotFoundProblemMsg(String fileName) {
+ return "error: \"" + fileName + "\" not found.";
+ }
+
+ private String generateXMLProblemMsg(String fileName) {
+ return "error: " + fileName + " causes xml problem.";
+ }
+
+ private int getLine(ASTNode varRef) {
+ return this.linetracker.getLineNumberOfOffset(varRef.sourceStart());
+ }
+
+ private String generateVarAlreadyDeclaredProblemMsg(RutaAbstractDeclaration var) {
+ return "error: Id \"" + var.getName() + "\" conflicts with already declared variable.";
+ }
+
+ private String generateVarConflictsWithTypeProblem(RutaAbstractDeclaration var) {
+ return "error: Identifier \"" + var.getName()
+ + "\" conflicts with already declared annotation type.";
+ }
+
+ public IProblem createUnknownFeatureTypeProblem(RutaFeatureDeclaration var) {
+ String message = "error: Type \"" + var.getType() + "\" of Feature \"" + var.getName()
+ + "\" is not defined.";
+ return new RutaCheckerDefaultProblem(this.fileName, message, var, getLine(var));
+ }
+
+ public IProblem createUnknownFeatureProblem(Expression var, String matchedType) {
+ // TODO refactor and find better solution
+ String feat = var.toString();
+ List childs = var.getChilds();
+ if (childs != null && !childs.isEmpty()) {
+ Object object = childs.get(0);
+ if (object instanceof ASTListNode) {
+ List childs2 = ((ASTListNode) object).getChilds();
+ if (childs2 != null && !childs2.isEmpty()) {
+ Object object2 = childs2.get(0);
+ if (object2 instanceof StringLiteral) {
+ StringLiteral sl = (StringLiteral) object2;
+ feat = sl.getValue().replaceAll("\"", "");
+ }
+ }
+ }
+ }
+ String message = "error: Feature \"" + feat + "\" is not defined.";
+ if (matchedType != null) {
+ message = "error: Feature \"" + feat + "\" is not defined for type \"" + matchedType + "\".";
+ }
+ return new RutaCheckerDefaultProblem(this.fileName, message, var, getLine(var));
+ }
+
+ public IProblem createWrongArgumentTypeProblem(Expression was, String expected) {
+ String message = "Wrong kind of argument: expected " + expected;
+ return new RutaCheckerDefaultProblem(this.fileName, message, was, getLine(was));
+ }
+
+ public IProblem createInheritenceFinalProblem(RutaVariableReference parent) {
+ String message = "Type \"" + parent.getName()
+ + "\" is final and cannot be used as a parent type.";
+ return new RutaCheckerDefaultProblem(this.fileName, message, parent, getLine(parent));
+ }
+
+ public IProblem createUnknownConditionProblem(RutaCondition cond) {
+ String message = "error: Condition \"" + cond.getName() + "\" is not defined.";
+ return new RutaCheckerDefaultProblem(this.fileName, message, cond, getLine(cond));
+ }
+
+ public IProblem createUnknownActionProblem(RutaAction action) {
+ String message = "error: Action \"" + action.getName() + "\" is not defined.";
+ return new RutaCheckerDefaultProblem(this.fileName, message, action, getLine(action));
+ }
+
+ public IProblem createWrongNumberOfArgumentsProblem(String name, Expression element, int expected) {
+ String message = "error: The element " + name + " expects " + expected + " arguments.";
+ return new RutaCheckerDefaultProblem(this.fileName, message, element, getLine(element));
+ }
+
+}
Added: uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaCheckerUtils.java
URL: http://svn.apache.org/viewvc/uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaCheckerUtils.java?rev=1477113&view=auto
==============================================================================
--- uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaCheckerUtils.java (added)
+++ uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaCheckerUtils.java Mon Apr 29 14:50:56 2013
@@ -0,0 +1,267 @@
+/*
+ * 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.validator;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.net.URL;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.Stack;
+
+import org.apache.uima.UIMAFramework;
+import org.apache.uima.analysis_engine.AnalysisEngineDescription;
+import org.apache.uima.resource.metadata.ConfigurationParameterSettings;
+import org.apache.uima.ruta.engine.RutaEngine;
+import org.apache.uima.ruta.ide.core.builder.RutaProjectUtils;
+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.CoreException;
+import org.eclipse.dltk.core.DLTKCore;
+import org.eclipse.dltk.core.IMethod;
+import org.eclipse.dltk.core.IModelElement;
+import org.eclipse.dltk.core.IScriptFolder;
+import org.eclipse.dltk.core.IScriptProject;
+import org.eclipse.dltk.core.ISourceModule;
+import org.eclipse.dltk.core.ModelException;
+
+public class RutaCheckerUtils {
+
+ public static Set<String> importScript(String path, int type, IScriptProject project)
+ throws InvalidXMLException, IOException, ModelException {
+ return importScript(path, type, project, false);
+ }
+
+ /**
+ * @param path
+ * relative to script folder of the project.<br>
+ * i.e.: "org.apache.uima.MyScript"
+ * @param type
+ * i.e. IModelElement.FIELD for fields to be collected and returned
+ * @return
+ * @throws InvalidXMLException
+ * @throws IOException
+ * @throws ModelException
+ */
+ public static Set<String> importScript(String path, int type, IScriptProject project,
+ boolean appendPath) throws InvalidXMLException, IOException, ModelException {
+ Stack<String> namespaceStack = new Stack<String>();
+
+ final Set<String> imports = new HashSet<String>();
+ List<IFolder> scriptFolders = null;
+ try {
+ scriptFolders = RutaProjectUtils.getAllScriptFolders(project);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ String fileNameWithoutExtension = path.substring(path.lastIndexOf('.') + 1);
+ String fileNameWithExtension = fileNameWithoutExtension + ".tm";
+ ISourceModule sourceModule = null;
+ boolean found = false;
+ for (IFolder eachFolder : scriptFolders) {
+
+ IScriptProject sp = DLTKCore.create(eachFolder.getProject());
+ IScriptFolder[] scriptFolders2 = sp.getScriptFolders();
+ for (IScriptFolder iScriptFolder : scriptFolders2) {
+ sourceModule = iScriptFolder.getSourceModule(fileNameWithExtension);
+ if (sourceModule.exists() && sourceModule.getResource() != null
+ && sourceModule.getResource().exists()) {
+ found = true;
+ break;
+ }
+ if (found)
+ break;
+ }
+ }
+ IModelElement elements[] = null;
+ namespaceStack.push(fileNameWithoutExtension);
+ try {
+ elements = sourceModule.getChildren();
+ for (int i = 0; i < elements.length; i++) {
+ IModelElement modelElement = elements[i];
+ int elementType = modelElement.getElementType();
+ if (elementType == type) {
+ if (elementType == IModelElement.METHOD) {
+ imports.add(namespaceStack.peek() + "." + modelElement.getElementName());
+ } else if (appendPath) {
+ imports.add(path + "." + modelElement.getElementName());
+ } else {
+ imports.add(modelElement.getElementName());
+ }
+ }
+ if (elementType == IModelElement.METHOD) {
+ String nSpace = namespaceStack.empty() ? modelElement.getElementName() : namespaceStack
+ .peek() + "." + modelElement.getElementName();
+ namespaceStack.push(nSpace);
+ imports.addAll(collectElements((IMethod) modelElement, type, namespaceStack));
+ namespaceStack.pop();
+ }
+ }
+ } catch (ModelException e) {
+ throw new FileNotFoundException();
+ }
+ return imports;
+ }
+
+ private static Set<String> collectElements(IMethod element, int type, Stack stack)
+ throws ModelException {
+ Set<String> fieldsCollection = new HashSet<String>();
+ IModelElement elements[] = element.getChildren();
+ if (elements == null) {
+ return fieldsCollection;
+ }
+ for (int i = 0; i < elements.length; i++) {
+ IModelElement modelElement = elements[i];
+ int elementType = modelElement.getElementType();
+ if (elementType == type) {
+ if (elementType == IModelElement.FIELD) {
+ fieldsCollection.add(modelElement.getElementName());
+ }
+ fieldsCollection.add(stack.peek() + "." + modelElement.getElementName());
+ }
+ if (elementType == IModelElement.METHOD) {
+ stack.push(stack.peek() + "." + modelElement.getElementName());
+ fieldsCollection.addAll(collectElements((IMethod) modelElement, type, stack));
+ stack.pop();
+ }
+ }
+ return fieldsCollection;
+ }
+
+ public static 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 static boolean checkEngineImport(String xmlFilePath, IScriptProject project) {
+ boolean result = false;
+ List<IFolder> allDescriptorFolders;
+ try {
+ allDescriptorFolders = RutaProjectUtils.getAllDescriptorFolders(project.getProject());
+ } catch (Exception e) {
+ return false;
+ }
+ for (IFolder folder : allDescriptorFolders) {
+ String fileExtended = xmlFilePath.replaceAll("[.]", "/") + ".xml";
+ IFile iFile = RutaCheckerUtils.getFile(folder, fileExtended);
+ result |= iFile.exists();
+ }
+ return result;
+ }
+
+ public static boolean checkScriptImport(String xmlFilePath, IScriptProject project) {
+ boolean result = false;
+ List<IFolder> allDescriptorFolders;
+ try {
+ allDescriptorFolders = RutaProjectUtils.getAllScriptFolders(project);
+ } catch (CoreException e) {
+ return false;
+ }
+ for (IFolder folder : allDescriptorFolders) {
+ String fileExtended = xmlFilePath.replaceAll("[.]", "/") + ".tm";
+ IFile iFile = RutaCheckerUtils.getFile(folder, fileExtended);
+ result |= iFile.exists();
+ }
+ return result;
+ }
+
+ /**
+ * @param resourceFilePath
+ * absolute full path. i.e.: "org.apache.uima.TestList.txt"
+ * @return file.exists
+ */
+ public static boolean checkRessourceExistence(String resourceFilePath, IScriptProject project) {
+ IFolder ddlFolder = project.getProject().getFolder(
+ RutaProjectUtils.getDefaultDescriptorLocation());
+ final String basicXML = "BasicEngine.xml";
+ IFile file = getFile(ddlFolder, basicXML);
+ AnalysisEngineDescription aed;
+ try {
+ URL url = file.getLocationURI().toURL();
+ aed = UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(url));
+ } catch (Exception e) {
+ e.printStackTrace();
+ return false;
+ }
+ ConfigurationParameterSettings configurationParameterSettings = aed.getAnalysisEngineMetaData()
+ .getConfigurationParameterSettings();
+ String[] paths = (String[]) configurationParameterSettings
+ .getParameterValue(RutaEngine.RESOURCE_PATHS);
+ if (paths == null) {
+ IFolder folder = project.getProject().getFolder(
+ RutaProjectUtils.getDefaultResourcesLocation());
+ String defaultPath = folder.getLocation().toPortableString();
+ paths = new String[] { defaultPath };
+ }
+ for (String string : paths) {
+ File iFile = new File(string, resourceFilePath);
+ // IFile iFile = getFile(folder, ressourceFilePath);
+ if (iFile.exists()) {
+ return true;
+ }
+
+ }
+ return false;
+ }
+
+ /**
+ * @param xmlFilePath
+ * absolute full path. i.e.: "org.apache.uima.myengine" ".xml" will be added.
+ * @return file.exists
+ */
+ public static IFile getEngine(String xmlFilePath, IScriptProject project) {
+ IFolder folder = project.getProject().getFolder(
+ RutaProjectUtils.getDefaultDescriptorLocation());
+ String fileExtended = xmlFilePath + ".xml";
+ return getFile(folder, fileExtended);
+ }
+
+ public static boolean checkTypeSystemImport(String localPath, IScriptProject project) {
+ boolean result = false;
+ List<IFolder> allDescriptorFolders;
+ try {
+ allDescriptorFolders = RutaProjectUtils.getAllDescriptorFolders(project.getProject());
+ } catch (Exception e) {
+ return false;
+ }
+ for (IFolder folder : allDescriptorFolders) {
+ String fileExtended = localPath.replaceAll("[.]", "/") + ".xml";
+ IFile iFile = RutaCheckerUtils.getFile(folder, fileExtended);
+ result |= iFile.exists();
+ }
+ return result;
+ }
+}
Added: uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaEngineAndCallChecker.java
URL: http://svn.apache.org/viewvc/uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaEngineAndCallChecker.java?rev=1477113&view=auto
==============================================================================
--- uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaEngineAndCallChecker.java (added)
+++ uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaEngineAndCallChecker.java Mon Apr 29 14:50:56 2013
@@ -0,0 +1,232 @@
+/*
+ * 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.validator;
+
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.uima.ruta.ide.parser.ast.TMActionConstants;
+import org.apache.uima.ruta.ide.parser.ast.TMStatementConstants;
+import org.apache.uima.ruta.ide.parser.ast.RutaAction;
+import org.apache.uima.ruta.ide.parser.ast.RutaImportStatement;
+import org.apache.uima.util.InvalidXMLException;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+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.Statement;
+import org.eclipse.dltk.compiler.problem.IProblem;
+import org.eclipse.dltk.compiler.problem.IProblemReporter;
+import org.eclipse.dltk.core.IModelElement;
+import org.eclipse.dltk.core.IScriptProject;
+import org.eclipse.dltk.core.ISourceModule;
+import org.eclipse.dltk.core.ModelException;
+import org.eclipse.dltk.core.builder.IBuildContext;
+import org.eclipse.dltk.core.builder.IBuildParticipant;
+import org.eclipse.dltk.core.builder.IBuildParticipantExtension;
+import org.eclipse.dltk.core.builder.ISourceLineTracker;
+
+public class RutaEngineAndCallChecker implements IBuildParticipant,
+ IBuildParticipantExtension {
+
+ private class EngineAndCallCheckerVisitor extends ASTVisitor {
+ private IProblemReporter rep;
+
+ private RutaCheckerProblemFactory problemFactory;
+
+ private Set<String> engines;
+
+ private Set<String> scripts;
+
+ private String curFile;
+
+ private HashSet<String> scriptsInnerBlocks;
+
+ public EngineAndCallCheckerVisitor(IProblemReporter rep, ISourceLineTracker linetracker,
+ String curFile) {
+ this.problemFactory = new RutaCheckerProblemFactory(curFile, linetracker);
+ this.rep = rep;
+ this.engines = new HashSet<String>();
+ this.scripts = new HashSet<String>();
+ this.scriptsInnerBlocks = new HashSet<String>();
+ this.curFile = curFile;
+
+ if (curFile != null && curFile.endsWith(".tm")) {
+ scripts.add(curFile.substring(0, curFile.length() - 3));
+ }
+ try {
+ String fnwe = curFile.substring(0, curFile.length() - 3);
+ scriptsInnerBlocks.addAll(RutaCheckerUtils.importScript(fnwe, IModelElement.METHOD,
+ project));
+ } catch (InvalidXMLException e) {
+ } catch (IOException e) {
+ } catch (ModelException e) {
+ }
+ }
+
+ @Override
+ public boolean visit(Statement s) throws Exception {
+ if (s instanceof RutaImportStatement) {
+ // handle engine imports
+ if (((RutaImportStatement) s).getType() == TMStatementConstants.S_IMPORT_ENGINE) {
+ SimpleReference sRef = (SimpleReference) ((RutaImportStatement) s).getExpression();
+ if (RutaCheckerUtils.checkEngineImport(sRef.getName(), project)) {
+ importEngine(sRef.getName());
+ } else {
+ IProblem problem = problemFactory.createFileNotFoundProblem(sRef);
+ rep.reportProblem(problem);
+ }
+ }
+ // handle script imports
+ if (((RutaImportStatement) s).getType() == TMStatementConstants.S_IMPORT_SCRIPT) {
+ SimpleReference stRef = (SimpleReference) ((RutaImportStatement) s).getExpression();
+ String sRefName = stRef.getName();
+ try {
+ Set<String> blocks = RutaCheckerUtils.importScript(sRefName,
+ IModelElement.METHOD, project);
+ scripts.add(sRefName);
+ if (!blocks.isEmpty()) {
+ scriptsInnerBlocks.addAll(blocks);
+ }
+ } catch (Exception e) {
+ }
+ }
+ return false;
+ }
+ return true;
+ }
+
+ private void importEngine(String name) {
+ engines.add(name);
+ int i = name.lastIndexOf('.');
+ if (i > 1) {
+ // TODO emit errors for doublettes (names in scripts and
+ // engines)
+ String lastPart = name.substring(i + 1);
+ if (lastPart != null && lastPart.length() != 0) {
+ engines.add(lastPart);
+ }
+ }
+ }
+
+ @Override
+ public boolean visit(Expression s) throws Exception {
+ if (s instanceof RutaAction) {
+ RutaAction action = (RutaAction) s;
+ if (action.getKind() == TMActionConstants.A_CALL) {
+ // TODO see antlr grammar: no viable child defined!
+ if (action.getChilds().size() > 0) {
+ SimpleReference ref = (SimpleReference) action.getChilds().get(0);
+ if (ref != null && !engines.contains(ref.getName())) {
+ String required = ref.getName();
+ for (String script : scripts) {
+ // check direct script-call
+ boolean a = script.endsWith(required);
+ if (a) {
+ return false;
+ }
+ }
+ for (String block : scriptsInnerBlocks) {
+ boolean b = block.equals(required);
+ if (b) {
+ return false;
+ }
+ }
+ IProblem problem = problemFactory.createFileNotFoundProblem(ref);
+ rep.reportProblem(problem);
+ }
+ }
+ return false;
+ }
+ return true;
+ }
+ return true;
+ }
+
+ @Override
+ public boolean visit(MethodDeclaration s) throws Exception {
+ return true;
+ }
+
+ @Override
+ public boolean visit(TypeDeclaration s) throws Exception {
+ return false;
+ }
+ }
+
+ public RutaEngineAndCallChecker(IScriptProject project) throws CoreException {
+ this.project = project;
+ }
+
+ private IScriptProject project;
+
+ public boolean beginBuild(int buildType) {
+ return true;
+ }
+
+ public void endBuild(IProgressMonitor monitor) {
+ }
+
+ public void build(IBuildContext context) throws CoreException {
+ // getAST:
+ Object mdObj = context.get(IBuildContext.ATTR_MODULE_DECLARATION);
+ if (!(mdObj instanceof ModuleDeclaration)) {
+ return;
+ }
+ ModuleDeclaration md = (ModuleDeclaration) mdObj;
+ IProblemReporter problemReporter = context.getProblemReporter();
+ ISourceModule smod = context.getSourceModule();
+
+ // traverse:
+ ISourceLineTracker linetracker = context.getLineTracker();
+ String fileName = smod.getElementName();
+ try {
+ ASTVisitor visitor = new EngineAndCallCheckerVisitor(problemReporter, linetracker, fileName);
+ md.traverse(visitor);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ // /**
+ // * @param filePath
+ // * absolute full path. i.e.: "org.apache.uima.myengine" ".xml" will be
+ // * added.
+ // * @return file.exists
+ // */
+ // private boolean checkBlockCall(String filePath) {
+ // // try engine
+ // if (checkEngineImport(filePath)) {
+ // return true;
+ // }
+ // String fileExtended = filePath + ".tm";
+ // IFolder scriptFolder = project.getProject().getFolder(
+ // RutaLanguageToolkit.getDefault()
+ // .getDefaultDescriptorLocation());
+ // IFile iFile = getFile(scriptFolder, fileExtended);
+ // return iFile.exists();
+ // }
+
+}
Added: uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaProblemIdentifier.java
URL: http://svn.apache.org/viewvc/uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaProblemIdentifier.java?rev=1477113&view=auto
==============================================================================
--- uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaProblemIdentifier.java (added)
+++ uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaProblemIdentifier.java Mon Apr 29 14:50:56 2013
@@ -0,0 +1,34 @@
+/*
+ * 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.validator;
+
+import org.apache.uima.ruta.ide.RutaIdePlugin;
+import org.eclipse.dltk.compiler.problem.IProblemIdentifier;
+
+public enum RutaProblemIdentifier implements IProblemIdentifier {
+
+ PROBLEM;
+
+ public String contributor() {
+ return RutaIdePlugin.PLUGIN_ID;
+ }
+
+}
+
Added: uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaRessourceChecker.java
URL: http://svn.apache.org/viewvc/uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaRessourceChecker.java?rev=1477113&view=auto
==============================================================================
--- uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaRessourceChecker.java (added)
+++ uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaRessourceChecker.java Mon Apr 29 14:50:56 2013
@@ -0,0 +1,220 @@
+/*
+ * 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.validator;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.uima.UIMAFramework;
+import org.apache.uima.resource.metadata.TypeDescription;
+import org.apache.uima.resource.metadata.TypeSystemDescription;
+import org.apache.uima.ruta.ide.core.builder.RutaProjectUtils;
+import org.apache.uima.ruta.ide.parser.ast.RutaRessourceReference;
+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.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.dltk.ast.ASTVisitor;
+import org.eclipse.dltk.ast.declarations.ModuleDeclaration;
+import org.eclipse.dltk.ast.expressions.Expression;
+import org.eclipse.dltk.compiler.problem.IProblem;
+import org.eclipse.dltk.compiler.problem.IProblemReporter;
+import org.eclipse.dltk.core.IScriptProject;
+import org.eclipse.dltk.core.ISourceModule;
+import org.eclipse.dltk.core.builder.IBuildContext;
+import org.eclipse.dltk.core.builder.IBuildParticipant;
+import org.eclipse.dltk.core.builder.IBuildParticipantExtension;
+import org.eclipse.dltk.core.builder.ISourceLineTracker;
+
+public class RutaRessourceChecker implements IBuildParticipant, IBuildParticipantExtension {
+
+ private class TypeCheckerVisitor extends ASTVisitor {
+ private IProblemReporter rep;
+
+ private String currentFile;
+
+ private ISourceLineTracker linetracker;
+
+ private Set<String> types;
+
+ private RutaCheckerProblemFactory problemFactory;
+
+ private String packageName;
+
+ private static final String errMsgHead = "Cannot find resource \"";
+
+ private static final String errMsgTailDefault = " \" in resource location.";
+
+ public TypeCheckerVisitor(IProblemReporter rep, ISourceLineTracker linetracker, String curFile,
+ Set<String> types) {
+ this.problemFactory = new RutaCheckerProblemFactory(curFile, linetracker);
+ this.linetracker = linetracker;
+ this.rep = rep;
+ this.packageName = "";
+ this.currentFile = curFile;
+ this.types = types;
+ }
+
+ @Override
+ public boolean visit(Expression s) throws Exception {
+ // traverse everything but RessourceReference
+ if (!(s instanceof RutaRessourceReference)) {
+ return true;
+ }
+ RutaRessourceReference resRef = (RutaRessourceReference) s;
+ if (RutaCheckerUtils.checkRessourceExistence(resRef.getValue(), project)) {
+ return false;
+ }
+ // ressource not valid
+ String errMsg = errMsgHead + resRef.getValue() + errMsgTailDefault;
+ IProblem problem = new RutaCheckerDefaultProblem(currentFile, errMsg, resRef,
+ linetracker.getLineNumberOfOffset(resRef.sourceStart()));
+ rep.reportProblem(problem);
+ return false;
+ }
+ }
+
+ public RutaRessourceChecker(IScriptProject project) throws CoreException {
+ this.project = project;
+ }
+
+ private IScriptProject project;
+
+ public boolean beginBuild(int buildType) {
+ return true;
+ }
+
+ public void endBuild(IProgressMonitor monitor) {
+ }
+
+ public void build(IBuildContext context) throws CoreException {
+ // getAST:
+ Object mdObj = context.get(IBuildContext.ATTR_MODULE_DECLARATION);
+ if (!(mdObj instanceof ModuleDeclaration)) {
+ return;
+ }
+ ModuleDeclaration md = (ModuleDeclaration) mdObj;
+ IProblemReporter problemReporter = context.getProblemReporter();
+ ISourceModule smod = context.getSourceModule();
+
+ // get Types:
+ Set<String> types = null;
+ try {
+ types = importBasicTypeSystem();
+ } catch (InvalidXMLException e1) {
+ System.err.println("ERROR: Failed to get BasicTypeSystem!! " + this.toString());
+ // problemReporter.reportProblem(problem)
+ } catch (IOException e1) {
+ System.err.println("ERROR: Failed to get BasicTypeSystem!! " + this.toString());
+ }
+ if (types == null) {
+ types = new HashSet<String>();
+ }
+
+ // traverse:
+ ISourceLineTracker linetracker = context.getLineTracker();
+ String fileName = smod.getElementName();
+ try {
+ ASTVisitor visitor = new TypeCheckerVisitor(problemReporter, linetracker, fileName, types);
+ md.traverse(visitor);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ private Set<String> importBasicTypeSystem() throws InvalidXMLException, IOException {
+ final String basicXmlFile = "BasicTypeSystem";
+ Set<String> types = importTypeSystem(basicXmlFile);
+ types.add("Annotation");
+ types.add("DocumentAnnotation");
+ return types;
+ }
+
+ /**
+ * @param xmlFilePath
+ * absolute full path. i.e.: "org.apache.uima.mytypes" ".xml" will be added.
+ * @return
+ * @throws InvalidXMLException
+ * @throws IOException
+ * when file not found
+ */
+ private Set<String> importTypeSystem(String xmlFilePath) throws InvalidXMLException, IOException {
+ IFolder folder = project.getProject().getFolder(
+ RutaProjectUtils.getDefaultDescriptorLocation());
+ String fileExtended = xmlFilePath + ".xml";
+ return getTypes(folder, fileExtended);
+ }
+
+ 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();
+ types = getTypes(url);
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ }
+ 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 Set<String> getTypes(URL resource) throws IOException, InvalidXMLException {
+ Set<String> types = new HashSet<String>();
+ TypeSystemDescription typeSysDescr = null;
+ typeSysDescr = UIMAFramework.getXMLParser().parseTypeSystemDescription(
+ new XMLInputSource(resource));
+ for (TypeDescription each : typeSysDescr.getTypes()) {
+ String name = each.getName();
+ String[] nameSpace = name.split("[.]");
+ types.add(nameSpace[nameSpace.length - 1]);
+ StringBuffer fullName = new StringBuffer();
+ if (nameSpace.length > 0) {
+ fullName.append(nameSpace[0]);
+ }
+ for (int i = 1; i < nameSpace.length; i++) {
+ // TODO fix workaround
+ if (!nameSpace[i].equals("type")) {
+ fullName.append('.');
+ fullName.append(nameSpace[i]);
+ }
+ }
+ types.add(fullName.toString());
+ }
+ return types;
+ }
+}
Added: uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaTypeChecker.java
URL: http://svn.apache.org/viewvc/uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaTypeChecker.java?rev=1477113&view=auto
==============================================================================
--- uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaTypeChecker.java (added)
+++ uima/sandbox/ruta/trunk/ruta-ep-ide/src/main/java/org/apache/uima/ruta/ide/validator/RutaTypeChecker.java Mon Apr 29 14:50:56 2013
@@ -0,0 +1,666 @@
+/*
+ * 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.validator;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.Stack;
+import java.util.TreeSet;
+
+import org.apache.uima.UIMAFramework;
+import org.apache.uima.resource.ResourceManager;
+import org.apache.uima.resource.metadata.FeatureDescription;
+import org.apache.uima.resource.metadata.TypeDescription;
+import org.apache.uima.resource.metadata.TypeSystemDescription;
+import org.apache.uima.ruta.ide.RutaIdePlugin;
+import org.apache.uima.ruta.ide.core.RutaCorePreferences;
+import org.apache.uima.ruta.ide.core.builder.RutaProjectUtils;
+import org.apache.uima.ruta.ide.parser.ast.TMStatementConstants;
+import org.apache.uima.ruta.ide.parser.ast.TMTypeConstants;
+import org.apache.uima.ruta.ide.parser.ast.RutaBlock;
+import org.apache.uima.ruta.ide.parser.ast.RutaDeclareDeclarationsStatement;
+import org.apache.uima.ruta.ide.parser.ast.RutaFeatureDeclaration;
+import org.apache.uima.ruta.ide.parser.ast.RutaImportStatement;
+import org.apache.uima.ruta.ide.parser.ast.RutaPackageDeclaration;
+import org.apache.uima.ruta.ide.parser.ast.RutaTypeDeclaration;
+import org.apache.uima.ruta.ide.parser.ast.RutaVariableDeclaration;
+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.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.Preferences;
+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.expressions.Expression;
+import org.eclipse.dltk.ast.references.SimpleReference;
+import org.eclipse.dltk.ast.statements.Statement;
+import org.eclipse.dltk.compiler.problem.IProblem;
+import org.eclipse.dltk.compiler.problem.IProblemReporter;
+import org.eclipse.dltk.compiler.problem.ProblemSeverity;
+import org.eclipse.dltk.core.IModelElement;
+import org.eclipse.dltk.core.IScriptProject;
+import org.eclipse.dltk.core.ISourceModule;
+import org.eclipse.dltk.core.builder.IBuildContext;
+import org.eclipse.dltk.core.builder.IBuildParticipant;
+import org.eclipse.dltk.core.builder.IBuildParticipantExtension;
+import org.eclipse.dltk.core.builder.ISourceLineTracker;
+
+public class RutaTypeChecker implements IBuildParticipant, IBuildParticipantExtension {
+
+ private class TypeCheckerVisitor extends ASTVisitor {
+ private final Stack<String> blocks;
+
+ private final Set<String> typeVariables;
+
+ private final Set<String> otherVariables;
+
+ private IProblemReporter rep;
+
+ private ISourceModule currentFile;
+
+ private ISourceLineTracker linetracker;
+
+ private Set<String> completeTypes;
+
+ private Set<String> shortTypes;
+
+ private RutaCheckerProblemFactory problemFactory;
+
+ private String packageName;
+
+ private TypeSystemDescription description;
+
+ private Set<String> otherTypes;
+
+ private Set<String> finalTypes;
+
+ private boolean reportWarningOnShortNames;
+
+ public TypeCheckerVisitor(IProblemReporter rep, ISourceLineTracker linetracker,
+ ISourceModule curFile, Set<String> completeTypes, Set<String> shortTypes) {
+ this.problemFactory = new RutaCheckerProblemFactory(curFile.getElementName(),
+ linetracker);
+ this.linetracker = linetracker;
+ this.rep = rep;
+ this.typeVariables = new HashSet<String>();
+ this.otherVariables = new HashSet<String>();
+ this.blocks = new Stack<String>();
+ this.packageName = "";
+ this.currentFile = curFile;
+ this.completeTypes = completeTypes;
+ this.shortTypes = shortTypes;
+ this.otherTypes = new HashSet<String>();
+ Set<String> uimaPredefTypes = new HashSet<String>();
+ uimaPredefTypes.addAll(Arrays.asList(new String[] { "uima.cas.Boolean", "uima.cas.Byte",
+ "uima.cas.Short", "uima.cas.Integer", "uima.cas.Long", "uima.cas.Float",
+ "uima.cas.Double", "uima.cas.String", "uima.cas.BooleanArray", "uima.cas.ByteArray",
+ "uima.cas.ShortArray", "uima.cas.IntegerArray", "uima.cas.LongArray",
+ "uima.cas.FloatArray", "uima.cas.DoubleArray", "uima.cas.StringArray",
+ "uima.cas.FSArray", "uima.cas.AnnotationBase", "uima.tcas.Annotation",
+ "uima.tcas.DocumentAnnotation", "uima.cas.FloatList", "uima.cas.IntegerList",
+ "uima.cas.StringList", "uima.cas.FSList", "uima.cas.EmptyFloatList",
+ "uima.cas.EmptyIntegerList", "uima.cas.EmptyStringList", "uima.cas.EmptyFSList",
+ "uima.cas.NonEmptyFloatList", "uima.cas.NonEmptyIntegerList",
+ "uima.cas.NonEmptyStringList", "uima.cas.NonEmptyFSList" }));
+ for (String string : uimaPredefTypes) {
+ int indexOf = string.lastIndexOf('.');
+ otherTypes.add(string);
+ otherTypes.add(string.substring(indexOf + 1, string.length()));
+ }
+ this.finalTypes = new HashSet<String>();
+ Set<String> uimaFinalTypes = new HashSet<String>();
+ uimaFinalTypes.addAll(Arrays.asList(new String[] { "uima.cas.Boolean", "uima.cas.Byte",
+ "uima.cas.Short", "uima.cas.Integer", "uima.cas.Long", "uima.cas.Float",
+ "uima.cas.Double", "uima.cas.BooleanArray", "uima.cas.ByteArray", "uima.cas.ShortArray",
+ "uima.cas.IntegerArray", "uima.cas.LongArray", "uima.cas.FloatArray",
+ "uima.cas.DoubleArray", "uima.cas.StringArray", "uima.cas.FSArray" }));
+
+ for (String string : uimaFinalTypes) {
+ int indexOf = string.lastIndexOf('.');
+ finalTypes.add(string);
+ finalTypes.add(string.substring(indexOf + 1, string.length()));
+ }
+
+ try {
+ this.description = getTypeSystemOfScript();
+ } catch (Exception e) {
+ RutaIdePlugin.error(e);
+ }
+
+ Preferences store = RutaIdePlugin.getDefault().getPluginPreferences();
+ reportWarningOnShortNames = !store
+ .getBoolean(RutaCorePreferences.BUILDER_IGNORE_DUPLICATE_SHORTNAMES);
+ }
+
+ @Override
+ public boolean endvisit(MethodDeclaration s) throws Exception {
+ if (s instanceof RutaBlock) {
+ blocks.pop();
+ }
+ return super.endvisit(s);
+ }
+
+ public boolean visit(MethodDeclaration s) throws Exception {
+ if (s instanceof RutaBlock) {
+ RutaBlock b = (RutaBlock) s;
+ blocks.push(b.getName());
+ }
+ return true;
+ }
+
+ @Override
+ public boolean visit(Statement s) throws Exception {
+ if (s instanceof RutaPackageDeclaration) {
+ this.packageName = ((RutaPackageDeclaration) s).getName();
+ return false;
+ }
+ if (s instanceof RutaDeclareDeclarationsStatement) {
+ RutaDeclareDeclarationsStatement dds = (RutaDeclareDeclarationsStatement) s;
+ ASTNode parent = dds.getParent();
+ if (parent != null && parent instanceof RutaVariableReference) {
+ RutaVariableReference p = (RutaVariableReference) parent;
+ String name = p.getName();
+ if (finalTypes.contains(name)) {
+ IProblem problem = problemFactory.createInheritenceFinalProblem(p);
+ rep.reportProblem(problem);
+ }
+ }
+ return true;
+ }
+
+ if (s instanceof RutaVariableDeclaration) {
+ RutaVariableDeclaration newVar = (RutaVariableDeclaration) s;
+ // if (otherVariables.contains(newVar.getName())) {
+ // IProblem problem = problemFactory
+ // .createVarAlreadyDeclaredProblem(newVar);
+ // rep.reportProblem(problem);
+ // return false;
+ // }
+ if (shortTypes.contains(newVar.getName())) {
+ IProblem problem = problemFactory.createIdConflictsWithTypeProblem(newVar);
+ rep.reportProblem(problem);
+ return false;
+ }
+ if ((newVar.getKind() & TMTypeConstants.TM_TYPE_AT) != 0) {
+ typeVariables.add(newVar.getName());
+ return false;
+ }
+ otherVariables.add(newVar.getName());
+ return false;
+ }
+ // if (s instanceof RutaFeatureDeclaration) {
+ // RutaFeatureDeclaration fd = (RutaFeatureDeclaration) s;
+ // }
+ if (s instanceof RutaTypeDeclaration) {
+ RutaTypeDeclaration newType = (RutaTypeDeclaration) s;
+ if (reportWarningOnShortNames && shortTypes.contains(newType.getName())) {
+ IProblem problem = problemFactory.createDuplicateShortName(newType,
+ ProblemSeverity.WARNING);
+ rep.reportProblem(problem);
+ return false;
+ }
+ String longName = getLongLocalName(newType.getName());
+ if (completeTypes.contains(longName)) {
+ IProblem problem = problemFactory.createIdConflictsWithTypeProblem(newType);
+ rep.reportProblem(problem);
+ return false;
+ }
+ if (typeVariables.contains(newType.getName()) || otherVariables.contains(newType.getName())) {
+ IProblem problem = problemFactory.createIdConflictsWithVariableProblem(newType);
+ rep.reportProblem(problem);
+ return false;
+ }
+ List<RutaFeatureDeclaration> features = newType.getFeatures();
+ if (features != null) {
+
+ for (RutaFeatureDeclaration each : features) {
+ String type = each.getType();
+ if (type.equals("INT") || type.equals("STRING") || type.equals("DOUBLE")
+ || type.equals("FLOAT") || type.equals("BOOLEAN")) {
+ continue;
+ }
+ if (!shortTypes.contains(type) && !completeTypes.contains(type)
+ && !otherTypes.contains(type)) {
+ IProblem problem = problemFactory.createUnknownFeatureTypeProblem(each);
+ rep.reportProblem(problem);
+ }
+ }
+ }
+ String[] nameSplit = newType.getName().split("[.]");
+ String shortName = nameSplit[nameSplit.length - 1];
+
+ completeTypes.add(longName);
+ shortTypes.add(shortName);
+ return false;
+ }
+ if (s instanceof RutaImportStatement) {
+ // handle type system imports
+ if (((RutaImportStatement) s).getType() == TMStatementConstants.S_IMPORT_TYPESYSTEM) {
+ SimpleReference sRef = (SimpleReference) ((RutaImportStatement) s).getExpression();
+ String localPath = sRef.getName();
+ try {
+ boolean checkTypeSystemImport = RutaCheckerUtils.checkTypeSystemImport(localPath,
+ project);
+ if (!checkTypeSystemImport) {
+ rep.reportProblem(problemFactory.createFileNotFoundProblem(sRef, localPath));
+ }
+ Set<String> importedTypes = importTypeSystem(localPath);
+ Set<String> importedShortTypes = getShortTypeNames(importedTypes);
+
+ if (reportWarningOnShortNames) {
+ List<String> checkDuplicateShortNames = checkDuplicateShortNames(completeTypes,
+ importedTypes);
+ if (!checkDuplicateShortNames.isEmpty()) {
+ rep.reportProblem(problemFactory.createDuplicateShortNameInImported(sRef,
+ localPath, checkDuplicateShortNames, ProblemSeverity.WARNING));
+ }
+ }
+ completeTypes.addAll(importedTypes);
+ shortTypes.addAll(importedShortTypes);
+ } catch (IOException e) {
+ rep.reportProblem(problemFactory.createFileNotFoundProblem(sRef, localPath));
+ } catch (InvalidXMLException e) {
+ rep.reportProblem(problemFactory.createXMLProblem(sRef, localPath));
+ }
+ return false;
+ }
+ // handle script-imports
+ if (((RutaImportStatement) s).getType() == TMStatementConstants.S_IMPORT_SCRIPT) {
+ SimpleReference sRef = (SimpleReference) ((RutaImportStatement) s).getExpression();
+ String localpath = sRef.getName();
+
+ // HOTFIX Peter add also the imported types of the imported type system!
+ try {
+ boolean checkScriptImport = RutaCheckerUtils
+ .checkScriptImport(localpath, project);
+ if (!checkScriptImport) {
+ rep.reportProblem(problemFactory.createFileNotFoundProblem(sRef, localpath));
+ }
+ Set<String> importedTypes = importTypeSystem(localpath + "TypeSystem");
+ Set<String> importedShortTypes = getShortTypeNames(importedTypes);
+ Preferences store = RutaIdePlugin.getDefault().getPluginPreferences();
+ if (reportWarningOnShortNames) {
+ List<String> checkDuplicateShortNames = checkDuplicateShortNames(completeTypes,
+ importedTypes);
+ if (!checkDuplicateShortNames.isEmpty()) {
+ rep.reportProblem(problemFactory.createDuplicateShortNameInImported(sRef,
+ localpath, checkDuplicateShortNames, ProblemSeverity.WARNING));
+ }
+ }
+ completeTypes.addAll(importedTypes);
+ shortTypes.addAll(importedShortTypes);
+ } catch (IOException e) {
+ rep.reportProblem(problemFactory.createFileNotFoundProblem(sRef, localpath));
+ }
+ // old stuff
+ Set<String> importedTypes = new HashSet<String>();
+ try {
+ importedTypes = RutaCheckerUtils.importScript(localpath, IModelElement.FIELD,
+ project, true);
+ } catch (IOException e) {
+ rep.reportProblem(problemFactory.createFileNotFoundProblem(sRef, localpath));
+ }
+ shortTypes.addAll(importedTypes);
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private String getLongLocalName(String name) {
+ if (name.indexOf(".") == -1) {
+ String longName = this.packageName
+ + "."
+ + currentFile.getElementName().substring(0,
+ currentFile.getElementName().length() - 3) + ".";
+ for (String each : blocks) {
+ longName += each + ".";
+ }
+ longName += name;
+ return longName;
+ }
+ return name;
+ }
+
+ private List<String> checkDuplicateShortNames(Set<String> types, Set<String> importedTypes) {
+ List<String> result = new ArrayList<String>();
+ for (String t1 : importedTypes) {
+ for (String t2 : types) {
+ if (checkTypeName(t1, t2)) {
+ result.add(t1);
+ result.add(t2);
+ }
+ }
+ }
+ return result;
+ }
+
+ private boolean checkTypeName(String t1, String t2) {
+ int lastIndexOf1 = t1.lastIndexOf(".");
+ int lastIndexOf2 = t2.lastIndexOf(".");
+ String shortName1 = t1.substring(lastIndexOf1 + 1, t1.length());
+ String shortName2 = t2.substring(lastIndexOf2 + 1, t2.length());
+ String namespace1 = "";
+ String namespace2 = "";
+ if (lastIndexOf1 >= 0) {
+ namespace1 = t1.substring(0, lastIndexOf1);
+ }
+ if (lastIndexOf2 >= 0) {
+ namespace2 = t2.substring(0, lastIndexOf2);
+ }
+ if (shortName1.equals(shortName2) && !namespace1.equals(namespace2)) {
+ return true;
+ }
+ return false;
+ }
+
+ private TypeSystemDescription getTypeSystemOfScript() throws InvalidXMLException, IOException {
+ IPath descriptorPath = RutaProjectUtils.getTypeSystemDescriptorPath(currentFile
+ .getResource().getLocation(), project.getProject());
+ TypeSystemDescription typeSysDescr = null;
+ if (descriptorPath.toFile().exists()) {
+ typeSysDescr = UIMAFramework.getXMLParser().parseTypeSystemDescription(
+ new XMLInputSource(descriptorPath.toPortableString()));
+ ResourceManager resMgr = UIMAFramework.newDefaultResourceManager();
+ IFolder folder = project.getProject().getFolder(
+ RutaProjectUtils.getDefaultDescriptorLocation());
+ resMgr.setDataPath(folder.getLocation().toPortableString());
+ typeSysDescr.resolveImports(resMgr);
+ }
+ return typeSysDescr;
+ }
+
+ @Override
+ public boolean visit(Expression s) throws Exception {
+ if (s instanceof RutaVariableReference) {
+ RutaVariableReference ref = (RutaVariableReference) s;
+ // filter everything but AnnotationTypeReferences
+ if ((ref.getType() & TMTypeConstants.TM_TYPE_AT) == 0) {
+ return false;
+ }
+ if (typeVariables.contains(ref.getName()) || completeTypes.contains(ref.getName())
+ || shortTypes.contains(ref.getName()) || otherTypes.contains(ref.getName())
+ || isLongLocalATRef(ref.getName()) || isLongExternalATRef(ref.getName())
+ ) {
+ return false;
+ }
+ if(isFeatureMatch(ref)) {
+ return false;
+ }
+ rep.reportProblem(problemFactory.createTypeProblem(ref, currentFile));
+ return false;
+ }
+ return true;
+ }
+
+ private boolean isFeatureMatch(RutaVariableReference ref) {
+ String name = ref.getName();
+ for (String each : shortTypes) {
+ if(checkFeatureMatch(name, each)) return true;
+ }
+ for (String each : completeTypes) {
+ if(checkFeatureMatch(name, each)) return true;
+ }
+ return false;
+ }
+
+ private boolean checkFeatureMatch(String name, String type) {
+ if(name.startsWith(type)) {
+ boolean foundAll = true;
+ String tail = name.substring(type.length() + 1);
+ String[] split = tail.split("[.]");
+ String typeToCheck = type;
+ for (String feat : split) {
+ typeToCheck = checkFSFeatureOfType(feat, typeToCheck);
+ foundAll &= (typeToCheck != null);
+ if(!foundAll) {
+ return false;
+ }
+ }
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ private String checkFSFeatureOfType(String feat, String type) {
+ if(type.indexOf(".") == -1) {
+ for (String each : completeTypes) {
+ String[] split = each.split("[.]");
+ if(split[split.length-1].equals(type)) {
+ type = each;
+ break;
+ }
+ }
+ }
+ TypeDescription t = description.getType(type);
+ if(t == null) return null;
+ FeatureDescription[] features = t.getFeatures();
+ for (FeatureDescription featureDescription : features) {
+ String name = featureDescription.getName();
+ String rangeTypeName = featureDescription.getRangeTypeName();
+ boolean isFS = isFeatureStructure(rangeTypeName);
+ if(name.equals(feat) && isFS) {
+ return rangeTypeName;
+ }
+ }
+ return null;
+ }
+
+ private boolean isFeatureStructure(String rangeTypeName) {
+ if(rangeTypeName.equals("uima.tcas.Annotation") || rangeTypeName.equals("uima.cas.TOP")) {
+ return true;
+ }
+ TypeDescription type = description.getType(rangeTypeName);
+ if(type == null) {
+ return false;
+ }
+ String supertypeName = type.getSupertypeName();
+ if(supertypeName != null) {
+ return isFeatureStructure(supertypeName);
+ }
+ return false;
+ }
+
+ private boolean isLongExternalATRef(String name) {
+ int lastIndexOf = name.lastIndexOf(".");
+ if (lastIndexOf == -1) {
+ return false;
+ }
+ for (String each : shortTypes) {
+ lastIndexOf = each.lastIndexOf(".");
+ if (lastIndexOf != -1 && each.endsWith(name)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private boolean isLongLocalATRef(String name) {
+ // TODO this methods does not work for blocks
+ String longName = this.packageName
+ + "."
+ + currentFile.getElementName()
+ .substring(0, currentFile.getElementName().length() - 3);
+ if (!name.startsWith(longName)) {
+ return false;
+ }
+ String ref;
+ try {
+ ref = name.substring(longName.length() + 1);
+ } catch (IndexOutOfBoundsException e) {
+ return false;
+ }
+ return shortTypes.contains(ref);
+ }
+ }
+
+ public RutaTypeChecker(IScriptProject project) throws CoreException {
+ this.project = project;
+ }
+
+ private IScriptProject project;
+
+ public boolean beginBuild(int buildType) {
+ return true;
+ }
+
+ public void endBuild(IProgressMonitor monitor) {
+ }
+
+ public void build(IBuildContext context) throws CoreException {
+ // getAST:
+ Object mdObj = context.get(IBuildContext.ATTR_MODULE_DECLARATION);
+ if (!(mdObj instanceof ModuleDeclaration)) {
+ return;
+ }
+ ModuleDeclaration md = (ModuleDeclaration) mdObj;
+ IProblemReporter problemReporter = context.getProblemReporter();
+ ISourceModule smod = context.getSourceModule();
+
+ // get Types:
+ Set<String> types = null;
+ try {
+ types = importBasicTypeSystem();
+ } catch (InvalidXMLException e1) {
+ System.err.println("ERROR: Failed to get BasicTypeSystem!! " + this.toString());
+ // problemReporter.reportProblem(problem)
+ } catch (IOException e1) {
+ System.err.println("ERROR: Failed to get BasicTypeSystem!! " + this.toString());
+ }
+ if (types == null) {
+ types = new TreeSet<String>();
+ }
+
+ // traverse:
+ ISourceLineTracker linetracker = context.getLineTracker();
+
+ Set<String> shortTypes = getShortTypeNames(types);
+ try {
+ ASTVisitor visitor = new TypeCheckerVisitor(problemReporter, linetracker, smod, types,
+ shortTypes);
+ md.traverse(visitor);
+ } catch (Exception e) {
+ RutaIdePlugin.error(e);
+ }
+ }
+
+ private Set<String> importBasicTypeSystem() throws InvalidXMLException, IOException,
+ CoreException {
+ final String basicXmlFile = "BasicTypeSystem";
+ Set<String> types = importTypeSystem(basicXmlFile);
+ types.add("uima.tcas.Annotation");
+ types.add("uima.tcas.DocumentAnnotation");
+ return types;
+ }
+
+ public Set<String> getShortTypeNames(Set<String> types) {
+ Set<String> result = new TreeSet<String>();
+ for (String string : types) {
+ String[] nameSpace = string.split("[.]");
+ result.add(nameSpace[nameSpace.length - 1]);
+ }
+ return result;
+ }
+
+ /**
+ * @param xmlFilePath
+ * absolute full path. i.e.: "org.apache.uima.mytypes" ".xml" will be added.
+ * @return
+ * @throws InvalidXMLException
+ * @throws IOException
+ * when file not found
+ * @throws Exception
+ */
+ private Set<String> importTypeSystem(String xmlFilePath) throws InvalidXMLException, IOException,
+ CoreException {
+
+ List<IFolder> folders = RutaProjectUtils.getAllDescriptorFolders(project.getProject());
+ String[] split = xmlFilePath.split("[.]");
+ String fileExtended = "";
+ for (String string : split) {
+ fileExtended += string;
+ fileExtended += "/";
+ }
+ fileExtended = fileExtended.substring(0, fileExtended.length() - 1) + ".xml";
+ Set<String> types = new TreeSet<String>();
+ for (IFolder folder : folders) {
+ types.addAll(getTypes(folder, fileExtended));
+ }
+ return types;
+ }
+
+ private Set<String> getTypes(IFolder folder, String filePath) throws InvalidXMLException,
+ IOException {
+ Set<String> types = new HashSet<String>();
+ IFile iFile = getFile(folder, filePath);
+ if (iFile.exists()) {
+ 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 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);
+ }
+ IFile file = folder.getFile(fName);
+ return file;
+ }
+
+ 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();
+ types.add(name);
+ }
+ return types;
+ }
+}