public void TestGreibachNormalForm() { Assert.IsFalse(grammar1.InGreibachNormalForm()); Assert.IsFalse(grammar2.InGreibachNormalForm()); Assert.IsFalse(grammar3.InGreibachNormalForm()); Assert.IsTrue(grammar1.ToGreibachNormalForm().InGreibachNormalForm()); Assert.IsTrue(grammar2.ToGreibachNormalForm().InGreibachNormalForm()); CFG grammar3Greibach = grammar3.ToGreibachNormalForm(); Assert.IsTrue(grammar3Greibach.InGreibachNormalForm()); Assert.IsTrue(derives(grammar3Greibach, "")); Assert.IsTrue(derives(grammar3Greibach, "()")); Assert.IsTrue(derives(grammar3Greibach, "()()")); Assert.IsTrue(derives(grammar3Greibach, "(())")); Assert.IsTrue(derives(grammar3Greibach, "(()())")); Assert.IsTrue(derives(grammar3Greibach, "()(()(()))(())")); Assert.IsFalse(derives(grammar3Greibach, "(")); Assert.IsFalse(derives(grammar3Greibach, ")")); Assert.IsFalse(derives(grammar3Greibach, "())")); Assert.IsFalse(derives(grammar3Greibach, "(()()")); Assert.IsFalse(derives(grammar3Greibach, "((())))")); Assert.IsFalse(derives(grammar3Greibach, "(()(())")); Assert.IsFalse(derives(grammar3Greibach, "()(()((()))(())))")); Assert.IsTrue(CFGBuilder.Start("A") .Derive("A").To("a") .Derive("A").ToEpsilon() .Build().InGreibachNormalForm()); Assert.IsFalse(CFGBuilder.Start("A") .Derive("A").To("a", "A") .Derive("A").ToEpsilon() .Build().InGreibachNormalForm()); }
private static bool derives(CFG grammar, string word) { if (!grammar.InGreibachNormalForm()) { throw new Exception("only grammars in Greibach normal form are supported"); } List <string> wordList = new List <string>(); wordList.AddRange(word.Select(c => c.ToString())); List <string> initialSententialForm = new List <string>(); initialSententialForm.Add(grammar.startVariable); return(derives(grammar, initialSententialForm, wordList)); }