org.eclipse.xtext.GrammarUtil Java Examples

The following examples show how to use org.eclipse.xtext.GrammarUtil. 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: OverriddenValueInspectorTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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 #2
Source File: RuleEngineGrammarAccess.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@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 File: TokenTypeRewriter.java    From n4js with 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
Source File: KeywordBasedValueConverter.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @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
Source File: OverriddenValueInspectorTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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 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 #7
Source File: OverriddenValueInspectorTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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 File: GrammarNaming.java    From xtext-core with 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
Source File: OverriddenValueInspectorTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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
Source File: OverriddenValueInspectorTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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
Source File: DefaultLocationInFileProvider.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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 File: OverriddenValueInspectorTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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 #13
Source File: GrammarTest.java    From xtext-eclipse with 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 #14
Source File: AbstractInternalAntlrParser.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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 #15
Source File: HiddenTerminalsTestLanguageGrammarAccess.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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 #16
Source File: ElementMatcherProvider.java    From xtext-core with 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 #17
Source File: NamedSerializationContextProvider.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public String getSignificantGrammarElement(final Iterable<ISerializationContext> contexts) {
  ParserRule rule = null;
  int index = Integer.MAX_VALUE;
  for (final ISerializationContext ctx : contexts) {
    {
      ParserRule pr = ctx.getParserRule();
      if ((pr == null)) {
        final Action action = ctx.getAssignedAction();
        if ((action != null)) {
          pr = GrammarUtil.containingParserRule(action);
        }
      }
      if ((pr != null)) {
        final Integer i = this.rules.get(pr);
        if (((i).intValue() < index)) {
          index = (i).intValue();
          rule = pr;
        }
      }
    }
  }
  if ((rule != null)) {
    return rule.getName();
  }
  return "unknown";
}
 
Example #18
Source File: GrammarElementDeclarationOrder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
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 #19
Source File: StableOrderSyntacticSequencerPDAProvider.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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 #20
Source File: FormatJavaValidator.java    From dsl-devkit with 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 #21
Source File: OverriddenValueInspectorTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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
Source File: GrammarUtilTest.java    From xtext-core with 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 #23
Source File: SimpleProjectWizardFragment.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.4
 */
public String getFileExtension(Grammar g) {
	if (modelFileExtension == null) {
		modelFileExtension = GrammarUtil.getSimpleName(g).toLowerCase();
		if (LOG.isInfoEnabled())
			LOG.info("No explicit 'fileExtension' configured. Using '" + modelFileExtension + "'.");
	}
	return modelFileExtension;
}
 
Example #24
Source File: XtendHighlightingCalculator.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected void collectKeywordsFromRule(IGrammarAccess grammarAccess, String ruleName, ImmutableSet.Builder<Keyword> builder) {
	AbstractRule rule = GrammarUtil.findRuleForName(grammarAccess.getGrammar(), ruleName);
	if (!(rule instanceof TerminalRule)) { // if someone decides to override ValidID with a terminal rule
		Iterator<EObject> i = rule.eAllContents();
		while (i.hasNext()) {
			EObject o = i.next();
			if (o instanceof Keyword) {
				builder.add((Keyword) o);
			}
		}
	}
}
 
Example #25
Source File: CodetemplatesProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private String getAssignedFeature(RuleCall call) {
	Assignment ass = GrammarUtil.containingAssignment(call);
	if (ass != null) {
		String result = ass.getFeature();
		if (result.equals(result.toLowerCase()))
			result = Strings.toFirstUpper(result);
		return result;
	}
	return null;
}
 
Example #26
Source File: XtextValidator.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected List<GeneratedMetamodel> getInheritedGeneratedMetamodels(ReferencedMetamodel metamodel) {
	List<GeneratedMetamodel> allGeneratedMetamodels = new ArrayList<GeneratedMetamodel>();
	Grammar grammar = GrammarUtil.getGrammar(metamodel);
	Set<Grammar> visited = Sets.newHashSet();
	for (Grammar usedGrammar : grammar.getUsedGrammars())
		Iterables.addAll(allGeneratedMetamodels, getAllGeneratedMetamodels(usedGrammar, visited));
	if (allGeneratedMetamodels.isEmpty())
		return Collections.emptyList();
	return allGeneratedMetamodels;
}
 
Example #27
Source File: XtextSerializerTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@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 #28
Source File: GrammarUtilTest.java    From xtext-core with 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
Source File: CurrentTypeFinder.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Boolean caseCompoundElement(CompoundElement object) {
	EClassifier wasType = currentType;
	for(AbstractElement element: object.getElements()) {
		if (doSwitch(element))
			return true;
	}
	if (object == stopElement)
		return true;
	if (GrammarUtil.isOptionalCardinality(object))
		currentType = getCompatibleType(currentType, wasType, object);
	return false;
}
 
Example #30
Source File: RuleWithoutInstantiationInspectorTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testUnorderedGroup_01() throws Exception {
	String grammarAsString = "grammar org.foo with org.eclipse.xtext.common.Terminals\n" +
			"generate metamodel 'foo.sample'\n" +
			"Model: x=X;\n" +
			"X : {X} | 'keyword0' & 'keyword1';\n";
	Grammar grammar = getGrammar(grammarAsString);
	ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(grammar, "X");
	validateRule(rule);
	assertEquals(warnings.toString(), 1, warnings.size());
}