Removed untyped contructor from ComponentRegistration and add a protected setter.
[castle.git] / Experiments / Generator / src / app / Template.boo
blob02b4de2be7ae7b6115abbc4106e8be0ac9308309
1 namespace Generator
3 import System
4 import System.IO
5 import System.Text
6 import System.Reflection
7 import Boo.Lang
8 import Boo.Lang.Compiler
9 import Boo.Lang.Compiler.Ast
10 import Boo.Lang.Compiler.IO
11 import Boo.Lang.Compiler.Pipelines
12 import Boo.Lang.Compiler.TypeSystem
13 import Boo.Lang.Compiler.Steps
14 import Boo.Lang.Parser
15 import MGutz.CodeInjection from "MGutz.CodeInjection"
16 import MGutz.CodeInjection.Antlr from "MGutz.CodeInjection"
18 class Template:
19 [Property(Filename)]
20 _filename as string
22 [Property(Debug)]
23 _debug as bool
25 private def constructor():
26 pass
28 def constructor(filename as string):
29 _filename = filename
31 def Process() as string:
32 return Process({})
34 def Process(variables as Hash) as string:
35 using reader = StreamReader(_filename):
36 code = ParseCode(reader, variables)
38 if _debug:
39 print code
41 compiler = BooCompiler()
42 compiler.Parameters.Ducky = true
43 compiler.Parameters.Debug = _debug
44 compiler.Parameters.Input.Add(StringInput(_filename, code))
45 compiler.Parameters.References.Add(typeof(GeneratorBase).Assembly)
46 compiler.Parameters.Pipeline = CompileToMemory()
47 compiler.Parameters.Pipeline.RemoveAt(0)
48 compiler.Parameters.Pipeline.Insert(0, WSABooParsingStep())
49 ctx = compiler.Run()
51 if len(ctx.Errors) > 1:
52 print "Compilation errors!"
53 for e in ctx.Errors:
54 print e unless e.Code == "BCE0028" #No entry point
56 asm = ctx.GeneratedAssembly
57 if asm == null:
58 raise Exception("No assembly generated")
60 templateType = asm.GetType("TemplateCode")
61 templateObj = templateType() as duck
63 return templateObj.RunTemplate(variables)
65 private def Sanitize(reader as TextReader) as TextReader:
66 out = reader.ReadToEnd()
67 reader.Close()
68 # Ugly fix to allow ${...} in templates
69 out = out.Replace('${', '<%= "$"+"{" %>')
70 return StringReader(out)
72 private def ParseCode(reader as TextReader, variables as Hash) as string:
73 lexer = AspLexer(Sanitize(reader))
74 parser = AspParser(lexer)
75 parser.template()
76 code = parser.Builder.ToString()
78 builder = StringBuilder()
79 builder.Append('import Generator.Extentions\n')
80 builder.Append('import Generator\n')
82 builder.Append('class TemplateCode():\n')
83 builder.Append('\tpublic def RunTemplate(vars as Hash) as string:\n')
84 for v in variables:
85 builder.Append("\t\t${v.Key} = vars['${v.Key}']\n")
86 builder.Append('\t\tout = System.Text.StringBuilder()\n')
87 builder.Append(code)
88 builder.Append('\t\treturn out.ToString()\n')
89 builder.Append('\tend\n')
90 builder.Append('end')
92 return builder.ToString()