Click here to Skip to main content
15,886,798 members
Articles / Programming Languages / C#

Writing your first Domain Specific Language, Part 2 of 2

Rate me:
Please Sign up or sign in to vote.
5.00/5 (26 votes)
3 Sep 2008CPOL12 min read 85.6K   1.1K   75  
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)
	{

		try
		{
			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("}"))
			{
				indentation--;
			}
			pretty.Append(new string('\t', indentation));
			pretty.AppendLine(line);


			if (line.Contains("{"))
			{
				indentation++;
			}


			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.

License

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


Written By
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.

Comments and Discussions