From 36fb690d33b1f487a8d299470cfe9c5d900c58a3 Mon Sep 17 00:00:00 2001 From: Peter Wu Date: Sun, 8 May 2016 16:01:51 +0200 Subject: Add skeleton for PicoRec NAT and ID regexes were taken from RegexTest.java. Tests are added before the implementation (test-driven development). --- src/PicoRec.java | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 src/PicoRec.java (limited to 'src') diff --git a/src/PicoRec.java b/src/PicoRec.java new file mode 100644 index 0000000..eec2f38 --- /dev/null +++ b/src/PicoRec.java @@ -0,0 +1,72 @@ +/** + * Recognizer for the language described by grammar-ll1.txt. + */ +import dk.brics.automaton.RegExp; +import dk.brics.automaton.RunAutomaton; + +public class PicoRec { + + /** Regular expression describing the ID symbol. */ + private final static String idRegex = "[a-z][a-z0-9]*"; + /** Regular expression describing the NAT symbol. */ + private final static String natRegex = "0|[1-9][0-9]*"; + + private final RunAutomaton idR, natR; + + public PicoRec() { + idR = new RunAutomaton(new RegExp(idRegex).toAutomaton()); + natR = new RunAutomaton(new RegExp(natRegex).toAutomaton()); + } + + /** + * Try to parse the input. + * + * @return true if the language is recognized, false otherwise. + */ + public boolean parse(String text) { + // TODO implement this + return false; + } + + + /* Convenience functions for testing. */ + + private void check(String input, boolean expectOk) { + boolean accepted = parse(input); + System.out.println("Testing input: " + input); + if (expectOk && !accepted || !expectOk && accepted) { + throw new RuntimeException("Unexpected result for " + input); + } + } + + private void check(String[] input, boolean expectOk) { + check(String.join("\n", input), expectOk); + } + + private void assertOk(String... input) { + check(input, true); + } + + private void assertFail(String... input) { + check(input, false); + } + + public static void main(String[] args) { + PicoRec rec = new PicoRec(); + + // minimal program satisfying the language, without whitespace. + rec.assertOk("begindeclare|end"); + // simple expression + rec.assertOk("begin declare a | a := 1 end"); + + // Trivial failures + rec.assertFail(""); + rec.assertFail("begin"); + rec.assertFail("begin declare"); + rec.assertFail("begin declare |"); + rec.assertFail("begin declare | end end"); + rec.assertFail("begin declare end"); + rec.assertFail("begin end"); + rec.assertFail("end"); + } +} -- cgit v1.2.1