Tuesday, January 13, 2015

Extend programming languages, online

Lets start with a useless construct: a 'pure' class. Defined as a class which does not produce side effects when invoked. Whether truly useless or poorly implemented is irrelevant. What's important is that you would like that feature in your language of choice.

Up until today, you are out of luck. Language design is tightly controlled and version updates take years. Well, no more! Head to http://xslang.azurewebsites.net/#/project/3

What follows is a brief tutorial on how to create your own programming language constructs. Understand that whatever you create is not along in an island but tightly integrated into csharp. First, you will create a project for your dsl:


In here, we're saying the dsl will be referred identified in your code with the keyword "pure". Both the parsing and the linking will be done using Roslyn and it will extends types. A word on extension types:

  • Namespace extension: Your constructs appear at the namespace level, same as classes, etc.
  • Type extension: Types headers will be modified. In this case: pure class MyClass.
  • Member extension: Your constructs appear inside types and look like methods.
  • Code extension: Adds statements, such as the asynch dsl discussed in previous posts.
Once created, editing the project takes you to the main IDE:

DSLs written in Roslyn have two main components: a parser and a linker. Parsing will analyze your extended code, fix (or rewrite, in Roslyn lingo) any problems it can and defer anything else to the linker. Parsing does not have access to any semantic information, hence deferring to the linking stage.

I will not go too much into the code because it is pretty standard Roslyn stuff: the parser will collect all method calls and assignments inside the pure class and it will schedule its linking, The linker makes sure that calls are made only to static or pure classes and assignments only modify internal state.

The only noteworthy snippet is the scheduling of individual linkers instead of the linking process having to again find all troublesome syntax nodes:

return Link(newNode, Linker.CheckAssignment);

This schedules the assigment newNode to be linked by CheckAssignment. This linker will be called as many times as scheduled and with the right syntax nodes.

Then you have all your code written and need to do a little debugging:

Same as in the home page, you get to write some test code and translate it into c# as to validate its correctness. While not the greatest way to debug, we also offer notifications triggered by console.write. But hey, you are extending c# in a few lines of code! 

No comments:

Post a Comment