Click here to Skip to main content
12,897,360 members (54,218 online)
Click here to Skip to main content


72 bookmarked
Posted 3 Sep 2008

Writing your first Domain Specific Language, Part 2 of 2

, 3 Sep 2008 CPOL
A guide to writing a compiler in .NET for beginners, using Irony.
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using FreightLanguageCompiler;
using Irony.Compiler;
using System.Text;
using System.IO;

public partial class _Default : System.Web.UI.Page 
	protected void Page_Load(object sender, EventArgs e)

		if (!IsPostBack)
			sourceCodeTextBox.Text = @"Set pricePerKG to 2.5;
If region is ""asia"" [
set pricePerKG to 2.2;
Set totalWeight to 0;
loop through order [
Set totalWeight to totalWeight + (quantity * weight);
Set freightCost to totalWeight * pricePerKG;
if customer is ""VIP"" [
set freightCost to freightCost * 0.7;
Freight cost is freightCost;

	protected void runButton_Click(object sender, EventArgs e)

			string js = FLCompiler.Compile(sourceCodeTextBox.Text);
			js = MakeIndented(js);
			javascriptTextBox.Text = js;
			ClientScript.RegisterClientScriptBlock(GetType(), "gend", js, true);
		catch (CompilationException ex)
			errorMessageParagraph.Visible = true;
			errorMessageParagraph.InnerText = ex.Message;


	/// <summary>
	/// Indent functions, if statments, and loops, just so the javascript is easier to read.
	/// </summary>
	private string MakeIndented(string js)
		int indentation = 0;
		StringReader sr = new StringReader(js);
		StringBuilder pretty = new StringBuilder();
		string line = sr.ReadLine();
		while (line != null)
			if (line.Contains("}"))
			pretty.Append(new string('\t', indentation));

			if (line.Contains("{"))

			line = sr.ReadLine();
		return pretty.ToString();

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Daniel Flower
Software Developer
China China
Daniel has a Bachelor of Science with First Class Honours from the University of Auckland, and has designed and developed software in companies large and small.

You may also be interested in...

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170424.1 | Last Updated 3 Sep 2008
Article Copyright 2008 by Daniel Flower
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid