about summary refs log tree commit diff
path: root/users/wpcarro/scratch/simple-select/parser.py
diff options
context:
space:
mode:
authorWilliam Carroll <wpcarro@gmail.com>2022-03-01T02·02-0800
committerclbot <clbot@tvl.fyi>2022-03-01T02·07+0000
commiteb412699b66e3bd222c6421b3cf363fb1af8fbbc (patch)
tree99919e9a81f6682c5583e6f4013b9de76796b9b1 /users/wpcarro/scratch/simple-select/parser.py
parentb5f78e433c80f4fc29550c6278bf9ef7a4a7dbe2 (diff)
feat(wpcarro/simple-select): Parse query language 🎉 r/3882
Seems to successfully handle inputs like...

```
> (-fname:"William" lname:/C.*l/) OR (fname:"William" -lname:"Carroll")
```

Change-Id: I5277cfbc7d102158eab5e1e71b2d95aaf13508fd
Reviewed-on: https://cl.tvl.fyi/c/depot/+/5340
Reviewed-by: wpcarro <wpcarro@gmail.com>
Autosubmit: wpcarro <wpcarro@gmail.com>
Tested-by: BuildkiteCI
Diffstat (limited to 'users/wpcarro/scratch/simple-select/parser.py')
-rw-r--r--users/wpcarro/scratch/simple-select/parser.py29
1 files changed, 16 insertions, 13 deletions
diff --git a/users/wpcarro/scratch/simple-select/parser.py b/users/wpcarro/scratch/simple-select/parser.py
index 407bff61c980..d26f970e57a2 100644
--- a/users/wpcarro/scratch/simple-select/parser.py
+++ b/users/wpcarro/scratch/simple-select/parser.py
@@ -3,26 +3,29 @@ class Parser(object):
         self.tokens = tokens
         self.i = 0
 
-    def prev(self):
-        return self.tokens[self.i - 1]
+    def exhausted(self):
+        return self.i >= len(self.tokens)
 
-    def curr(self):
-        return self.tokens[self.i]
+    def peek(self, n=0):
+        return self.tokens[self.i + n]
 
-    def consume(self):
+    def advance(self):
         if not self.exhausted():
             self.i += 1
-            return self.prev()
+        return self.peek(n=-1)
 
     def match(self, xs):
-        if not self.exhausted() and self.curr() in xs:
-            self.consume()
+        if self.peek() in xs:
+            self.advance()
             return True
         return False
 
-    def expect(self, xs):
-        if not self.match(xs):
-            raise Exception("Expected token \"{}\" but received \"{}\"".format(xs, self.curr()))
+    def test(self, predicate):
+        return predicate(self.tokens, self.i)
 
-    def exhausted(self):
-        return self.i >= len(self.tokens)
+    def expect(self, predicate):
+        if self.exhausted():
+            raise Exception("Unexpected EOL")
+        if predicate(self.peek()):
+            return self.advance()
+        raise Exception("Unexpected token: \"{}\"".format(self.peek()))