## 位域外部申明_（外部）域特定语言的完整指南_danpu0978的博客-程序员信息网

• 什么 ：定义后，我们将研究19个DSL实例
• 原因 ：使用DSL可以带来哪些具体好处？
• 方法 ：我们将讨论构建DSL的不同方法以及成功的因素是什么

## 19个领域特定语言的示例

### 1. DOT –定义图形的DSL

DOT是一种可以描述有向图或无向图的语言。

digraph graphname {
yellow -> orange -> red;
orange -> green;
}

### 2. PlantUML –绘制UML图的DSL

PlantUML可用于定义不同种类的UML图。 例如，我们可以定义一个序列图。

@startuml
actor MyUser
actor CustomerCare
database database
MyUser -> CustomerCare : Ask a refund
CustomerCare -> database : Verify the data
CustomerCare -> MyUser : Issue a refund
@enduml

### 3. Sed –定义文本转换的DSL

s/Jack/John/g

10,/stophere/d

length($0) > 80 或计算文件中的行数： END { print NR } UNIX的哲学是使用几个或这些小工具，并将它们组合起来以执行最令人惊奇和最复杂的任务。 例如，您可以获取一个输入文件，使用sed对其进行转换，然后使用gawk打印选定的零件。 ### 5. Gherkin –定义功能测试的DSL Gherkin是用于定义功能测试的DSL。 它具有非常灵活的语法，使其看起来几乎像自由文本。 基本上，开发人员，分析师和客户可以围坐在桌子旁并定义一些方案。 然后这些场景将作为测试可执行，以验证应用程序是否符合期望。 这是我们如何定义从ATM提款的期望： Scenario: Verify withdraw at the ATM works correctly Given John has 500$ on his account
When John ask to withdraw 200$And John inserts the correct PIN Then 200$ are dispensed by the ATM
And John has 300$on his account 我真的很喜欢这种DSL，因为使用它的门槛很低。 但是，此DSL需要开发人员使用GPL定义一些代码。 实际上，开发人员如何定义特定的命令，例如：“ {name}的帐户中有{amount}$”，并在为项目选择的GPL中定义执行该命令的代码（Ruby，Java或其他支持的）。 一旦开发人员创建了特定于所需应用程序的命令，所有用户都可以在定义其功能测试时使用它们。 也可以以其他方式开始：首先，根据需要编写方案，尝试捕获需求，然后只有开发人员将每个命令映射到GPL中的相应功能。

### 6.网站规范–用于功能Web测试的DSL

Gherkin不是唯一用于定义测试的DSL。 网站规范可用于定义特定于Web应用程序的功能测试。

Open $url Clock on create # Select a store Within card-panel-store Select [date-test=stores] label Remember test as$StoreName
Click
Select button continue
!Class should not contain "disabled"
Click
Select element .preview-value
Property text should be StoreName 在这种情况下，开发人员无需定义命令到GPL的翻译，因为这种语言的用户可以使用特定的命令，例如解释程序知道如何执行的“点击”。 现在，只需最少的培训，任何人都可以描述与网站的特定互动以及预期的结果。 很整洁吧？ ### 7. SQL –数据库 您可能听说过SQL。 它是一种语言，用于定义如何从关系数据库中插入，修改或提取数据。 让我们从STATS表中获取一些统计信息： SELECT MAX(TEMP_F), MIN(TEMP_F), AVG(RAIN_I), ID FROM STATS GROUP BY ID; 当然，您不希望普通的Joe能够编写复杂的查询：SQL不是一种琐碎的语言，它需要一些时间来掌握。 但是，您不需要经过培训就可以学习SQL。 实际上，许多DBA都不是开发人员。 也许Joe不应以对数据库的写访问权受到信任，但他可以获取读访问权限并编写简单的查询来回答自己的问题，而不必问别人并等待获得答案。 假设他需要知道亚特兰大八月的最高气温： SELECT MAX(value) FROM TEMPERATURES WHERE city="Atlanta" AND month="August"; 也许Joe永远不会达到DBA的水平，但是他可以学习一些基本查询并使其适应自己的需求，从而使他变得更加独立，并使他的同事专注于工作而不是帮助他。 ### 8. HTML –网站布局 我真的希望您听说过这种用于定义文档的非常成功的语言。 令人惊讶的是，我们可以在20年前定义HTML页面，当时大多数人将台式计算机连接到分辨率为640×480像素的显示器，而现在这些页面可以在我们的智能手机上运行的浏览器中呈现。 我想这是DSL可以实现的一个很好的例子。 <html> <head> <title>My beautiful page</title> </head> <body> <div id="main"> <h1>Really interesting title!</h1> <p>And the content is even better!</p> <div>consid </body> </html> 请注意，HTML实际上是关于定义文档的：它们的结构和包含的信息。 然后，同一文档在台式计算机，平板电脑或智能手机上的呈现方式将有所不同。 同一文档的消费方式与残疾人不同。 针对视力障碍者的特定浏览器通过阅读内容来帮助他们使用HTML定义的文档，并支持导航到文档的不同部分。 ### 9. CSS –样式 级联样式表语言定义了用于可视化文档的样式。 我们可以使用它来定义HTML文档在屏幕上的显示方式或打印时的显示方式。 p.center { text-align: center; color: red; } @page :left { margin: 0.5cm; } @page :right { margin: 0.8cm; } CSS掌握起来并不是一件容易的事，但是许多具有基本的编程知识或根本没有编程知识的人都可以使用它来更改网页的外观。 该DSL在使网站设计民主化方面发挥了重要作用。 ### 10. XML –数据编码 几年前，XML似乎是解决IT中所有问题的解决方案。 现在炒作早已一去不复返了，但是XML仍然存在。 可靠的DSL代表数据，而另一种则非常灵活。 <library> <author firstName="John" lastName="Doe" id="JDOE" /> <book title="The Story of Mr. Doe" author="JDOE" /> </library> 尽管它不是最易读或令人印象深刻的语言，但是每个人都可以修改XML文件中包含的数据。 ### 11. UML –可视化建模 并非所有的DSL都必须是文本的！ 语言也可以是图形的。 例如， 统一建模语言是一种规则明确的语言。 它可以用来定义通常用于支持讨论的图表。 有人还使用它们来生成代码，甚至定义整个应用程序（如果您对这种东西感兴趣，请查看“模型驱动的体系结构”）。 UML：DSL的示例 UML是一种广泛的语言（有人说肿吗？）。 UML保护伞之后包含许多不同种类的图表。 他们都有共同点。 并非所有人都同意UML是DSL 。 虽然它绝对是一种语言，但有人会说它不是特定于领域的，而是通用的。 可以通过UML配置文件来添加域特定性。 我认为它是特定于建模的语言。 现在，这是一个案例，它说明了定义什么是DSL和什么不是DSL的规则并不容易，主要是因为是很难定义的术语。 ### 12. VHDL –硬件设计 VHDL是用于定义电路的DSL。 从前，电子工程师习惯于设计复杂的系统，直接决定要使用哪些门以及如何将它们连接在一起。 VHDL改变了所有这一切，提供了那些工程师可以用来定义其系统的更高层次的概念。 DFF : process(RST, CLK) is begin if RST = '1' then Q <= '0'; elsif rising_edge(CLK) then Q <= D; end if; end process DFF; 摘自Wikipedia的示例。 有一些工具可以处理这些定义，以得出实际的电路布局，准备进行印刷。 Verilog是另一个类似于VHDL的DSL。 ### 13. ANTLR –词法分析器和解析器定义 ANTLR带有自己的DSL，用于定义词法分析器和解析器语法。 这些是用于识别文本结构的指令。 例如，这是词法分析器语法的一小段： // Identifiers ID : [_]*[a-z][A-Za-z0-9_]* ; // Literals INTLIT : '0'|[1-9][0-9]* ; DECLIT : '0'|[1-9][0-9]* '.' [0-9]+ ; STRINGLIT : '"' ~["]* '"' ; JavaCC，Lex，Yacc和Bison是相似的工具，并且都受到Backus-Naur格式的启发，它们的DSL略有不同。 ### 14.制作系统 Make是一种语言，用于描述如何构建内容以及不同步骤之间的依赖关系。 例如，您可以定义如何生成可执行文件，并指定要执行的操作，您首先需要3个目标文件。 然后，您可以为每个目标文件定义如何从相应的源文件中获取它。 CC=gcc CFLAGS=-I. DEPS = some_header_file.h OBJ_FILES = file1.o file2.o %.o: %.c(DEPS)
$(CC) -c -o [email protected]$< $(CFLAGS) myExecutable:$(OBJ_FILES)
gcc -o [email protected] $^$(CFLAGS)

### 15. Latex –文档布局

\documentclass[12pt]{article}
\usepackage{lingmacros}
\usepackage{tree-dvips}
\begin{document}
\section{Introduction}
Here it start my introduction
\subsection{Details}
Here I go in more details.
\end{document}

### 16. OCL –模型约束

OCL代表对象约束语言，可用于定义对象的其他约束。 通常，它与UML一起使用。

context Meeting inv: self.end > self.start

### 17. XPath – XML节点选择

XPath可用于选择XML文档中的节点。 例如，假设您有一个代表餐馆列表的文档，而您想获取最后一个餐馆：

/restaurants/restaurant[last()]

XPath表达式用于XSLT中，以定义要转换的元素，或者它们可以与许多库结合使用，以用于各种语言，以定义要从文档中提取的元素。 如果您想知道XSLT是什么，它是一种定义XML文档转换的语言。

### 18. BPEL –业务流程

BPEL是一种用于定义Web服务之间的协作以实现业务流程的语言。 当世界正经历其面向服务的架构 （SOA）阶段时，它曾经更加流行。

Eclipse BPEL的示例（https://eclipse.org/bpel/）

### 19. Actulus建模语言–用于计算人寿保险和养老金的DSL

riskmodel RiskLifeDeath(p : Person) : LifeDeath(p) where
intensities =
alive -> dead by gompertzMakehamDeath(p)

### 那么我们可以将DSL用于什么呢？

• 定义要执行的命令：如sed或gawk
• 描述文档或它们的某些特定方面：例如html，latex或CSS
• 定义规则或流程：例如BPMN或Actulus

## DSL与GPLS：使用领域特定语言的5个优点

1. 我们可以对它们进行更好的分析：尽管实际上不可能保证用C或Java编写的程序会尊重某些特征（例如不以无限循环结尾），但是当我们使用DSL时，我们可以执行各种分析。 正是由于它们的功能有限，它们更易于分析。
2. 他们更安全。 使用DSL时，可能出错的事情更少。 使用HTML或SQL时最后一次出现Null指针异常是什么时候？ 没错 如果我们正在做一些至关重要的事情，例如处理某人或他的金钱的健康状况，这非常重要。
3. 如果存在错误，则这些错误是特定于域的错误，因此更易于理解。 它们是特定于域的：因此错误与空指针无关，而与域专家可以理解的事情有关。
5. 我们可以更轻松地教授它们：它们的范围有限，因此仅需学习较少的内容即可掌握它们所需的时间和培训更少。

# 为什么采用领域特定语言？

1. 他们让您与领域专家进行交流 。 你写医疗申请吗？ 当您谈论阵列for循环时 ，医生不理解，但是如果您使用的是关于患者，体温测量血压的DSL，他们会比您更了解它
2. 他们让您专注于重要概念。 他们隐藏了实施或技术细节，只公开了真正重要的信息。

## 与领域专家沟通

• 您可以构建医疗应用程序，并且需要与医生沟通以了解配套软件应建议的治疗方法
• 您可以构建营销自动化软件。 您需要市场营销人员向您解释如何识别与特定配置文件匹配的客户，为他们提供特定的交易
• 您可以为汽车行业构建软件。 您需要与工程师沟通以了解如何控制制动器
• 您可以为会计师构建软件。 您需要代表所有特定税法以适用于给定的上下文，并且需要一名会计师向您解释它们

• 让领域专家阅读或编写高级测试。 像是可执行的要求
• 与领域专家共同开发时，开发人员可以快速获得反馈

## 专注与生产力

DSL提取一些技术细节以专注于捕获的知识这一事实具有重要的意义。

## 反对DSL的典型（错误）原因

• 为问题写出最简洁明了的解决方案
• 您无法快速编写解决方案
• 你不能写一个可以理解的解决方案
• 您无法提供可以理解的错误
• 您无法显示它并与领域专家讨论
• 您无法提供对眼前的问题有意义的工具支持
• 解决方案的可重用性：如果您使用C编写它，则以后将无法在其他上下文中使用该解决方案。 使用DSL，您可以先构建一次解决方案，然后再构建几个代码生成器或解释器。
• 实际上，DSL可以更快，因为生成器可以专用于某种架构

DSL不够灵活

# 如何创建领域特定的语言

• 您可以使用哪些工具来构建DSL
• 最重要的成功因素是什么
• 你需要哪些技能

## 我们可以使用哪些工具来构建领域特定的语言？

### 文字语言

#### 务实的自己动手做

1. 您可以使用ANTLR定义词法分析器和解析器语法。 你不知道ANTLR吗？ 没问题，这是有关ANTLR的不错的教程 。 在此博客中，还有许多其他有关ANTLR的文章
2. 您可以以更易于使用的格式转换ANTLR产生的解析树。 这样就得到了代码模型。
3. 您可以解析引用，构建验证，并将类型系统实现为对代码模型的一组操作。 听起来很复杂，但是如果您知道自己在做什么，则可以用几百行代码来完成。
4. 最后，您可以解释或编译代码模型
5. 您为您的语言构建了一个简单的编辑器。 有关如何执行此操作的信息，请在此博客上或本书中查找教程。 我倾向于使用我自己创建的可黑客入侵的编辑器 。 我把它命名为Kanvas

#### 文字

Xtext是构建文本语言的可靠解决方案。 在实践中，您可以按照与ANTLR相似的方式来定义语法，而不仅仅是获得解析器，而是获得一个不错的编辑器。 默认情况下，此编辑器是Eclipse插件。 这意味着您将能够在Eclipse中编辑用DSL编写的文件。 如果您知道Eclipse平台的工作方式，则可以创建RCP应用程序：即，精简版的Eclipse基本仅支持您的语言，并删除了许多对用户无用的东西。

The editors generated by Xtext can be deeply customized, if you know what you are doing. You can get away with minor changes with a reasonable effort, but if you want to do advanced stuff you need to learn the Eclipse internals and this is not a walk in the park.

Recently Xtext escaped the “Eclipse trap” by adding the possibility of generating editors also for IntelliJ IDEA and… the web! When I first found out this I was extremely excited. Me, as many other developers, switched to IntelliJ some years ago and I was missing a way to easily build editors for IntelliJ IDEA. So this was great news, even if Xtext has been created to work with Eclipse so the support for IntelliJ IDEA is not as mature and battle-tested as the one for Eclipse. I did not try yet the web editor, but from what I understood it generates a server side application which is basically an headless Eclipse and on the client side it generates three different editors based on three technologies (each one with a different level of completeness). The one fully supported is Orion , an Eclipse project. While the other two are the well-known CodeMirror and ACE .

You may want to check out this list of projects implemented with Xtext to get an idea of what is possible to achieve using Xtext.

#### Textual languages: other tools

If I had to build a textual language in most cases I would go for one of the two approaches defined earlier: either my do-it-yourself approach or using Xtext. That said there are alternatives on which I think it makes sense to keep an eye on.

textX is a Python framework inspired by Xtext. You can define the grammar of your language with a syntax very, very close to the one used by Xtext. textX does not use EMF or generate code but it use instead the metaprogramming power of Python to define classes in memory. While it seems nice and easy to use, textX does not generate editor support like Xtext, so that is a major difference.

If you want to get a better feeling of how textX works take a look at this video.

There are other tools like Spoofax. I did not use it myself so I cannot vouch for it. It is more academic stuff than an industrial-grade language workbench, so I would suggest a bit of caution.
Spoofax can be used inside Eclipse. It is based on a set of DSLs to use to create other DSLs.

If you want to look into Spoofax you may want to look at this free short book from Eelco Visser named Declare Your Language .

### Graphical languages

Graphical languages seem approachable and frequently domain experts feel more at ease with them than with textual languages and their geeky syntaxes. Graphical languages require building specific editors to be used and they are less flexible than textual languages. Also, they are less frequently used than textual languages and the tools to build graphical languages tend to be less mature and more clunky. Here I present you a list of a few options. If you want to read a more complete list you can look into this survey on graphical modeling editors.

#### GMF, the painful solution

There is one way to build graphical editors for your language that over time acquired quite a (not-exactly-positive) reputation. Its name is GMF: Graphical Modeling Framework .
Yes, you can use it to build editors which can be used inside Eclipse. Similarly to Xtext it is based on EMF. Basically you use EMF to define the structure of your data and then GMF permits to specify how the different elements are represented, how their connections are displayed and that sort of stuff. Typically you then edit the details of each element in a separate panel, a sort of form.
You can see an example of a GMF editor in the picture below.

Now, the documentation is basically unexisting and to make it work is a challenge which requires a great amount of patience and determination.

This framework has potential and it is powerful and flexible, but working with it is far from being an enjoyable experience.

#### Sirius, hiding GMF

There are tools built on top of GMF to make the experience less terrible for the language designer. A simple tool is Eclipse Eugenia , while a more complex one is Eclipse Sirius .

I have used Eclipse Eugenia and it helped jump starting my editor, but it is a limited tool and if you want to customize your editor you are back to GMF.

I have not used Eclipse Sirius myself but it seems to be decently supported by Obeo and being used at Thales, so I would expect it to have at least reasonable maturity and usability.

#### MetaEdit+, the commercial solution

MetaEdit+ is a language workbench for defining graphical languages. Contrary to all the other tools we discussed it is a commercial tool. Now, generally I prefer to base my languages on open-source solutions because I found them more reliable. I know that in the worst case I can always jump in and mantain the platform myself, if I really need to. With a commercial solution instead what happens if the provider goes out of business? Maybe I can keep using the tool I bought for a while, until it is not compatible with the operating-system I am using and I end up trapped. That said MetaCase (the company behind MetaEdit+) is a solid company which has been in business for quite a few years.

I have assisted in two occasions to a presentation from Juha-Pekka Tolvanen and I was positively impressed both of the time. They have a mature solution and they use it to build a bunch of interesting DSLs for their clients. I like very much to check their regular tweets on the DSL of the week . Here a few samples:

So if you ever need a graphical language I would advise to consider this solution. The alternative is in my opinion to use a full-blown projectional editor, which permits to create also graphical languages, but not only those. 好奇？ 继续阅读。

### Projectional editors

Projectional editors are extremely powerful and exciting but they are unfamiliar to many users. I can give you the theory bit, and throw at you a definition, but if you really want to understand them watch the video below.

A projectional editor is an editor that show a projection of the content stored on file. The user interacts with such projection and the editor translates those interactions to changes to the persisted model. When you use a text editor you see characters, you add or delete characters and characters are actually saved on disk. In a projectional editor you could edit tables, diagrams and even what it looks like text, but those changes would be persisted in some format different from what you see on screen. Maybe in some XML format, maybe in a binary format. The point is that you can work with those files only inside their special editor. If you think about it, this is the case also for all the graphical languages: you see nice pictures, you drag them around, connect lines and in the end the editor save some obscure format, not the nice pictures you see on the screen. The point with projectional editors is that they are much more flexible than your typical graphical language. You can combine different notations and support all sort of representation you need for your case.

You could also take a look at this explanation of projectional editing written by Martin Fowler.

#### Jetbrains MPS

Jetbrains MPS is a tool that I have been using for some years, working on it daily on most of last 12 months. It is an extremely powerful tool and it is the most mature projectional editor available out there. It is no accident: Jetbrains has invested significantly on developing it over more than a decade.

Do you want to see how it looks like? 观看视频。

I find very useful MPS to build families of interoperable languages with advanced tooling. Imagine several DSLs to describe the logic of your problems, to define tests, to define documentation. Imagine all sort of simulators, debuggers, tools to analyze code coverage. Everything built on one platform.

Now, it means you need to be ready to embrace Jetbrains MPS and to invest a significant amount of time to properly learn it (or hire someone like me). However if you are ready to do the investment it can simply revolutionize your processes.

#### Intentional Platform

This one is the mysterious and intriguing one.

Charles Simonyi is the man who designed Excel, one of the first space tourists and one of the richiest men on earth. In 1995 he wrote the revolutionary paper The Death of Computer Languages, The Birth of Intentional Programming . In this paper he presents a new, more intuitive way of programming, fundamentally based on projectional editors. He starts working at Microsoft on these ideas, but in 2002 he leaves Microsost to cofound Intentional Software. Since then the publicly available information on their tool, the Intentional Platform has been extremely scarce. They have published a few papers and given a few presentations.

I have heard from people that have used it that it has a lot of potential but it is not there yet. For sure I would love to put my hands on it. The closest you can get is to read this somehow old review of the Intentional Platform from Martin Fowler. Maybe one day even us mortals will have the possibility to know more about this legendary tool.

As far as I know they work with selected companies but for now their tool is not publicly available.

#### Whole Platform

This is a good Language Workbench too frequently overlooked. While it has been used in production for many years in a large company in Italy, it is lacking a little bit on the documentation and marketing side. Yes, I know it is sad that pure engineering awesomeness is not enough to gain popularity. Anyway if you want to know more about it you can read my post on getting started with the whole platform .

There are a few concepts that I find quite interesting. I am not an expert on the Whole Platform: I have just played with it and talked with his authors.

One aspect that I find really interesting and different with respect to the other Language Workbenches is that the Whole Platform supports quite well working with existing formats, and evolve from existing processes to more advanced Language-Engineering approaches. For example, it is quite easy to define grammars for existing formats in order to parse them.

The following is an example of a grammar to parse JSON but the same approach has been used to parse very complex formats used in the banking domain.

Another idea I love about the Whole Platform is the Pattern Language: the possibility to take a model (in this sense a piece of Java code is a model) and define variability points that could be filled with values from another model.

Whole Platform – Pattern Language

Whole Platform – Graphical Language

Also, the Whole Platform is quite rich and it supports also graphical languages.

Riccardo Solmi and Enrico Persiani are the minds behind the Whole Platform and you should probably talk to them if you are interested in using this Language Workbench.
The images of the Whole Plargorm I have used are released unfer the CC Attribution 2.0 license (https://creativecommons.org/licenses/by/2.0/)

### Comparing the different approaches

APPROACH TYPE WHEN TO USE IT
Do-it-yourself Textual You need to be in absolute control of the platforms supported and you do not want any vendor lock-in

textX Textual You love the flexibility of dynamic languages while editor support is not important to you
Spoofax Textual You like to work with a sound theoretical approach and you are not afraid of a few bumps in the road
GMF 图形化 You need extreme flexibility to build your very own graphical editor
Eclipse Sirius 图形化 You are ready to trade some flexibility to get things done quicker and saving some mind sanity
MetaEdit+ 图形化 You are fine using commercial software for a stragegic component and you want results quickly
Jetbrains MPS Projectional You want to build family of languages with powerful and complex tooling like simulators, debuggers, testing support and more
Intentional Workbench Projectional You have some connection that give you access to the most mysterios and hyped Language Workbench
Whole Platform Projectional You want to support existing formats and transition smoothly to a new approach

One thing I would like to stress is that projectional editing is a superset of the graphical editing. So you can define graphical languages using Jetbrains MPS. Given there is not a clear and great alternative to build only graphical DSLs I would use Jetbrains MPS in that case. Alternatively I would consider build the tooling myself targeting the web. Another interesting option could be looking into something like FXDiagram .

### 还不够吗？

If you want to keep an eye on the new Language Workbenches that come up I suggest you follow the “Language Workbench Challenge”, a workshop that is typically colocated with the Software Language Engineering conference. I co-authored a paper and attended the last edition and it was awesome.

## What do I need to make my DSL succeed?

There are just two things that will seem obvious but are not:

1. You need your users to use it
2. You need your users to get benefits from using it

To achieve this you will need to build the right tool support and adopt the right skills. We are going to discuss all of this in this section.

### Get users to use it

The first point means that you need to win the support of users. During my PhD I conducted a survey on the reasons why DSLs are not adopted. There are several causes, but one important factor is resistance from users, especially when they are developers .

If you target a DSL to developers, they could resist because they feel they are not in control as when they use a General Purpose Language (GPL). They could also fear that a DSL lowers the bar, being simpler to use than, let's say, Java. In addition to that, as all innovations, a new DSL is threatening for seasoned developers because it reduces the importance of some of their skills, like the vast experience in dealing with the quirks of the current GPL you are using at your company.

If your DSL is intended to non-developers generally it is easier to win their support. 为什么？ Because you are giving them a superpower: the ability to do something on their own . They could use a DSL to automatize a procedure that previously was done manually. Maybe before the DSL was available the only possibility for them to do something was bothering some developer to write custom code. Now they get a DSL which means more power and independence because of it. Still they could resist adopting it if they perceive it as too difficult or if they feel it does not match their way of thinking.

To me the key as a DSL designer in this case is being humble and listen . Listen to the developers, work on capturing their experience and embedding it in the design of the DSL or the tooling around it. Involve them in the design of the DSL. When talking with your users, technical or not, communicate that the DSL will be a tool for them, designed to support them and derived by their understanding of the domain at hand. When designing DSLs the cowboy approach does not work, you need to succeed as a team or not succeed at all.

### Give benefits to users

If you get the support of users and people start using it you win only if they get a significant advantage from using the DSL.

We have discussed the importance of a DSL as communication tool, as a medium to support co-design. This is vital.

In addition to this, you can increase significantly the productivity of your users by building first-class tool support.

• a great editor with syntax highlighting and auto completion: so that learning the language and using it feel like a breeze
• great error messages: a DSL is an high level language and error can be very significant for users
• simulators: nothing helps users as the possibility to interact with a simulator and see the results of what they are writing
• static analysis: in some contexts the possibility to analyze the code and reassure against possible mistake is a big win

These are a few ideas but more can be adopted, depending on the specific case. Specific tools support for specific languages.

## Tool support: why we do not care about internal Domain Specific Languages

There is one factor that is frequently overlooked and this is tool support.

Many practicioners think that the only relevant thing is the syntax of your language or what it permits to express, with everything else being a detail.

This is just fundamentally wrong because the tool support can multiply exponentially the productivity when using any language, especially a DSL. This is a crucial aspect to consider, because the language should be designed considering tool support.

Because when building Domain Specific Languages, if you want to get serious, you have to build good tool support. Tool support is an essential key in delivering value.

I recorded this short video on this very subject.

Tool support is the reason why internal domain specific languages (ie, fake DSLs) are irrelevant: they do not have any significant tool support.

When using some host languages you can bend them enough of getting some sort of feeling of having your own little language, but that is it. There are some languages that are flexible enough to give a sort of decent … like ruby. With other languages you get very poor results. I feel pity for the people trying to build “internal DSLs” for languages like Scala or Java. The worst of all is lispers. I understand their philosophy “if you want to solve a problem in LISP, first you create your LISP dialect and then solve it using it”. I understand and I think it is a great technique. Just let's not pretend this is a real DSL. This is not something you can share and work with closely with domain experts. It can be your trick to be more productive, but that is it.

You see those ridicuosouly long chains of method calls and you hear someone presenting those as Domain Specific Language. That makes me feel a mix of two emotions:

• pity for him and his users
• rage for the confusion it creates. Real DSLs are very different and they can bring real benefits. Stop mixing them with this… thing

Just build a real DSL, so an external DSL!

## What skills are needed to write a DSL?

Typically you need to be able to have high abstraction skills , the same you need typically for metaprogramming. If writing a library is 3 times harder than writing a program, writing a framework or a DSL is typically 3 times harder than writing a library.

You need to be humble : you may need a developer, but typically you need to create this DSL for other professional that are going to use it for their job. Listen to what theydo, understand how they work. What could seem wrong or naive to you could have reasons you do not yet understand. Acting as the all-mighty-expert is the single best way to create a failed DSL, not useful in practice and therefore not used.

Aside from this, practice and learn. Keeping doing it for a few years should do the trick.

# 资源资源

Now that you have seen what DSLs can bring you and you have an idea how to build them you should be happy.

But you are not, you want more, you want to understand better DSLs, you want to learn everything about them.

Well, I do not know about everything, but definitely I can give you some pointers. I can tell you where to find the good stuff.

Let's see what we can find:

### 图书

I would start suggesting to read the DSL Engineering by Markus Völter . This PDF version of the book is donation-ware. So just read it and donate. Alternatively you can find the printed version on Amazon.

The book start with an introduction part: it is very useful to set your terminology straight. After that it comes the DSL design part, focusing on different aspects separately. If you do not have direct access to an expert to teach you how to design DSLs reading this part of this book is the best alternative I can recommend (together with as much practice as you can, of course).

Then it comes the part about implementation: remember that Markus has a PhD, but he is first of all someone who gets things done so this part is very well written, with examples based on Xtext, Spoofax and MPS.

Part IV is about scenarios in which DSLs are useful. Given this is based on his large experience in this field there are a lot of interesting comments.

I had the occasion to work with Markus. I used to admire him a lot before meet him and I now I admire him even more. He is simply the best one on this field, so if you can learn something from him do it. Read his books, watch his presentations, follow his projects. It will be a good way to invest your time. He is lately working on Jetbrains MPS stuff, so you should follow what is going on with mbeddr and IETS3 . Mbeddr is both a set of plugins for MPS and an implementation of the C language in MPS with special domain-specific extensions to support development of embedded software. IETS3 is instead an expression language built in MPS.

Martin Fowler is a very famous thought leader and bestseller author. I really admire his clarity. He is the author of Domain Specific Languages , a book about both internal and external DSLs.
I find the mental models presented in the book quite useful and elegant. In practice however I find internal DSLs irrelevant, so I am interested in only some portions of this book.

There are 15 chapters dedicated specifically to external domain specific languages. While those chapters are organized around implementation techniques there are comments and remarks from which you can learn some design principles.

I think the sections on the alternative computational models and code generation are very valuable. You will have an hard time finding an exploration to these topics at this level of detail anywhere else.

The book is 7 years old and the techniques may have evolved since the book was written, but the vast majority of the considerations presented in the book are still valid. And of course they are thoughtful and well explained, as you would expect from Martin Fowler.

If you are interested in textual languages and in particular on ANTLR you should definitely look into the Language Implementation Patterns from Terence Parr. I like the author, I like the publisher (the Pragmatic Bookshelf) and unsurprisingly I love the book.

The book starts discussing different parsing algorithms. If you like to learn how stuff works you should take a look at these chapters. Then there are chapters about working with the Abstract Syntax Tree, extracting information, transforming it. This is the kind of stuff you need to learn if you want to become a Language Engineer. Also, there chapters on resolving references, building symbol tables or implementing a typesystem. These are the foundations to learn how to process the information expressed in your DSL.

Finally Terence explains you how to use the information you have processed by building an interpreter or a code generator. At this point you end your journey, having seen how to build a useful language from start to finish. This book will give you solid basis to learn how to implement DSLs. The only thing missing is a discussion on how to design DSLs, but this is not the goal of this book.

If you are looking into MPS there are not many resources around. It could make sense to buy the two books from Fabien Campagne on the MPS Language Workbench . They explain in details all the many features of MPS (admittedly some are a bit obscure). If I would have to find one thing missing is more advices on language design. These books are very good references to learn how MPS works, but there is not much guidance on how to combine these features to get your results. One reason for that is that MPS is an extremely powerful tool, which can be used in very different ways so it is not easy to give general directions.

Volume I explains separately the different aspects of a language: how to define the structure (the metamodel), how to define the editors, the behavior, the constraints, the typesystem rules and so on. Most of the chapters are in reference-manual style (eg the chapter The Structure AspectStructure In Practice ). Everything you need to learn to get started and build real languages with MPS is explained in Volume I.

Volume II is mostly about the advanced stuff that you can safely ignore at the beginning. I suggest looking into this book only when you feel comfortable with all the topics explained in Volume I. If you have never used MPS before it will take some time. Volume II explaine you how to use the build framework to define complex building configurations, it gives you an overview of all the different kinds of testing you may want to use for your languages. It also show you how to define custom aspects for your language or custom persistence.

I have bought the Google Play version but they are available also in print form.

On Xtext there is a quite practical and enjoyable book from Lorenzo Bettini: Implementing Domain-Specific Languages with Xtext and Xtend . I wrote a review on the second edition of this book: if you want to read my long-form opinion of that book you can visit the link.

If you want to learn how to write textual languages with good tool support you could start following a couple of tutorials on Xtext and then jump to this book. This book will explain you everything you need to know to use Xtext to build rather complex editors for your language. The only caveat is that Xtext is part of a complex ecosytem so if you really want to become an expert of Xtext you need to learn EMF and Xtend. The book does a good job in teaching you what you need to know to get started on these subjects but you may have to complete your education with other resources too, when you want to progress.

What I like about this book is that is not a reference manual, but it contains indications and opinions on topics like Scoping or building a typesystem rules (the author has some significative experience on this specific topic). Also, the author is interested in best practices so you will read his take on testing and continuos integration. The kind of stuff you should not ignore if you are serious about language engineering.

If you are interested in DSLs in general you can take a look at DSLs in Action . The book is interesting but I have two comments:

1. It focus way too much on internal DSLs, which are, as we all know, not the real thing
2. They have misspelled my name. -1 point for that

Specifically on external DSLs there is not much: the author briefly discuss Xtext and then spend a chapter on using Scala parser combinators to build external DSLs. That would not have been my first choice. So if you are interested in learning how to implement an external DSL do not pick this book. However if you want a gentle introduction to the topic of DSLs, if you are a degenerate who prefers internal DSLs instead of external DSLs, or if you want to read every available resource on DSLs this book would be a good choice.

Domain Driven Design is a relevant and important book to read. Because you need skills to understand the domain, in order to be able to represent it in your language, and to design your language so that it can capture it. Now, I should probably just praise this book and stress how much I have enjoyed it. Unfortunately I tend to err on the honesty side so I warn you: this is one of the most boring books I have ever read. It is important, it is useful, it is great but it just so plain and long. It stayed on my night stand for months.

What you should get how of this book is the importance of capturing the Domain in all of your software artifacts. The book stress the importance of building a common language to be shared among the stakeholders. This is completely and absolutely relevant if you want to build Domain Specific Languages. What is not part of this book is how to map this domain model to a language. For that part you should refer to the other books, specific to DSLs design. This book is a good complement to any of them.

### 公司介绍

I design and implement Domain Specific Languages for a living but instead of tell you how great I am, I will instead list other companies that you could work with.

The first, obvious name is Itemis. They are a German company with small offices in France and Switzerland. They employ some of the best in the field: I have met and worked with Markus Völter and Bernd Kolb and I am seriously impressed by the level at which they work. They have worked with so many companies and have done so many projects that the list will be scarely too long. I would just say that in the later years they have done amazing work using Jetbrains MPS. They have created the mbeddr project and from it they have derived a set of utilities, named the mbeddr platform, which contributed enormously to the growth of MPS. They have contributed early and significantly to the Language Workbench community, so if you need some help on a DSL you should seriously consider working with them.

TypeFox is another German company. I have interviewed one of the founders some time ago. Several Xtext core committers are involved in the company so as you can imagine they have some serious competencies on Xtext and the EMF platform in general. If you need Xtext training or consulting I would consider them the top-choice. They are also a Solution Member of Eclipse and I would expect them to be able to build complex Eclipse-based solutions. If you want to hear more you can read this interview to Jan Köhnlein . Jan is one of the founders of the company and we talked a few months after the company was created.

Jetbrains is obviously the company behind Jetbrains MPS. Recently they started offering training on MPS. I asked about this during my interview at Vaclav Pech . They offer training, either basic or advanced, on their premises in Prague or on-site.

At the moment I do not think they offer MPS consulting (for that you can talk to me or to Itemis).

## 结论

There are many reasons why you should really consider Domain Specific Languages. I have seen companies benefit enormously from DSLs. Most of the people I have worked with used DSLs as a key differentiator that helped them increase productivity by 10-20 times, reduce time-to-market and feedback cycles, increase the longevity of their business logic and much more.

Aside from the practical benefits I find the topic extremely fascinating. Most of all I feel that by building DSLs we build powerful tools that help other people do their job. As language designers we act as enablers, our languages can be used by skilled professionals to achieve great things and this is an amazing feeling for me.

### 请问你能帮帮我吗？

If you found this guide useful please share it, spread the work and link it. I spent several years working on this subject and a few weeks working on this guide. I would be very happy if you could help me reach others who could find it useful.

Thank you so much!

A few ideas:

• Send an e-mail to your colleagues

### HTML期末大作业~餐饮文化学生网页设计作业(HTML+CSS+JavaScript)[email protected]码住夏天-web网页设计的博客-程序员信息网

HTML期末大作业~基于HTML+CSS+JavaScript饮食网站设计与实现 关于HTML期末网页制作，大作业A+水平 ~饮食网页作业HTML+CSS+JavaScript实现，共有联系我们 在线留言 资质荣誉 行业资讯 成功案例 新闻资讯 产品中心 发展历史 关于我们 8...