Lesson 8. Capstone: Building a domain-specific language

 

In this project, you will

  • Learn what a domain-specific language (DSL) is
  • Create a simple DSL for handling user input from an HTML formatter
  • Create a simple DSL for repeating or looping templates around an array

Before you build a DSL, let’s first define what one is. A domain-specific language uses a programming language’s features and syntax in a clever way to make solving a particular task appear as if it has first-class support by the programming language itself. For example, a common type of DSL seen in JavaScript is used by unit test libraries:

describe('push', function() {
  it('should add new values to the end of an array', function() {
    // perform test
  });
});

This is a DSL because it looks like you’re using natural language to state that you are describing push, and then giving the actual description: it should add new values to the end of an array. In reality, the describe and it parts of the sentences are functions, and the rest of the sentences are parameters to those functions.

Other languages such as Ruby have a lot of DSLs. Ruby in particular is so malleable and has so much syntactic sugar that it makes creating DSLs extremely easy. JavaScript, on the other hand, has not historically lent itself to easy DSL creation. But with tagged templates, that may change. For example, a clever programmer might be able to utilize tagged templates to change the preceding unit-testing DSL into this syntax:

8.1. Creating some helper functions

8.2. Create an HTML-escaping DSL

8.3. Create a DSL for converting arrays into HTML

Summary