예제 #1
0
        public void TestOptionalRule()
        {
            var rule = new OptionalRule(new StringRule("test"));

            Assert.IsTrue(rule.Match("test"));
            Assert.IsTrue(rule.Match("something"));
        }
예제 #2
0
        private Rule Interpret(Grammar grammar, ISemanticNode node)
        {
            Rule rule = null;

            if (node is BranchSemanticNode branch)
            {
                switch ((EbnfNodeType)branch.NodeType)
                {
                case EbnfNodeType.Group:
                    rule = Interpret(grammar, branch.Children[0]);
                    break;

                case EbnfNodeType.Repeat:
                    rule = new RepeatRule(grammar, Interpret(grammar, branch.Children[0]));
                    break;

                case EbnfNodeType.Optional:
                    rule = new OptionalRule(grammar, Interpret(grammar, branch.Children[0]));
                    break;

                case EbnfNodeType.Not:
                    rule = new NotRule(grammar, Interpret(grammar, branch.Children[0]));
                    break;

                case EbnfNodeType.And:
                    rule = new AndRule(grammar, branch.Children.Select(child => Interpret(grammar, child)));
                    break;

                case EbnfNodeType.Or:
                    rule = new OrRule(grammar, branch.Children.Select(child => Interpret(grammar, child)));
                    break;

                case EbnfNodeType.None:
                    rule = Interpret(grammar, branch.Children.Single());
                    break;

                case EbnfNodeType.Root:
                case EbnfNodeType.Rule:
                case EbnfNodeType.Token:
                default:
                    throw new Exception();
                }
            }
            else if (node is LeafSemanticNode leaf)
            {
                switch ((EbnfNodeType)leaf.NodeType)
                {
                case EbnfNodeType.Identifier:
                    rule = grammar.ReferenceRule(leaf.Value);
                    break;

                case EbnfNodeType.String:
                case EbnfNodeType.Regex:
                    break;

                default:
                    throw new Exception();
                }
            }

            if (rule == null)
            {
                throw new Exception();
            }
            else
            {
                return(rule);
            }
        }