Java Code Examples for org.eclipse.xtext.AbstractRule

The following examples show how to use org.eclipse.xtext.AbstractRule. These examples are extracted from open source projects. 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 Project: xtext-eclipse   Source File: RuleOverrideUtil.java    License: 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 2
Source Project: xtext-core   Source File: SemanticNodeIterator.java    License: 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 3
Source Project: xtext-core   Source File: SuperCallScope.java    License: 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 4
@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 5
@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 6
@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 7
@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 8
Source Project: xtext-core   Source File: HiddenTokenSequencer.java    License: 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 Project: xtext-core   Source File: XtextLinkerTest.java    License: 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 10
@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 11
Source Project: xtext-core   Source File: ElementMatcherProvider.java    License: 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 12
@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 13
@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 14
Source Project: xtext-core   Source File: Xtext2EcoreTransformer.java    License: 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 15
@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 16
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 17
public void inspect(Grammar grammar) {
	this.inspectedGrammar = grammar;
	for(AbstractRule rule: grammar.getRules()) {
		if (!validatedRules.contains(rule)) {
			// different entry points yield different error messages
			Set<AbstractRule> storedRules = validatedRules;
			validatedRules = Sets.newHashSet();
			doSwitch(rule);
			storedRules.addAll(validatedRules);
			storedRules = validatedRules;
		}
	}
}
 
Example 18
Source Project: xtext-core   Source File: AntlrGrammarGenUtil.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.9
 */
public static String getArgumentList(final RuleCall ruleCall, boolean passCurrentIntoFragment, boolean isPredicate) {
	final List<NamedArgument> arguments = ruleCall.getArguments();
	AbstractRule abstractRule = ruleCall.getRule();
	boolean needsCurrent = passCurrentIntoFragment && GrammarUtil.isEObjectFragmentRule(abstractRule) && !GrammarUtil.isDatatypeRule((ParserRule) getOriginalElement(abstractRule));
	if (arguments.isEmpty()) {
		if (needsCurrent) {
			return isPredicate ? "[null]" : "[$current]";
		}
		return "";
	}
	ParserRule rule = (ParserRule) abstractRule;
	StringBuilder result = new StringBuilder();
	result.append("[");
	if (needsCurrent) {
		if (isPredicate) {
			result.append("null, ");
		} else {
			result.append("$current, ");
		}
	}
	Joiner.on(", ").appendTo(result, Iterables.transform(rule.getParameters(), new Function<Parameter, String>() {
		@Override
		public String apply(Parameter input) {
			for(NamedArgument argument: arguments) {
				if (argument.getParameter() == input) {
					return conditionToAntlr(argument.getValue(), true);
				}
			}
			throw new IllegalStateException("Cannot find argument for parameter: " + input.getName());
		}
	}));
	result.append("]");
	return result.toString();
}
 
Example 19
Source Project: dsl-devkit   Source File: FormatGeneratorUtil.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the all GrammarRules in the inheritance hierarchy excluding overridden rules.
 *
 * @param model
 *          the model
 * @param targetClass
 *          the target class
 * @return all unique grammar rules
 */
private static List<GrammarRule> getAllUniqueGrammarRules(final FormatConfiguration model, final Class<?> targetClass) {
  final Set<AbstractRule> grammarElements = Sets.newHashSet();
  final Set<String> grammarElementNames = Sets.newHashSet(); // ensure that identically named rules in a parent grammar are not returned
  List<GrammarRule> allRules = getAllGrammarRules(model);
  List<GrammarRule> result = Lists.newArrayList();
  for (int i = allRules.size() - 1; i > -1; i--) {
    GrammarRule rule = allRules.get(i);
    if (grammarElements.add(rule.getTargetRule()) && targetClass.isInstance(rule.getTargetRule())
        && grammarElementNames.add(rule.getTargetRule().getName())) {
      result.add(0, rule);
    }
  }
  return result;
}
 
Example 20
/**
 * Outputs the list of given hidden tokens.
 *
 * @param hiddens
 *          list of hidden tokens, may be {@code null}
 */
private void emitHiddenTokens(final List<INode> hiddens) {
  if (hiddens == null || hiddens.isEmpty()) {
    return;
  }
  boolean lastNonWhitespace = true;
  for (INode node : hiddens) {
    if (node instanceof LeadingCommentsMarkerNode && !(lastEmittedNode != null && lastEmittedNode.getText().endsWith(NEW_LINE))) {
      delegate.acceptWhitespace(hiddenTokenHelper.getWhitespaceRuleFor(null, NEW_LINE), NEW_LINE, null);
    }
    if (tokenUtil.isCommentNode(node)) {
      if (lastNonWhitespace) {
        delegate.acceptWhitespace(hiddenTokenHelper.getWhitespaceRuleFor(null, EMPTY_STRING), EMPTY_STRING, null);
      }
      lastNonWhitespace = true;
      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) {
    delegate.acceptWhitespace(hiddenTokenHelper.getWhitespaceRuleFor(null, EMPTY_STRING), EMPTY_STRING, null);
  }
  // Register all the hiddens as already emitted ones not to output same nodes twice
  emittedComments.addAll(hiddens);
}
 
Example 21
/**
 * Gets or creates the {@link KeywordCollector} instance for the given {@link AbstractRule}.
 * 
 * @param rule
 *          the {@link AbstractRule}, must not be {@code null}
 * @return the {@link KeywordCollector} instance for the given {@link AbstractRule}, never {@code null}
 */
protected KeywordCollector getKeywordCollector(final AbstractRule rule) {
  KeywordCollector keywordCollector = keywordCollectors.get(rule);
  if (keywordCollector == null) {
    keywordCollector = new KeywordCollector(rule, isIgnoreCase());
    keywordCollectors.put(rule, keywordCollector);
  }
  return keywordCollector;
}
 
Example 22
private void firstRuleIsConvertedTo(final CharSequence text, final CharSequence expected) {
  try {
    final String actual = this._grammarAccessExtensions.grammarFragmentToString(IterableExtensions.<AbstractRule>head(this._parseHelper.parse(Strings.toUnixLineSeparator(text)).getRules()), "//");
    Assert.assertEquals(expected.toString().trim(), actual);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 23
Source Project: gef   Source File: DotNodeModelStreamer.java    License: 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 24
Source Project: xtext-core   Source File: RuleNames.java    License: 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 25
Source Project: xtext-core   Source File: XtextLinkerTest.java    License: 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 26
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;
}
 
Example 27
Source Project: xtext-eclipse   Source File: GrammarTest.java    License: 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 Project: xtext-extras   Source File: GrammarAccessUtil.java    License: 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 29
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 30
@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);
		}
	}
}