by Maksym Trushyn
5 May 2011 11:09
I wanted to create the "Hello World" application for Boo.OMeta.Parser but it turned out that it is not so easy. Of course I could just parse "print 'Hello world'" but it doesn't show essential idea of the parser. Instead I came up with idea to parse something very famous from literature having sense from DSL perspective. "To be or not to be..." matched both criteries. So this is what I want to share:
namespace Vincent.Tests
import System
import Boo.OMeta
import Boo.OMeta.Parser
import Boo.Lang.Compiler.Ast
import Boo.Lang.Compiler.Steps
import Boo.Lang.Compiler.IO
import System.IO
def newShakespeareAssignment(l,r):
return BinaryExpression(Operator: BinaryOperatorType.Assign, Left: l, Right: newStringLiteral(flatString(r)))
syntax Shakespeare:
assignment = shakespeare_assignment | super
shakespeare_assignment = (++(~(tit),_) >> r, tit, reference >> l, ("."|"") ^ newShakespeareAssignment(l,r) )
tit = --("," | ":"| " "), "that is the"
def OMetaParseAndRun(code as string):
compiler = Boo.Lang.Compiler.BooCompiler()
compiler.Parameters.OutputWriter = StringWriter()
compiler.Parameters.References.Add(typeof(Shakespeare).Assembly)
compiler.Parameters.Pipeline = Boo.Lang.Compiler.Pipelines.CompileToMemory()
compiler.Parameters.Pipeline.Add(RunAssembly())
compiler.Parameters.Pipeline.Replace(typeof(Parsing), Boo.OMeta.Parser.BooParserStep())
compiler.Parameters.Input.Add(StringInput("", code))
return compiler.Run()
code = """
To be, or not to be, that is the question.
print "\$question"
"""
output = StringWriter()
Console.SetOut(output)
OMetaParseAndRun(code)
assert output.ToString() == "To be, or not to be\r\n"
The application compiles and executes the famous Shakespeare's quotation. It is demonstration of flexibility of Boo.OMeta.Parser. It also demonstrates how the extendable parser can be used as a tool for creation of external DSLs. Please notice that the standard compiler pipeline was used. The only thing was changed is that parser step was changed from standard to Boo.OMeta.Parser.
CompilingShakespeare.zip (185.26 kb)
0e6a0d88-6f61-4ad6-943f-fdf5e00f92e9|3|5.0