Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Implementing Domain-Specific Languages with Xtext and Xtend
Implementing Domain-Specific Languages with Xtext and Xtend

Implementing Domain-Specific Languages with Xtext and Xtend: Learn how to implement a DSL with Xtext and Xtend using easy-to-understand examples and best practices. , Second Edition

eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Implementing Domain-Specific Languages with Xtext and Xtend

Chapter 1. Implementing a DSL

In this chapter, we will provide a brief introduction on Domain-Specific Languages (DSLs) and the issues concerning their implementation, especially in the context of an Integrated Development Environment (IDE). In the initial part of the chapter, we will sketch the main tasks for implementing a DSL and its integration in an IDE. At the end of the chapter, we will also show you how to install Xtext and will give you a glimpse of what you can do with Xtext. It is an Eclipse framework for the development of DSLs that covers all aspects of a language implementation, including its integration in the Eclipse IDE.

This chapter will cover the following topics:

  • An introduction to DSLs
  • The main steps for implementing a DSL
  • The typical IDE tooling for a DSL
  • The very first demo of Xtext

Domain-Specific Languages

Domain Specific Languages, abbreviated to DSLs, are programming languages or specification languages that target a specific problem domain. They are not meant to provide features for solving all kinds of problems. You probably will not be able to implement all programs you can implement with, for instance, Java or C, which are known as General Purpose Languages (GPL). On the other hand, if your problem's domain is covered by a particular DSL, you will be able to solve that problem easier and faster using that DSL instead of a GPL.

Some examples of DSLs are SQL (for querying relational databases), Mathematica (for symbolic mathematics), HTML, and many others you have probably used in the past. A program or specification written in a DSL can then be interpreted or compiled into a GPL. In other cases, the specification can represent simple data that will be processed by other systems.

For a wider introduction to DSLs, you should refer to the books Fowler 2010, Ghosh 2010, and Voelter 2013.

Need for a new language

You may now wonder why you need to introduce a new DSL for describing specific data, models, or applications, instead of using XML, which allows you to describe data in a machine in human-readable form. There are so many tools now that allow you to read, write, or exchange data in XML without having to parse such data according to a specific syntax such as an XML Schema Definition (XSD). There is basically only one syntax (the XML tag syntax) to learn, and then all data can be represented with XML.

Of course, this is also a matter of taste, but many people, including myself, find that XML is surely machine readable, but not so much human-readable. It is fine to exchange data in XML, if the data in that format is produced by a program. But often, people (programmers and users) are requested to specify data in XML manually; for instance, for specifying an application's specific configuration.

If writing an XML file can be a pain, reading it back can be even worse. In fact, XML tends to be verbose, and it fills documents with too much additional syntax noise due to all the tags. The tags help a computer to process XML, but they surely distract people when they have to read and write XML files.

Consider a very simple example of an XML file describing people:

<people>
  <person>
    <name>James</name>
    <surname>Smith</surname>
    <age>50</age>
  </person>
  <person employed="true">
    <name>John</name>
    <surname>Anderson</surname>
    <age>40</age>
  </person>
</people>

It is not straightforward for a human to grasp the actual information about a person from such a specification—a human is distracted by all those tags. Also, writing such a specification may be a burden. An editor might help with some syntax highlighting and early user feedback concerning validation, but still there are too many additional details.

JSON (JavaScript Object Notation) could be used as a less verbose alternative to XML. However, the burden of manually reading, writing, and maintaining specifications in JSON is only slightly reduced with respect to XML.

The following version is written in an ad hoc DSL:

person {
  name=James
  surname=Smith
  age=50
}
person employed {
  name=John
  surname=Anderson
  age=40
}

This contains less noise, and the information is easier to grasp. We could even do better and have a more compact specification:

James Smith (50)
John Anderson (40) employed

After all, since this DSL only lets users describe the name and age of people, why not design it to make the description both compact, easy to read and write?

Implementing a DSL

For the end user, using a DSL is surely easier than writing XML code. However, the developer of the DSL is now left with the task of implementing it.

Implementing a DSL means developing a program that is able to read text written in that DSL, parse it, process it, and then possibly interpret it or generate code in another language. Depending on the aim of the DSL, this may require several phases, but most of these phases are typical of all implementations.

In this section, we only sketch the main aspects of implementing a DSL. For a deeper introduction to language implementations and the theory behind, we refer the interested reader to the book Aho et al. 2007.

Note

From now on, throughout the book, we will not distinguish, unless strictly required by the context, between DSL and programming language.

Parsing

First of all, when reading a program written in a programming language, the implementation has to make sure that the program respects the syntax of that language.

To this aim, we need to break the program into tokens. Each token is a single atomic element of the language; this can be a keyword (such as class in Java), an identifier (such as a Java class name), or a literal, that is, a fixed value. Examples of literals are string literals, typically surrounded by quotes, integer literals, and boolean literals (for example, true and false). Other kinds of tokens are operators (such as arithmetic and comparison operators) and separators (such as parentheses and terminating semicolons).

For instance, in the preceding example, employed is a keyword, the parentheses are separators, James is an identifier, and 50 is an integer literal.

The process of converting a sequence of characters into a sequence of tokens is called lexical analysis, and the program or procedure that performs such analysis is called a lexical analyzer, lexer, or simply a scanner. This analysis is usually implemented by using regular expressions syntax.

Having the sequence of tokens from the input file is not enough, we must make sure that they form a valid statement in our language; that is, they respect the syntactic structure expected by the language. This phase is called parsing or syntactic analysis. The program or procedure that performs such analysis is called a parser.

Let's recall the DSL to describe the name and age of various people and a possible input text:

James Smith (50)
John Anderson (40) employed

In this example, each line of the input must respect the following structure:

  • two identifiers
  • the separator (
  • one integer literal
  • the separator )
  • the optional keyword employed

In our language, tokens are separated by white spaces, and lines are separated by a newline character.

You can now deduce that the parser relies on the lexer. In fact, the parser asks the lexer for tokens and tries to build valid statement of the language.

If you have never implemented a programming language, you might be scared at this point by the task of implementing a parser, for instance, in Java. You are probably right, since this is not easy. The DSL we just used as an example is very small and still it would require some effort to implement. What if your DSL has to deal also with, say, arithmetic expressions? In spite of their apparently simple structure, arithmetic expressions are recursive by their own nature; thus a parser implemented in Java would have to deal with recursion as well, and, in particular, it should avoid possible endless loops.

There are tools to deal with parsing so that you do not have to implement a parser by hand. In particular, there are DSLs to specify the grammar of the language, and from this specification, they automatically generate the code for the lexer and parser. For this reason, these tools are called parser generators or compiler-compilers. In this context, such specifications are called grammars. A grammar is a set of rules that describe the form of the elements that are valid according to the language syntax.

Here are some examples of tools for specifying grammars.

Bison and Flex (Levine 2009) are the most famous in the C context: from a high level specification of the syntactic structure (Bison) and lexical structure (Flex) of a language, they generate the parser and lexer in C, respectively. Bison is an implementation of Yacc (Yet Another Compiler-compiler, Brown et al. 1995), and there are variants for other languages as well, such as Racc for Ruby.

In the Java world, the most well-known is probably ANTLR (ANother Tool for Language Recognition) pronounced Antler, (see the book Parr 2007). This allows the programmer to specify the grammar of the language in one single file (without separating the syntactic and lexical specifications in different files), and then it automatically generates the parser in Java.

Just to have an idea of what the specification of grammars looks like in ANTLR, here is a very simplified grammar for an expression language for arithmetic expressions with sum and multiplication (as we will see in Chapter 9, Type Checking we cannot write a recursive rule such as the one shown in the following snippet):

expression
  : INT
  | expression '*' expression
  | expression '+' expression
;

Even if you do not understand all the details, it should be straightforward to get its meaning—an expression is either an integer literal or (recursively) two expressions with an operator in between (either * or +).

From such a specification, you automatically get the Java code that will parse such expressions.

The Abstract Syntax Tree (AST)

Parsing a program is only the first stage in a programming language implementation. Once the program is checked as correct from the syntactic point of view, the implementation will have to do something with the elements of the program.

First of all, the overall correctness of a program cannot always be determined during parsing. One of the correctness checks that cannot be performed during parsing is type checking, that is, checking that the program is correct with respect to types. For instance, in Java, you cannot assign a string value to an integer variable, or you can only assign instances of a variable's declared type or subclasses thereof.

Trying to embed type checking in a grammar specification could either make the specification more complex, or it could be simply impossible, since some type checks can be performed only when other program parts have already been parsed.

Type checking is part of the semantic analysis of a program. This often includes managing the symbol table, that is, for instance, handling the variables that are declared and that are visible only in specific parts of the program (think of fields in a Java class and their visibility in methods).

For these reasons, during parsing, we should also build a representation of the parsed program and store it in memory so that we can perform the semantic analysis on the memory representation without needing to parse the same text over and over again. A convenient representation in memory of a program is a tree structure called the Abstract Syntax Tree (AST). The AST represents the abstract syntactic structure of the program. Being abstract, the tree representation does not represent many details of the original program, such as grouping parentheses and formatting spaces. In this tree, each node represents a construct of the program.

Once the AST is stored in memory, we will not need to parse the program anymore, and we can perform all the additional semantic checks on the AST. If all the checks succeed, we can use the AST for the final stage of the implementation, which can be the interpretation of the program or code generation.

In order to build the AST, we need two additional things.

First of all, we need the code for representing the nodes of such a tree. If we are using Java, this means that we need to write some Java classes, typically one for each language construct. For instance, for the expression language, we might write one class for the integer literal and one for the binary expression. Remember that since the grammar is recursive, we need a base class for representing the abstract concept of an expression. For example:

public interface Expression { }

public class Literal implements Expression {
  Integer value;
  // constructor and set methods...
}

public class BinaryExpression implements Expression {
  Expression left, right;
  String operator;
  // constructor and set methods...
}

Then, we need to annotate the grammar specification with actions that construct the AST during the parsing. These actions are basically Java code blocks embedded in the grammar specification itself. The following is just an (simplified) example, and it does not necessarily respect the actual ANTLR syntax:

expression:
  INT { $value = new Literal(Integer.parseInt($INT.text)); }
| left=expression '*' right=expression {
  $value = new BinaryExpression($left.value, $right.value);
  $value.setOperator("*");
}
| left=expression '+' right=expression {
  $value = new BinaryExpression($left.value, $right.value);
  $value.setOperator("+");
}
;

IDE integration

Even if you have implemented your DSL, that is, the mechanisms to read, validate, and execute programs written in your DSL, your work cannot really be considered finished.

Nowadays, many programmers are accustomed to use powerful IDEs such as Eclipse. For this reason, a DSL should be shipped with good IDE support. This will increase the likelihood of your DSL being adopted and successful.

If your DSL is supported by all the powerful features in an IDE such as a syntax-aware editor, immediate feedback, incremental syntax checking, suggested corrections, auto-completion, and so on, then it will be easier to learn, use, and maintain.

In the following sections, we will see the most important features concerning IDE integration. In particular, we will assume Eclipse as the underlying IDE (since Xtext is mainly an Eclipse framework).

Syntax highlighting

The ability to see the program colored and formatted with different visual styles according to the elements of the language (for example, comments, keywords, strings, and so on) is not just cosmetic.

First of all, it gives immediate feedback concerning the syntactic correctness of what you are writing. For instance, if string constants (typically enclosed in quotes) are rendered as red, and you see that at some point in the editor the rest of your program is all red, you may soon get an idea that somewhere in between you forgot to insert the closing quotation mark.

Background validation

The programming cycle consisting of writing a program with a text editor, saving it, switching to the command line, running the compiler, and in the case of errors, shifting back to the text editor is surely not productive.

The programming environment should not let the programmer realize about errors too late. On the contrary, it should continuously check the program in the background while the programmer is writing, even if the current file has not been saved yet. The sooner the environment can tell the programmer about errors, the better it is. The longer it takes to realize that there is an error, the higher the cost in terms of time and mental effort to correct it.

Error markers

When your DSL parser and checker issue some errors, the programmer should not have to go to the console to discover such errors. Your implementation should highlight the parts of the program with errors directly in the editor by underlining (for instance, in red) only the parts that actually contain the errors. It should also put some error markers with an explicit message on the left of the editor in correspondence to the lines with errors, and should also fill the Problems view with all these errors. The programmer will then have the chance to easily spot the parts of the program that need to be fixed.

Content assist

Content assist is the feature that automatically, or on demand, provides suggestions on how to complete the statement/expression the programmer just typed. The proposed content should make sense in that specific program context in order to be effectively useful. For instance, when editing a Java file, after the keyword new, Eclipse proposes only Java class names as possible completions.

Again, this has to do with productivity. It does not make much sense to be forced to know all the syntax of a programming language by heart (especially for DSLs, which are not common languages such as Java), neither to know all the language's library classes and functions.

In Eclipse, the content assist is usually accessed with the keyboard shortcut Ctrl + Space bar.

Hyperlinking

Hyperlinking is a feature that makes it possible to navigate between references in a program. For example, from a variable to its declaration, or from a function, call to the function definition. If your DSL provides declarations of any sort (for instance, variable declarations or functions) and a way to refer to them (for instance, referring to a variable or invoking a declared function), then it should also provide Hperlinking from a token referring to a declaration. It should be possible to directly jump to the corresponding declaration. This is particularly useful if the declaration is in a file different from the one being edited. In Eclipse, this corresponds to pressing F3 or using Ctrl + click.

Hovering is a similar IDE feature—if you need some information about a specific program element, just hovering on that element should display a pop-up window with some documentation about that element.

Quickfixes

If the programmer made a mistake and your DSL implementation is able to fix it somehow, why not help the programmer by offering suggested quickfixes?

As an example, in the Eclipse Java editor, if you invoke a method that does not exist in the corresponding class, you are provided with some quickfixes. For instance, you are given a chance to fix this problem by actually creating such a method. This is typically implemented by a context menu available from the error marker.

In a test-driven scenario this is actually a methodology. Since you write tests before the actual code to test, you can simply write the test that invokes a method that does not exist yet, and then employ the quickfix to let the IDE create that method for you.

Outline

If a program is big, it is surely helpful to have an outline of it showing only the main components. Clicking on an element of the outline should bring the programmer directly to the corresponding source line in the editor.

Furthermore, the outline can also include other pieces of information such as types and structure that are not immediately understood by just looking at the program text. It is handy to have a view that is organized differently, perhaps sorted alphabetically to help with navigation.

Automatic build

In an Eclipse Java project, when you modify one Java file and save it, you know that Eclipse will automatically compile that file and, consequently, all the files that depend on the file you have just modified. There is no need to manually call the Java compiler.

Summarizing DSL implementation

In this section, we briefly and informally introduced the main steps to implement a DSL.

The IDE tooling can be implemented on top of Eclipse, which already provides a comprehensive framework.

Indeed, all the features of the Eclipse Java editor, which is part of the project JDT (Java Development Tools), are based on the Eclipse framework; thus, you can employ all the mechanisms offered by Eclipse to implement the same features for your own DSL.

Unfortunately, this task is not really easy, it certainly requires a deep knowledge of the internals of the Eclipse framework and lot of programming.

Finally, the parser and the checker will have to be connected to the Eclipse editing framework.

To make things a little bit worse, if you learned how to use all these tools (and this requires time) for implementing a DSL, when it comes to implement a new DSL, your existing knowledge will help you, but the time to implement the new DSL will still be huge.

All these learning and timing issues might push you to stick with XML, since the effort to produce a new DSL does not seem to be worthwhile. Indeed, there are many existing parsing and processing technologies for XML for different platforms that can be used, not to mention existing editors and IDE tooling for XML.

But what if there was a framework that lets you achieve all these tasks in a very quick way? What if this framework, once learned (yes, you cannot avoid learning new things), lets you implement new DSLs even quicker than the previous ones?

Enter Xtext

Xtext is an Eclipse framework for implementing programming languages and DSLs. It lets you implement languages quickly, and most of all, it covers all aspects of a complete language infrastructure, starting from the parser, code generator, or interpreter, up to a complete Eclipse IDE integration with all the typical IDE features we discussed previously.

The really amazing thing about Xtext is that, to start a DSL implementation, it only needs a grammar specification similar to ANTLR. You do not have to annotate the rules with actions to build the AST, since the creation of the AST (and the Java classes to store the AST) is handled automatically by Xtext itself. Starting from this specification, Xtext will automatically generate all the mechanisms sketched previously. It will generate the lexer, the parser, the AST model, the construction of the AST to represent the parsed program, and the Eclipse editor with all the IDE features!

Xtext comes with good and smart default implementations for all these aspects, and indeed most of these defaults will surely fit your needs. However, every single aspect can be customized by the language designer.

With all these features, Xtext is easy to use. It produces a professional result quickly, and it is even fun to use.

Since version 2.9.0, Xtext allows you to seamlessly port your DSL implementation and IDE tooling to IntelliJ and also to embed your DSL editor in a web application.

Installing Xtext

We will use the latest version of Eclipse. At the time of writing this book, the latest version of Eclipse is 4.6, named Neon. This version requires Java 8, so you will also have to make sure that you have Java 8 installed (see https://www.eclipse.org/downloads).

Xtext is an Eclipse framework; thus, it can be installed into your Eclipse installation using the update site as follows:

http://download.eclipse.org/modeling/tmf/xtext/updates/composite/releases

Just copy this URL into the dialog you get when you navigate to Help | Install New Software… in the textbox Work with and press Enter; after some time (required to contact the update site), you will be presented with lots of possible features to install, grouped by categories. Navigate to the Xtext category and select the Xtext Complete SDK feature.

Alternatively, an Eclipse distribution for DSL developers based on Xtext is also available from the main Eclipse downloads page, http://www.eclipse.org/downloads, called Eclipse IDE for Java and DSL Developers.

Using Xtext with IntelliJ will be discussed later in Chapter 11, Continuous Integration.

Note

At the time of writing this book, the current version of Xtext was 2.10, and this is the version used in this book.

Let's try Xtext

Hopefully, by now you should be eager to see for yourself what Xtext can do! In this section, we will briefly present the steps to write your first Xtext project and see what you get. Do not worry if you have no clue about most of the things you will see in this demo; they will be explained in the coming chapters.

Perform the following steps:

  1. Start Eclipse and navigate to File | New | Project…; in the dialog, navigate to the Xtext category and select Xtext Project. Refer to the following screenshot:
    Let's try Xtext
  2. In the next dialog, you can leave all the defaults and press Finish:
    Let's try Xtext
  3. The wizard will create several Eclipse projects and will open the file MyDsl.xtext, which is the grammar definition of the new DSL we are about to implement. You do not need to understand all the details of this file's contents for the moment. But if you understood how the grammar definitions work from the examples in the previous sections, you might have an idea of what this DSL does. It accepts lines starting with the keyword Hello followed by an identifier, then followed by !. Refer to the following screenshot:
    Let's try Xtext
  4. Now, it is time to start the first Xtext generation, so navigate to the file MyDsl.xtext in the org.xtext.example.mydsl project, right-click on it, and navigate to Run As | Generate Xtext Artifacts. The output of the generation will be shown in the Console view. You will note that a file will be downloaded from the Internet (thus, an Internet connection is required at this stage): ''downloading file from http://download.itemis.com/antlr-generator-3.2.0-patch.jar …''. This JAR will be downloaded and stored in your project once and for all as .antlr-generator-3.2.0-patch.jar (this file cannot be delivered together with Xtext installation: its license, BSD, is not compatible with the Eclipse Public License. Note however that such a jar is not needed at runtime). Note that since this file starts with a dot, it is automatically hidden from the Eclipse Package Explorer, just like the files .classpath and .project. You can make them visible by removing the filter .* resources in the Package Explorer. Wait for that file to be downloaded, and once you read Done in the console, the code generation phase is finished, and you will note that all the projects now contain much more code. Of course, you will have to wait for Eclipse to build the projects and you need to make sure that Project | Build Automatically is enabled.

    Tip

    If you want to avoid downloading this additional JAR, you need to install an additional feature into your Eclipse. Use this update site:

    http://download.itemis.com/updates/releases/

    Navigate to the Xtext Antlr category and install the feature Xtext Antlr SDK Feature. When you restarted Eclipse, if you create a new Xtext project from scratch and you run Generate Xtext Artifacts, then the additional JAR is not needed anymore.

  5. Your DSL implementation is now ready to be tested! Since what the wizard created for you are Eclipse plug-in projects, you need to start a new Eclipse instance to see your implementation in action. To do so, right-click on the org.xtext.example.mydsl project and navigate to Run As | Run Configurations…; in the dialog, select Eclipse Application, and then the New button to create a new launch configuration. Select it and click on Run. Refer to the following screenshot:
    Let's try Xtext

    Note

    If for any reason, you are using an earlier version than Java 8, before you start the new Eclipse instance, you must make sure that the launch configuration has enough PermGen size; otherwise, you will experience out of memory errors. You need to specify this VM argument in your launch configuration's Arguments tab, in the box VM arguments: -XX:MaxPermSize=256m.

  6. A new Eclipse instance will be run and a new workbench will appear (you may have to close the Welcome View). In this instance, your DSL implementation is available. Make sure you are using the Plug-in Development perspective or the Java perspective (you select the perspective with Window | Perspective | Open Perspective). Let's create a new General project (File | New | Project… | General | Project) and call it, for instance, sample. Inside this project, create a new file (File | New | File); the name of the file is not important, but the file extension must be mydsl (remember that this was the extension we chose in the Xtext new project wizard). As soon as the file is created, it will also be opened in a text editor, and you will be asked to convert the project to an Xtext project. You should accept that to make your DSL editor work correctly in Eclipse.
  7. Now, try all the things that Xtext created for you! The editor features syntax highlighting. You can see that by default Xtext DSLs are already set up to deal with Java-like comments such as // and /* */. You also get immediate error feedback with error markers in the relevant parts of the file, even if you have not saved the file yet. The error markers will also appear in the Problems view and in the corresponding file in the Package Explorer as you soon as you save the file. The outline view is automatically synchronized with the elements in the text editor. The editor also features code completion. All of these features have been automatically generated by Xtext starting from a grammar specification file:
    Let's try Xtext

This short demo should have convinced you about the powerful features of Xtext. Implementing the same features manually would require a huge amount of work. The result of the code generated by Xtext is so close to what Eclipse provides you for Java that your DSLs implemented in Xtext will be of high-quality and will provide the users with all the IDE tooling benefits.

The aim of this book

Xtext comes with a lot of nice documentation; you can find it in your Eclipse help system or online at https://www.eclipse.org/Xtext/documentation/.

This book aims at being complementary to the official documentation, trying to give you enough information to start being productive in implementing DSLs with Xtext. This book will try to teach you some methodologies and best practices when using Xtext, filling some bits of information that are not present in the official documentation. This book will also focus on automatic testing methodologies so that your DSL implementation will have a solid JUnit test suite. This will help you develop your Xtext DSL faster, with better confidence, and to keep it maintainable. Most chapters will have a tutorial nature and will provide you with enough information to make sure you understand what is going on. However, the official documentation should be kept at hand to learn more details about the mechanisms we will use throughout the book.

The source codes of the examples shown in this book are available online as a Git repository at https://github.com/LorenzoBettini/packtpub-xtext-book-2nd-examples.

We strongly suggest that you try to implement the examples yourself from scratch while reading the chapters of the book. Then, you can compare your implementation with the sources you find on the Git repository.

We will maintain the source code of the examples up-to-date with respect to future releases of Xtext. In the main README file at the preceding URL, we will also document possible updates to the source code and to the contents of the book itself.

We do not commit the generated files into the Git repository, for example, the src-gen and xtend-gen folders; thus, for each example in the repository, you will need to generate the Xtext artifacts yourself, using the procedure you used when creating the first project. In the README file, we also document an automated procedure, using the Eclipse Installer Oomph, for having an Eclipse with all the required plug-ins for developing with Xtext and a workspace with all the sources of the examples and the corresponding generated files.

Summary

In this chapter, we introduced the main concepts related to implementing a DSL, including IDE features. At this point, you should also have an idea of what Xtext can do for you.

In the next chapter, we will use an uncomplicated DSL to demonstrate the main mechanisms and to get you familiar with the Xtext development workflow.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Leverage the latest features of Xtext and Xtend to develop a domain-specific language.
  • Integrate Xtext with popular third party IDEs and get the best out of both worlds.
  • Discover how to test a DSL implementation and how to customize runtime and IDE aspects of the DSL

Description

Xtext is an open source Eclipse framework for implementing domain-specific languages together with IDE functionalities. It lets you implement languages really quickly; most of all, it covers all aspects of a complete language infrastructure, including the parser, code generator, interpreter, and more. This book will enable you to implement Domain Specific Languages (DSL) efficiently, together with their IDE tooling, with Xtext and Xtend. Opening with brief coverage of Xtext features involved in DSL implementation, including integration in an IDE, the book will then introduce you to Xtend as this language will be used in all the examples throughout the book. You will then explore the typical programming development workflow with Xtext when we modify the grammar of the DSL. Further, the Xtend programming language (a fully-featured Java-like language tightly integrated with Java) will be introduced. We then explain the main concepts of Xtext, such as validation, code generation, and customizations of runtime and UI aspects. You will have learned how to test a DSL implemented in Xtext with JUnit and will progress to advanced concepts such as type checking and scoping. You will then integrate the typical Continuous Integration systems built in to Xtext DSLs and familiarize yourself with Xbase. By the end of the book, you will manually maintain the EMF model for an Xtext DSL and will see how an Xtext DSL can also be used in IntelliJ.

Who is this book for?

This book is targeted at programmers and developers who want to create a domain-specific language with Xtext. They should have a basic familiarity with Eclipse and its functionality. Previous experience with compiler implementation can be helpful but is not necessary since this book will explain all the development stages of a DSL.

What you will learn

  • Write Xtext grammar for a DSL;
  • Use Xtend as an alternative to Java to write cleaner, easier-to-read, and more maintainable code;
  • Build your Xtext DSLs easily with Maven/Tycho and Gradle;
  • Write a code generator and an interpreter for a DSL;
  • Explore the Xtext scoping mechanism for symbol resolution;
  • Test most aspects of the DSL implementation with JUnit;
  • Understand best practices in DSL implementations with Xtext and Xtend;
  • Develop your Xtext DSLs using Continuous Integration mechanisms;
  • Use an Xtext editor in a web application
Estimated delivery fee Deliver to Latvia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 31, 2016
Length: 426 pages
Edition : 2nd
Language : English
ISBN-13 : 9781786464965
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Latvia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Publication date : Aug 31, 2016
Length: 426 pages
Edition : 2nd
Language : English
ISBN-13 : 9781786464965
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 120.97
Implementing Domain-Specific Languages with Xtext and Xtend
€36.99
Groovy for Domain-Specific Languages, Second Edition
€41.99
Eclipse Plug-in Development Beginner's Guide
€41.99
Total 120.97 Stars icon
Banner background image

Table of Contents

16 Chapters
1. Implementing a DSL Chevron down icon Chevron up icon
2. Creating Your First Xtext Language Chevron down icon Chevron up icon
3. Working with the Xtend Programming Language Chevron down icon Chevron up icon
4. Validation Chevron down icon Chevron up icon
5. Code Generation Chevron down icon Chevron up icon
6. Customizing Xtext Components Chevron down icon Chevron up icon
7. Testing Chevron down icon Chevron up icon
8. An Expression Language Chevron down icon Chevron up icon
9. Type Checking Chevron down icon Chevron up icon
10. Scoping Chevron down icon Chevron up icon
11. Continuous Integration Chevron down icon Chevron up icon
12. Xbase Chevron down icon Chevron up icon
13. Advanced Topics Chevron down icon Chevron up icon
14. Conclusions Chevron down icon Chevron up icon
A. Bibliography Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7
(7 Ratings)
5 star 71.4%
4 star 28.6%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




L. Milligan May 28, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
“A theory should be as simple as possible, and no simpler.” Albert Einstein is supposed to have said that. Well, maybe. But whoever said it was right. And it applies to software as well, which is why Domain Specific Language (DSL) is so often the right solution to a software engineering problem. A well-designed DSL can simplify the architecture of a system while also providing the expressive power to match the peculiar complexities of the problem domain.This book is more than a tutorial; it is an introductory course in Xtext, a tool that provides an amazing level of automation in the production of a DSL. Xtext leverages other technologies, like ANTLR and EMF, and then provides all of the features that make a language easy to use: syntax coloring, content assist, outlines, validation and problem tracking, cross-reference linking, code-generation and integration with the Eclipse build mechanism. Lorenzo Bettini has done the hard work of presenting all of the features of Xtext in depth and with clear and meaningful examples. He explains the many different ways that an Xtext DSL can be customized, including sections on Xtend, itself a DSL which is adept at traversing the EMF Abstract Syntax Tree, and on the Google Guice injection framework. Code generation, interpreted language, test-driven development, build and distribution are all covered with enough detail to be meaningful without overwhelming the reader.In sum, I highly recommend this book to software developers who are looking for the right introduction to a powerful tool. Like scientific theories and software, a book should be as simple as possible, and no simpler. This is such a book. John Milligan
Amazon Verified review Amazon
Andrew Oct 03, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
An excellent up-to-date reference book for the Xtext framework and, more in general, for DSL design and implementation principles.This new version of the book streamlined the already solid contents of the first edition. The author still pursues a step-by-step presentation fashion that easily allows readers to get on to all Xtext-related functionalities. A really well-defined book sectioning permits grasping all the book contents; readers can efficiently use the book likewise a tool users' guide.The author strengthens tips and examples throughout the book and, most of all, proposes a new set of advanced topics that more trained users will definitely appreciate! The chapter on continuos integration should be always used as a reference guide for plugin development technologies!
Amazon Verified review Amazon
Enrico Denti Nov 10, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Libro ben scritto, aggiornato, chiaro, con molti esempi: un testo interessante su un argomento non banale. Unico piccolo neo, a volte potrebbe essere utile avere tutto il codice di un esempio raccolto in un box unico, anziché doverlo recuperare per parti dove viene spiegato, ma si tratta di un dettaglio.
Amazon Verified review Amazon
Cliente Amazon Feb 25, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Chiaro, con molti esempi. Ho trovato quello che cercavo.
Amazon Verified review Amazon
Max Feb 22, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Das Buch ist eine sehr gute Einführung in das Thema Xtext, behandelt aber auch alle wichtigen Themen in der notwendigen Tiefe. Ich habe mir nicht nur das Buch sondern auch des E-Book als PDF zugelegt und beides war jeden Euro wert.Wer eine DSL bauen möchte, die dann auch in der Praxis eingesetzt wird, ist nicht nur mit Xtext gute beraten sondern auch mit diesem Buch!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela