Exemple #1
0
        static void _RunCompiledLexCodeGen()
        {
            // create our expressions
            var digits = CharFA <string> .Repeat(
                CharFA <string> .Set("0123456789"),
                1, -1
                , "Digits");

            var word = CharFA <string> .Repeat(
                CharFA <string> .Set(new CharRange[] { new CharRange('A', 'Z'), new CharRange('a', 'z') }),
                1, -1
                , "Word");

            var whitespace = CharFA <string> .Repeat(
                CharFA <string> .Set(" \t\r\n\v\f"),
                1, -1
                , "Whitespace");

            // initialize our lexer
            var lexer = CharFA <string> .ToLexer(digits, word, whitespace);

            // create the symbol table (include the error symbol at index/id 3)
            var symbolTable = new string[] { "Digits", "Word", "Whitespace", "#ERROR" };
            // create the DFA table we'll use to generate code
            var dfaTable = lexer.ToDfaStateTable(symbolTable);
            // create our new class
            var compClass = new CodeTypeDeclaration("RegexGenerated");

            compClass.TypeAttributes = System.Reflection.TypeAttributes.Class;
            compClass.Attributes     = MemberAttributes.Final | MemberAttributes.Static;
            // add the symbol table field - in production we'll set the name
            // to something more appropriate
            var symtblField = new CodeMemberField(typeof(string[]), "LexSymbols");

            symtblField.Attributes = MemberAttributes.Static | MemberAttributes.Public;
            // generate the symbol table init code
            symtblField.InitExpression = CharFA <string> .GenerateSymbolTableInitializer(symbolTable);

            compClass.Members.Add(symtblField);
            // Generate and add the compiled lex method code
            compClass.Members.Add(CharFA <string> .GenerateLexMethod(dfaTable, 3));
            // in production we'd change the name of the returned method
            // above
            // add the DFA table field - in production we'd change the name
            var dfatblField = new CodeMemberField(typeof(CharDfaEntry[]), "LexDfaTable");

            dfatblField.Attributes = MemberAttributes.Static | MemberAttributes.Public;
            // generate the DFA state table init code
            dfatblField.InitExpression = CharFA <string> .GenerateDfaStateTableInitializer(dfaTable);

            compClass.Members.Add(dfatblField);
            // create the C# provider and generate the code
            // we'll usually want to put this in a namespace
            // but we haven't here
            var prov = CodeDomProvider.CreateProvider("cs");

            prov.GenerateCodeFromType(compClass, Console.Out, new CodeGeneratorOptions());
        }