Java Code Examples for org.eclipse.xtext.GrammarUtil

The following examples show how to use org.eclipse.xtext.GrammarUtil. 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
/**
 * Extracts the grammar from this transition or the NFA if this transition does not point to an
 * {@link AbstractElement}.
 */
private Grammar getGrammar(Nfa<ISynState> nfa) {
	AbstractElement grammarElement = getGrammarElement();
	if (grammarElement == null) {
		grammarElement = nfa.getStart().getGrammarElement();
		if (grammarElement == null) {
			grammarElement = nfa.getStop().getGrammarElement();
			if (grammarElement == null) {
				Iterator<ISynState> iter = nfa.getStart().getFollowers().iterator();
				while (grammarElement == null && iter.hasNext()) {
					grammarElement = iter.next().getGrammarElement();
				}
			}
		}
	}
	Grammar grammar = GrammarUtil.getGrammar(grammarElement);
	return grammar;
}
 
Example 2
@Inject
public RuleEngineGrammarAccess(GrammarProvider grammarProvider,
		XbaseGrammarAccess gaXbase,
		XtypeGrammarAccess gaXtype) {
	this.grammar = internalFindGrammar(grammarProvider);
	this.gaXbase = gaXbase;
	this.gaXtype = gaXtype;
	this.pModel = new ModelElements();
	this.pDeclaration = new DeclarationElements();
	this.pDevice = new DeviceElements();
	this.pState = new StateElements();
	this.pRule = new RuleElements();
	this.pXBlockExpression = new XBlockExpressionElements();
	this.pXSwitchExpression = new XSwitchExpressionElements();
	this.tBEGIN = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.example.homeautomation.RuleEngine.BEGIN");
	this.tEND = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.example.homeautomation.RuleEngine.END");
}
 
Example 3
Source Project: n4js   Source File: TokenTypeRewriter.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private static void rewriteIdentifiers(N4JSGrammarAccess ga,
		ImmutableMap.Builder<AbstractElement, Integer> builder) {
	ImmutableSet<AbstractRule> identifierRules = ImmutableSet.of(
			ga.getBindingIdentifierRule(),
			ga.getIdentifierNameRule(),
			ga.getIDENTIFIERRule());
	for (ParserRule rule : GrammarUtil.allParserRules(ga.getGrammar())) {
		for (EObject obj : EcoreUtil2.eAllContents(rule.getAlternatives())) {
			if (obj instanceof Assignment) {
				Assignment assignment = (Assignment) obj;
				AbstractElement terminal = assignment.getTerminal();
				int type = InternalN4JSParser.RULE_IDENTIFIER;
				if (terminal instanceof CrossReference) {
					terminal = ((CrossReference) terminal).getTerminal();
					type = IDENTIFIER_REF_TOKEN;
				}
				if (terminal instanceof RuleCall) {
					AbstractRule calledRule = ((RuleCall) terminal).getRule();
					if (identifierRules.contains(calledRule)) {
						builder.put(assignment, type);
					}
				}
			}
		}
	}
}
 
Example 4
/**
 * @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 5
@Test
public void testBug280011_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("Q : \'x\' a = ID | \'y\' a = ID ;");
  _builder.newLine();
  String grammarAsString = _builder.toString();
  final Grammar grammar = this.getGrammar(grammarAsString);
  AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "Q");
  final ParserRule rule = ((ParserRule) _findRuleForName);
  this.validateRule(rule);
  Assert.assertTrue(this.warnings.toString(), this.warnings.isEmpty());
}
 
Example 6
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 7
@Test
public void testUnorderedGroup_04() 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 : (\'x\' a = ID & \'y\' b = ID) a = 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.assertEquals(this.warnings.toString(), 2, this.warnings.size());
}
 
Example 8
Source Project: xtext-core   Source File: GrammarNaming.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public AntlrGrammar getLexerGrammar(final Grammar it) {
  AntlrGrammar _xifexpression = null;
  boolean _isCombinedGrammar = this.isCombinedGrammar(it);
  if (_isCombinedGrammar) {
    _xifexpression = this.getParserGrammar(it);
  } else {
    String _internalLexerPackage = this.getInternalLexerPackage(it);
    StringConcatenation _builder = new StringConcatenation();
    String _grammarNamePrefix = this.getGrammarNamePrefix(it);
    _builder.append(_grammarNamePrefix);
    _builder.append("Internal");
    String _simpleName = GrammarUtil.getSimpleName(it);
    _builder.append(_simpleName);
    _builder.append("Lexer");
    _xifexpression = new AntlrGrammar(_internalLexerPackage, _builder.toString());
  }
  return _xifexpression;
}
 
Example 9
@Test
public void testAssignedAction_02() 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} 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 10
@Test
public void testBug306281_02() 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 = \'-\' | {Binary.left=current} operator = \'+\') right=ID)* 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.assertEquals(this.warnings.toString(), 2, this.warnings.size());
}
 
Example 11
/**
 * Returns the smallest node that covers all assigned values of the given object. It handles the semantics of {@link Action
 * actions} and {@link RuleCall unassigned rule calls}.
 * 
 * @return the minimal node that covers all assigned values of the given object.
 * @since 2.3
 */
protected ICompositeNode findNodeFor(EObject semanticObject) {
	ICompositeNode result = NodeModelUtils.getNode(semanticObject);
	if (result != null) {
		ICompositeNode node = result;
		while (GrammarUtil.containingAssignment(node.getGrammarElement()) == null && node.getParent() != null && !node.getParent().hasDirectSemanticElement()) {
			ICompositeNode parent = node.getParent();
			if (node.hasSiblings()) {
				for(INode sibling: parent.getChildren()) {
					EObject grammarElement = sibling.getGrammarElement();
					if (grammarElement != null && GrammarUtil.containingAssignment(grammarElement) != null) {
						result = parent;
					}
				}
			}
			node = parent;
		}
	}
	return result;
}
 
Example 12
Source Project: dsl-devkit   Source File: FormatJavaValidator.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Verify that only rule self directives are used for terminal, enum and data type rules.
 *
 * @param model
 *          the GrammarRule
 */
@Check
public void checkDataTypeOrEnumRule(final GrammarRule model) {
  if (model.getTargetRule() instanceof TerminalRule || model.getTargetRule() instanceof EnumRule
      || (model.getTargetRule() instanceof ParserRule && GrammarUtil.isDatatypeRule((ParserRule) model.getTargetRule()))) {
    Iterator<EObject> grammarElementAccessors = collectGrammarElementAccessors(model);
    boolean selfAccessOnly = Iterators.all(grammarElementAccessors, new Predicate<EObject>() {
      @Override
      public boolean apply(final EObject input) {
        return input instanceof GrammarElementReference && ((GrammarElementReference) input).getSelf() != null;
      }
    });
    if (!selfAccessOnly) {
      error(NLS.bind("For data type, enum or terminal rule {0} only ''rule'' directive may be used", model.getTargetRule().getName()), FormatPackage.Literals.GRAMMAR_RULE__DIRECTIVES, ILLEGAL_DIRECTIVE_CODE);
    }
  }
}
 
Example 13
@Test
public void testOptionalAction_02() 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 14
Source Project: xtext-eclipse   Source File: GrammarTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private AbstractRule checkConcreteImplRule(Grammar grammar, String ruleName) {
	AbstractRule concreteRule = GrammarUtil.findRuleForName(grammar, ruleName);
	assertNotNull(concreteRule);
	EClassifier returnType = ((ParserRule)concreteRule).getType().getClassifier();
	String returnTypeName = getClassifierName(returnType);
	assertEquals(ruleName, returnTypeName + "_Impl");
	List<Assignment> assignments = GrammarUtil.containedAssignments(concreteRule);
	assertEquals(1, assignments.size());
	assertEquals("name", assignments.get(0).getFeature());
	assertEquals("=", assignments.get(0).getOperator());
	List<Action> containedActions = GrammarUtil.containedActions(concreteRule);
	assertEquals(1, containedActions.size());
	assertEquals(returnTypeName, getClassifierName(containedActions.get(0).getType().getClassifier()));
	List<Keyword> containedKeywords = GrammarUtil.containedKeywords(concreteRule);
	assertEquals(1, containedKeywords.size());
	assertEquals(returnTypeName, containedKeywords.get(0).getValue());
	return concreteRule;
}
 
Example 15
@Override
public List<AbstractElement> getMissingMandatoryElements() {
	List<AbstractElement> result = missingMandatoryElements;
	if (result == null) {
		String predicate = getRecognitionException().toString();
		int idx = predicate.indexOf("grammarAccess");
		int lastIdx = predicate.lastIndexOf('(');
		predicate = predicate.substring(idx + "grammarAccess.".length(), lastIdx);
		String ruleMethodGetter = predicate.substring(0, predicate.indexOf('('));
		String elementGetter = predicate.substring(predicate.indexOf('.') + 1);
		IGrammarAccess grammarAccess = getGrammarAccess();
		Object ruleAccess = invokeNoArgMethod(ruleMethodGetter, grammarAccess);
		UnorderedGroup group = (UnorderedGroup) invokeNoArgMethod(elementGetter, ruleAccess);
		List<AbstractElement> missingElements = Lists.newArrayList();
		for(int i = 0; i < group.getElements().size(); i++) {
			AbstractElement element = group.getElements().get(i);
			if (!GrammarUtil.isOptionalCardinality(element) && unorderedGroupHelper.canSelect(group, i)) {
				missingElements.add(element);
			}
		}
		result = ImmutableList.copyOf(missingElements);
		missingMandatoryElements = result;
	}
	return result;
}
 
Example 16
@Inject
public HiddenTerminalsTestLanguageGrammarAccess(GrammarProvider grammarProvider) {
	this.grammar = internalFindGrammar(grammarProvider);
	this.pModel = new ModelElements();
	this.pWithoutHiddens = new WithoutHiddensElements();
	this.pWithHiddens = new WithHiddensElements();
	this.pOverridingHiddens = new OverridingHiddensElements();
	this.pOverridingHiddensCall = new OverridingHiddensCallElements();
	this.pInheritingHiddens = new InheritingHiddensElements();
	this.pDatatypeHiddens = new DatatypeHiddensElements();
	this.pDatatypeRule = new DatatypeRuleElements();
	this.pHidingHiddens = new HidingHiddensElements();
	this.pInheritingHiddensCall = new InheritingHiddensCallElements();
	this.tML_COMMENT = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.parser.terminalrules.HiddenTerminalsTestLanguage.ML_COMMENT");
	this.tSL_COMMENT = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.parser.terminalrules.HiddenTerminalsTestLanguage.SL_COMMENT");
	this.tWS = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.parser.terminalrules.HiddenTerminalsTestLanguage.WS");
	this.tANY_OTHER = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.parser.terminalrules.HiddenTerminalsTestLanguage.ANY_OTHER");
}
 
Example 17
Source Project: xtext-core   Source File: ElementMatcherProvider.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected List<MatcherTransition> findTransitionsToToken(MatcherState from, Set<MatcherState> targets,
		boolean returning, boolean canReturn, Set<MatcherState> visited) {
	if (!visited.add(from))
		return Collections.emptyList();
	if (targets != null && targets.contains(from))
		targets = null;
	List<MatcherTransition> result = Lists.newArrayList();
	for (MatcherTransition transition : returning ? from.getOutgoingAfterReturn() : from.getOutgoing()) {
		if (transition.getTarget().isParserRuleCall())
			result.addAll(findTransitionsToToken(transition.getTarget(), targets, false, transition.getTarget()
					.isParserRuleCallOptional(), visited));
		else if (targets == null || targets.contains(transition.getTarget()))
			result.add(transition);
	}
	if (canReturn && from.isEndState())
		for (MatcherState caller : findRuleCallsTo(GrammarUtil.containingRule(from.getGrammarElement()),
				Sets.<AbstractRule> newHashSet()))
			result.addAll(findTransitionsToToken(caller, targets, true, true, visited));
	return result;
}
 
Example 18
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 19
public int getElementID(EObject ele) {
	Integer result = elementIDCache.get(ele);
	if (result == null) {
		Grammar grammar = GrammarUtil.getGrammar(ele);
		if (!elementIDCache.containsKey(grammar)) {
			String grammarName = grammar.getName() + "#" + System.identityHashCode(grammar);
			List<String> indexed = Lists.newArrayList();
			for (EObject o : elementIDCache.keySet())
				if (o instanceof Grammar)
					indexed.add(((Grammar) o).getName() + "#" + System.identityHashCode(o));
			throw new IllegalStateException("No ID found. Wrong grammar. \nRequested: " + grammarName
					+ "\nAvailable: " + Joiner.on(", ").join(indexed));
		} else
			throw new IllegalStateException("No ID found. Not indexed. \nElement: " + EmfFormatter.objPath(ele));
	}
	return result;
}
 
Example 20
Source Project: xtext-core   Source File: GrammarUtilTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@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 21
@Test
public void testBug280011_03() 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("Q : \'x\' a = ID \'y\' a = ID ;");
  _builder.newLine();
  String grammarAsString = _builder.toString();
  final Grammar grammar = this.getGrammar(grammarAsString);
  AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "Q");
  final ParserRule rule = ((ParserRule) _findRuleForName);
  this.validateRule(rule);
  Assert.assertEquals(this.warnings.toString(), 2, this.warnings.size());
}
 
Example 22
@Test
public void testFragment_05() 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 : Named*;");
  _builder.newLine();
  _builder.append("fragment Named: 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(), 1, this.warnings.size());
  AbstractRule _findRuleForName_1 = GrammarUtil.findRuleForName(grammar, "Named");
  final ParserRule fragment = ((ParserRule) _findRuleForName_1);
  this.validateRule(fragment);
  Assert.assertEquals(this.warnings.toString(), 0, this.warnings.size());
}
 
Example 23
Source Project: xtext-core   Source File: ValidatorFragment2.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.14
 */
protected TypeReference getConfigurableIssueCodesProviderClass() {
  String _runtimeBasePackage = this._xtextGeneratorNaming.getRuntimeBasePackage(this.getGrammar());
  String _plus = (_runtimeBasePackage + ".validation.");
  String _simpleName = GrammarUtil.getSimpleName(this.getGrammar());
  String _plus_1 = (_plus + _simpleName);
  String _plus_2 = (_plus_1 + "ConfigurableIssueCodesProvider");
  return new TypeReference(_plus_2);
}
 
Example 24
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 25
Source Project: sarl   Source File: AbstractCodeElementExtractor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public TypeReference getLanguageKeywordAccessor() {
	final Grammar grammar = getGrammar();
	final String basePackage = this.naming.getRuntimeBasePackage(grammar);
	return new TypeReference(basePackage + ".services." //$NON-NLS-1$
			+ GrammarUtil.getSimpleName(grammar).toUpperCase() + "GrammarKeywordAccess"); //$NON-NLS-1$
}
 
Example 26
Source Project: xtext-core   Source File: SerializerFragment2.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private boolean isUnassignedRuleCall(final RuleCall c) {
  boolean _isEObjectRuleCall = GrammarUtil.isEObjectRuleCall(c);
  if (_isEObjectRuleCall) {
    return false;
  }
  final Assignment ass = GrammarUtil.containingAssignment(c);
  return ((ass == null) || GrammarUtil.isBooleanAssignment(ass));
}
 
Example 27
protected CharSequence _compileRule(final Assignment it, final Grammar grammar, final AntlrOptions options) {
  StringConcatenation _builder = new StringConcatenation();
  String _contentAssistRuleName = AntlrGrammarGenUtil.getContentAssistRuleName(GrammarUtil.containingRule(it));
  _builder.append(_contentAssistRuleName);
  _builder.append("__");
  String _gaElementIdentifier = this._grammarAccessExtensions.gaElementIdentifier(AntlrGrammarGenUtil.<Assignment>getOriginalElement(it));
  _builder.append(_gaElementIdentifier);
  _builder.newLineIfNotEmpty();
  _builder.append("\t");
  _builder.append("@init {");
  _builder.newLine();
  _builder.append("\t\t");
  _builder.append("int stackSize = keepStackSize();");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("}");
  _builder.newLine();
  _builder.append(":");
  _builder.newLine();
  _builder.append("\t");
  String _assignmentEbnf = this.assignmentEbnf(it.getTerminal(), it, options, false);
  _builder.append(_assignmentEbnf, "\t");
  _builder.newLineIfNotEmpty();
  _builder.append(";");
  _builder.newLine();
  _builder.append("finally {");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("restoreStackSize(stackSize);");
  _builder.newLine();
  _builder.append("}");
  _builder.newLine();
  return _builder;
}
 
Example 28
Source Project: xtext-core   Source File: GrammarUtilTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testAllMetamodelDeclarations_03() throws Exception {
  this.with(XtextStandaloneSetup.class);
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar foo with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate g \'http://3\' as bar");
  _builder.newLine();
  _builder.append("import \'http://www.eclipse.org/emf/2002/Ecore\' as bar");
  _builder.newLine();
  _builder.append("startrule returns bar::startrule: name=ID;");
  _builder.newLine();
  String model = _builder.toString();
  Resource r = this.getResourceFromString(model);
  EObject _get = r.getContents().get(0);
  Grammar g = ((Grammar) _get);
  List<AbstractMetamodelDeclaration> decls = GrammarUtil.allMetamodelDeclarations(g);
  Assert.assertEquals(3, decls.size());
  AbstractMetamodelDeclaration decl = decls.get(0);
  Assert.assertTrue((decl instanceof GeneratedMetamodel));
  Assert.assertEquals("bar", decl.getAlias());
  Assert.assertNotNull(decl.getEPackage());
  Assert.assertEquals("http://3", decl.getEPackage().getNsURI());
  decl = decls.get(1);
  Assert.assertTrue((decl instanceof ReferencedMetamodel));
  Assert.assertNotNull(decl.getEPackage());
  Assert.assertEquals("http://www.eclipse.org/emf/2002/Ecore", decl.getEPackage().getNsURI());
  Assert.assertEquals("bar", decl.getAlias());
  decl = decls.get(2);
  Assert.assertTrue((decl instanceof ReferencedMetamodel));
  Assert.assertNotNull(decl.getEPackage());
  Assert.assertEquals("http://www.eclipse.org/emf/2002/Ecore", decl.getEPackage().getNsURI());
  Assert.assertEquals("ecore", decl.getAlias());
  AbstractRule abstractRule = g.getRules().get(0);
  Assert.assertSame(decls.get(0), abstractRule.getType().getMetamodel());
}
 
Example 29
/**
 * Returns the invocation of the element accessor method as fully qualified Java statement.
 * Example: return FowlerDslTestLanguageGrammarAccess.INSTANCE.prStatemachine().ele1AssignmentStates()
 */
public StringConcatenationClient gaFullAccessor(final AbstractElement ele) {
  StringConcatenationClient _client = new StringConcatenationClient() {
    @Override
    protected void appendTo(StringConcatenationClient.TargetStringConcatenation _builder) {
      TypeReference _grammarAccess = GrammarAccessExtensions.this.getGrammarAccess(GrammarUtil.getGrammar(ele));
      _builder.append(_grammarAccess);
      _builder.append(".INSTANCE.");
      String _gaRuleElementAccessor = GrammarAccessExtensions.this.gaRuleElementAccessor(ele);
      _builder.append(_gaRuleElementAccessor);
    }
  };
  return _client;
}
 
Example 30
protected void collectReachableRules(ParserRule pr, Set<ParserRule> rules, Set<ParserRule> visited) {
	if (!visited.add(pr))
		return;
	for (RuleCall rc : GrammarUtil.containedRuleCalls(pr))
		if (isParserRule(rc.getRule())) {
			if (GrammarUtil.containingAssignment(rc) != null)
				rules.add((ParserRule) rc.getRule());
			collectReachableRules((ParserRule) rc.getRule(), rules, visited);
		}
}