home · contact · privacy
f23a7aaacb58e8f89604f85ec1b525e0e0ac9d01
[plomrogue2-experiments] / new2 / plomrogue / parser.py
1 import unittest
2 from plomrogue.errors import ArgError
3
4
5 class Parser:
6
7     def __init__(self, game=None):
8         self.game = game
9
10     def tokenize(self, msg):
11         """Parse msg string into tokens.
12
13         Separates by ' ' and '\n', but allows whitespace in tokens quoted by
14         '"', and allows escaping within quoted tokens by a prefixed backslash.
15         """
16         tokens = []
17         token = ''
18         quoted = False
19         escaped = False
20         for c in msg:
21             if quoted:
22                 if escaped:
23                     token += c
24                     escaped = False
25                 elif c == '\\':
26                     escaped = True
27                 elif c == '"':
28                     quoted = False
29                 else:
30                     token += c
31             elif c == '"':
32                 quoted = True
33             elif c in {' ', '\n'}:
34                 if len(token) > 0:
35                     tokens += [token]
36                     token = ''
37             else:
38                 token += c
39         if len(token) > 0:
40             tokens += [token]
41         return tokens
42
43     def parse(self, msg):
44         """Parse msg as call to function, return function with args tuple.
45
46         Respects function signature defined in function's .argtypes attribute.
47         """
48         tokens = self.tokenize(msg)
49         if len(tokens) == 0:
50             return None, ()
51         func = self.game.get_command(tokens[0])
52         argtypes = ''
53         if hasattr(func, 'argtypes'):
54             argtypes = func.argtypes
55         if func is None:
56             return None, ()
57         if len(argtypes) == 0:
58             if len(tokens) > 1:
59                 raise ArgError('Command expects no argument(s).')
60             return func, ()
61         if len(tokens) == 1:
62             raise ArgError('Command expects argument(s).')
63         args_candidates = tokens[1:]
64         args = self.argsparse(argtypes, args_candidates)
65         return func, args
66
67     def argsparse(self, signature, args_tokens):
68         tmpl_tokens = signature.split()
69         if len(tmpl_tokens) != len(args_tokens):
70             raise ArgError('Number of arguments (' + str(len(args_tokens)) +
71                            ') not expected number (' + str(len(tmpl_tokens))
72                            + ').')
73         args = []
74         string_string = 'string'
75         for i in range(len(tmpl_tokens)):
76             tmpl = tmpl_tokens[i]
77             arg = args_tokens[i]
78             if tmpl == 'int:nonneg':
79                 if not arg.isdigit():
80                     raise ArgError('Argument must be non-negative integer.')
81                 args += [int(arg)]
82             elif tmpl == string_string:
83                 args += [arg]
84             elif tmpl[:len(string_string) + 1] == string_string + ':':
85                 if not hasattr(self.game, 'get_string_options'):
86                     raise ArgError('No string option directory.')
87                 string_option_type = tmpl[len(string_string) + 1:]
88                 options = self.game.get_string_options(string_option_type)
89                 if options is None:
90                     raise ArgError('Unknown string option type.')
91                 if arg not in options:
92                     msg = 'Argument #%s must be one of: %s' % (i + 1, options)
93                     raise ArgError(msg)
94                 args += [arg]
95             else:
96                 raise ArgError('Unknown argument type: %s' % tmpl)
97         return args