2 from functools import partial
5 class ArgError(Exception):
11 def __init__(self, game=None):
14 def tokenize(self, msg):
15 """Parse msg string into tokens.
17 Separates by ' ' and '\n', but allows whitespace in tokens quoted by
18 '"', and allows escaping within quoted tokens by a prefixed backslash.
37 elif c in {' ', '\n'}:
48 """Parse msg as call to method, return method with arguments.
50 Respects method signatures defined in methods' .argtypes attributes.
52 tokens = self.tokenize(msg)
55 method, argtypes = self.game.get_command_signature(tokens[0])
58 if len(argtypes) == 0:
60 raise ArgError('Command expects no argument(s).')
63 raise ArgError('Command expects argument(s).')
64 args_candidates = tokens[1:]
65 args = self.argsparse(argtypes, args_candidates)
66 return partial(method, *args)
68 def parse_yx_tuple(self, yx_string, range_):
69 """Parse yx_string as yx_tuple:nonneg argtype, return result.
71 The range_ argument may be 'nonneg' (non-negative, including 0)
72 or 'pos' (positive, excluding 0).
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.')
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.')
86 tokens = yx_string.split(',')
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])
93 def argsparse(self, signature, args_tokens):
94 """Parse into / return args_tokens as args defined by signature.
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.
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))
107 string_string = 'string'
108 for i in range(len(tmpl_tokens)):
109 tmpl = tmpl_tokens[i]
111 if tmpl == 'int:nonneg':
112 if not arg.isdigit():
113 raise ArgError('Argument must be non-negative integer.')
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.')
124 for tok in sub_tokens:
125 if not tok.isdigit():
126 raise ArgError('Argument sequence must only contain '
127 'non-negative integers.')
130 elif tmpl == string_string:
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)
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)
144 raise ArgError('Unknown argument type.')
148 class TestParser(unittest.TestCase):
150 def test_tokenizer(self):
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'])
163 def test_unhandled(self):
165 self.assertEqual(p.parse(''), None)
166 self.assertEqual(p.parse(' '), None)
167 self.assertEqual(p.parse('x'), None)
169 def test_argsparse(self):
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',)),