public void TestBinary() { var rule = Grammar.Binary(3); Assert.AreEqual("001", rule.FirstValue("1")); Assert.AreEqual("101", rule.FirstValue("5")); Assert.AreEqual("000", rule.FirstValue("8")); var number = Grammar.ConvertToValue("number", int.Parse, Grammar.Digits); var add = Grammar.Accumulate <int>("add", (left, right) => left + right, number + Grammar.MatchChar('+') + number); rule = Grammar.ConvertBinary(add); Assert.AreEqual("10", rule.FirstValue("1+1")); Assert.AreEqual("100", rule.FirstValue("3+1")); rule = Grammar.ConvertBinary(add, 4); Assert.AreEqual("0010", rule.FirstValue("1+1")); Assert.AreEqual("0100", rule.FirstValue("3+1")); Assert.AreEqual("0001", rule.FirstValue("10+7")); rule = Grammar.Binary(4); Assert.AreEqual("1111", rule.FirstValue("-1")); Assert.AreEqual("1110", rule.FirstValue("-2")); Assert.AreEqual("1101", rule.FirstValue("-3")); Assert.AreEqual("0000", rule.FirstValue("-16")); }
public void TestAccumulate() { var number = Grammar.ConvertToValue("number", int.Parse, Grammar.Digits); var add = Grammar.Accumulate <int>("add", (left, right) => left + right, number + Grammar.MatchChar('+') + number); var subtract = Grammar.Accumulate <int>("sub", (left, right) => left - right, number + Grammar.MatchChar('-') + number); Assert.AreEqual(11, add.ParseTree("5+6").FirstValue <int>()); Assert.AreEqual(21, add.ParseTree("15+6").FirstValue <int>()); Assert.AreEqual(-1, subtract.ParseTree("5-6").FirstValue <int>()); Assert.AreEqual(9, subtract.ParseTree("15-6").FirstValue <int>()); var convertRule = Grammar.ConvertToValue("convert", int.Parse, Grammar.Digit); var rule = Grammar.Node("node", Grammar.Accumulate <int>("accumulate", (a, b) => a + b, Grammar.FirstValue <int>("fv_conv", convertRule))); Assert.AreEqual(2, rule.FirstValue <int>("2")); rule = Grammar.Accumulate <int>("accumulate", (a, b) => a + b, convertRule + Grammar.MatchChar('+') + convertRule); Assert.AreEqual(4, rule.FirstValue <int>("2+2")); }