home · contact · privacy
Add basic multiplayer roguelike chat example.
[plomrogue2-experiments] / new2 / plomrogue / parser.py
diff --git a/new2/plomrogue/parser.py b/new2/plomrogue/parser.py
new file mode 100644 (file)
index 0000000..a56b5d1
--- /dev/null
@@ -0,0 +1,93 @@
+import unittest
+from plomrogue.errors import ArgError
+
+
+class Parser:
+
+    def __init__(self, game=None):
+        self.game = game
+
+    def tokenize(self, msg):
+        """Parse msg string into tokens.
+
+        Separates by ' ' and '\n', but allows whitespace in tokens quoted by
+        '"', and allows escaping within quoted tokens by a prefixed backslash.
+        """
+        tokens = []
+        token = ''
+        quoted = False
+        escaped = False
+        for c in msg:
+            if quoted:
+                if escaped:
+                    token += c
+                    escaped = False
+                elif c == '\\':
+                    escaped = True
+                elif c == '"':
+                    quoted = False
+                else:
+                    token += c
+            elif c == '"':
+                quoted = True
+            elif c in {' ', '\n'}:
+                if len(token) > 0:
+                    tokens += [token]
+                    token = ''
+            else:
+                token += c
+        if len(token) > 0:
+            tokens += [token]
+        return tokens
+
+    def parse(self, msg):
+        """Parse msg as call to function, return function with args tuple.
+
+        Respects function signature defined in function's .argtypes attribute.
+        """
+        tokens = self.tokenize(msg)
+        if len(tokens) == 0:
+            return None, ()
+        func = self.game.get_command(tokens[0])
+        argtypes = ''
+        if hasattr(func, 'argtypes'):
+            argtypes = func.argtypes
+        if func is None:
+            return None, ()
+        if len(argtypes) == 0:
+            if len(tokens) > 1:
+                raise ArgError('Command expects no argument(s).')
+            return func, ()
+        if len(tokens) == 1:
+            raise ArgError('Command expects argument(s).')
+        args_candidates = tokens[1:]
+        args = self.argsparse(argtypes, args_candidates)
+        return func, args
+
+    def argsparse(self, signature, args_tokens):
+        tmpl_tokens = signature.split()
+        if len(tmpl_tokens) != len(args_tokens):
+            raise ArgError('Number of arguments (' + str(len(args_tokens)) +
+                           ') not expected number (' + str(len(tmpl_tokens))
+                           + ').')
+        args = []
+        string_string = 'string'
+        for i in range(len(tmpl_tokens)):
+            tmpl = tmpl_tokens[i]
+            arg = args_tokens[i]
+            if tmpl == string_string:
+                args += [arg]
+            elif tmpl[:len(string_string) + 1] == string_string + ':':
+                if not hasattr(self.game, 'get_string_options'):
+                    raise ArgError('No string option directory.')
+                string_option_type = tmpl[len(string_string) + 1:]
+                options = self.game.get_string_options(string_option_type)
+                if options is None:
+                    raise ArgError('Unknown string option type.')
+                if arg not in options:
+                    msg = 'Argument #%s must be one of: %s' % (i + 1, options)
+                    raise ArgError(msg)
+                args += [arg]
+            else:
+                raise ArgError('Unknown argument type: %s' % tmpl)
+        return args