Created
May 10, 2012 21:04
-
-
Save dragan/2655887 to your computer and use it in GitHub Desktop.
A simple DSL in C#.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Text; | |
using Mono.CSharp; | |
namespace CompilerDsl | |
{ | |
class EntryPoint | |
{ | |
public static void Main (string[] args) | |
{ | |
var code = string.Format(Rules.DslClass, Rules.CompileRules); | |
var evaluator = new Evaluator(new CompilerSettings(), | |
new Report(new ConsoleReportPrinter())); | |
evaluator.ReferenceAssembly(typeof(Rule).Assembly); | |
//evaluator.Run("using System;"); | |
//evaluator.Run("using System.Collections.Generic;"); | |
//evaluator.Run("using CompilerDsl;"); | |
//evaluator.Run(code); | |
evaluator.Compile(code); | |
string getRules = @"var dsl = new CompilerDsl.Dsl(); | |
dsl.LoadRules();"; | |
object result; | |
bool result_set; | |
evaluator.Evaluate(getRules, out result, out result_set); | |
if (result_set) | |
{ | |
List<Rule> rules = result as List<Rule>; | |
foreach (var rule in rules) | |
{ | |
Console.WriteLine("Identifier: {0}", rule.Identifier); | |
var ruleContext = new RuleContext(); | |
rule.Block.Invoke(ruleContext); | |
Console.WriteLine(); | |
} | |
} | |
Console.WriteLine("Done..."); | |
} | |
} | |
class Rules | |
{ | |
public static string CompileRules = @"Compile(""*"", (ruleContext) => { | |
ruleContext.Layout(""/default/""); | |
ruleContext.Filter(""Liquid""); | |
});"; | |
public static string DslClass = @"using System; | |
using System.Collections.Generic; | |
namespace CompilerDsl {{ | |
public class Dsl | |
{{ | |
List<Rule> Rules {{ get; set; }} | |
bool EvaluatedRules {{ get; set; }} | |
public Dsl() | |
{{ | |
Rules = new List<Rule>(); | |
}} | |
public IEnumerable<Rule> LoadRules() | |
{{ | |
{0} | |
return Rules; | |
}} | |
public void Compile(string identifier, Action<RuleContext> block) | |
{{ | |
Rules.Add(new Rule {{ Identifier = identifier, Block = block }}); | |
}} | |
public void Route(string identifier, Action<RuleContext> block) | |
{{ | |
Rules.Add(new Rule {{ Identifier = identifier, Block = block }}); | |
}} | |
}} | |
}} | |
"; | |
} | |
public class Rule | |
{ | |
public string Identifier { get; set; } | |
public Action<RuleContext> Block { get; set; } | |
} | |
public class RuleContext | |
{ | |
public void Layout(string layoutIdentifier) | |
{ | |
Console.WriteLine("Layout: " + layoutIdentifier); | |
} | |
public void Filter(string filter) | |
{ | |
Console.WriteLine("Filter: " + filter); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment