1: public class DynamicMGrammarCompiler
2: {
3:
4: /// <summary>
5: /// Compile the module, and store the graph in the byte[], so the
6: /// client application can cache this compiled image
7: /// </summary>
8: /// <param name="module"></param>
9: /// <returns></returns>
10: public Module CompileModule(Module module)
11: {
12:
13: MGrammarCompiler compiler = new MGrammarCompiler();
14: ErrorReporter reporter = ErrorReporter.Standard;
15: TextReader reader = new StringReader(module.MGrammar);
16: FileStream fs = null;
17: try
18: {
19: SourceItem item = new SourceItem(module.ParserName, reader);
20: item.ContentType = GContentType.Mg;
21: SourceItem[] items = new SourceItem[] { item };
22: compiler.SourceItems = items;
23: compiler.Target = Target.Mgx;
24: compiler.TypeCheckActions = true;
25: compiler.OutFile = Path.GetTempFileName();
26: compiler.Execute(reporter);
27: //read bytes
28: string filepath = Path.Combine(Path.GetDirectoryName(compiler.OutFile), Path.GetFileNameWithoutExtension(compiler.OutFile) + ".mgx");
29: fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
30: byte[] bytes = new byte[fs.Length];
31: fs.Read(bytes, (int)0, (int)fs.Length);
32: fs.Close();
33: module.Bytes = bytes;
34: }
35: finally
36: {
37: if (null!=fs)
38: {
39: fs.Close();
40: }
41: reader.Close();
42: }
43: return module;
44: }
45:
46: /// <summary>
47: /// Parse the instancedata through the compiled image within the module
48: /// </summary>
49: /// <param name="module"></param>
50: /// <param name="instanceData"></param>
51: /// <returns></returns>
52: public object ParseData(Module module, string instanceData)
53: {
54:
55: object result = null;
56: MemoryStream ms = null;
57: StringReader sr = new StringReader(instanceData);
58: try
59: {
60: ms = new MemoryStream(module.Bytes);
61: DynamicParser parser = MGrammarCompiler.LoadParserFromMgx(ms, module.ParserName);
62: if (null == parser)
63: {
64: throw new NullReferenceException(string.Format("Language with name '{0}' not found in MGrammar image!", module.ParserName));
65: }
66:
67: result = parser.ParseObject(sr, ErrorReporter.Standard);
68: }
69: finally
70: {
71: if (null != ms)
72: {
73: ms.Close();
74: }
75: sr.Close();
76: }
77: return result;
78: }
79:
80: /// <summary>
81: /// Both Compile and Parse.
82: /// </summary>
83: /// <param name="module"></param>
84: /// <param name="instanceData"></param>
85: /// <returns></returns>
86: public object CompileModuleAndParseData(Module module, string instanceData)
87: {
88: module = CompileModule(module);
89: return ParseData(module, instanceData);
90: }
91: }