Ioannis Panagopoulos blog

Tutorials on HTML5, Javascript, WinRT and .NET

Domain Specific Languages with M - Part 3/3 Consuming the DSL at runtime in C#

by Ioannis Panagopoulos

In this last post of the small series we will see how we can load the syntax of a DSL in C# and then feed it with an input text that we need to be parsed. In this post we have already described how to write the DSL syntax and in this post we have seen how to decorate it with productions.

 

So following the process described in those posts we end up with a file containing the description of the syntax of our DSL, along with its productions (eg the file Renting_en.mg available for download in the zip file provided at the end of this post).

 

We open Visual Studio 2010 and create a new console application. We add two new references to the project (System.Dataflow and Microsoft.M).

 

First, we load the file that contains the syntax of the DSL grammar and create some sort of “compiler” with it:

Stream mgStream = File.OpenRead(@"<Path to file>\Renting_en.mg");
CompilationResults Compilation = Compiler.Compile(new CompilerOptions
{
   Sources ={new TextItem
             {
                 Name="RentGrammar",
                 Reader = new StreamReader(mgStream),
                 ContentType = TextItemType.MGrammar
             }
            }
 
});

Then we will create the parser for our DSL language:

Parser theParser = Compilation.ParserFactories["Renting.RentLanguage"].Create();
theParser.GraphBuilder = new NodeGraphBuilder();

Note that the name of the language “Renging.RentLanguage” is exactly the same with the one defined within the .mg file.

The only thing left is parsing the input text in the file “Charges_en.txt” and dumping the result to the Console. You will see that you will get all the productions as specified in the DSL grammar.

Node root = (Node)theParser.Parse(@"<Path to file>\Charges_en.txt", null);            
Console.Write(root.WriteToString());

From this point you can explore the root object and get whatever you like from the production tree created. This post concludes the small introduction to the M language. If you would like more on M feel free to contact me. The solution along with the parser and the demo input language file can be downloaded

here

 

Shout it

kick it on DotNetKicks.com

blog comments powered by Disqus
hire me