Java Code Examples for org.eclipse.xtext.AbstractRule#getAlternatives()

The following examples show how to use org.eclipse.xtext.AbstractRule#getAlternatives() . 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
/**
 * @throws IllegalArgumentException if the rule is not a datatype rule or does not fulfill
 *   the pattern <pre>RuleName: 'keyword' | 'other';</pre>
 */
@Override
public void setRule(AbstractRule rule) {
	this.rule = rule;
	if (!GrammarUtil.isDatatypeRule(rule))
		throw new IllegalArgumentException(rule.getName() + " is not a data type rule");
	if (!(rule.getAlternatives() instanceof Alternatives) && !(rule.getAlternatives() instanceof Keyword)) {
		throw new IllegalArgumentException(rule.getName() + " is not a simple keyword nor an alternative");
	}
	if (rule.getAlternatives() instanceof Keyword) {
		keywords = ImmutableSet.of(keywordToString((Keyword) rule.getAlternatives()));
	} else {
		Alternatives alternatives = (Alternatives) rule.getAlternatives();
		ImmutableSet.Builder<String> builder = ImmutableSet.builder();
		for(AbstractElement element: alternatives.getElements()) {
			if (!(element instanceof Keyword)) {
				throw new IllegalArgumentException(rule.getName() + "'s body does not contain an alternative of keywords");
			}
			builder.add(keywordToString((Keyword) element));
		}
		keywords = builder.build();
	}
}
 
Example 2
@Test public void testRuleCalledSuper() throws Exception {
	XtextResource resource = getResourceFromString(
			"grammar com.acme.Bar with org.eclipse.xtext.common.Terminals\n" +
			"generate metamodel 'myURI'\n" +
			"Model: super=super;\n" + 
			"super: name=ID;");

	IResourceValidator validator = get(IResourceValidator.class);
	List<Issue> issues = validator.validate(resource, CheckMode.FAST_ONLY, CancelIndicator.NullImpl);
	assertEquals(issues.toString(), 1, issues.size());
	assertEquals("Discouraged rule name 'super'", issues.get(0).getMessage());
	Grammar grammar = (Grammar) resource.getContents().get(0);
	AbstractRule model = grammar.getRules().get(0);
	Assignment assignment = (Assignment) model.getAlternatives();
	RuleCall ruleCall = (RuleCall) assignment.getTerminal();
	assertSame(grammar.getRules().get(1), ruleCall.getRule());
}
 
Example 3
@Test
public void testFindCurrentType_01() throws Exception {
  this.with(XtextStandaloneSetup.class);
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar myLang with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate g \'http://1\'");
  _builder.newLine();
  _builder.append("Rule:");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("Fragment;");
  _builder.newLine();
  _builder.append("fragment Fragment*: name=ID;");
  _builder.newLine();
  String model = _builder.toString();
  final XtextResource r = this.getResourceFromString(model);
  EObject _get = r.getContents().get(0);
  final Grammar grammar = ((Grammar) _get);
  final AbstractRule rule = IterableExtensions.<AbstractRule>head(grammar.getRules());
  final AbstractElement fragmentCall = rule.getAlternatives();
  final EClassifier currentType = GrammarUtil.findCurrentType(fragmentCall);
  Assert.assertEquals("Rule", currentType.getName());
}
 
Example 4
protected AbstractElement getEntryGrammarElement(ICompositeNode entryPoint) {
	EObject grammarElement = entryPoint.getGrammarElement();
	if (grammarElement instanceof RuleCall) {
		AbstractRule rule = ((RuleCall) grammarElement).getRule();
		if (rule instanceof ParserRule) {
			if (!GrammarUtil.isMultipleCardinality(rule.getAlternatives())) {
				grammarElement = rule.getAlternatives();
			}
		}
	} else if (grammarElement instanceof ParserRule) {
		grammarElement = ((ParserRule) grammarElement).getAlternatives();
	} else if (grammarElement instanceof CrossReference) {
		grammarElement = GrammarUtil.containingAssignment(grammarElement);
	}
	AbstractElement result = (AbstractElement) grammarElement;
	if (result instanceof Action) {
		return getEntryGrammarElement((ICompositeNode) entryPoint.getFirstChild());
	}
	return result;
}
 
Example 5
@Test
public void testFindCurrentType_03() throws Exception {
  this.with(XtextStandaloneSetup.class);
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar myLang with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate g \'http://1\'");
  _builder.newLine();
  _builder.append("Rule:");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("Fragment;");
  _builder.newLine();
  _builder.append("fragment Fragment: name=ID SecondFragment;");
  _builder.newLine();
  _builder.append("fragment SecondFragment: {SubRule.named=current} value=ID;");
  _builder.newLine();
  String model = _builder.toString();
  final XtextResource r = this.getResourceFromString(model);
  EObject _get = r.getContents().get(0);
  final Grammar grammar = ((Grammar) _get);
  final AbstractRule rule = IterableExtensions.<AbstractRule>head(grammar.getRules());
  final AbstractElement fragmentCall = rule.getAlternatives();
  final EClassifier currentType = GrammarUtil.findCurrentType(fragmentCall);
  Assert.assertEquals("SubRule", currentType.getName());
}
 
Example 6
@Test
public void testFindCurrentType_04() throws Exception {
  this.with(XtextStandaloneSetup.class);
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar myLang with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate g \'http://1\'");
  _builder.newLine();
  _builder.append("Rule:");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("Fragment;");
  _builder.newLine();
  _builder.append("fragment Fragment: name=ID SecondFragment?;");
  _builder.newLine();
  _builder.append("fragment SecondFragment: {SubRule.named=current} value=ID;");
  _builder.newLine();
  String model = _builder.toString();
  final XtextResource r = this.getResourceFromString(model);
  EObject _get = r.getContents().get(0);
  final Grammar grammar = ((Grammar) _get);
  final AbstractRule rule = IterableExtensions.<AbstractRule>head(grammar.getRules());
  final AbstractElement fragmentCall = rule.getAlternatives();
  final EClassifier currentType = GrammarUtil.findCurrentType(fragmentCall);
  Assert.assertEquals("Rule", currentType.getName());
}
 
Example 7
Source Project: n4js   File: CustomN4JSParser.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private String getRuleName(ICompositeNode entryPoint) {
	// This does not work well from Xpect since Xpect messes with the injectors and
	// thereby causes trouble with object identities of the grammar access.
	EObject grammarElement = entryPoint.getGrammarElement();
	if (grammarElement instanceof RuleCall) {
		RuleCall rc = (RuleCall) grammarElement;
		AbstractRule rule = rc.getRule();
		if (rule instanceof ParserRule) {
			if (!GrammarUtil.isMultipleCardinality(rule.getAlternatives())) {
				grammarElement = rule.getAlternatives();
				String[][] names = getRequiredRuleNames(getRuleName((AbstractElement) grammarElement),
						Ints.asList(getParamConfig(entryPoint)),
						(AbstractElement) grammarElement);
				if (names.length > 0) {
					return names[0][0];
				}
			}
		}
	}
	if (grammarElement instanceof ParserRule) {
		return getRuleName(((ParserRule) grammarElement).getAlternatives());
	}
	AbstractElement result = (AbstractElement) grammarElement;
	if (result instanceof Action) {
		return getRuleName((ICompositeNode) entryPoint.getFirstChild());
	}
	return getRuleName(result);
}
 
Example 8
@Test public void testObjectRemoval() throws Exception {
	Resource res = getResource(newTestGrammar());

	composer.beginRecording(res);
	Grammar grammar = (Grammar) res.getContents().get(0);
	AbstractRule rule = grammar.getRules().get(0);
	Alternatives alternatives = (Alternatives) rule.getAlternatives();
	alternatives.getElements().remove(2);
	TextEdit edit = composer.endRecording();

	assertMatches("'foo' | 'bar'", edit);
}
 
Example 9
@Test public void testObjectModificationAndRemoval() throws Exception {
	Resource res = getResource(newTestGrammar());

	composer.beginRecording(res);
	Grammar grammar = (Grammar) res.getContents().get(0);
	AbstractRule rule = grammar.getRules().get(0);
	Alternatives alternatives = (Alternatives) rule.getAlternatives();
	Keyword bazKeyword = (Keyword) alternatives.getElements().get(2);
	bazKeyword.setValue("BAZ");
	alternatives.getElements().remove(bazKeyword);
	TextEdit edit = composer.endRecording();

	assertMatches("'foo' | 'bar'", edit);
}
 
Example 10
@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 11
@Override
public Boolean caseAbstractRule(AbstractRule object) {
	if (!validatedRules.add(object))
		return Boolean.FALSE;
	ruleStack.add(object);
	Boolean result = object.getAlternatives() == null ? Boolean.FALSE : doSwitch(object.getAlternatives());
	ruleStack.remove(object);
	return result;
}
 
Example 12
/**
 * Returns all {@link CompoundElement} of type compoundType in a specific context.
 *
 * @param <T>
 *          - Group, UnorderedGroup or Alternatives
 * @param parent
 *          the context from which to return elements
 * @param compoundType
 *          the specific type of the compound elements
 * @return List a list with elements of type compoundType
 */
@SuppressWarnings("unchecked")
protected <T extends CompoundElement> List<T> getCompoundElements(final AbstractRule parent, final Class<T> compoundType) {
  AbstractElement alternatives = parent.getAlternatives();
  if (alternatives instanceof Alternatives) {
    Alternatives group = (Alternatives) alternatives;
    return Lists.newArrayList(Iterables.filter(group.getElements(), compoundType));
  } else if (alternatives instanceof CompoundElement) {
    return Lists.newArrayList(Iterables.filter(alternatives.eContents(), compoundType));
  } else if (compoundType.isInstance(alternatives)) {
    return Lists.newArrayList((T) alternatives);
  }
  return Collections.emptyList();
}
 
Example 13
@Override
protected String getUnassignedRuleCallToken(RuleCall ruleCall, INode node) {
	if (node != null)
		return node.getText().trim();
	AbstractRule rule = ruleCall.getRule();
	if (GrammarUtil.isDatatypeRule(rule)) {
		if (rule.getAlternatives() instanceof Keyword)
			return ((Keyword) rule.getAlternatives()).getValue();
		if (rule.getAlternatives() instanceof Alternatives)
			for (AbstractElement ele : ((Alternatives) rule.getAlternatives()).getElements())
				if (ele instanceof Keyword)
					return ((Keyword) ele).getValue();
	}
	return "";
}
 
Example 14
@Test public void testParseCrossRef() throws Exception {
		Grammar model = (Grammar) getModel("grammar foo with org.eclipse.xtext.common.Terminals " +
				"generate foo 'bar' as boo " +
				"Model returns boo::Model : 'a' stuff+=Stuff*; " +
				"Stuff returns boo::Stuff : 'stuff' name=ID refersTo=[boo::Stuff];");
		AbstractRule rule = model.getRules().get(1);
		Group group = (Group) rule.getAlternatives();
		Assignment assignment = (Assignment) group.getElements().get(2);
		CrossReference reference = (CrossReference) assignment.getTerminal();
		assertEquals("boo", reference.getType().getMetamodel().getAlias());
//		assertWithXtend("'boo'", "eAllContents.typeSelect(xtext::CrossReference).first().type.metamodel.alias", model);
		assertEquals("Stuff", reference.getType().getClassifier().getName());
//		assertWithXtend("'Stuff'", "eAllContents.typeSelect(xtext::CrossReference).first().type.classifier.name", model);
	}
 
Example 15
@Test public void testMultiAction4() throws Exception {
	AbstractRule rule = parseRule("Model: 'a' {Type1} | 'b' {Type2} | 'c' | name=ID;");
	Alternatives alt = (Alternatives) rule.getAlternatives();
	assertTypes(nfa.getNFA(alt).getTypes(), "Type1", "Type2", "Model", "null");
	assertTypes(nfa.getNFA(alt.getElements().get(0)).getTypesToCheck(), "Type1");
	assertTypes(nfa.getNFA(alt.getElements().get(1)).getTypesToCheck(), "Type2");
	assertTypes(nfa.getNFA(alt.getElements().get(2)).getTypesToCheck());
	assertTypes(nfa.getNFA(alt.getElements().get(3)).getTypesToCheck(), "Model");
}
 
Example 16
@Ignore("Serialization does not have the correct context information")
@Test
public void testFQNInSuper_02() {
	Grammar grammar = load(URI.createURI("classpath:/org/eclipse/xtext/grammarinheritance/InheritanceTestLanguage.xtext"));
	AbstractRule rule = GrammarUtil.findRuleForName(grammar, "FQN");
	Assert.assertNotNull(rule);
	Group group = (Group) rule.getAlternatives();
	RuleCall ruleCall = (RuleCall) group.getElements().get(0);
	TerminalRule id = (TerminalRule) ruleCall.getRule();
	Assert.assertSame(grammar, GrammarUtil.getGrammar(id));
	String string = get(ISerializer.class).serialize(rule.getAlternatives());
	Assert.assertEquals("ID (\".\" ID)*", string);
	// currently wrong result is 
	Assert.assertEquals("super::ID (\".\" super::ID)*", string);
}
 
Example 17
@Test
public void testFindCurrentType_05() throws Exception {
  this.with(XtextStandaloneSetup.class);
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar myLang with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate g \'http://1\'");
  _builder.newLine();
  _builder.append("Rule:");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("Fragment;");
  _builder.newLine();
  _builder.append("fragment Fragment returns Rule:");
  _builder.newLine();
  _builder.append("    ");
  _builder.append("name=ID Fragment?");
  _builder.newLine();
  _builder.append(";");
  _builder.newLine();
  String model = _builder.toString();
  final XtextResource r = this.getResourceFromString(model);
  EObject _get = r.getContents().get(0);
  final Grammar grammar = ((Grammar) _get);
  final AbstractRule rule = IterableExtensions.<AbstractRule>head(grammar.getRules());
  final AbstractElement fragmentCall = rule.getAlternatives();
  final EClassifier currentType = GrammarUtil.findCurrentType(fragmentCall);
  Assert.assertEquals("Rule", currentType.getName());
}
 
Example 18
@Test
public void testFindCurrentType_06() throws Exception {
  this.with(XtextStandaloneSetup.class);
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar myLang with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate g \'http://1\'");
  _builder.newLine();
  _builder.append("Rule:");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("Fragment;");
  _builder.newLine();
  _builder.append("fragment Fragment returns Rule:");
  _builder.newLine();
  _builder.append("    ");
  _builder.append("name=ID Fragment?");
  _builder.newLine();
  _builder.append(";");
  _builder.newLine();
  String model = _builder.toString();
  final XtextResource r = this.getResourceFromString(model);
  EObject _get = r.getContents().get(0);
  final Grammar grammar = ((Grammar) _get);
  final AbstractRule rule = IterableExtensions.<AbstractRule>last(grammar.getRules());
  AbstractElement _alternatives = rule.getAlternatives();
  final AbstractElement fragmentCall = IterableExtensions.<AbstractElement>last(((Group) _alternatives).getElements());
  final EClassifier currentType = GrammarUtil.findCurrentType(fragmentCall);
  Assert.assertEquals("Rule", currentType.getName());
}
 
Example 19
@Test public void testSingleAssignmentOrNull() throws Exception {
	AbstractRule rule = parseRule("Model: 'foo' name=ID?;");
	Group group = (Group) rule.getAlternatives();
	assertTypes(nfa.getNFA(group).getTypes(), "Model", "null");
	assertTypes(nfa.getNFA(group.getElements().get(0)).getTypesToCheck());
}
 
Example 20
/**
 * The method being overridden expects a rule of a certain form (body does not contain an alternative of keywords
 * and a single rule) but the rules arriving here don't have this format.
 * <p>
 * Therefore pass to that method the first one of the two nested rules Some-Identifier that are expected in any of
 * the rules arriving here.
 *
 * For more details see grammar rules
 * <ul>
 * <li><code>N4JSPropertyComputedName</code></li>
 * <li><code>JsPropertyComputedName</code></li>
 * <li><code>TypesComputedPropertyName</code></li>
 * </ul>
 */
@Override
public void setRule(AbstractRule rule) {
	// TODO make this safer / throw exceptions more informative exceptions
	// rule: '[' (SymbolLiteralComputedName | StringLiteralComputedName) ']'
	Group g = (Group) rule.getAlternatives();
	Alternatives elem = (Alternatives) g.getElements().get(1);
	// SymbolLiteralComputedName: N4JSIdentifier '.' N4JSIdentifier
	AbstractRule symLitCompName = ((RuleCall) elem.getElements().get(0)).getRule();
	Group g2 = (Group) symLitCompName.getAlternatives();
	RuleCall identCall = (RuleCall) g2.getElements().get(0);
	AbstractRule ident = identCall.getRule();
	super.setRule(ident);
}