Пример #1
0
        public Grammar BuildGrammar(string grammar, params string[] implicitNames)
        {
            var resultGrammar = new Grammar();

            foreach (var name in implicitNames)
            {
                resultGrammar.SetImplicit(name);
            }

            parser.Lock();

            ISemanticNode semantics = parser.Parse(grammar);

            var root = (BranchSemanticNode)semantics;

            foreach (BranchSemanticNode decl in root.Children.Cast <BranchSemanticNode>())
            {
                var left = (LeafSemanticNode)decl.Children[0];
                var name = left.Value;

                ISemanticNode right = decl.Children[1];

                if (right is BranchSemanticNode branch)
                {
                    Rule rule = Interpret(resultGrammar, right);
                    resultGrammar.DefineRule(name, rule);
                }
                else if (right is LeafSemanticNode leaf)
                {
                    switch ((EbnfNodeType)leaf.NodeType)
                    {
                    case EbnfNodeType.Identifier:
                        resultGrammar.DefineRule(name, resultGrammar.ReferenceRule(leaf.Value));
                        break;

                    case EbnfNodeType.String:
                        resultGrammar.DefineString(name, leaf.Value);
                        break;

                    case EbnfNodeType.Regex:
                        resultGrammar.DefineRegex(name, leaf.Value);
                        break;

                    default:
                        throw new Exception();
                    }
                }
                else
                {
                    throw new Exception();
                }
            }

            return(resultGrammar);
        }