Java Code Examples for org.eclipse.xtext.GrammarUtil#containingParserRule()

The following examples show how to use org.eclipse.xtext.GrammarUtil#containingParserRule() . 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: TreeConstructionReportImpl.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected String checkUnconsumed(AbstractToken token, IEObjectConsumer instanceDescription) {
	if (token.getGrammarElement() == null)
		return null;
	boolean finalNode = nfaProvider.getNFA(token.getGrammarElement()).isEndState();
	if (!finalNode || instanceDescription.isConsumed())
		return null;
	ParserRule parserRule = GrammarUtil.containingParserRule(token.getGrammarElement());
	StringBuffer b = new StringBuffer();
	b.append("Can not leave rule '");
	b.append(parserRule.getName());
	b.append("' since the current object '");
	b.append(instanceDescription.getEObject().eClass().getName());
	b.append("' has features with unconsumed values: ");
	Map<EStructuralFeature, Integer> unconsumedTokens = instanceDescription.getUnconsumed();
	int i = 0;
	for (Map.Entry<EStructuralFeature, Integer> unconsumedFeature2NumberEntry : unconsumedTokens.entrySet()) {
		b.append("'");
		b.append(unconsumedFeature2NumberEntry.getKey().getName());
		b.append("':");
		b.append(unconsumedFeature2NumberEntry.getValue());
		if (++i != unconsumedTokens.size())
			b.append(", ");
	}
	return b.toString();
}
 
Example 2
Source File: NamedSerializationContextProvider.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public String getSignificantGrammarElement(final Iterable<ISerializationContext> contexts) {
  ParserRule rule = null;
  int index = Integer.MAX_VALUE;
  for (final ISerializationContext ctx : contexts) {
    {
      ParserRule pr = ctx.getParserRule();
      if ((pr == null)) {
        final Action action = ctx.getAssignedAction();
        if ((action != null)) {
          pr = GrammarUtil.containingParserRule(action);
        }
      }
      if ((pr != null)) {
        final Integer i = this.rules.get(pr);
        if (((i).intValue() < index)) {
          index = (i).intValue();
          rule = pr;
        }
      }
    }
  }
  if ((rule != null)) {
    return rule.getName();
  }
  return "unknown";
}
 
Example 3
Source File: RequiredRuleNameComputer.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected String adjustRuleName(String ruleName, Param param) {
	AbstractElement elementToParse = param.elementToParse;
	Set<Parameter> context = getAssignedParameters(elementToParse, param.paramStack);
	if (!context.isEmpty()) {
		ParserRule containingRule = GrammarUtil.containingParserRule(elementToParse);
		String antlrRuleName = ruleNames.getAntlrRuleName(containingRule);
		int len = antlrRuleName.length();
		if (antlrRuleName.startsWith("rule")) {
			len += 2; // rule__XYZ instead of ruleXYZ
		}
		int config = getParameterConfig(context);
		String result = ruleNames.getAntlrRuleName(containingRule, config) + ruleName.substring(len);
		return result;
	}
	return ruleName;
}
 
Example 4
Source File: AbstractParseTreeConstructor.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.0
 */
protected void initStream(AbstractToken token, WsMergerStream out) {
	AbstractElement rootMostElement = null;
	if (!token.getTokensForSemanticChildren().isEmpty()) {
		for (AbstractToken t : Lists.reverse(token.getTokensForSemanticChildren()))
			if (t.getGrammarElement() != null) {
				rootMostElement = t.getGrammarElement();
				break;
			}
	} else if (token.getGrammarElement() != null) {
		rootMostElement = token.getGrammarElement();
	}
	if (rootMostElement != null) {
		ParserRule rootRule = GrammarUtil.containingParserRule(rootMostElement);
		out.init(rootRule);
	}
}
 
Example 5
Source File: AbstractJavaBasedContentProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected void lookupCrossReference(CrossReference crossReference, ContentAssistContext contentAssistContext,
		ICompletionProposalAcceptor acceptor, Predicate<IEObjectDescription> filter) {
	ParserRule containingParserRule = GrammarUtil.containingParserRule(crossReference);
	if (!GrammarUtil.isDatatypeRule(containingParserRule)) {
		EReference ref;
		if (containingParserRule.isWildcard()) {
			// TODO we need better ctrl flow analysis here
			// The cross reference may come from another parser rule then the current model 
			ref = GrammarUtil.getReference(crossReference, contentAssistContext.getCurrentModel().eClass());
		} else {
			ref = GrammarUtil.getReference(crossReference);
		}
		if (ref != null) {
			lookupCrossReference(crossReference, ref, contentAssistContext, acceptor, filter);
		}
	}
}
 
Example 6
Source File: CheckHighlightingCalculator.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void highlightSpecialIdentifiers(final IHighlightedPositionAcceptor acceptor, final ICompositeNode root) {
  TerminalRule idRule = grammarAccess.getIDRule();

  for (ILeafNode leaf : root.getLeafNodes()) {
    if (commentProvider.isJavaDocComment(leaf)) {
      // not really a special identifier, but we don't want to iterate over the leaf nodes twice, do we?
      acceptor.addPosition(leaf.getOffset(), leaf.getLength(), CheckHighlightingConfiguration.JAVADOC_ID);
    } else if (!leaf.isHidden()) {
      if (leaf.getGrammarElement() instanceof Keyword) {
        // Check if it is a keyword used as an identifier.
        ParserRule rule = GrammarUtil.containingParserRule(leaf.getGrammarElement());
        if (FEATURE_CALL_ID_RULE_NAME.equals(rule.getName())) {
          acceptor.addPosition(leaf.getOffset(), leaf.getLength(), DefaultHighlightingConfiguration.DEFAULT_ID);
        }
      } else {
        highlightSpecialIdentifiers(leaf, acceptor, idRule);
      }
    }
  }
}
 
Example 7
Source File: ContentAssistContextFactory.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public INode getContainingDatatypeRuleNode(INode node) {
	INode result = node;
	EObject grammarElement = result.getGrammarElement();
	if (grammarElement != null) {
		ParserRule parserRule = GrammarUtil.containingParserRule(grammarElement);
		while (parserRule != null && GrammarUtil.isDatatypeRule(parserRule)) {
			result = result.getParent();
			grammarElement = result.getGrammarElement();
			parserRule = GrammarUtil.containingParserRule(grammarElement);
		}
	}
	return result;
}
 
Example 8
Source File: ParameterConfigHelper.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public static Set<Parameter> getAssignedParameters(AbstractElement element, int parameterConfig) {
	if (parameterConfig != 0) {
		ParserRule parserRule = GrammarUtil.containingParserRule(element);
		Set<Parameter> allParameters = ImmutableSet.copyOf(parserRule.getParameters());
		int seen = 0;
		for(Set<Parameter> candidate: Sets.powerSet(allParameters)) {
			if (seen == parameterConfig) {
				return candidate;
			}
			seen++;
		}
	}
	return Collections.emptySet();
}
 
Example 9
Source File: ParameterConfigHelper.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public static int getParameterConfig(Set<Parameter> params) {
	if (params.isEmpty()) {
		return 0;
	}
	Parameter firstParam = params.iterator().next();
	ParserRule parserRule = GrammarUtil.containingParserRule(firstParam);
	return getParameterConfig(params, parserRule);
}
 
Example 10
Source File: N4JSLinker.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Installs proxies for all non containment references and only if the node representing the EObject that contains
 * the cross reference has got leaf nodes (as a leaf node represents the cross reference).
 *
 * @param resource
 *            the N4JSResource
 * @param obj
 *            the EObject containing the cross reference
 * @param producer
 *            the error/warning producer
 * @param parentNode
 *            the node representing obj inside the node model
 */
private void installProxies(N4JSResource resource, EObject obj, IDiagnosticProducer producer,
		ICompositeNode parentNode, boolean dontCheckParent) {
	final EClass eClass = obj.eClass();
	if (eClass.getEAllReferences().size() - eClass.getEAllContainments().size() == 0)
		return;

	for (INode node = parentNode.getFirstChild(); node != null; node = node.getNextSibling()) {
		EObject grammarElement = node.getGrammarElement();
		if (grammarElement instanceof CrossReference && hasLeafNodes(node)) {
			producer.setNode(node);
			CrossReference crossReference = (CrossReference) grammarElement;
			final EReference eRef = GrammarUtil.getReference(crossReference, eClass);
			if (eRef == null) {
				ParserRule parserRule = GrammarUtil.containingParserRule(crossReference);
				final String feature = GrammarUtil.containingAssignment(crossReference).getFeature();
				throw new IllegalStateException("Couldn't find EReference for crossreference '" + eClass.getName()
						+ "::" + feature + "' in parser rule '" + parserRule.getName() + "'.");
			}
			createAndSetProxy(resource, obj, node, eRef, crossReference, producer);
			afterCreateAndSetProxy(obj, node, eRef, crossReference, producer);
		} else if (grammarElement instanceof RuleCall && node instanceof ICompositeNode) {
			RuleCall ruleCall = (RuleCall) grammarElement;
			AbstractRule calledRule = ruleCall.getRule();
			if (calledRule instanceof ParserRule && ((ParserRule) calledRule).isFragment()) {
				installProxies(resource, obj, producer, (ICompositeNode) node, true);
			}
		}
	}
	if (!dontCheckParent && shouldCheckParentNode(parentNode)) {
		installProxies(resource, obj, producer, parentNode.getParent(), dontCheckParent);
	}
}
 
Example 11
Source File: AbstractJavaBasedContentProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void completeAssignment(Assignment assignment, ContentAssistContext contentAssistContext,
		ICompletionProposalAcceptor acceptor) {
	ParserRule parserRule = GrammarUtil.containingParserRule(assignment);
	String methodName = "complete" + Strings.toFirstUpper(parserRule.getName()) + "_"
			+ Strings.toFirstUpper(assignment.getFeature());
	invokeMethod(methodName, acceptor, contentAssistContext.getCurrentModel(), assignment, contentAssistContext);
}
 
Example 12
Source File: TraceToDot.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected Digraph drawPTC(TreeConstructionReportImpl report) {
	Digraph digraph = new Digraph();
	Set<AbstractToken> drawnTokens = new HashSet<AbstractToken>();
	Set<ParserRule> drawnRules = new HashSet<ParserRule>();
	List<AbstractToken> traces = new ArrayList<AbstractToken>();
	traces.add(report.getSuccess());
	traces.addAll(report.getDeadends());
	boolean solid = true;
	for (AbstractToken token : traces) {
		while (token != null && !drawnTokens.contains(token)) {
			// String ser = ((AbstractToken) t).serialize().replaceAll(
			// "\\\\", "\\\\");
			String tokenDescription = token.getClass().getSimpleName() + "\\n"
					+ token.getEObjectConsumer() + "\\n'" /* + ser */+ "'";
			digraph.add(new Node(token, tokenDescription));
			if (token.getGrammarElement() != null) {
				ParserRule parserRule = GrammarUtil.containingParserRule(token
						.getGrammarElement());
				if (parserRule != null && !drawnRules.contains(parserRule)) {
					drawnRules.add(parserRule);
					drawRule(parserRule, digraph);
				}
			}
			if (token.getNext() != null) {
				Edge edge = new Edge(token.getNext(), token);
				edge.setLabel(String.valueOf((token).getTransitionIndex()));
				if (!solid)
					edge.setStyle("dashed");
				digraph.add(edge);
			}
			drawnTokens.add(token);
			token = token.getNext();
		}
		solid = false;
	}
	return digraph;
}
 
Example 13
Source File: SerializationContext.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public ParserRule getParameterDeclarator() {
	Action action = getAssignedAction();
	if (action != null) {
		return GrammarUtil.containingParserRule(action);
	}
	ParserRule rule = getParserRule();
	if (rule != null) {
		return rule;
	}
	return null;
}
 
Example 14
Source File: LazyLinker.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private void installProxies(EObject obj, IDiagnosticProducer producer,
		Multimap<EStructuralFeature.Setting, INode> settingsToLink, ICompositeNode parentNode, boolean dontCheckParent) {
	final EClass eClass = obj.eClass();
	if (eClass.getEAllReferences().size() - eClass.getEAllContainments().size() == 0)
		return;

	for (INode node = parentNode.getFirstChild(); node != null; node = node.getNextSibling()) {
		EObject grammarElement = node.getGrammarElement();
		if (grammarElement instanceof CrossReference && hasLeafNodes(node)) {
			producer.setNode(node);
			CrossReference crossReference = (CrossReference) grammarElement;
			final EReference eRef = GrammarUtil.getReference(crossReference, eClass);
			if (eRef == null) {
				ParserRule parserRule = GrammarUtil.containingParserRule(crossReference);
				final String feature = GrammarUtil.containingAssignment(crossReference).getFeature();
				throw new IllegalStateException("Couldn't find EReference for crossreference '"+eClass.getName()+"::"+feature+"' in parser rule '"+parserRule.getName()+"'.");
			}
			if (!eRef.isResolveProxies() /*|| eRef.getEOpposite() != null see https://bugs.eclipse.org/bugs/show_bug.cgi?id=282486*/) {
				final EStructuralFeature.Setting setting = ((InternalEObject) obj).eSetting(eRef);
				settingsToLink.put(new SettingDelegate(setting), node);
			} else {
				createAndSetProxy(obj, node, eRef);
				afterCreateAndSetProxy(obj, node, eRef, crossReference, producer);
			}
		} else if (grammarElement instanceof RuleCall && node instanceof ICompositeNode) {
			RuleCall ruleCall = (RuleCall) grammarElement;
			AbstractRule calledRule = ruleCall.getRule();
			if (calledRule instanceof ParserRule && ((ParserRule) calledRule).isFragment()) {
				installProxies(obj, producer, settingsToLink, (ICompositeNode) node, true);
			}
		}
	}
	if (!dontCheckParent && shouldCheckParentNode(parentNode)) {
		installProxies(obj, producer, settingsToLink, parentNode.getParent(), dontCheckParent);
	}
}
 
Example 15
Source File: NodeModelStreamer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.0
 */
protected ParserRule findRootRuleForRegion(INode node) {
	if (GrammarUtil.isEObjectRule(node.getGrammarElement()))
		return (ParserRule) node.getGrammarElement();
	if (node.hasDirectSemanticElement())
		return GrammarUtil.containingParserRule(node.getGrammarElement());
	if (node.getParent() != null)
		return findRootRuleForRegion(node.getParent());
	return null;
}
 
Example 16
Source File: GrammarAccessExtensions.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected String _localVar(final AbstractElement it) {
  String _xblockexpression = null;
  {
    final ParserRule rule = GrammarUtil.containingParserRule(it);
    final int index = this.contentsAsList(rule).indexOf(it);
    _xblockexpression = ("otherlv_" + Integer.valueOf(index));
  }
  return _xblockexpression;
}
 
Example 17
Source File: ParserBasedContentAssistContextFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void computeFollowElements(Collection<FollowElement> followElements, final Collection<AbstractElement> result) {
	FollowElementCalculator calculator = new FollowElementCalculator();
	calculator.acceptor = new IFollowElementAcceptor(){
		@Override
		public void accept(AbstractElement element) {
			ParserRule rule = GrammarUtil.containingParserRule(element);
			if (rule == null || !GrammarUtil.isDatatypeRule(rule))
				result.add(element);
		}
	};
	for(FollowElement element: followElements) {
		computeFollowElements(calculator, element);
	}
}
 
Example 18
Source File: ConcreteSyntaxDiagnosticProvider.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
public ParserRule getRule() {
	return GrammarUtil.containingParserRule(rule.getGrammarElement());
}
 
Example 19
Source File: Xtext2EcoreTransformer.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
private EClassifierInfo createEClassifierInfo(TypeRef typeRef, String name) throws TransformationException {
	if (eClassifierInfos.getInfo(typeRef) != null)
		throw new IllegalArgumentException("Cannot create EClass for same type twice "
				+ typeRef.getClassifier().getName());
	//					+ GrammarUtil.getQualifiedName(typeRef));

	String classifierName = GrammarUtil.getTypeRefName(typeRef);
	if (classifierName == null)
		classifierName = name;
	if (classifierName == null)
		throw new TransformationException(TransformationErrorCode.NoSuchTypeAvailable, "Cannot reference unnamed type.", typeRef);

	AbstractMetamodelDeclaration metaModel = typeRef.getMetamodel();
	if (metaModel == null)
		throw new TransformationException(TransformationErrorCode.UnknownMetaModelAlias, "Cannot create type for " + classifierName
				+ " because its EPackage is unknown.", typeRef);
	EPackage generatedEPackage = getGeneratedEPackage(metaModel);
	if (generatedEPackage == null) {
		throw new TransformationException(TransformationErrorCode.CannotCreateTypeInSealedMetamodel,
				"Cannot create type '" + classifierName + "' in alias " + typeRef.getMetamodel().getAlias(), typeRef);
	}

	EClassifier classifier = generatedEPackage.getEClassifier(classifierName);
	if (classifier == null) {
		if (GrammarUtil.containingParserRule(typeRef) != null) {
			classifier = EcoreFactory.eINSTANCE.createEClass();
		} else if (GrammarUtil.containingEnumRule(typeRef) != null) {
			classifier = EcoreFactory.eINSTANCE.createEEnum();
		} else {
			for (AbstractMetamodelDeclaration mmd : grammar.getMetamodelDeclarations()) {
				if (mmd instanceof ReferencedMetamodel && mmd.getEPackage() != null && mmd.getEPackage().getNsURI().equals(EcorePackage.eNS_URI)) {
					throw new TransformationException(TransformationErrorCode.NoSuchTypeAvailable, "Cannot create datatype " + classifierName, typeRef);
				}
			}
			throw new TransformationException(TransformationErrorCode.NoSuchTypeAvailable, "Cannot create datatype " + classifierName + ". If this is supposed to return EString, make sure you have imported '"+EcorePackage.eNS_URI+"'", typeRef);
		}
		classifier.setName(classifierName);
		generatedEPackage.getEClassifiers().add(classifier);
		typeRef.setClassifier(classifier);

		EClassifierInfo result;
		if (classifier instanceof EClass)
			result = EClassifierInfo.createEClassInfo((EClass) classifier, true, getGeneratedEPackageURIs(), GrammarUtil.getGrammar(typeRef));
		else // datatype or enum
			result = EClassifierInfo.createEDataTypeInfo((EDataType) classifier, true);

		if (!eClassifierInfos.addInfo(typeRef, result))
			throw new IllegalStateException("cannot add type for typeRef twice: '" + classifierName + "'");
		SourceAdapter.adapt(classifier, typeRef);
		return result;
	}
	typeRef.setClassifier(classifier);
	SourceAdapter.adapt(classifier, typeRef);
	return eClassifierInfos.getInfo(classifier);
}
 
Example 20
Source File: ContextPDAProvider.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected Set<ISerState> collectPushForAction(ISerState action) {
	ParserRule rule = GrammarUtil.containingParserRule(action.getGrammarElement());
	LinkedHashSet<ISerState> result = Sets.<ISerState>newLinkedHashSet();
	collectPushForAction(action, rule, result, Sets.<ISerState>newHashSet());
	return result;
}