Java Code Examples for org.eclipse.xtext.Grammar

The following examples show how to use org.eclipse.xtext.Grammar. 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
@Override
protected IRenameStrategy createRenameStrategy(final EObject targetElement, final IRenameElementContext context) {
	return new XtextSwitch<IRenameStrategy>() {

		@Override
		public IRenameStrategy caseAbstractMetamodelDeclaration(AbstractMetamodelDeclaration metamodelDeclaration) {
			return metamodelDeclarationProvider.get();
		}

		@Override
		public IRenameStrategy caseAbstractRule(AbstractRule rule) {
			return ruleProvider.get();
		}

		@Override
		public IRenameStrategy caseGrammar(Grammar grammar) {
			return XtextRenameStrategyProvider.super.createRenameStrategy(targetElement, context);
		}
	}.doSwitch(targetElement);
}
 
Example 2
@Override
public List<String> resolveValues(TemplateVariable variable,
		XtextTemplateContext castedContext) {
	String enumerationName = variable.getVariableType()
			.getParams().iterator().next();
	Grammar grammar = getGrammar(castedContext);
	if (grammar == null)
		return Collections.emptyList();
	EEnum enumeration = (EEnum) getEClassifierForGrammar(enumerationName, grammar);
	if (enumeration == null) {
		return Collections.emptyList();
	}
	return Lists.transform(enumeration.getELiterals(), new Function<EEnumLiteral, String>() {
		@Override
		public String apply(EEnumLiteral enumLiteral) {
			return enumLiteral.getLiteral();
		}
	});
}
 
Example 3
@Test
public void testOptionalAction_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("First : Second (isSecond=\'keyword\' | {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 4
public List<String> initialHiddenTokens(final Grammar it) {
  List<String> _xblockexpression = null;
  {
    boolean _isDefinesHiddenTokens = it.isDefinesHiddenTokens();
    if (_isDefinesHiddenTokens) {
      final Function1<AbstractRule, String> _function = (AbstractRule it_1) -> {
        return this.ruleName(it_1);
      };
      return IterableExtensions.<String>toList(ListExtensions.<AbstractRule, String>map(it.getHiddenTokens(), _function));
    }
    int _size = it.getUsedGrammars().size();
    boolean _equals = (_size == 1);
    if (_equals) {
      return this.initialHiddenTokens(IterableExtensions.<Grammar>head(it.getUsedGrammars()));
    }
    _xblockexpression = CollectionLiterals.<String>emptyList();
  }
  return _xblockexpression;
}
 
Example 5
Source Project: n4js   Source File: N4JSRenameStrategy.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the TypeExpressions grammar
 */
protected Grammar getTypeExpressionsGrammar() {
	Grammar grammar = grammarProvider.getGrammar(this);
	while (grammar != null) {
		if ("org.eclipse.n4js.ts.TypeExpressions".equals(grammar.getName())) {
			return grammar;
		}
		List<Grammar> grammars = grammar.getUsedGrammars();
		if (!grammars.isEmpty()) {
			grammar = grammars.iterator().next();
		} else {
			return null;
		}
	}
	return grammar;
}
 
Example 6
Source Project: xtext-core   Source File: XtextValidationTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testPredicatedUnorderedGroup_04() throws Exception {
	String grammarAsText =
			"grammar test with org.eclipse.xtext.common.Terminals\n" +
			"generate test 'http://test'\n" +
			"A: =>(name=ID value=B);\n" +
			"B: name=ID & value=STRING;";
	
	Grammar grammar = (Grammar) getModel(grammarAsText);
	XtextValidator validator = get(XtextValidator.class);
	ValidatingMessageAcceptor messageAcceptor = new ValidatingMessageAcceptor(null, true, false);
	Group predicatedGroup = (Group) grammar.getRules().get(0).getAlternatives();
	Group groupContent = (Group) predicatedGroup.getElements().get(0);
	Assignment valueAssignment = (Assignment) groupContent.getElements().get(1);
	messageAcceptor.expectedContext(
			grammar.getRules().get(0).getAlternatives(),
			valueAssignment.getTerminal(),
			grammar.getRules().get(1).getAlternatives()
	);
	validator.setMessageAcceptor(messageAcceptor);
	validator.checkUnorderedGroupIsNotPredicated(grammar);
	messageAcceptor.validate();
}
 
Example 7
Source Project: xtext-core   Source File: GrammarParserTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testEnum_08() throws Exception {
	String modelAsString =
		"grammar TestLanguage with org.eclipse.xtext.common.Terminals\n" +
		"generate testLanguage 'http://www.eclipse.org/2009/tmf/xtext/AbstractEnumRulesTest/TestEnum/8'\n" +
		"Model: enumValue=MyEnum;\n" +
		"enum MyEnum: Value | Value = 'foo';";
	Grammar grammar = (Grammar) getModel(modelAsString);
	assertTrue(grammar.eResource().getErrors().toString(), grammar.eResource().getErrors().isEmpty());
	checkEnums(grammar);
	EPackage pack = grammar.getMetamodelDeclarations().get(0).getEPackage();
	assertEquals("http://www.eclipse.org/2009/tmf/xtext/AbstractEnumRulesTest/TestEnum/8", pack.getNsURI());
	EEnum eEnum = (EEnum) pack.getEClassifier("MyEnum");
	assertNotNull(eEnum);
	assertEquals(1, eEnum.getELiterals().size());
	EEnumLiteral value = eEnum.getELiterals().get(0);
	assertEquals("Value", value.getName());
	assertEquals(0, value.getValue());
	assertEquals("Value", value.getLiteral());
}
 
Example 8
Source Project: xtext-core   Source File: XtextValidator.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Check
public void checkGrammarName(Grammar g) {
	String name = g.getName();
	if (name == null) {
		return;
	}
	String[] split = name.split("\\.");
	if (split.length == 1)
		error("You must use a namespace.", XtextPackage.Literals.GRAMMAR__NAME);
	for (int i = 0; i < split.length - 1; i++) {
		String nsEle = split[i];
		if (Character.isUpperCase(nsEle.charAt(0)))
			warning("Namespace elements should start with a lower case letter.", XtextPackage.Literals.GRAMMAR__NAME);
	}
	String ele = split[split.length - 1];
	if (!Character.isUpperCase(ele.charAt(0)))
		error("The last element should start with an upper case letter.", XtextPackage.Literals.GRAMMAR__NAME);
}
 
Example 9
Source Project: xtext-core   Source File: XtextValidationTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testBug_282852_08() throws Exception {
	Grammar base = XtextFactory.eINSTANCE.createGrammar();
	AbstractRule ruleFoo = XtextFactory.eINSTANCE.createParserRule();
	ruleFoo.setName("Foo");
	base.getRules().add(ruleFoo);
	AbstractRule subRuleFoo = XtextFactory.eINSTANCE.createParserRule();
	subRuleFoo.setName("foo");
	AbstractRule subRuleFoo2 = XtextFactory.eINSTANCE.createParserRule();
	subRuleFoo2.setName("fOO");
	AbstractRule subRuleFoo3 = XtextFactory.eINSTANCE.createParserRule();
	subRuleFoo3.setName("FOO");
	base.getRules().add(subRuleFoo);
	base.getRules().add(subRuleFoo2);
	base.getRules().add(subRuleFoo3);

	XtextValidator validator = get(XtextValidator.class);
	configureValidator(validator, this, subRuleFoo);
	validator.checkRuleName(subRuleFoo);
	assertEquals("A rule's name has to be unique even case insensitive. The conflicting rules are 'FOO', 'Foo' and 'fOO'.", lastMessage);
}
 
Example 10
Source Project: xtext-core   Source File: XtextValidationTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testPredicatedUnorderedGroup_01() throws Exception {
	String grammarAsText =
			"grammar test with org.eclipse.xtext.common.Terminals\n" +
			"generate test 'http://test'\n" +
			"Model: =>(name=ID & value=STRING);\n";
	
	Grammar grammar = (Grammar) getModel(grammarAsText);
	ValidatingMessageAcceptor messageAcceptor = new ValidatingMessageAcceptor(null, true, false);
	messageAcceptor.expectedContext(
			grammar.getRules().get(0).getAlternatives(),
			((CompoundElement) grammar.getRules().get(0).getAlternatives()).getElements().get(0)
	);
	PredicateUsesUnorderedGroupInspector inspector = new PredicateUsesUnorderedGroupInspector(messageAcceptor);
	inspector.inspect(grammar);
	messageAcceptor.validate();
}
 
Example 11
Source Project: xtext-core   Source File: XtextValidationTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testBug_282852_03() throws Exception {
	Grammar base = XtextFactory.eINSTANCE.createGrammar();
	Grammar child = XtextFactory.eINSTANCE.createGrammar();
	child.getUsedGrammars().add(base);
	AbstractRule ruleFoo = XtextFactory.eINSTANCE.createParserRule();
	ruleFoo.setName("Foo");
	base.getRules().add(ruleFoo);
	AbstractRule subRuleFoo = XtextFactory.eINSTANCE.createParserRule();
	subRuleFoo.setName("Foo");
	child.getRules().add(subRuleFoo);

	XtextValidator validator = get(XtextValidator.class);
	validator.setMessageAcceptor(this);
	validator.checkRuleName(subRuleFoo);
	assertNull(lastMessage);
}
 
Example 12
@Override
public SerializationContextMap<Nfa<ISemState>> getSemanticSequencerNFAs(Grammar grammar) {
	SerializationContextMap<Nfa<ISemState>> cached = cache.get(grammar);
	if (cached != null)
		return cached;
	SerializationContextMap.Builder<Nfa<ISemState>> builder = SerializationContextMap.builder();
	SerializationContextMap<ISynAbsorberState> PDAs = pdaProvider.getSyntacticSequencerPDAs(grammar);
	for (SerializationContextMap.Entry<ISynAbsorberState> e : PDAs.values()) {
		ISynAbsorberState synState = e.getValue();
		for (EClass type : e.getTypes()) {
			List<ISerializationContext> contexts = e.getContexts(type);
			try {
				SemNfa nfa = createNfa(grammar, synState, type);
				builder.put(contexts, nfa);
			} catch (Exception x) {
				LOG.error("Error during static analysis of context '" + contexts + "': " + x.getMessage(), x);
			}
		}
	}
	SerializationContextMap<Nfa<ISemState>> result = builder.create();
	cache.put(grammar, result);
	return result;
}
 
Example 13
/**
 * 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 14
Source Project: xtext-core   Source File: XtextValidationTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testCycleInTypeHierarchy() throws Exception {
	String grammarAsText = "grammar test with org.eclipse.xtext.common.Terminals" +
			" generate test 'http://test'";
	grammarAsText += " RuleA: RuleB;";
	grammarAsText += " RuleB: RuleC;";
	grammarAsText += " RuleC: RuleA;";
	grammarAsText += " RuleD: RuleA;";

	Grammar grammar = (Grammar) getModel(grammarAsText);
	AbstractMetamodelDeclaration metamodelDeclaration = grammar.getMetamodelDeclarations().get(0);
	
	XtextValidator validator = get(XtextValidator.class);
	ValidatingMessageAcceptor messageAcceptor = new ValidatingMessageAcceptor(grammar.getRules().get(0).getType(), true, false);
	messageAcceptor.expectedContext(
			grammar.getRules().get(1).getType(),
			grammar.getRules().get(2).getType()
	);
	validator.setMessageAcceptor(messageAcceptor);
	validator.checkGeneratedPackage((GeneratedMetamodel) metamodelDeclaration, Diagnostician.INSTANCE, Collections.EMPTY_MAP);
	messageAcceptor.validate();
}
 
Example 15
protected Grammar internalFindGrammar(GrammarProvider grammarProvider) {
	Grammar grammar = grammarProvider.getGrammar(this);
	while (grammar != null) {
		if ("org.eclipse.xtext.common.types.xtext.ui.ContentAssistTestLanguage".equals(grammar.getName())) {
			return grammar;
		}
		List<Grammar> grammars = grammar.getUsedGrammars();
		if (!grammars.isEmpty()) {
			grammar = grammars.iterator().next();
		} else {
			return null;
		}
	}
	return grammar;
}
 
Example 16
Source Project: xtext-core   Source File: EMFGeneratorFragment2.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected String getEcoreFilePath(final Grammar grammar) {
  String _xblockexpression = null;
  {
    final String ecoreModelFolder = this.getProjectConfig().getRuntime().getEcoreModelFolder();
    String _modelPluginID = this.getModelPluginID();
    String _plus = ("/" + _modelPluginID);
    String _plus_1 = (_plus + "/");
    String _plus_2 = (_plus_1 + ecoreModelFolder);
    String _plus_3 = (_plus_2 + "/");
    String _modelName = this.getModelName(grammar);
    String _plus_4 = (_plus_3 + _modelName);
    _xblockexpression = (_plus_4 + ".ecore");
  }
  return _xblockexpression;
}
 
Example 17
protected Grammar internalFindGrammar(GrammarProvider grammarProvider) {
	Grammar grammar = grammarProvider.getGrammar(this);
	while (grammar != null) {
		if ("org.eclipse.xtext.testlanguages.ActionTestLanguage2".equals(grammar.getName())) {
			return grammar;
		}
		List<Grammar> grammars = grammar.getUsedGrammars();
		if (!grammars.isEmpty()) {
			grammar = grammars.iterator().next();
		} else {
			return null;
		}
	}
	return grammar;
}
 
Example 18
Source Project: xtext-core   Source File: UsedRulesFinder.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public void compute(Grammar grammar) {
	if (!grammar.getRules().isEmpty()) {
		AbstractRule firstRule = grammar.getRules().get(0);
		if (firstRule instanceof ParserRule) {
			doSwitch(firstRule);
			doSwitch(grammar);
		}
	}
}
 
Example 19
protected Grammar internalFindGrammar(GrammarProvider grammarProvider) {
	Grammar grammar = grammarProvider.getGrammar(this);
	while (grammar != null) {
		if ("org.eclipse.xtext.valueconverter.QualifiedNameTestLanguage".equals(grammar.getName())) {
			return grammar;
		}
		List<Grammar> grammars = grammar.getUsedGrammars();
		if (!grammars.isEmpty()) {
			grammar = grammars.iterator().next();
		} else {
			return null;
		}
	}
	return grammar;
}
 
Example 20
Source Project: xtext-core   Source File: EMFGeneratorFragment2.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create a clone of the original grammar. The clone will not refer to a node model.
 */
private Grammar cloneGrammarIntoNewResourceSet(final Grammar original) {
  final Resource originalResource = original.eResource();
  XtextResourceSet _xtextResourceSet = new XtextResourceSet();
  final XtextResourceSet clonedResourceSet = EcoreUtil2.<XtextResourceSet>clone(_xtextResourceSet, originalResource.getResourceSet());
  final Resource clonedResource = clonedResourceSet.getResource(originalResource.getURI(), false);
  EObject _head = IterableExtensions.<EObject>head(clonedResource.getContents());
  return ((Grammar) _head);
}
 
Example 21
Source Project: xtext-core   Source File: GrammarUtilTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testAllMetamodelDeclarations_01() throws Exception {
  this.with(XtextStandaloneSetup.class);
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar foo with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("import \'http://www.eclipse.org/emf/2002/Ecore\' as ecore");
  _builder.newLine();
  _builder.append("generate g \'http://3\' as ecore");
  _builder.newLine();
  _builder.append("startrule returns ecore::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(2, decls.size());
  AbstractMetamodelDeclaration decl = decls.get(0);
  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());
  decl = decls.get(1);
  Assert.assertEquals("ecore", decl.getAlias());
  Assert.assertNotNull(decl.getEPackage());
  Assert.assertEquals("http://3", decl.getEPackage().getNsURI());
}
 
Example 22
protected Grammar internalFindGrammar(GrammarProvider grammarProvider) {
	Grammar grammar = grammarProvider.getGrammar(this);
	while (grammar != null) {
		if ("org.eclipse.xtext.ui.tests.editor.contentassist.Bug287941TestLanguage".equals(grammar.getName())) {
			return grammar;
		}
		List<Grammar> grammars = grammar.getUsedGrammars();
		if (!grammars.isEmpty()) {
			grammar = grammars.iterator().next();
		} else {
			return null;
		}
	}
	return grammar;
}
 
Example 23
Source Project: xtext-core   Source File: NodeModelUtilsTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testFindActualSemanticObjectFor_04() throws Exception {
	String grammarString = "grammar foo.Bar with org.eclipse.xtext.common.Terminals generate foo 'bar' Model:name=ID;";
	Grammar grammar = (Grammar) getModel(grammarString);
	ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(NodeModelUtils.getNode(grammar), grammarString.indexOf("name"));
	EObject object = NodeModelUtils.findActualSemanticObjectFor(leafNode);
	assertTrue(object instanceof Assignment);
}
 
Example 24
/**
 * @since 2.4
 */
protected String getSuperClassName(Grammar grammar) {
	Grammar superGrammar = getSuperGrammar(grammar);
	if(isInheritImplementation() && superGrammar != null)
		return getProposalProviderClassName(superGrammar);
	else 
		return "org.eclipse.xtext.ui.editor.contentassist.AbstractJavaBasedContentProposalProvider";
		
}
 
Example 25
protected void asserTranslatesToDebugGrammar(final CharSequence xtextGrammar, final String expectedDebugGrammar) {
  try {
    EObject _model = super.getModel(xtextGrammar.toString());
    final Grammar grammar = ((Grammar) _model);
    DefaultGeneratorModule _defaultGeneratorModule = new DefaultGeneratorModule();
    final Injector injector = Guice.createInjector(_defaultGeneratorModule);
    final AntlrGeneratorFragmentTest.InMemFSA inMem = new AntlrGeneratorFragmentTest.InMemFSA();
    final AntlrOptions options = new AntlrOptions();
    injector.<AntlrDebugGrammarGenerator>getInstance(AntlrDebugGrammarGenerator.class).generate(grammar, options, inMem);
    Assert.assertEquals(expectedDebugGrammar, IterableExtensions.<Object>head(inMem.getAllFiles().values()).toString());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 26
Source Project: dsl-devkit   Source File: TransformUtil.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Looks up an EClass visible in the context of a grammar.
 *
 * @param grammar
 *          context grammar
 * @param packageName
 *          package name
 * @param className
 *          class name
 * @return EClass or null
 */
public static EClass lookupEClass(final Grammar grammar, final String packageName, final String className) {
  EPackage ePackage = lookupEPackage(grammar, packageName);
  if (ePackage != null) {
    EClassifier eClassifier = ePackage.getEClassifier(className);
    if (eClassifier instanceof EClass) {
      return (EClass) eClassifier;
    }
  }
  LOG.info("no class found with name " + packageName + "::" + className);
  return null;
}
 
Example 27
@Override
public void generate(Grammar grammar, XpandExecutionContext ctx) {
	if (delegate != null)
		delegate.generate(grammar, ctx);
	else
		fallback.generate(grammar, ctx);
}
 
Example 28
@Test public void testUnorderedGroup_15() throws Exception {
	String grammarAsString = "grammar org.foo with org.eclipse.xtext.common.Terminals\n" +
			"generate metamodel 'foo.sample'\n" +
			"X : x=ID? & 'x';\n";
	Grammar grammar = getGrammar(grammarAsString);
	ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(grammar, "X");
	validateRule(rule);
	assertEquals(warnings.toString(), 1, warnings.size());
}
 
Example 29
protected Grammar internalFindGrammar(GrammarProvider grammarProvider) {
	Grammar grammar = grammarProvider.getGrammar(this);
	while (grammar != null) {
		if ("org.eclipse.xtext.parser.antlr.Bug299237TestLanguage".equals(grammar.getName())) {
			return grammar;
		}
		List<Grammar> grammars = grammar.getUsedGrammars();
		if (!grammars.isEmpty()) {
			grammar = grammars.iterator().next();
		} else {
			return null;
		}
	}
	return grammar;
}
 
Example 30
Source Project: xtext-core   Source File: WebIntegrationFragment.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected TypeReference getServletClass(final Grammar grammar) {
  String _webBasePackage = this._xtextGeneratorNaming.getWebBasePackage(grammar);
  String _plus = (_webBasePackage + ".");
  String _simpleName = GrammarUtil.getSimpleName(grammar);
  String _plus_1 = (_plus + _simpleName);
  String _plus_2 = (_plus_1 + "Servlet");
  return new TypeReference(_plus_2);
}