4 class ArgError(Exception):
10 def __init__(self, game=None):
13 def tokenize(self, msg):
14 """Parse msg string into tokens.
16 Separates by ' ' and '\n', but allows whitespace in tokens quoted by
17 '"', and allows escaping within quoted tokens by a prefixed backslash.
36 elif c in {' ', '\n'}:
47 """Parse msg as call to function, return function with args tuple.
49 Respects function signature defined in function's .argtypes attribute.
51 tokens = self.tokenize(msg)
54 func, argtypes = self.game.get_command_signature(tokens[0])
57 if len(argtypes) == 0:
59 raise ArgError('Command expects no argument(s).')
62 raise ArgError('Command expects argument(s).')
63 args_candidates = tokens[1:]
64 args = self.argsparse(argtypes, args_candidates)
67 def parse_yx_tuple(self, yx_string, range_):
68 """Parse yx_string as yx_tuple:nonneg argtype, return result.
70 The range_ argument may be 'nonneg' (non-negative, including 0)
71 or 'pos' (positive, excluding 0).
74 def get_axis_position_from_argument(axis, token):
75 if len(token) < 3 or token[:2] != axis + ':' or \
76 not token[2:].isdigit():
77 raise ArgError('Non-int arg for ' + axis + ' position.')
79 if n < 1 and range_ == 'pos':
80 raise ArgError('Arg for ' + axis + ' position < 1.')
81 elif n < 0 and range_ == 'nonneg':
82 raise ArgError('Arg for ' + axis + ' position < 0.')
85 tokens = yx_string.split(',')
87 raise ArgError('Wrong number of yx-tuple arguments.')
88 y = get_axis_position_from_argument('Y', tokens[0])
89 x = get_axis_position_from_argument('X', tokens[1])
92 def argsparse(self, signature, args_tokens):
93 """Parse into / return args_tokens as args defined by signature.
95 Expects signature to be a ' '-delimited sequence of any of the strings
96 'int:nonneg', 'yx_tuple:nonneg', 'yx_tuple:pos', 'string',
97 'seq:int:nonneg', 'string:' + an option type string accepted by
98 self.game.get_string_options, defining the respective argument types.
100 tmpl_tokens = signature.split()
101 if len(tmpl_tokens) != len(args_tokens):
102 raise ArgError('Number of arguments (' + str(len(args_tokens)) +
103 ') not expected number (' + str(len(tmpl_tokens))
106 string_string = 'string'
107 for i in range(len(tmpl_tokens)):
108 tmpl = tmpl_tokens[i]
110 if tmpl == 'int:nonneg':
111 if not arg.isdigit():
112 raise ArgError('Argument must be non-negative integer.')
114 elif tmpl == 'yx_tuple:nonneg':
115 args += [self.parse_yx_tuple(arg, 'nonneg')]
116 elif tmpl == 'yx_tuple:pos':
117 args += [self.parse_yx_tuple(arg, 'pos')]
118 elif tmpl == 'seq:int:nonneg':
119 sub_tokens = arg.split(',')
120 if len(sub_tokens) < 1:
121 raise ArgError('Argument must be non-empty sequence.')
123 for tok in sub_tokens:
124 if not tok.isdigit():
125 raise ArgError('Argument sequence must only contain '
126 'non-negative integers.')
129 elif tmpl == string_string:
131 elif tmpl[:len(string_string) + 1] == string_string + ':':
132 if not hasattr(self.game, 'get_string_options'):
133 raise ArgError('No string option directory.')
134 string_option_type = tmpl[len(string_string) + 1:]
135 options = self.game.get_string_options(string_option_type)
137 raise ArgError('Unknown string option type.')
138 if arg not in options:
139 msg = 'Argument #%s must be one of: %s' % (i + 1, options)
143 raise ArgError('Unknown argument type.')
147 class TestParser(unittest.TestCase):
149 def test_tokenizer(self):
151 self.assertEqual(p.tokenize(''), [])
152 self.assertEqual(p.tokenize(' '), [])
153 self.assertEqual(p.tokenize('abc'), ['abc'])
154 self.assertEqual(p.tokenize('a b\nc "d"'), ['a', 'b', 'c', 'd'])
155 self.assertEqual(p.tokenize('a "b\nc d"'), ['a', 'b\nc d'])
156 self.assertEqual(p.tokenize('a"b"c'), ['abc'])
157 self.assertEqual(p.tokenize('a\\b'), ['a\\b'])
158 self.assertEqual(p.tokenize('"a\\b"'), ['ab'])
159 self.assertEqual(p.tokenize('a"b'), ['ab'])
160 self.assertEqual(p.tokenize('a"\\"b'), ['a"b'])
162 def test_unhandled(self):
164 self.assertEqual(p.parse(''), None)
165 self.assertEqual(p.parse(' '), None)
166 self.assertEqual(p.parse('x'), None)
168 def test_argsparse(self):
169 from functools import partial
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',)),
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',)),
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',)),
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',)),