home · contact · privacy
To command parser, add string options; use TASK syntax for task commands.
[plomrogue2-experiments] / parser.py
1 import unittest
2 from functools import partial
3
4
5 class ArgError(Exception):
6     pass
7
8
9 class Parser:
10
11     def __init__(self, game=None):
12         self.game = game
13
14     def tokenize(self, msg):
15         """Parse msg string into tokens.
16
17         Separates by ' ' and '\n', but allows whitespace in tokens quoted by
18         '"', and allows escaping within quoted tokens by a prefixed backslash.
19         """
20         tokens = []
21         token = ''
22         quoted = False
23         escaped = False
24         for c in msg:
25             if quoted:
26                 if escaped:
27                     token += c
28                     escaped = False
29                 elif c == '\\':
30                     escaped = True
31                 elif c == '"':
32                     quoted = False
33                 else:
34                     token += c
35             elif c == '"':
36                 quoted = True
37             elif c in {' ', '\n'}:
38                 if len(token) > 0:
39                     tokens += [token]
40                     token = ''
41             else:
42                 token += c
43         if len(token) > 0:
44             tokens += [token]
45         return tokens
46
47     def parse(self, msg):
48         """Parse msg as call to method, return method with arguments.
49
50         Respects method signatures defined in methods' .argtypes attributes.
51         """
52         tokens = self.tokenize(msg)
53         if len(tokens) == 0:
54             return None
55         method, argtypes = self.game.get_command_signature(tokens[0])
56         if method is None:
57             return None
58         if len(argtypes) == 0:
59             if len(tokens) > 1:
60                 raise ArgError('Command expects no argument(s).')
61             return method
62         if len(tokens) == 1:
63             raise ArgError('Command expects argument(s).')
64         args_candidates = tokens[1:]
65         args = self.argsparse(argtypes, args_candidates)
66         return partial(method, *args)
67
68     def parse_yx_tuple(self, yx_string, range_):
69         """Parse yx_string as yx_tuple:nonneg argtype, return result.
70
71         The range_ argument may be 'nonneg' (non-negative, including 0)
72         or 'pos' (positive, excluding 0).
73         """
74
75         def get_axis_position_from_argument(axis, token):
76             if len(token) < 3 or token[:2] != axis + ':' or \
77                     not token[2:].isdigit():
78                 raise ArgError('Non-int arg for ' + axis + ' position.')
79             n = int(token[2:])
80             if n < 1 and range_ == 'pos':
81                 raise ArgError('Arg for ' + axis + ' position < 1.')
82             elif n < 0 and range_ == 'nonneg':
83                 raise ArgError('Arg for ' + axis + ' position < 0.')
84             return n
85
86         tokens = yx_string.split(',')
87         if len(tokens) != 2:
88             raise ArgError('Wrong number of yx-tuple arguments.')
89         y = get_axis_position_from_argument('Y', tokens[0])
90         x = get_axis_position_from_argument('X', tokens[1])
91         return (y, x)
92
93     def argsparse(self, signature, args_tokens):
94         """Parse into / return args_tokens as args defined by signature.
95
96         Expects signature to be a ' '-delimited sequence of any of the strings
97         'int:nonneg', 'yx_tuple:nonneg', 'yx_tuple:pos', 'string',
98         'seq:int:nonneg', 'string:' + an option type string accepted by
99         self.game.get_string_options, defining the respective argument types.
100         """
101         tmpl_tokens = signature.split()
102         if len(tmpl_tokens) != len(args_tokens):
103             raise ArgError('Number of arguments (' + str(len(args_tokens)) +
104                            ') not expected number (' + str(len(tmpl_tokens))
105                            + ').')
106         args = []
107         string_string = 'string'
108         for i in range(len(tmpl_tokens)):
109             tmpl = tmpl_tokens[i]
110             arg = args_tokens[i]
111             if tmpl == 'int:nonneg':
112                 if not arg.isdigit():
113                     raise ArgError('Argument must be non-negative integer.')
114                 args += [int(arg)]
115             elif tmpl == 'yx_tuple:nonneg':
116                 args += [self.parse_yx_tuple(arg, 'nonneg')]
117             elif tmpl == 'yx_tuple:pos':
118                 args += [self.parse_yx_tuple(arg, 'pos')]
119             elif tmpl == 'seq:int:nonneg':
120                 sub_tokens = arg.split(',')
121                 if len(sub_tokens) < 1:
122                     raise ArgError('Argument must be non-empty sequence.')
123                 seq = []
124                 for tok in sub_tokens:
125                     if not tok.isdigit():
126                         raise ArgError('Argument sequence must only contain '
127                                        'non-negative integers.')
128                     seq += [int(tok)]
129                 args += [seq]
130             elif tmpl == string_string:
131                 args += [arg]
132             elif tmpl[:len(string_string) + 1] == string_string + ':':
133                 if not hasattr(self.game, 'get_string_options'):
134                     raise ArgError('No string option directory.')
135                 string_option_type = tmpl[len(string_string) + 1:]
136                 options = self.game.get_string_options(string_option_type)
137                 if options is None:
138                     raise ArgError('Unknown string option type.')
139                 if arg not in options:
140                     msg = 'Argument #%s must be one of: %s' % (i + 1, options)
141                     raise ArgError(msg)
142                 args += [arg]
143             else:
144                 raise ArgError('Unknown argument type.')
145         return args
146
147
148 class TestParser(unittest.TestCase):
149
150     def test_tokenizer(self):
151         p = Parser()
152         self.assertEqual(p.tokenize(''), [])
153         self.assertEqual(p.tokenize(' '), [])
154         self.assertEqual(p.tokenize('abc'), ['abc'])
155         self.assertEqual(p.tokenize('a b\nc  "d"'), ['a', 'b', 'c', 'd'])
156         self.assertEqual(p.tokenize('a "b\nc d"'), ['a', 'b\nc d'])
157         self.assertEqual(p.tokenize('a"b"c'), ['abc'])
158         self.assertEqual(p.tokenize('a\\b'), ['a\\b'])
159         self.assertEqual(p.tokenize('"a\\b"'), ['ab'])
160         self.assertEqual(p.tokenize('a"b'), ['ab'])
161         self.assertEqual(p.tokenize('a"\\"b'), ['a"b'])
162
163     def test_unhandled(self):
164         p = Parser()
165         self.assertEqual(p.parse(''), None)
166         self.assertEqual(p.parse(' '), None)
167         self.assertEqual(p.parse('x'), None)
168
169     def test_argsparse(self):
170         p = Parser()
171         assertErr = partial(self.assertRaises, ArgError, p.argsparse)
172         assertErr('', ['foo'])
173         assertErr('string', [])
174         assertErr('string string', ['foo'])
175         self.assertEqual(p.argsparse('string', ('foo',)),
176                          (['foo'], {}))
177         self.assertEqual(p.argsparse('string string', ('foo', 'bar')),
178                          (['foo', 'bar'], {}))
179         assertErr('int:nonneg', [''])
180         assertErr('int:nonneg', ['x'])
181         assertErr('int:nonneg', ['-1'])
182         assertErr('int:nonneg', ['0.1'])
183         self.assertEqual(p.argsparse('int:nonneg', ('0',)),
184                          ([0], {}))
185         assertErr('yx_tuple:nonneg', ['x'])
186         assertErr('yx_tuple:nonneg', ['Y:0,X:-1'])
187         assertErr('yx_tuple:nonneg', ['Y:-1,X:0'])
188         assertErr('yx_tuple:nonneg', ['Y:1.1,X:1'])
189         assertErr('yx_tuple:nonneg', ['Y:1,X:1.1'])
190         self.assertEqual(p.argsparse('yx_tuple:nonneg', ('Y:1,X:2',)),
191                          ([(1, 2)], {}))
192         assertErr('yx_tuple:pos', ['Y:0,X:1'])
193         assertErr('yx_tuple:pos', ['Y:1,X:0'])
194         assertErr('seq:int:nonneg', [''])
195         assertErr('seq:int:nonneg', [','])
196         assertErr('seq:int:nonneg', ['a'])
197         assertErr('seq:int:nonneg', ['a,1'])
198         assertErr('seq:int:nonneg', [',1'])
199         assertErr('seq:int:nonneg', ['1,'])
200         self.assertEqual(p.argsparse('seq:int:nonneg', ('1,2,3',)),
201                          ([[1, 2, 3]], {}))