### Fine-tune EMF Setup with StandaloneSetup
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/302_configuration.html
Use StandaloneSetup as a Workflow bean for advanced EMF setup, including classpath scanning and registering generated EPackages and GenModel files.
```java
bean = StandaloneSetup {
platformUri = "${rootPath}"
scanClassPath = true
registerGeneratedEPackage = "my.project.DomainmodelPackage"
registerGenModelFile = "platform:/resource/my.project/model/Domainmodel.genmodel"
}
```
--------------------------------
### Xtext Template for Cross-References (Statemachine Example)
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/310_eclipse_support.html
An example template demonstrating the use of the CrossReference resolver to create transitions between states in the Xtext Statemachine example. It pre-populates 'event' and 'state' placeholders.
```xml
${event:CrossReference('Transition.event')} => ${state:CrossReference('Transition.state')}
```
--------------------------------
### Xbase Extension Method Examples
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/305_xbase.html
Illustrates various ways to invoke extension methods in Xbase.
```xbase
foo
```
```xbase
my.foo
```
```xbase
my.foo(x)
```
```xbase
oh.my.foo(bar)
```
--------------------------------
### Xtend API Example with Units
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtend.doc/contents/101_gettingstarted.html
An example demonstrating Xtend's expressive API capabilities, specifically showing how to use custom units for calculations.
```xtend
assertEquals(42.km/h, (40_000.m + 2.km) / 60.min)
```
--------------------------------
### shortestPathTo Method (Starts, Stack, Matches)
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.xbase.testdata/src/org/eclipse/xtext/common/types/testSetups/Bug347739.java.txt
Finds the shortest path of states from a set of starting states to a target configuration defined by stack and matching criteria. Useful for finding optimal transitions in PDAs.
```java
public static List shortestPathTo(Bug347739ThreeTypeParams pda,
Iterable starts, Iterator stack, Bug347739OneTypeParam matches, Bug347739OneTypeParam canPass) {
return null;
}
```
--------------------------------
### Xtext DSL Example for Namespace Imports
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/303_runtime_concepts.html
Illustrates how to use package and import declarations in a sample DSL to manage namespaces and inheritance.
```xtext
package foo {
import bar.Foo
entity Bar extends Foo {
}
}
package bar {
entity Foo {}
}
```
--------------------------------
### Basic If Expression Example
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/305_xbase.html
A simple example of an if expression, showing the basic syntax for conditional value selection.
```xbase
if (isFoo) this else that
```
--------------------------------
### Domain Model Language Example
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/104_jvmdomainmodel.html
This example showcases a domain model language with support for Java generics, full expressions, and lambda expressions.
```xtext
import java.util.List
package my.model {
entity Person {
name: String
firstName: String
friends: List
address : Address
op getFullName() : String {
return firstName + " " + name;
}
op getFriendsSortedByFullName() : List {
return friends.sortBy[ f | f.fullName ]
}
}
entity Address {
street: String
zip: String
city: String
}
}
```
--------------------------------
### Java Test Setup with Annotation
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.common.types.eclipse.tests/testdata/org/eclipse/xtext/common/types/testSetups/Bug334943Client.java.txt
This Java code defines a class with a static method annotated with @TestAnnotationWithDefaults. It serves as a client setup for testing specific bug scenarios.
```java
package org.eclipse.xtext.common.types.testSetups;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
public class Bug334943Client {
@TestAnnotationWithDefaults
public static void someOperation() {
}
}
```
--------------------------------
### Xtend Class Definition Example
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtend.doc/contents/202_xtend_classes_members.html
An exemplary Xtend file demonstrating package declaration, imports, and a class with a constructor, field, and method.
```xtend
package com.acme
import java.util.List
class MyClass {
String name
new(String name) {
this.name = name
}
def String first(List elements) {
elements.get(0)
}
}
```
--------------------------------
### Xtend Annotations Example
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtend.doc/contents/202_xtend_classes_members.html
Demonstrates the usage of various annotations on classes, fields, methods, and parameters in Xtend. Supports key-value pairs and default values.
```xtend
@TypeAnnotation("some value")
class MyClass {
@FieldAnnotation(value = @NestedAnnotation(true))
static val CONSTANT = 'a compile-time constant'
@MethodAnnotation(constant = CONSTANT)
def String myMethod(@ParameterAnnotation String param) {
//...
}
}
```
--------------------------------
### Configure Semantic Highlighting Styles
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/310_eclipse_support.html
Implement IHighlightingConfiguration to define and register custom styles for semantic highlighting. This example shows how to configure a style for cross-references.
```java
public class HighlightingConfiguration
implements IHighlightingConfiguration {
// lexical stuff goes here
// ..
public final static String CROSS_REF = "CrossReference";
public void configure(IHighlightingConfigurationAcceptor acceptor) {
// lexical stuff goes here
// ..
acceptor.acceptDefaultHighlighting(CROSS_REF,
"Cross-References", crossReferenceTextStyle());
}
public TextStyle crossReferenceTextStyle() {
TextStyle textStyle = new TextStyle();
textStyle.setStyle(SWT.ITALIC);
return textStyle;
}
}
```
--------------------------------
### Xtext DSL Example for Simple Name Referencing
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/303_runtime_concepts.html
Demonstrates referencing entities by their simple names within a package, showcasing scope resolution.
```xtext
package bar {
entity Bar extends Foo {}
entity Foo {}
}
```
--------------------------------
### Configure Xtext-Web Editor
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.web.example.jetty/src/main/webapp/codemirror-statemachine-stateless.html
Configures the base URL and module paths for Xtext-Web and CodeMirror. This setup is required before creating the editor instance.
```javascript
var baseUrl = window.location.pathname;
var fileIndex = baseUrl.indexOf("codemirror-statemachine-stateless.html");
if (fileIndex > 0)
baseUrl = baseUrl.slice(0, fileIndex)
require.config({
baseUrl: baseUrl,
paths: {
"jquery": "webjars/jquery/3.6.0/jquery.min",
"xtext/xtext-codemirror": "xtext/@xtext-version-placeholder@/xtext-codemirror",
},
packages: [
{
name: "codemirror",
location: "webjars/codemirror/5.41.0",
main: "lib/codemirror"
}
]
});
require(["xtext/cm-mode-statemachine", "xtext/xtext-codemirror"], function(mode, xtext) {
xtext.createEditor({baseUrl:baseUrl});
});
```
--------------------------------
### trace Method
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.xbase.testdata/src/org/eclipse/xtext/common/types/testSetups/Bug347739.java.txt
Generates a trace of states from a starting configuration to a target configuration. Useful for debugging and understanding PDA execution flow.
```java
protected static TraceItem trace(
Bug347739ThreeTypeParams pda, Iterable starts, Iterator stack,
Bug347739OneTypeParam matches, Bug347739OneTypeParam canPass) {
return null;
}
```
--------------------------------
### Runtime Injector Setup
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/302_configuration.html
Use this method to create an Injector for your Xtext language in a standalone application. It initializes the language infrastructure and registers EMF factories and EPackages.
```java
public static void main(String[] args) {
Injector injector = new MyDslStandaloneSetup().createInjectorAndDoEMFRegistration();
MyApplication application = injector.getInstance(MyApplication.class);
application.run();
}
```
--------------------------------
### Initialize Xtext-Web Editor with Orion
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.web.example.jetty/src/main/webapp/orion-entities-resource.html
Configures RequireJS and initializes the Xtext editor within the Orion environment. This setup is necessary for the editor to function correctly.
```javascript
var baseUrl = window.location.pathname;
var fileIndex = baseUrl.indexOf("orion-entities-resource.html");
if (fileIndex > 0)
baseUrl = baseUrl.slice(0, fileIndex)
require.config({
baseUrl: baseUrl,
paths: {
"text": "webjars/requirejs-text/2.0.15/text",
"jquery": "webjars/jquery/3.6.0/jquery.min",
"xtext/xtext-orion": "xtext/@xtext-version-placeholder@/xtext-orion",
}
});
require(["orion/code_edit/built-codeEdit-amd"], function() {
require(["xtext/xtext-orion"], function(xtext) {
xtext.createEditor({
syntaxDefinition: "xtext/entities-syntax",
baseUrl: baseUrl,
}).done(function(editorViewer) {
$("#save-button").click(function() {
editorViewer.xtextServices.saveResource();
});
$("#revert-button").click(function() {
editorViewer.xtextServices.revertResource();
});
});
});
});
```
--------------------------------
### Configure Dependency Injection Bindings in a Module
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/302_configuration.html
Implement a Guice Module to define mappings between types and their implementations. This example binds IScopeProvider to a custom MyConcreteScopeProvider.
```java
public class MyDslRuntimeModule implements Module {
@Override
public void configure(Binder binder) {
binder
.bind(IScopeProvider.class)
.to(MyConcreteScopeProvider.class);
}
}
```
--------------------------------
### Java Class with Test Annotation
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.xbase.testdata/src/org/eclipse/xtext/common/types/testSetups/Bug334943Client.java.txt
This snippet shows a static method within a Java class annotated with @TestAnnotationWithDefaults. It serves as a basic example for test setup.
```Java
package org.eclipse.xtext.common.types.testsetups;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
public class Bug334943Client {
@TestAnnotationWithDefaults
public static void someOperation() {
}
}
```
--------------------------------
### DOM Initialization using Builder Syntax
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/305_xbase.html
Shows how to create a DOM using Xbase code with extension libraries and builder syntax for HTML pages.
```xbase
html([ html |
head(html, [
// initialize head
])
] )
```
```xbase
html() [ html |
html.head() [
// initialize head
]
]
```
```xbase
html [
head [
// initialize head
]
]
```
--------------------------------
### Xtext Template for Enumerations (Domainmodel Example)
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/310_eclipse_support.html
An example template using the Enum resolver to set the 'Visibility' of an entity in the Xtext Domainmodel example. It provides a dropdown for selecting visibility literals.
```xml
${public:Enum('Visibility')} entity ${Name} {
${cursor}
}
```
--------------------------------
### Define a Simple File Template
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/310_eclipse_support.html
Create a basic file template for a DSL using annotations and the 'generateFiles' method. This example defines a 'Hello World' template with a customizable name.
```java
@FileTemplate(label="Hello World", icon="file_template.png", description="Create a hello world for MyDsl.")
final class HelloWorldFile {
val helloName = combo("Hello Name:", #["Xtext", "World", "Foo", "Bar"], "The name to say 'Hello' to")
override generateFiles(IFileGenerator generator) {
generator.generate('''«folder»/«name».mydsl''', '''
Hello «helloName»!
''')
}
}
```
--------------------------------
### Example Grammar Rule
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/303_runtime_concepts.html
An example grammar rule demonstrating implied constraints for types, features, quantities, and values.
```xtext
MyRule:
({MySubRule} "sub")? (strVal+=ID intVal+=INT)*;
```
--------------------------------
### XBlockExpression Example
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/104_jvmdomainmodel.html
This is an example of an XBlockExpression, which represents a block of code enclosed in curly braces, often used for operation bodies.
```xtext
{
return "Hello World" + "!"
}
```
--------------------------------
### Xbase Type Reference Examples
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/305_xbase.html
Illustrates various ways to reference types in Xbase, including simple names, fully qualified names, and parameterized types with wildcards and bounds. Also shows function types.
```xbase
java.lang.String
```
```xbase
String
```
```xbase
List>
```
```xbase
List extends Comparable extends FooBar>
```
```xbase
List super MyLowerBound>
```
```xbase
List extends =>Boolean>
```
--------------------------------
### Configure Xtext-Web and Create Editor
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.web.example.jetty/src/main/webapp/orion-statemachine-stateless.html
Sets up the require.js configuration for Xtext-Web and initializes the editor with a state machine syntax definition. Ensure the baseUrl is correctly set to locate Xtext resources.
```javascript
var baseUrl = window.location.pathname;
var fileIndex = baseUrl.indexOf("orion-statemachine-stateless.html");
if (fileIndex > 0) baseUrl = baseUrl.slice(0, fileIndex)
require.config({
baseUrl: baseUrl,
paths: {
"text": "webjars/requirejs-text/2.0.15/text",
"jquery": "webjars/jquery/3.6.0/jquery.min",
"xtext/xtext-orion": "xtext/@xtext-version-placeholder@/xtext-orion",
}
});
require(["orion/code_edit/built-codeEdit-amd"], function() {
require(["xtext/xtext-orion"], function(xtext) {
xtext.createEditor({
syntaxDefinition: "xtext/statemachine-syntax",
baseUrl: baseUrl,
});
});
});
```
--------------------------------
### Configure Xtext-Web Editor
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.web.example.jetty/src/main/webapp/codemirror-statemachine-static.html
Sets up the base URL, module paths, and packages for Xtext-Web and CodeMirror. This script should be run before initializing the editor.
```javascript
var baseUrl = window.location.pathname;
var fileIndex = baseUrl.indexOf("codemirror-statemachine-static.html");
if (fileIndex > 0) baseUrl = baseUrl.slice(0, fileIndex)
require.config({
baseUrl: baseUrl,
paths: {
"jquery": "webjars/jquery/3.6.0/jquery.min",
"xtext/xtext-codemirror": "xtext/@xtext-version-placeholder@/xtext-codemirror",
},
packages: [{
name: "codemirror",
location: "webjars/codemirror/5.41.0",
main: "lib/codemirror"
}]
});
require(["xtext/cm-mode-statemachine", "xtext/xtext-codemirror"], function(mode, xtext) {
xtext.createEditor({
baseUrl: baseUrl,
});
});
```
--------------------------------
### Abstract Multimap Implementation Setup
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.common.types.eclipse.tests/testdata/org/eclipse/xtext/common/types/testSetups/Bug438740.java.txt
This abstract class serves as a base for testing Multimap implementations, featuring nested abstract classes for collections and iterators. It is part of the test setup for Bug 438740.
```java
abstract class Bug438740 implements Multimap {
abstract class Coll extends AbstractCollection {
Collection delegate;
Coll(K key, Collection delegate,
Coll ancestor) {
this.delegate = delegate;
}
abstract class Iter implements Iterator {
Iter() {
}
Iter(Iterator delegateIterator) {
}
}
}
}
```
--------------------------------
### Xtend Extension Methods Example
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtend.doc/contents/202_xtend_classes_members.html
Demonstrates how to use the 'extension' keyword to make instance methods of a field available as extension methods on another object. This allows for a more fluent API by calling methods directly on the object, which are then dispatched to the extension provider.
```xtend
interface EntityPersistence {
public save(Entity e)
public update(Entity e)
public delete(Entity e)
}
class MyServlet {
extension EntityPersistence ep = Factory.get(EntityPersistence)
...
}
val Person person = ...
person.save // calls ep.save(person)
person.name = 'Horst'
person.update // calls ep.update(person)
person.delete // calls ep.delete(person)
```
--------------------------------
### Left-Recursive Grammar Rule
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/301_grammarlanguage.html
This is an example of a left-recursive grammar rule that is not allowed in LL-based grammars.
```xtext
Expression:
Expression '+' Expression |
'(' Expression ')' |
INT;
```
--------------------------------
### Xtend Language Basics: Literals, Collections, and Control Flow
Source: https://context7.com/eclipse-xtext/xtext/llms.txt
Demonstrates Xtend's immutable and mutable collection literals, type inference, extension methods, expression-based if/switch, and for-range loops. Also shows a chained collection pipeline example.
```xtend
// Literals, operators, and type inference
val list = #['Hello', 'World'] // immutable List
val set = #{1, 3, 5} // immutable Set
val map = #{'one' -> 1, 'two' -> 2} // immutable Map
// Extension methods on collections via lambdas
val upper = list.map[toUpperCase].head // => "HELLO"
val big = set.filter[it >= 3].size // => 2
// Mutable collections via factory methods
val mutableList = newArrayList
mutableList.add("Foo")
// if as an expression
val label = if ('foo' != 'BAR'.toLowerCase) 'match' else 'no-match' // => "match"
// switch with type guards (safe instanceof cascade)
val Object obj = 'a string'
val kind = switch obj {
Number : 'number'
String : 'string'
} // => "string"
// for..range loop
var sum = 0
for (i : 1 .. 5) { sum += i } // sum == 15
// Chained collection pipeline (from Movies example)
// Find year of best-rated movie from the 1980s
val bestYear = movies
.filter[(1980..1989).contains(year)]
.maxBy[rating]
.year
```
--------------------------------
### Initialize Xtext-Web Editor with State Machine Syntax
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.web.example.jetty/src/main/webapp/orion-statemachine-autogenerate.html
Configures RequireJS and initializes the Xtext-Web editor for state machine syntax, setting up save and revert functionality.
```javascript
var baseUrl = window.location.pathname;
var fileIndex = baseUrl.indexOf("orion-statemachine-autogenerate.html");
if (fileIndex > 0) baseUrl = baseUrl.slice(0, fileIndex)
require.config({
baseUrl: baseUrl,
paths: {
'text': 'webjars/requirejs-text/2.0.15/text',
'jquery': 'webjars/jquery/3.6.0/jquery.min',
"xtext/xtext-orion": "xtext/@xtext-version-placeholder@/xtext-orion",
}
});
require(["orion/code_edit/built-codeEdit-amd"], function() {
require(['xtext/xtext-orion'], function(xtext) {
xtext.createEditor({
syntaxDefinition: "xtext/statemachine-syntax",
baseUrl: baseUrl,
}).done(function(editorViewer) {
var xtextServices = editorViewer.xtextServices;
$('#save-button').click(function() {
xtextServices.saveResource();
});
$('#revert-button').click(function() {
xtextServices.revertResource();
});
xtextServices.successListeners.push(function(serviceType, result) {
if (serviceType == 'validate' && result.issues.every(function(issue) {issue.severity != 'error'})) {
// Option 1: use a simple GET request
$('#generator-result').html('');
// Option 2: use the 'generate' function
xtextServices.generate({artifactId: '/hidden.txt'}).done(function(result) {
console.log(result);
});
}
});
});
});
});
```
--------------------------------
### CodeMirror Editor Integration
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/330_web_support.html
Configuration example for integrating Xtext with the CodeMirror editor using RequireJS and WebJars.
```APIDOC
## CodeMirror Editor Integration
### Description
Configuration for loading Xtext with the CodeMirror editor. Uses WebJars for dependencies and specifies CodeMirror package location.
### Code Example
```javascript
require.config({
paths: {
"jquery": "webjars/jquery//jquery.min",
"xtext/xtext-codemirror": "xtext//xtext-codemirror"
},
packages: [{
name: "codemirror",
location: "webjars/codemirror/",
main: "lib/codemirror"
}]
});
require(["xtext/xtext-codemirror"], function(xtext) {
xtext.createEditor();
});
```
```
--------------------------------
### Xtend Hello World Program
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtend.doc/contents/101_gettingstarted.html
A basic 'Hello World' program in Xtend, showcasing the 'def' keyword for method declaration and standard class/main method structure.
```xtend
class HelloWorld {
def static void main(String[] args) {
println("Hello World")
}
}
```
--------------------------------
### Ace Editor Integration
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/330_web_support.html
Configuration example for integrating Xtext with the Ace editor using RequireJS and WebJars.
```APIDOC
## Ace Editor Integration
### Description
Configuration for loading Xtext with the Ace editor. Uses WebJars for dependencies.
### Code Example
```javascript
require.config({
paths: {
"jquery": "webjars/jquery//jquery.min",
"ace/ext/language_tools": "webjars/ace//src/ext-language_tools",
"xtext/xtext-ace": "xtext//xtext-ace"
}
});
require(["webjars/ace//src/ace"], function() {
require(["xtext/xtext-ace"], function(xtext) {
xtext.createEditor();
});
});
```
```
--------------------------------
### Orion Editor Integration
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/330_web_support.html
Configuration example for integrating Xtext with the Orion editor using RequireJS and WebJars.
```APIDOC
## Orion Editor Integration
### Description
Configuration for loading Xtext with the Orion editor. Requires manual download of Orion as it's not available on WebJars.
### Code Example
```javascript
require.config({
paths: {
"text": "webjars/requirejs-text//text",
"jquery": "webjars/jquery//jquery.min",
"xtext/xtext-orion": "xtext//xtext-orion"
}
});
require(["orion/code_edit/built-codeEdit-amd"], function() {
require(["xtext/xtext-orion"], function(xtext) {
xtext.createEditor();
});
});
```
```
--------------------------------
### Using Imported Static Extension Method
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtend.doc/contents/202_xtend_classes_members.html
Demonstrates calling the imported `singletonList` extension method on an instance of `MyClass`.
```xtend
new MyClass().singletonList()
// calls Collections.singletonList(new MyClass())
```
--------------------------------
### Define a Simple Java Class (POJO)
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/302_configuration.html
A plain Java object used as an example for MWE2 configuration.
```java
package com.mycompany;
public class Person {
private String name;
public void setName(String name) {
this.name = name;
}
private final List children = new ArrayList();
public void addChild(Person child) {
this.children.add(child);
}
}
```
--------------------------------
### Grammar Definition for Scoping Example
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/303_runtime_concepts.html
Defines a simple grammar with a cross-reference ('superElement') that requires custom scoping logic.
```xtext
grammar org.xtext.example.mydsl.MyScopingDsl with
org.eclipse.xtext.common.Terminals
generate myDsl "http://www.xtext.org/example/mydsl/MyScopingDsl"
Root:
elements+=Element;
Element:
'element' name=ID ('extends' superElement=[Element])?;
```
--------------------------------
### Equivalent Java Code for MWE2 Object Creation
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/302_configuration.html
This main method demonstrates the object creation and configuration that MWE2 performs declaratively.
```java
package com.mycompany;
public class CreatePersons {
public static void main(String[] args) {
Person grandpa = new Person();
grandpa.setName("Grandpa");
Person father = new Person();
father.setName("Father");
grandpa.addChild(father);
Person son = new Person();
son.setName("Son");
father.addChild(son);
}
}
```
--------------------------------
### Object Initialization with 'with' Operator
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/305_xbase.html
Demonstrates the 'with' operator (=>) for concise object initialization using lambda expressions and the implicit 'it' parameter.
```xbase
val person = new Person => [
firstName = 'John'
lastName = 'Coltrane'
]
```
--------------------------------
### Left Recursive Grammar for Expressions
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/307_special_languages.html
An example of a left-recursive grammar for arithmetic expressions, which is not suitable for Xtext's parser.
```Xtext
Expression :
Expression '+' Expression |
Expression '*' Expression |
INT;
```
--------------------------------
### Xtext Grammar Definition
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/303_runtime_concepts.html
Example Xtext grammar for defining an Entity with a mandatory quoted name and an optional short name.
```xtext
grammar org.xtext.example.mydsl.MyDsl with org.eclipse.xtext.common.Terminals
generate myDsl "http://www.xtext.org/example/mydsl/MyDsl"
Model:
entities+=Entity*;
Entity:
'Entity' name=QUOTED_NAME shortName=ID?;
terminal QUOTED_NAME:
'\'' ID (ID | ' ')* '\'';
```
--------------------------------
### Classpath Scope Hierarchy Example
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/303_runtime_concepts.html
Demonstrates a typical classpath scope hierarchy, showing the order in which class path entries are considered. This is relevant for understanding how Xtext resolves types from external libraries.
```plaintext
classpathScope{stuff from bin/}
-> classpathScope{stuff from foo.jar/}
-> ...
-> classpathScope{stuff from JRE System Library}
-> NULLSCOPE{}
```
--------------------------------
### Xtend Block Expression Example 1
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtend.doc/contents/203_xtend_expressions.html
Execute a sequence of expressions imperatively. The value of the last expression is the result of the block.
```xtend
{
doSideEffect("foo")
result
}
```
--------------------------------
### Xtend While Loop
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtend.doc/contents/203_xtend_expressions.html
Demonstrates the syntax for a while loop, which repeatedly executes an expression as long as the predicate evaluates to true.
```xtend
while (true) {
doSideEffect("foo")
}
```
```xtend
while ((i=i+1) < max)
doSideEffect("foo")
```
--------------------------------
### Java Constructor Definition
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.common.types.eclipse.tests/testdata/org/eclipse/xtext/common/types/testSetups/InitializerWithConstructor.java.txt
Defines a constructor for a Java class. This example shows a protected constructor that calls the superclass constructor.
```java
protected InitializerWithConstructor(String unused) {
super();
}
```
--------------------------------
### canReach Method
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.xbase.testdata/src/org/eclipse/xtext/common/types/testSetups/Bug347739.java.txt
Checks if a given state is reachable from a starting state with a specific stack configuration. Used in PDA analysis.
```java
public static boolean canReach(Bug347739ThreeTypeParams pda, STATE state,
Iterator stack, Bug347739OneTypeParam matches, Bug347739OneTypeParam canPass) {
return true;
}
```
--------------------------------
### Xbase Lambda Expression Examples
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/305_xbase.html
Illustrates different ways to define lambda expressions in Xbase, including those without parameters, with explicit argument types, and with inferred argument types.
```xbase
[ | "foo" ] // lambda expression without parameters
```
```xbase
[ String s | s.toUpperCase() ] // explicit argument type
```
```xbase
[ a, b, c | a+b+c ] // inferred argument types
```
--------------------------------
### Check if Expression is Multiline
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtend.performance.tests/testData/org/eclipse/xtext/xbase/formatting/XbaseFormatter2.xtend.txt
Determines if an XExpression spans multiple lines based on its node's start and end lines.
```xtend
def protected boolean isMultiline(XExpression expression, FormattableDocument doc) {
val node = expression.nodeForEObject
return node != null && node.startLine != node.endLine
}
```
--------------------------------
### Configure Standard Xtext Project
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/302_configuration.html
Use `StandardProjectConfig` to set up a typical Xtext project with default values. Specify `baseName`, `rootPath`, and enable specific subprojects like `eclipsePlugin`. `createEclipseMetaData` is also shown.
```xtext
project = StandardProjectConfig {
baseName = "org.example.domainmodel"
rootPath = rootPath
eclipsePlugin = {
enabled = true
}
createEclipseMetaData = true
}
```
--------------------------------
### Initialize Xtext-Web Editor
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.web.example.jetty/src/main/webapp/ace-statemachine-static.html
Loads the Xtext ACE editor module and creates an editor instance, associating it with the 'xtext/ace-mode-statemachine' syntax definition. This enables syntax highlighting and other editor features for the state machine DSL.
```javascript
require(["webjars/ace/1.3.3/src/ace"], function() {
require(["xtext/xtext-ace"], function(xtext) {
xtext.createEditor({
syntaxDefinition: "xtext/ace-mode-statemachine",
baseUrl: baseUrl
});
});
});
```
--------------------------------
### Xtend Constructor Declaration
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtend.doc/contents/202_xtend_classes_members.html
Example of Xtend constructors, using the 'new' keyword and demonstrating delegation to other constructors with 'this(args...)'.
```xtend
class MyClass extends AnotherClass {
new(String s) {
super(s)
}
new() {
this("default")
}
}
```
--------------------------------
### StandaloneSetup for Imported Ecore Models
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/303_runtime_concepts.html
Initialize imported Ecore models within the doSetup() method of your language's StandaloneSetup class. This ensures EMF registration for models not generated by Xtext.
```java
public class MyLanguageStandaloneSetup extends MyLanguageStandaloneSetupGenerated {
public static void doSetup() {
if (!EPackage.Registry.INSTANCE.containsKey(MyPackage.eNS_URI))
EPackage.Registry.INSTANCE.put(MyPackage.eNS_URI, MyPackage.eINSTANCE);
new MyLanguageStandaloneSetup().createInjectorAndDoEMFRegistration();
}
}
```
--------------------------------
### Entry Rule for Entity
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.tests/src/org/eclipse/xtext/generator/parser/InternalParserExample.java.txt
Defines the entry point for parsing an 'Entity' rule. It ensures proper setup and recovery mechanisms are in place.
```Java
// $ANTLR start entryRuleEntity
// ../org.eclipse.xtext.example.domainmodel.ui/src-gen/org/eclipse/xtext/example/contentassist/antlr/internal/InternalDomainmodel.g:223:1: entryRuleEntity : ruleEntity EOF ;
public final void entryRuleEntity() throws RecognitionException {
try {
// ../org.eclipse.xtext.example.domainmodel.ui/src-gen/org/eclipse/xtext/example/contentassist/antlr/internal/InternalDomainmodel.g:223:17: ( ruleEntity EOF )
// ../org.eclipse.xtext.example.domainmodel.ui/src-gen/org/eclipse/xtext/example/contentassist/antlr/internal/InternalDomainmodel.g:224:1: ruleEntity EOF
{
if ( backtracking==0 ) {
before(grammarAccess.getEntityRule());
}
pushFollow(FOLLOW_ruleEntity_in_entryRuleEntity427);
ruleEntity();
_fsp--;
if (failed) return ;
if ( backtracking==0 ) {
after(grammarAccess.getEntityRule());
}
match(input,EOF,FOLLOW_EOF_in_entryRuleEntity434); if (failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end entryRuleEntity
```
--------------------------------
### Builder Syntax with Lambda Expression
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/305_xbase.html
Demonstrates calling a Java method with a lambda expression as the last argument, enabling builder-like syntax.
```xbase
foo(42) [ String s | s.toUpperCase ]
```
--------------------------------
### Lexer Rule for Identifiers (InternalLexerExample.java)
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.tests/src/org/eclipse/xtext/generator/parser/InternalLexerExample.java.txt
Defines the pattern for recognizing identifiers, which can optionally start with '^' and are followed by alphanumeric characters or underscores.
```Java
// ../org.eclipse.xtext.example.domainmodel.ui/src-gen/org/eclipse/xtext/example/contentassist/antlr/internal/InternalDomainmodel.g:1957:11: ( '^' )? ( 'a' .. 'z' | 'A' .. 'Z' | '_' ) ( 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' )*
{
// ../org.eclipse.xtext.example.domainmodel.ui/src-gen/org/eclipse/xtext/example/contentassist/antlr/internal/InternalDomainmodel.g:1957:11: ( '^' )?
int alt1=2;
int LA1_0 = input.LA(1);
if ( (LA1_0=='^') ) {
alt1=1;
}
switch (alt1) {
case 1 :
// ../org.eclipse.xtext.example.domainmodel.ui/src-gen/org/eclipse/xtext/example/contentassist/antlr/internal/InternalDomainmodel.g:1957:11: '^'
{
match('^');
}
break;
}
if ( (input.LA(1)>='A' && input.LA(1)<='Z')||input.LA(1)=='_'||(input.LA(1)>='a' && input.LA(1)<='z') ) {
input.consume();
}
else {
MismatchedSetException mse =
new MismatchedSetException(null,input);
recover(mse); throw mse;
}
// ../org.eclipse.xtext.example.domainmodel.ui/src-gen/org/eclipse/xtext/example/contentassist/antlr/internal/InternalDomainmodel.g:1957:40: ( 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' )*
loop2:
do {
int alt2=2;
int LA2_0 = input.LA(1);
if ( ((LA2_0>='0' && LA2_0<='9')||(LA2_0>='A' && LA2_0<='Z')||LA2_0=='_'||(LA2_0>='a' && LA2_0<='z')) ) {
alt2=1;
}
switch (alt2) {
case 1 :
// ../org.eclipse.xtext.example.domainmodel.ui/src-gen/org/eclipse/xtext/example/contentassist/antlr/internal/InternalDomainmodel.g:1957:40: ( 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' )
{
if ( (input.LA(1)>='0' && input.LA(1)<='9')||(input.LA(1)>='A' && input.LA(1)<='Z')||input.LA(1)=='_'||(input.LA(1)>='a' && input.LA(1)<='z') ) {
input.consume();
}
else {
MismatchedSetException mse =
new MismatchedSetException(null,input);
recover(mse); throw mse;
}
}
break;
default :
break loop2;
}
} while (true);
}
this.type = _type;
}
finally {
}
}
// $ANTLR end RULE_ID
```
--------------------------------
### Initialize Xtext-Web Editor with CodeMirror
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.web.example.jetty/src/main/webapp/codemirror-statemachine-resource.html
Configures RequireJS and initializes the Xtext-Web editor with CodeMirror for state machine resources. Includes event handlers for save, revert, generate, resource change, and disable actions.
```javascript
var baseUrl = window.location.pathname;
var fileIndex = baseUrl.indexOf("codemirror-statemachine-resource.html");
if (fileIndex > 0) baseUrl = baseUrl.slice(0, fileIndex)
require.config({
baseUrl: baseUrl,
paths: {
"jquery": "webjars/jquery/3.6.0/jquery.min",
"xtext/xtext-codemirror": "xtext/@xtext-version-placeholder@/xtext-codemirror",
},
packages: [{
name: "codemirror",
location: "webjars/codemirror/5.41.0",
main: "lib/codemirror"
}]
});
require(["xtext/cm-mode-statemachine", "xtext/xtext-codemirror"], function(mode, xtext) {
var editor = xtext.createEditor({
baseUrl: baseUrl,
});
$("#save-button").click(function() {
editor.xtextServices.saveResource();
});
$("#revert-button").click(function() {
editor.xtextServices.revertResource();
});
$("#generate-button").click(function() {
window.open('http://' + location.host + baseUrl + 'xtext-service/generate?resource=' + editor.xtextServices.options.resourceId);
});
$("#change-resource").change(function() {
var resourceId = $("#change-resource option:selected").attr("value");
editor.xtextServices.serviceBuilder.changeResource(resourceId);
});
$("#disable-button").click(function() {
xtext.removeServices(editor);
});
});
```
--------------------------------
### AST Node Instantiation and Value Assignment (Java Equivalent)
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/307_special_languages.html
Illustrates the Java-like logic for instantiating an AST node and assigning a value from a parsed INT rule. This is generated by Xtext.
```java
// value=INT
if (current == null)
current = new NumberLiteral();
current.setValue(ruleINT());
...
```
--------------------------------
### Lexer Rule for Single-line Comments
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.tests/src/org/eclipse/xtext/generator/parser/InternalLexerExample2.java.txt
Defines the lexer rule for recognizing single-line comments, which start with '//' and continue to the end of the line.
```Java
// $ANTLR start RULE_SL_COMMENT
public final void mRULE_SL_COMMENT() throws RecognitionException {
try {
int _type = RULE_SL_COMMENT;
// ../org.eclipse.xtext.generator.tests/src-gen/org/eclipse/xtext/grammarinheritance/parser/antlr/internal/InternalAbstractTestLanguage.g:234:17: ( '//' (~ ( ( '\n' | '\r' ) ) )* ( ( '\r' )? '\n' )? )
// ../org.eclipse.xtext.generator.tests/src-gen/org/eclipse/xtext/grammarinheritance/parser/antlr/internal/InternalAbstractTestLanguage.g:234:19: '//' (~ ( ( '\n' | '\r' ) ) )* ( ( '\r' )? '\n' )?
{
match("//");
// ../org.eclipse.xtext.generator.tests/src-gen/org/eclipse/xtext/grammarinheritance/parser/antlr/internal/InternalAbstractTestLanguage.g:234:24: (~ ( ( '\n' | '\r' ) ) )*
loop8:
do {
int alt8=2;
int LA8_0 = input.LA(1);
if ( ((LA8_0>='\u0000' && LA8_0<='\t')||(LA8_0>='\u000B' && LA8_0<='\f')||(LA8_0>='\u000E' && LA8_0<='\uFFFE')) ) {
alt8=1;
}
switch (alt8) {
case 1 :
// ../org.eclipse.xtext.generator.tests/src-gen/org/eclipse/xtext/grammarinheritance/parser/antlr/internal/InternalAbstractTestLanguage.g:234:24: ~ ( ( '\n' | '\r' ) )
{
if ( (input.LA(1)>='\u0000' && input.LA(1)<='\t')||(input.LA(1)>='\u000B' && input.LA(1)<='\f')||(input.LA(1)>='\u000E' && input.LA(1)<='\uFFFE') ) {
input.consume();
}
else {
MismatchedSetException mse =
new MismatchedSetException(null,input);
recover(mse); throw mse;
}
}
break;
default :
break loop8;
}
} while (true);
// ../org.eclipse.xtext.generator.tests/src-gen/org/eclipse/xtext/grammarinheritance/parser/antlr/internal/InternalAbstractTestLanguage.g:234:47: ( ( '\r' )? '\n' )?
loop9: do {
int alt9=2;
int LA9_0 = input.LA(1);
if ( (LA9_0=='\n'||LA9_0=='\r') ) {
alt9=1;
}
switch (alt9) {
case 1 :
// ../org.eclipse.xtext.generator.tests/src-gen/org/eclipse/xtext/grammarinheritance/parser/antlr/internal/InternalAbstractTestLanguage.g:234:47: ( ( '\r' )? '\n' )
{
if ( input.LA(1)=='\n'||input.LA(1)=='\r' ) {
input.consume();
}
else {
MismatchedTokenException mre = new MismatchedTokenException(null,input);
recover(mre); throw mre;
}
}
break;
default :
break loop9;
}
} while (true);
}
this.type = _type;
}
finally {
}
}
// $ANTLR end RULE_SL_COMMENT
```
--------------------------------
### Configure File Wizard Generation
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/310_eclipse_support.html
Enable the generation of a wizard for new DSL files by setting 'generate' to true in the MWE2 file's language section.
```groovy
fileWizard = {
generate = true
}
```
--------------------------------
### Xtend Throwing Exceptions
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtend.doc/contents/203_xtend_expressions.html
Demonstrates the syntax for throwing exceptions in Xtend, which is identical to Java.
```xtend
{
...
if (myList.isEmpty)
throw new IllegalArgumentException("the list must not be empty")
...
}
```
--------------------------------
### Xtext Grammar Rule: DataType Definition
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/102_domainmodelwalkthrough.html
Defines a DataType, which starts with the keyword 'datatype' followed by an identifier assigned to the 'name' feature.
```xtext
DataType:
'datatype' name=ID;
```
--------------------------------
### Configure Default Highlighting Styles
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/310_eclipse_support.html
Implement IHighlightingConfiguration to register default styles for elements like keywords and comments. This populates the preferences page and initializes the ITextAttributeProvider.
```java
public class DefaultHighlightingConfiguration
implements IHighlightingConfiguration {
public static final String KEYWORD_ID = "keyword";
public static final String COMMENT_ID = "comment";
public void configure(IHighlightingConfigurationAcceptor acceptor) {
acceptor.acceptDefaultHighlighting(
KEYWORD_ID, "Keyword", keywordTextStyle());
acceptor.acceptDefaultHighlighting(COMMENT_ID, "Comment", commentTextStyle();
}
public TextStyle keywordTextStyle() {
TextStyle textStyle = new TextStyle();
textStyle.setColor(new RGB(127, 0, 85));
textStyle.setStyle(SWT.BOLD);
return textStyle;
}
}
```
--------------------------------
### Get Binary Operation Precedence
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtend.performance.tests/testData/org/eclipse/xtext/xbase/formatting/XbaseFormatter2.xtend.txt
Retrieves the grammar rule for a binary operation's feature, used to determine operator precedence.
```xtend
def protected AbstractRule binaryOperationPrecedence(EObject op) {
val node = op.nodeForFeature(XABSTRACT_FEATURE_CALL__FEATURE)
if (node != null && node.grammarElement instanceof CrossReference) {
val terminal = (node.grammarElement as CrossReference).terminal
if (terminal instanceof RuleCall)
return (terminal as RuleCall).rule
}
}
```
--------------------------------
### Get Text Around Offset
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtend.performance.tests/testData/org/eclipse/xtext/xbase/formatting/FormattableDocument.xtend.txt
Retrieves the text snippet surrounding a given FormattingData offset, including up to five lines before and after the target.
```xtend
def protected Pair getTextAround(FormattingData data1) {
val back = (0..5).fold(data1.offset, [last, i| if(last > 0) document.lastIndexOf("\n", last - 1) else -1 ])
val forward = (0..5).fold(data1.offset, [last, i| if(last > 0) document.indexOf("\n", last + 1) else -1 ])
val fiveLinesBackOffset = if(back >= 0) back else 0
val fiveLinesForwardOffset = if(forward >= 0) forward else document.length
val prefix = document.substring(fiveLinesBackOffset, data1.offset)
val postfix = document.substring(data1.offset + data1.length, fiveLinesForwardOffset)
prefix -> postfix
}
```
--------------------------------
### Local Extension Method Definition and Call
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtend.doc/contents/202_xtend_classes_members.html
Defines a local extension method `doSomething` and then calls it using extension syntax.
```xtend
class MyClass {
def doSomething(Object obj) {
// do something with obj
}
def extensionCall(Object obj) {
obj.doSomething() // calls this.doSomething(obj)
}
}
```
--------------------------------
### Programmatic Resource Validation in Java
Source: https://github.com/eclipse-xtext/xtext/blob/main/org.eclipse.xtext.doc/contents/303_runtime_concepts.html
Validate a resource programmatically using IResourceValidator. This example demonstrates iterating through issues and printing their severity and message.
```Java
@Inject IResourceValidator resourceValidator;
public void checkResource(Resource resource) {
List issues = resourceValidator.validate(resource,
CheckMode.ALL, CancelIndicator.NullImpl);
for (Issue issue: issues) {
switch (issue.getSeverity()) {
case ERROR:
System.out.println("ERROR: " + issue.getMessage());
break;
case WARNING:
System.out.println("WARNING: " + issue.getMessage());
break;
default: // do nothing
}
}
}
```