org.eclipse.xtext.AbstractRule Java Examples

The following examples show how to use org.eclipse.xtext.AbstractRule. 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: ElementMatcherProvider.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected Set<MatcherState> findRuleCallsTo(AbstractRule rule, Set<AbstractRule> visited) {
	if (!visited.add(rule))
		return Collections.emptySet();
	Set<MatcherState> result = Sets.newHashSet();
	Iterator<EObject> i = rule.eAllContents();
	while (i.hasNext()) {
		EObject obj = i.next();
		if (obj instanceof AbstractElement) {
			MatcherState state = nfaProvider.getNFA((AbstractElement) obj);
			if (state.hasTransitions())
				for (MatcherTransition incoming : state.getAllIncoming())
					if (incoming.isRuleCall() && result.add(incoming.getSource())
							&& incoming.getSource().isEndState())
						result.addAll(findRuleCallsTo(
								GrammarUtil.containingRule(incoming.getSource().getGrammarElement()), visited));
		}
	}
	return result;
}
 
Example #2
Source File: OverriddenValueInspectorTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testUnassignedRule_01() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar org.foo with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate metamodel \'foo.sample\'");
  _builder.newLine();
  _builder.append("First : Second name+=ID;");
  _builder.newLine();
  _builder.append("Second: name+=ID;");
  _builder.newLine();
  String grammarAsString = _builder.toString();
  final Grammar grammar = this.getGrammar(grammarAsString);
  AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "First");
  final ParserRule rule = ((ParserRule) _findRuleForName);
  this.validateRule(rule);
  Assert.assertTrue(this.warnings.toString(), this.warnings.isEmpty());
}
 
Example #3
Source File: OverriddenValueInspectorTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testBug306281_10() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar org.foo with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate metamodel \'foo.sample\'");
  _builder.newLine();
  _builder.append("Model : name=ID (({Binary.left=current} operator = [Model] | {Binary.left=current} operator = [Model]) name=ID);");
  _builder.newLine();
  String grammarAsString = _builder.toString();
  final Grammar grammar = this.getGrammar(grammarAsString);
  AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "Model");
  final ParserRule rule = ((ParserRule) _findRuleForName);
  this.validateRule(rule);
  Assert.assertTrue(this.warnings.toString(), this.warnings.isEmpty());
}
 
Example #4
Source File: Xtext2EcoreTransformer.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
private boolean deriveFeatures() {
	boolean result = true;
	for (AbstractRule rule : grammar.getRules()) {
		try {
			if (rule instanceof ParserRule && !GrammarUtil.isDatatypeRule((ParserRule) rule) && !isWildcardFragment(rule)) {
				deriveFeatures((ParserRule) rule);
			} else if (rule instanceof EnumRule) {
				deriveEnums((EnumRule) rule);
			}
		}
		catch (TransformationException e) {
			result = false;
			reportError(e);
		}
	}
	return result;
}
 
Example #5
Source File: XtextGrammarQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Fix(XtextLinkingDiagnosticMessageProvider.UNRESOLVED_RULE)
public void fixUnresolvedRule(final Issue issue, IssueResolutionAcceptor acceptor) {
	final String ruleName = issue.getData()[0];
	acceptor.accept(issue, "Create rule '" + ruleName + "'", "Create rule '" + ruleName + "'", NULL_QUICKFIX_IMAGE,
			new ISemanticModification() {
				@Override
				public void apply(final EObject element, IModificationContext context) throws BadLocationException {
					AbstractRule abstractRule = EcoreUtil2.getContainerOfType(element, ParserRule.class);
					ICompositeNode node = NodeModelUtils.getNode(abstractRule);
					int offset = node.getEndOffset();
					String nl = context.getXtextDocument().getLineDelimiter(0);
					StringBuilder builder = new StringBuilder(nl+nl);
					if (abstractRule instanceof TerminalRule)
						builder.append("terminal ");
					String newRule = builder.append(ruleName).append(":" + nl + "\t" + nl + ";").toString();
					context.getXtextDocument().replace(offset, 0, newRule);
				}
			});
	createLinkingIssueResolutions(issue, acceptor);
}
 
Example #6
Source File: XtextCrossReferenceSerializer.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected String getUnconvertedLinkText(EObject object, EReference reference, EObject context) {
	if (reference == XtextPackage.eINSTANCE.getGrammar_UsedGrammars())
		return ((Grammar) object).getName();
	if (reference == XtextPackage.eINSTANCE.getTypeRef_Metamodel()) {
		AbstractMetamodelDeclaration casted = (AbstractMetamodelDeclaration) object;
		return casted.getAlias();
	}
	if (reference == XtextPackage.eINSTANCE.getAbstractMetamodelDeclaration_EPackage())
		return ((EPackage) object).getNsURI();
	if (object instanceof AbstractRule) {
		if (reference == XtextPackage.eINSTANCE.getRuleCall_Rule()) {
			if (((RuleCall)context).isExplicitlyCalled()) {
				return super.getUnconvertedLinkText(object, reference, context);
			}
		}
		return ((AbstractRule) object).getName();
	}
	return super.getUnconvertedLinkText(object, reference, context);
}
 
Example #7
Source File: OverriddenValueInspectorTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testBug306281_11() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar org.foo with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate metamodel \'foo.sample\'");
  _builder.newLine();
  _builder.append("Model returns Model: SubModel ({Binary.params+=current} operator =\'+\' params+=SubModel)*;");
  _builder.newLine();
  _builder.append("SubModel returns Model: \'(\'Model\')\';");
  _builder.newLine();
  String grammarAsString = _builder.toString();
  final Grammar grammar = this.getGrammar(grammarAsString);
  AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "Model");
  final ParserRule rule = ((ParserRule) _findRuleForName);
  this.validateRule(rule);
  Assert.assertTrue(this.warnings.toString(), this.warnings.isEmpty());
}
 
Example #8
Source File: HiddenTokenSequencer.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected void emitHiddenTokens(List<INode> hiddens /* Set<INode> comments, */) {
	if (hiddens == null)
		return;
	boolean lastNonWhitespace = true;
	for (INode node : hiddens) {
		if (tokenUtil.isCommentNode(node)) {
			if (lastNonWhitespace)
				delegate.acceptWhitespace(hiddenTokenHelper.getWhitespaceRuleFor(null, ""), "", null);
			lastNonWhitespace = true;
			//				comments.remove(node);
			delegate.acceptComment((AbstractRule) node.getGrammarElement(), node.getText(), (ILeafNode) node);
		} else {
			delegate.acceptWhitespace((AbstractRule) node.getGrammarElement(), node.getText(), (ILeafNode) node);
			lastNonWhitespace = false;
		}
		lastEmittedNode = node;
	}
	if (lastNonWhitespace)// FIXME: determine the whitespace rule correctly 
		delegate.acceptWhitespace(hiddenTokenHelper.getWhitespaceRuleFor(null, ""), "", null);
}
 
Example #9
Source File: OverriddenValueInspectorTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testNoMarkerForCalledRules_01() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar org.foo with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate metamodel \'foo.sample\'");
  _builder.newLine();
  _builder.append("First returns Object: Second;");
  _builder.newLine();
  _builder.append("Second returns Object: name=ID name=ID;");
  _builder.newLine();
  String grammarAsString = _builder.toString();
  final Grammar grammar = this.getGrammar(grammarAsString);
  AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "First");
  ParserRule rule = ((ParserRule) _findRuleForName);
  this.validateRule(rule);
  Assert.assertEquals(this.warnings.toString(), 0, this.warnings.size());
  AbstractRule _findRuleForName_1 = GrammarUtil.findRuleForName(grammar, "Second");
  rule = ((ParserRule) _findRuleForName_1);
  this.validateRule(rule);
  Assert.assertEquals(this.warnings.toString(), 2, this.warnings.size());
}
 
Example #10
Source File: OverriddenValueInspectorTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testBug306281_06() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar org.foo with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate metamodel \'foo.sample\'");
  _builder.newLine();
  _builder.append("Model : name=ID (({Binary.left=current} operator = [Model] | {Binary.left=current} operator = [Model]) right=ID)*;");
  _builder.newLine();
  String grammarAsString = _builder.toString();
  final Grammar grammar = this.getGrammar(grammarAsString);
  AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "Model");
  final ParserRule rule = ((ParserRule) _findRuleForName);
  this.validateRule(rule);
  Assert.assertTrue(this.warnings.toString(), this.warnings.isEmpty());
}
 
Example #11
Source File: SuperCallScope.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Iterable<IEObjectDescription> getElements(EObject object) {
	if (object instanceof AbstractRule) {
		Grammar grammar = GrammarUtil.getGrammar(context);
		AbstractRule rule = (AbstractRule) object;
		if (GrammarUtil.getGrammar(rule) == grammar) {
			return Lists.newArrayList(
					EObjectDescription.create(GrammarUtil.getSimpleName(grammar) + "." + rule.getName(), rule),
					EObjectDescription.create(grammar.getName() + "." + rule.getName(), rule));
		}
		List<IEObjectDescription> result = Lists.newArrayList(
				EObjectDescription.create(SUPER + "." + rule.getName(), rule),
				EObjectDescription.create(GrammarUtil.getSimpleName(grammar) + "." + rule.getName(), rule),
				EObjectDescription.create(grammar.getName() + "." + rule.getName(), rule));
		AbstractRule contextRule = GrammarUtil.containingRule(context);
		if (contextRule != null && contextRule.getName().equals(rule.getName())) {
			result.add(0, EObjectDescription.create(SUPER, rule));
		}
		return result;
	}
	return Collections.emptyList();
}
 
Example #12
Source File: SemanticNodeIterator.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean isEObjectNode(INode node) {
	if (node.getGrammarElement() instanceof AbstractRule)
		return true;
	if (node.getGrammarElement() instanceof Action)
		return true;
	if (GrammarUtil.isAssignedEObjectRuleCall(node.getGrammarElement())) {
		if (node.hasDirectSemanticElement())
			return true;
		AbstractRule rule = ((RuleCall) node.getGrammarElement()).getRule();
		node = node.getParent();
		while (node != null) {
			if (GrammarUtil.isAssigned(node.getGrammarElement()))
				return true;
			if (node.getGrammarElement() instanceof Action
					&& GrammarUtil.containingRule(node.getGrammarElement()) == rule)
				return false;
			node = node.getParent();
		}
		return true;
	}
	return false;
}
 
Example #13
Source File: ConcreteSyntaxConstraintProvider.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean ruleContainsAssignedAction(AbstractRule rule, Set<AbstractRule> visited) {
	if (!visited.add(rule))
		return false;
	TreeIterator<EObject> i = rule.eAllContents();
	while (i.hasNext()) {
		EObject o = i.next();
		if (o instanceof Action && ((Action) o).getFeature() != null)
			return true;
		else if (o instanceof Assignment)
			i.prune();
		else if (o instanceof RuleCall && isParserRule(((RuleCall) o).getRule())) {
			if (ruleContainsAssignedAction(((RuleCall) o).getRule(), visited))
				return true;
		}
	}
	return false;
}
 
Example #14
Source File: RuleOverrideUtil.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public List<IEObjectDescription> getOverriddenRules(final AbstractRule originalRule) {
	Grammar grammar = GrammarUtil.getGrammar(originalRule);
	final List<IEObjectDescription> overriddenRules = newArrayList();
	IAcceptor<AbstractRule> acceptor = new IAcceptor<AbstractRule>() {
		@Override
		public void accept(AbstractRule overriddenRule) {
			if (overriddenRule != null) {
				IEObjectDescription description = EObjectDescription.create(
						qualifiedNameProvider.getFullyQualifiedName(overriddenRule), overriddenRule);
				overriddenRules.add(description);
			}
		}
	};
	findOverriddenRule(originalRule, grammar.getUsedGrammars(), acceptor);
	return overriddenRules;
}
 
Example #15
Source File: XtextLinkerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testQualifiedRuleCall_02() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar test with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate test \'http://test\'");
  _builder.newLine();
  _builder.append("Rule: name=ID;");
  _builder.newLine();
  _builder.append("terminal STRING: super;");
  _builder.newLine();
  final String grammarAsString = _builder.toString();
  final XtextResource resource = this.getResourceFromString(grammarAsString);
  EObject _get = resource.getContents().get(0);
  Grammar grammar = ((Grammar) _get);
  AbstractRule _get_1 = grammar.getRules().get(1);
  final TerminalRule string = ((TerminalRule) _get_1);
  AbstractElement _alternatives = string.getAlternatives();
  final RuleCall callToSuper = ((RuleCall) _alternatives);
  Assert.assertEquals(GrammarUtil.findRuleForName(IterableExtensions.<Grammar>head(grammar.getUsedGrammars()), "STRING"), callToSuper.getRule());
}
 
Example #16
Source File: OverriddenValueInspectorTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testOptionalAction_01() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar org.foo with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate metamodel \'foo.sample\'");
  _builder.newLine();
  _builder.append("First : Second ({First.second=current} id=INT)? name=ID;");
  _builder.newLine();
  _builder.append("Second: \'keyword\' name=ID;");
  _builder.newLine();
  String grammarAsString = _builder.toString();
  final Grammar grammar = this.getGrammar(grammarAsString);
  AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "First");
  final ParserRule rule = ((ParserRule) _findRuleForName);
  this.validateRule(rule);
  Assert.assertEquals(this.warnings.toString(), 2, this.warnings.size());
}
 
Example #17
Source File: AbstractValueConverterServiceTest.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Asserts that the value-to-string conversion for all the specified values results in strings that are equal to the specified input values surrounded by
 * double-quotes.
 * 
 * @param rule
 *          the rule used for the value-to-string conversion, must not be {@code null}
 * @param values
 *          values to be converted, must not be {@code null}
 */
protected void assertToStringConvertedQuoted(final AbstractRule rule, final Iterable<String> values) {
  List<String> failures = Lists.newArrayList();
  for (String value : values) {
    String actual = getValueConverterService().toString(value, rule.getName());
    if (!actual.equals('"' + value + '"')) {
      failures.add(value);
    }
  }
  if (!failures.isEmpty()) {
    fail("All specified values must be quoted. The following invalid identifiers were not enquoted: " + Joiner.on(", ").join(failures));
  }
}
 
Example #18
Source File: DotNodeModelStreamer.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void writeSemantic(ITokenStream out, ICompositeNode node)
		throws IOException {
	AbstractRule rule = tokenUtil.getTokenRule(node);
	Object val = valueConverter.toValue(tokenUtil.serializeNode(node),
			rule.getName(), node);

	if (val instanceof ID && ((ID) val).getType() == ID.Type.HTML_STRING) {
		writeHTMLStringSemantic(rule,
				(DotFormatter.DotFormattingConfigBasedStream) out, node);
	} else {
		super.writeSemantic(out, node);
	}
}
 
Example #19
Source File: XtextProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private void completeInheritedRules(EObject model, ContentAssistContext context,
		ICompletionProposalAcceptor acceptor) {
	final Grammar grammar = GrammarUtil.getGrammar(model);
	Set<AbstractRule> allRules = collectOverrideCandidates(grammar);
	Map<String, AbstractRule> existingRules = collectExistingRules(grammar);
	for (final AbstractRule newRule : allRules) {
		if (existingRules.put(newRule.getName(), newRule) == null) {
			createOverrideProposal(newRule, grammar, context, acceptor);
		}
	}
}
 
Example #20
Source File: AntlrContentAssistGrammarGenerator.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected CharSequence compileRules(final Grammar g, final AntlrOptions options) {
  StringConcatenation _builder = new StringConcatenation();
  {
    List<ParserRule> _allParserRules = GrammarUtil.allParserRules(g);
    List<EnumRule> _allEnumRules = GrammarUtil.allEnumRules(g);
    Iterable<AbstractRule> _plus = Iterables.<AbstractRule>concat(_allParserRules, _allEnumRules);
    Collection<? extends AbstractElement> _allAlternatives = GrammarUtil.getAllAlternatives(g);
    Iterable<EObject> _plus_1 = Iterables.<EObject>concat(_plus, _allAlternatives);
    Collection<? extends AbstractElement> _allGroups = GrammarUtil.getAllGroups(g);
    Iterable<EObject> _plus_2 = Iterables.<EObject>concat(_plus_1, _allGroups);
    Collection<? extends AbstractElement> _allUnorderedGroups = GrammarUtil.getAllUnorderedGroups(g);
    Iterable<EObject> _plus_3 = Iterables.<EObject>concat(_plus_2, _allUnorderedGroups);
    Collection<? extends AbstractElement> _allAssignments = GrammarUtil.getAllAssignments(g);
    final Function1<EObject, Boolean> _function = (EObject it) -> {
      return Boolean.valueOf(this._grammarAccessExtensions.isCalled(GrammarUtil.containingRule(it), g));
    };
    Iterable<EObject> _filter = IterableExtensions.<EObject>filter(Iterables.<EObject>concat(_plus_3, _allAssignments), _function);
    for(final EObject rule : _filter) {
      _builder.newLine();
      CharSequence _compileRule = this.compileRule(rule, g, options);
      _builder.append(_compileRule);
      _builder.newLineIfNotEmpty();
    }
  }
  {
    boolean _isCombinedGrammar = this.isCombinedGrammar();
    if (_isCombinedGrammar) {
      CharSequence _compileTerminalRules = this.compileTerminalRules(g, options);
      _builder.append(_compileTerminalRules);
      _builder.newLineIfNotEmpty();
    }
  }
  return _builder;
}
 
Example #21
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 #22
Source File: ConcreteSyntaxConstraintProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean ruleContainsRecursiveUnassignedRuleCall(AbstractRule rule, Set<AbstractRule> visited) {
	if (!visited.add(rule))
		return true;
	TreeIterator<EObject> i = rule.eAllContents();
	while (i.hasNext()) {
		EObject o = i.next();
		if (o instanceof Assignment)
			i.prune();
		else if (o instanceof RuleCall && isParserRule(((RuleCall) o).getRule())) {
			if (ruleContainsRecursiveUnassignedRuleCall(((RuleCall) o).getRule(), visited))
				return true;
		}
	}
	return false;
}
 
Example #23
Source File: SyntaxFilteredScopesTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void test_06() {
	List<AbstractRule> rules = grammarAccess.getGrammar().getRules();
	for(AbstractRule rule: rules) {
		if (GrammarUtil.isDatatypeRule(rule)) {
			List<String> values = getEnumeratedValues((ParserRule) rule);
			assertNotNull(values);
		}
	}
}
 
Example #24
Source File: FirstSetComputer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Boolean caseRuleCall(RuleCall object) {
	AbstractRule rule = object.getRule();
	if (rule instanceof TerminalRule) {
		ruleCalls.put((TerminalRule) rule, object);
	} else {
		boolean result = doSwitch(rule.getAlternatives());
		if (result) {
			return true;
		}
	}
	return GrammarUtil.isOptionalCardinality(object);
}
 
Example #25
Source File: RuleNames.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public static RuleNames tryGetRuleNames(AbstractRule rule) {
	Adapter adapter = (Adapter) EcoreUtil.getAdapter(rule.eAdapters(), RuleNames.class);
	if (adapter == null) {
		return null;
	}
	return adapter.getRuleNames();
}
 
Example #26
Source File: GrammarAccessUtil.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
private static String getElementPath(AbstractElement ele) {
	EObject obj = ele;
	StringBuffer buf = new StringBuffer();
	while ((!(obj.eContainer() instanceof AbstractRule))
			&& obj.eContainer() != null) {
		EObject tmp = obj.eContainer();
		buf.insert(0, tmp.eContents().indexOf(obj));
		buf.insert(0, "_");
		obj = tmp;
	}
	return buf.toString();
}
 
Example #27
Source File: GrammarTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testExampleGrammar() throws Exception {
	with(Ecore2XtextTestStandaloneSetup.class);
	Grammar grammar = getGrammarAccess().getGrammar();
	EList<AbstractMetamodelDeclaration> metamodelDeclarations = grammar.getMetamodelDeclarations();
	assertEquals(2, metamodelDeclarations.size());
	
	AbstractRule intDatatypeRule = GrammarUtil.findRuleForName(grammar, "INT0");
	assertNotNull(intDatatypeRule);

	AbstractRule concrete0Rule = GrammarUtil.findRuleForName(grammar, "Concrete0");
	assertNotNull(concrete0Rule);
	
	AbstractRule abstractRule = GrammarUtil.findRuleForName(grammar, "Abstract");
	AbstractElement alternatives = abstractRule.getAlternatives();
	assertTrue(alternatives instanceof Alternatives);
	assertEquals(3, ((Alternatives) alternatives).getElements().size());
	assertTrue(GrammarUtil.containedAssignments(abstractRule).isEmpty());
	
	checkConcreteImplRule(grammar, "Concrete0_Impl");
	checkConcreteImplRule(grammar, "Concrete1_Impl");
	
	ParserRule rootRule = (ParserRule) grammar.getRules().get(0);
	assertEquals("Root", rootRule.getName());
	List<Assignment> assignments = GrammarUtil.containedAssignments(rootRule);
	assertEquals(4, assignments.size());
	assertEquals("name", assignments.get(0).getFeature());
	assertEquals("classes", assignments.get(1).getFeature());
	assertEquals("+=", assignments.get(1).getOperator());
	assertEquals("classes", assignments.get(2).getFeature());
	assertEquals("+=", assignments.get(2).getOperator());
	assertEquals("concrete0", assignments.get(3).getFeature());
	assertEquals("=", assignments.get(3).getOperator());
}
 
Example #28
Source File: GrammarAccessExtensions.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public boolean isCalled(final AbstractRule rule, final Grammar grammar) {
  boolean _xblockexpression = false;
  {
    final List<AbstractRule> allRules = GrammarUtil.allRules(grammar);
    _xblockexpression = ((allRules.indexOf(rule) == 0) || IterableExtensions.<RuleCall>exists(Iterables.<RuleCall>concat(ListExtensions.<AbstractRule, List<RuleCall>>map(allRules, ((Function1<AbstractRule, List<RuleCall>>) (AbstractRule it) -> {
      return GrammarUtil.containedRuleCalls(it);
    }))), ((Function1<RuleCall, Boolean>) (RuleCall ruleCall) -> {
      AbstractRule _rule = ruleCall.getRule();
      return Boolean.valueOf(Objects.equal(_rule, rule));
    })));
  }
  return _xblockexpression;
}
 
Example #29
Source File: XtextLinkerTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testImplicitNamedParameterLinking_02() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar test.Lang with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate test \'http://test\'");
  _builder.newLine();
  _builder.append("Root<MyParam>: rule=Rule<true>;");
  _builder.newLine();
  _builder.append("Rule<MyParam>: name=ID child=Root<false>?;");
  _builder.newLine();
  final String grammarAsString = _builder.toString();
  EObject _model = this.getModel(grammarAsString);
  final Grammar grammar = ((Grammar) _model);
  AbstractRule _head = IterableExtensions.<AbstractRule>head(grammar.getRules());
  final ParserRule rootRule = ((ParserRule) _head);
  AbstractRule _last = IterableExtensions.<AbstractRule>last(grammar.getRules());
  final ParserRule lastRule = ((ParserRule) _last);
  AbstractElement _alternatives = lastRule.getAlternatives();
  AbstractElement _last_1 = IterableExtensions.<AbstractElement>last(((Group) _alternatives).getElements());
  final Assignment lastAssignment = ((Assignment) _last_1);
  AbstractElement _terminal = lastAssignment.getTerminal();
  final RuleCall ruleCall = ((RuleCall) _terminal);
  final NamedArgument argument = IterableExtensions.<NamedArgument>head(ruleCall.getArguments());
  Assert.assertEquals(IterableExtensions.<Parameter>head(rootRule.getParameters()), argument.getParameter());
  Condition _value = argument.getValue();
  Assert.assertFalse(((LiteralCondition) _value).isTrue());
}
 
Example #30
Source File: ParseTreeConstructorUtil.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public static List<AbstractElement> calcRootFollowers(Grammar g) {
	List<AbstractElement> callees = new ArrayList<AbstractElement>();
	for (AbstractRule r : GrammarUtil.allRules(g))
		if (r instanceof ParserRule) {
			ParserRule pr = (ParserRule) r;
			if (!GrammarUtil.isDatatypeRule(pr) && !pr.isFragment())
				callees.add(pr.getAlternatives());
		}
	return callees;
}