1. Lucian Brănescu-Mihăilă
  2. lsp

Commits

Lucian Brănescu-Mihăilă  committed d1bb611

Generalize parser collection handling.

  • Participants
  • Parent commits 790eecd
  • Branches default

Comments (0)

Files changed (1)

File lsp.py

View file
 
 class List(list, Collection):
     start = '('
-    end = ')'
+    stop = ')'
 
     def __repr__(self):
         return '(' + ' '.join(map(str, self)) + ')'
 
 class Vector(list, Collection):
     start = '['
-    end = ']'
+    stop = ']'
 
     def __repr__(self):
         return '[' + ' '.join(map(str, self)) + ']'
         return exp
 
 
+def parse_coll(kind, tokens, quoting):
+    exp = []
+
+    while True:
+        try:
+            if tokens[0] == kind.stop:
+                break
+        except IndexError:
+            raise SyntaxError("Expected '{0}'".format(kind.stop))
+
+        exp.append(parse(tokens))
+
+    tokens.pop(0)  # Remove ')'
+    exp = kind(exp)
+
+    return quote_wrap(exp, quoting)
+
+
 def parse(tokens):
     if len(tokens) == 0:
         raise SyntaxError("Unexpected EOF")
 
     # Lists
     if tok == '(':
-        exp = []
+        return parse_coll(List, tokens, quoting)
+    elif tok == '[':
+        return parse_coll(Vector, tokens, quoting)
 
-        while True:
-            try:
-                if tokens[0] == ')':
-                    break
-            except IndexError:
-                raise SyntaxError("Expected ')'")
-
-            exp.append(parse(tokens))
-
-        tokens.pop(0)  # Remove ')'
-        exp = List(exp)
-
-        return quote_wrap(exp, quoting)
-
-    if tok == ')':
-        raise SyntaxError("Unexpected ')'")
+    for i in [List.stop, Vector.stop]:
+        if tok == i:
+            raise SyntaxError("Unexpected '{0}'".format(i))
 
     # Strings
     if len(tok) >= 2 and tok[0] == '"' and tok[-1] == '"':