Java Code Examples for org.eclipse.xtext.nodemodel.util.NodeModelUtils#getTokenText()

The following examples show how to use org.eclipse.xtext.nodemodel.util.NodeModelUtils#getTokenText() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GamlSyntaxErrorMessageProvider.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
private String translateMessage(final EObject contextobj, final String message, final INode node) {
	String msg = message;
	if (msg.startsWith("mismatched ch")) {
		final String ch = msg.substring(msg.lastIndexOf(' '), msg.length());
		msg = "Character expected " + ch;
	} else if (msg.startsWith("mismatched in")) {
		msg = msg.replace("mismatched input", "Found");
	} else {
		if (contextobj != null) {
			// if (DEBUG.IS_ON()) {
			// DEBUG.OUT("No exception but EObject present");
			// }
			msg += "Error in expression '" + NodeModelUtils.getTokenText(NodeModelUtils.getNode(contextobj)) + "'";
		} else if (node != null) {
			// if (DEBUG.IS_ON()) {
			// DEBUG.OUT("No exception but Node present");
			// }
			msg += "Error in expression '" + NodeModelUtils.getTokenText(node) + "'";
		}
	}
	return msg;
}
 
Example 2
Source File: EGaml.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Gets the name of the ref represented by this eObject
 *
 * @param o
 *            the o
 * @return the name of ref
 */
@Override
public String getNameOfRef(final EObject o) {
	final ICompositeNode n = NodeModelUtils.getNode(o);
	if (n != null) { return NodeModelUtils.getTokenText(n); }
	if (o instanceof VariableRef) {
		return ((VariableRef) o).getRef().getName();
	} else if (o instanceof UnitName) {
		return ((UnitName) o).getRef().getName();
	} else if (o instanceof ActionRef) {
		return ((ActionRef) o).getRef().getName();
	} else if (o instanceof SkillRef) {
		return ((SkillRef) o).getRef().getName();
	} else if (o instanceof EquationRef) {
		return ((EquationRef) o).getRef().getName();
	} else if (o instanceof TypeRef) {
		return ((TypeRef) o).getRef().getName();
	} else {
		return "";
	}
}
 
Example 3
Source File: ParseTreeUtil.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the source text assigned to the given feature of the given object. Does not work for multi-valued features. Optionally also converts the source
 * text using the corresponding value converter. Conversion is only performed for keywords, rule call or cross reference grammar rules.
 * <p>
 * This method does not perform a check to make sure the feature matches the given object.
 *
 * @param object
 *          the semantic object
 * @param feature
 *          the feature to be considered when parsing the parse tree model
 * @param convert
 *          {@code true} if the parsed string needs conversion using its value converter
 * @return the parsed string from the node model
 */
public static String getParsedStringUnchecked(final EObject object, final EStructuralFeature feature, final boolean convert) {
  INode node = Iterables.getFirst(NodeModelUtils.findNodesForFeature(object, feature), null);
  if (node != null) {
    if (convert) {
      final LazyLinkingResource res = (LazyLinkingResource) object.eResource();
      EObject grammarElement = node.getGrammarElement();
      if (res != null && (grammarElement instanceof Keyword || grammarElement instanceof RuleCall || grammarElement instanceof CrossReference)) {
        final DefaultLinkingService linkingService = (DefaultLinkingService) res.getLinkingService();
        return linkingService.getCrossRefNodeAsString(node);
      }
    }
    // result may contain escape sequences or quotes
    return NodeModelUtils.getTokenText(node);
  }
  return null;
}
 
Example 4
Source File: FormatLinkingService.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Tries to find {@link Constant} that my be defined in the same formatter or in any formatter that is extended by the current formatter.
 * An appropriate constant should be matched by comparing its name with the desired one.
 *
 * @param resourceSet
 *          to be used for loading
 * @param node
 *          parse subtree for the reference
 * @return A singleton list containing the desired constant, or an empty list if not found.
 */
private List<EObject> getConstant(final ResourceSet resourceSet, final INode node) {
  String constantFullyQualifiedName = NodeModelUtils.getTokenText(node);
  String formatName = URI.createURI(constantFullyQualifiedName).trimFileExtension().toString();
  if (formatName != null) {
    FormatConfiguration result = loadExtendedFormatConfiguration(formatName, resourceSet);
    if (result != null) {
      EList<Constant> constants = result.getConstants();
      for (Constant constant : constants) {
        if (constantFullyQualifiedName.equals(formatName + "." + constant.getName())) {
          return Collections.<EObject> singletonList(constant);
        }
      }
    }
  }
  return Collections.emptyList();
}
 
Example 5
Source File: XtextGeneratorLanguage.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected void validateReferencedMetamodel(final ReferencedMetamodel ref) {
  if (((ref.getEPackage() != null) && (!ref.getEPackage().eIsProxy()))) {
    return;
  }
  final EReference eref = XtextPackage.Literals.ABSTRACT_METAMODEL_DECLARATION__EPACKAGE;
  final List<INode> nodes = NodeModelUtils.findNodesForFeature(ref, eref);
  String _xifexpression = null;
  boolean _isEmpty = nodes.isEmpty();
  if (_isEmpty) {
    _xifexpression = "(unknown)";
  } else {
    _xifexpression = NodeModelUtils.getTokenText(nodes.get(0));
  }
  final String refName = _xifexpression;
  final String grammarName = GrammarUtil.getGrammar(ref).getName();
  final String msg = ((((("The EPackage " + refName) + " in grammar ") + grammarName) + " could not be found. ") + "You might want to register that EPackage in your workflow file.");
  throw new IllegalStateException(msg);
}
 
Example 6
Source File: NodeModelSemanticSequencer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void createSequence(ISerializationContext context, EObject semanticObject) {
	SemanticNodeIterator ni = new SemanticNodeIterator(semanticObject);
	while (ni.hasNext()) {
		Triple<INode, AbstractElement, EObject> node = ni.next();
		if (node.getSecond() instanceof RuleCall) {
			RuleCall rc = (RuleCall) node.getSecond();
			TypeRef ruleType = rc.getRule().getType();
			if (ruleType == null || ruleType.getClassifier() instanceof EClass)
				acceptSemantic(semanticObject, rc, node.getThird(), node.getFirst());
			else if (GrammarUtil.containingCrossReference(node.getSecond()) != null) {
				EStructuralFeature feature = FeatureFinderUtil.getFeature(node.getSecond(),
						semanticObject.eClass());
				acceptSemantic(semanticObject, rc, semanticObject.eGet(feature), node.getFirst());
			} else {
				String strVal = NodeModelUtils.getTokenText(node.getFirst());
				Object val = valueConverter.toValue(strVal, ruleNames.getQualifiedName(rc.getRule()),
						node.getFirst());
				acceptSemantic(semanticObject, rc, val, node.getFirst());
			}
		} else if (node.getSecond() instanceof Keyword)
			acceptSemantic(semanticObject, node.getSecond(), node.getFirst().getText(), node.getFirst());
		else if (node.getSecond() instanceof Action) {
			acceptSemantic(semanticObject, node.getSecond(), semanticObject, node.getFirst());
		}
	}
}
 
Example 7
Source File: StringRepresentation.java    From xsemantics with Eclipse Public License 1.0 5 votes vote down vote up
protected String stringRepForEObjectNotProcessed(EObject eObject) {
	final ICompositeNode node = NodeModelUtils.getNode(eObject);
	if (node != null) {
		return NodeModelUtils.getTokenText(node);
	}
	return stringRepForEObject(eObject);
}
 
Example 8
Source File: XsemanticsNodeModelUtils.java    From xsemantics with Eclipse Public License 1.0 5 votes vote down vote up
public String getProgramText(EObject object) {
	final ICompositeNode node = NodeModelUtils.getNode(object);
	if (node == null) {
		return null;
	}
	return NodeModelUtils.getTokenText(node);
}
 
Example 9
Source File: FormatLinkingService.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Tries to find {@link FormatConfiguration} for the base formatter ({@code with} clause).
 *
 * @param resourceSet
 *          to be used for loading
 * @param node
 *          parse subtree for the reference
 * @return A singleton list containing the base format configuration, or an empty list if not found.
 */
private List<EObject> getExtendedFormatConfiguration(final ResourceSet resourceSet, final INode node) {
  String formatName = NodeModelUtils.getTokenText(node);
  if (formatName != null) {
    FormatConfiguration result = loadExtendedFormatConfiguration(formatName, resourceSet);
    if (result != null) {
      return Collections.<EObject> singletonList(result);
    }
  }
  return Collections.emptyList();
}
 
Example 10
Source File: TestLanguageRenameService.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected EObject getElementWithIdentifierAt(XtextResource xtextResource, int offset) {
	if (offset >= 0) {
		if (xtextResource != null) {
			IParseResult parseResult = xtextResource.getParseResult();
			if (parseResult != null) {
				ICompositeNode rootNode = parseResult.getRootNode();
				if (rootNode != null) {
					ILeafNode leaf = NodeModelUtils.findLeafNodeAtOffset(rootNode, offset);
					if (leaf != null && isIdentifier(leaf)) {
						EObject element = eObjectAtOffsetHelper.resolveElementAt(xtextResource, offset);
						if (element != null) {
							IQualifiedNameProvider nameProvider = xtextResource.getResourceServiceProvider()
									.get(IQualifiedNameProvider.class);
							QualifiedName fqn = nameProvider.getFullyQualifiedName(element);
							if (fqn != null) {
								String leafText = NodeModelUtils.getTokenText(leaf);
								if (fqn.getSegmentCount() == 1 && Objects.equal(fqn.toString(), leafText)
										|| Objects.equal(fqn.getLastSegment(), leafText)) {
									return element;
								}
							}
						}
					}
				}
			}
		}
	}
	return null;
}
 
Example 11
Source File: Linker.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void afterCreateAndSetProxy(EObject obj, INode node, EReference eRef, CrossReference xref, IDiagnosticProducer diagnosticProducer) {
	AbstractElement terminal = xref.getTerminal();
	if (!(terminal instanceof RuleCall)) { 
		throw new IllegalArgumentException(String.valueOf(xref));
	}
	AbstractRule rule = ((RuleCall) terminal).getRule();
	try {
		String tokenText = NodeModelUtils.getTokenText(node);
		valueConverterService.toValue(tokenText, rule.getName(), node);
	} catch(ValueConverterException e) {
		diagnosticProducer.addDiagnostic(new DiagnosticMessage(e.getMessage(), Severity.ERROR, Diagnostic.SYNTAX_DIAGNOSTIC, Strings.EMPTY_ARRAY));
	}
}
 
Example 12
Source File: LanguageConfig.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.3
 */
protected void validateReferencedMetamodel(ReferencedMetamodel ref) {
	if (ref.getEPackage() != null && !ref.getEPackage().eIsProxy())
		return;
	EReference eref = XtextPackage.Literals.ABSTRACT_METAMODEL_DECLARATION__EPACKAGE;
	List<INode> nodes = NodeModelUtils.findNodesForFeature(ref, eref);
	String refName = nodes.isEmpty() ? "(unknown)" : NodeModelUtils.getTokenText(nodes.get(0));
	String grammarName = GrammarUtil.getGrammar(ref).getName();
	String msg = "The EPackage " + refName + " in grammar " + grammarName + " could not be found. ";
	msg += "You might want to register that EPackage in your workflow file.";
	throw new IllegalStateException(msg);
}
 
Example 13
Source File: ImportsCollector.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void _visit(final JvmDeclaredType jvmType, final INode originNode, final ImportsAcceptor acceptor) {
  JvmDeclaredType _declaringType = jvmType.getDeclaringType();
  boolean _tripleEquals = (_declaringType == null);
  if (_tripleEquals) {
    this.collectTypeImportFrom(jvmType, acceptor);
  }
  final String text = NodeModelUtils.getTokenText(originNode);
  final String outerSegment = this.getFirstNameSegment(text);
  final JvmDeclaredType outerType = this.findDeclaringTypeBySimpleName(jvmType, outerSegment);
  if ((outerType == null)) {
    throw new IllegalStateException();
  }
  this.collectTypeImportFrom(outerType, acceptor);
}
 
Example 14
Source File: TypeUsageCollector.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
private String getFirstNameSegment(EObject owner, EReference reference) {
	List<INode> nodes = NodeModelUtils.findNodesForFeature(owner, reference);
	if (nodes.size() == 1) {
		String text = NodeModelUtils.getTokenText(nodes.get(0));
		return getFirstNameSegment(text);
	}
	throw new IllegalStateException("Cannot find node for feature");
}
 
Example 15
Source File: ASTExtensions.java    From balzac with Apache License 2.0 5 votes vote down vote up
public static String nodeToString(EObject eobj) {
    try {
        return NodeModelUtils.getTokenText(NodeModelUtils.getNode(eobj));
    } catch (Exception e) {
        String errorMsg = e.getClass().getSimpleName() + (e.getMessage() != null ? ": " + e.getMessage() : "");
        logger.error("Error retrieving the node text for eobject {}: {}", eobj, errorMsg);
        return "<unable to retrieve the node string>";
    }
}
 
Example 16
Source File: CompileTimeEvaluationError.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns this error's message with a suffix explaining where the error occurred if {@link #astNode} is given. This
 * method ignores field {@link #feature}.
 */
public String getMessageWithLocation() {
	if (astNode == null) {
		return message;
	}
	final INode node = NodeModelUtils.findActualNodeFor(astNode);
	final String tokenText = node != null ? NodeModelUtils.getTokenText(node) : null;
	if (tokenText == null) {
		return message;
	}
	return message + " at \"" + tokenText + "\"";
}
 
Example 17
Source File: FindReferencesXpectMethod.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * This Xpect methods compares all computed references at a given EObject to the expected references. The expected
 * references include the line number.
 */
@Xpect
@ParameterParser(syntax = "('at' arg1=OFFSET)?")
public void findReferences(
		@N4JSCommaSeparatedValuesExpectation IN4JSCommaSeparatedValuesExpectation expectation,
		IEObjectCoveringRegion offset) {
	// When you write Xpect test methods, ALWAYS retrieve eObject via IEObjectCoveringRegion to get the right
	// eObject!
	// Do NOT use EObject arg1!
	EObject context = offset.getEObject();
	EObject argEObj = offsetHelper.resolveElementAt((XtextResource) context.eResource(), offset.getOffset());
	// If not a cross-reference element, use context instead
	if (argEObj == null)
		argEObj = context;

	EObject eObj = argEObj;

	if (argEObj instanceof ParameterizedTypeRef)
		eObj = ((ParameterizedTypeRef) argEObj).getDeclaredType();

	List<EObject> refs = findReferenceHelper.findReferences(eObj, context.eResource().getResourceSet());
	ArrayList<String> result = Lists.newArrayList();
	for (EObject ref : refs) {
		if (ref instanceof PropertyNameOwner)
			ref = ((PropertyNameOwner) ref).getDeclaredName();

		ICompositeNode srcNode = NodeModelUtils.getNode(ref);
		int line = srcNode.getStartLine();

		String moduleName;
		if (ref.eResource() instanceof N4JSResource) {
			N4JSResource n4jsResource = (N4JSResource) ref.eResource();
			moduleName = n4jsResource.getModule().getQualifiedName();
		} else {
			moduleName = "(unknown resource)";
		}

		String text = NodeModelUtils.getTokenText(srcNode);
		if (ref instanceof GenericDeclaration)
			text = ((GenericDeclaration) ref).getDefinedType().getName();

		String resultText = moduleName + " - " + text + " - " + line;

		result.add(resultText);
	}

	expectation.assertEquals(result);
}
 
Example 18
Source File: N4JSLinker.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates the proxy with a custom encoded URI format (starting with "|"). The object used to produce the encoded
 * URI are collected as tuple inside {@link N4JSResource}. Then the node text is checked if it is convertible to a
 * valid value. If there is a {@link BadEscapementException} is thrown then there is either a warning or an error
 * produced via the diagnosticProducer.
 *
 *
 * @param resource
 *            the N4JSResource
 * @param obj
 *            the EObject containing the cross reference
 * @param node
 *            the node representing the EObject
 * @param eRef
 *            the cross reference in the domain model
 * @param xref
 *            the cross reference in the node model
 * @param diagnosticProducer
 *            to produce errors or warnings
 * @return the created proxy
 */
private EObject createProxy(N4JSResource resource, EObject obj, INode node, EReference eRef, CrossReference xref,
		IDiagnosticProducer diagnosticProducer) {
	final URI uri = resource.getURI();
	/*
	 * as otherwise with 0 the EObjectDescription created for Script would be fetched
	 */
	final int fragmentNumber = resource.addLazyProxyInformation(obj, eRef, node);
	final URI encodedLink = uri.appendFragment("|" + fragmentNumber);
	EClass referenceType = findInstantiableCompatible(eRef.getEReferenceType());
	final EObject proxy = EcoreUtil.create(referenceType);
	((InternalEObject) proxy).eSetProxyURI(encodedLink);
	AbstractElement terminal = xref.getTerminal();
	if (!(terminal instanceof RuleCall)) {
		throw new IllegalArgumentException(String.valueOf(xref));
	}
	AbstractRule rule = ((RuleCall) terminal).getRule();
	try {
		String tokenText = NodeModelUtils.getTokenText(node);
		Object value = valueConverterService.toValue(tokenText, rule.getName(), node);
		if (obj instanceof IdentifierRef && value instanceof String) {
			((IdentifierRef) obj).setIdAsText((String) value);
		} else if (obj instanceof ParameterizedTypeRef && value instanceof String) {
			((ParameterizedTypeRef) obj).setDeclaredTypeAsText((String) value);
		} else if (obj instanceof LabelRef && value instanceof String) {
			((LabelRef) obj).setLabelAsText((String) value);
		} else if (obj instanceof ParameterizedPropertyAccessExpression && value instanceof String) {
			((ParameterizedPropertyAccessExpression) obj).setPropertyAsText((String) value);
		} else if (obj instanceof ImportDeclaration && value instanceof String) {
			((ImportDeclaration) obj).setModuleSpecifierAsText((String) value);
		} else if (obj instanceof NamedImportSpecifier && value instanceof String) {
			((NamedImportSpecifier) obj).setImportedElementAsText((String) value);
		} else if ((obj instanceof JSXPropertyAttribute) && (value instanceof String)) {
			((JSXPropertyAttribute) obj).setPropertyAsText((String) value);
		} else {
			setOtherElementAsText(tokenText, obj, value);
		}
	} catch (BadEscapementException e) {
		diagnosticProducer.addDiagnostic(new DiagnosticMessage(e.getMessage(), e.getSeverity(), e.getIssueCode(),
				Strings.EMPTY_ARRAY));
	} catch (N4JSValueConverterException vce) {
		diagnosticProducer.addDiagnostic(new DiagnosticMessage(vce.getMessage(), vce.getSeverity(),
				vce.getIssueCode(), Strings.EMPTY_ARRAY));
	} catch (N4JSValueConverterWithValueException vcwve) {
		diagnosticProducer.addDiagnostic(new DiagnosticMessage(vcwve.getMessage(), vcwve.getSeverity(),
				vcwve.getIssueCode(), Strings.EMPTY_ARRAY));
	}
	return proxy;
}
 
Example 19
Source File: FGUtils.java    From n4js with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * <b>Attention:</b> This call is expensive due to the nested call to
 * {@link NodeModelUtils#getTokenText(org.eclipse.xtext.nodemodel.INode)}
 *
 * @return label text that is the actual text from the source code.
 */
public static String getSourceText(EObject eo) {
	ICompositeNode actualNode = NodeModelUtils.findActualNodeFor(eo);
	String text = NodeModelUtils.getTokenText(actualNode);
	return text;
}