2 from plomrogue.errors import ArgError
3 from plomrogue.mapping import YX
8 def __init__(self, game=None):
11 def tokenize(self, msg):
12 """Parse msg string into tokens.
14 Separates by ' ' and '\n', but allows whitespace in tokens quoted by
15 '"', and allows escaping within quoted tokens by a prefixed backslash.
34 elif c in {' ', '\n'}:
45 """Parse msg as call to function, return function with args tuple.
47 Respects function signature defined in function's .argtypes attribute.
49 tokens = self.tokenize(msg)
52 func = self.game.get_command(tokens[0])
54 if hasattr(func, 'argtypes'):
55 argtypes = func.argtypes
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)
68 def parse_yx_tuple(self, yx_string, range_=None):
69 """Parse yx_string as yx_tuple, return result.
71 The range_ argument may be 'nonneg' (non-negative, including
72 0) or 'pos' (positive, excluding 0).
76 def get_axis_position_from_argument(axis, token):
77 if len(token) < 3 or token[:2] != axis + ':' or \
78 not (token[2:].isdigit() or token[2] == '-'):
79 raise ArgError('Non-int arg for ' + axis + ' position.')
81 if n < 1 and range_ == 'pos':
82 raise ArgError('Arg for ' + axis + ' position < 1.')
83 elif n < 0 and range_ == 'nonneg':
84 raise ArgError('Arg for ' + axis + ' position < 0.')
87 tokens = yx_string.split(',')
89 raise ArgError('Wrong number of yx-tuple arguments.')
90 y = get_axis_position_from_argument('Y', tokens[0])
91 x = get_axis_position_from_argument('X', tokens[1])
94 def argsparse(self, signature, args_tokens):
95 """Parse into / return args_tokens as args defined by signature.
97 Expects signature to be a ' '-delimited sequence of any of the strings
98 'int:nonneg', 'yx_tuple', 'yx_tuple:nonneg', 'yx_tuple:pos', 'string',
99 'seq:int:nonneg', 'string:' + an option type string accepted by
100 self.game.get_string_options, defining the respective argument types.
102 tmpl_tokens = signature.split()
103 if len(tmpl_tokens) != len(args_tokens):
104 raise ArgError('Number of arguments (' + str(len(args_tokens)) +
105 ') not expected number (' + str(len(tmpl_tokens))
108 string_string = 'string'
109 for i in range(len(tmpl_tokens)):
110 tmpl = tmpl_tokens[i]
112 if tmpl == 'int:nonneg':
113 if not arg.isdigit():
114 raise ArgError('Argument must be non-negative integer.')
116 elif tmpl == 'yx_tuple:nonneg':
117 args += [self.parse_yx_tuple(arg, 'nonneg')]
118 elif tmpl == 'yx_tuple:pos':
119 args += [self.parse_yx_tuple(arg, 'pos')]
120 elif tmpl == 'yx_tuple':
121 args += [self.parse_yx_tuple(arg)]
122 elif tmpl == 'seq:int:nonneg':
126 sub_tokens = arg.split(',')
127 if len(sub_tokens) < 1:
128 raise ArgError('Argument must be non-empty sequence.')
130 for tok in sub_tokens:
131 if not tok.isdigit():
132 raise ArgError('Argument sequence must only contain '
133 'non-negative integers.')
136 elif tmpl == string_string:
138 elif tmpl[:len(string_string) + 1] == string_string + ':':
139 if not hasattr(self.game, 'get_string_options'):
140 raise ArgError('No string option directory.')
141 string_option_type = tmpl[len(string_string) + 1:]
142 options = self.game.get_string_options(string_option_type)
144 raise ArgError('Unknown string option type.')
145 if arg not in options:
146 msg = 'Argument #%s must be one of: %s' % (i + 1, options)
150 raise ArgError('Unknown argument type.')
154 class TestParser(unittest.TestCase):
156 def test_tokenizer(self):
158 self.assertEqual(p.tokenize(''), [])
159 self.assertEqual(p.tokenize(' '), [])
160 self.assertEqual(p.tokenize('abc'), ['abc'])
161 self.assertEqual(p.tokenize('a b\nc "d"'), ['a', 'b', 'c', 'd'])
162 self.assertEqual(p.tokenize('a "b\nc d"'), ['a', 'b\nc d'])
163 self.assertEqual(p.tokenize('a"b"c'), ['abc'])
164 self.assertEqual(p.tokenize('a\\b'), ['a\\b'])
165 self.assertEqual(p.tokenize('"a\\b"'), ['ab'])
166 self.assertEqual(p.tokenize('a"b'), ['ab'])
167 self.assertEqual(p.tokenize('a"\\"b'), ['a"b'])
169 def test_unhandled(self):
171 self.assertEqual(p.parse(''), (None, ()))
172 self.assertEqual(p.parse(' '), (None, ()))
173 #self.assertEqual(p.parse('x'), (None, ()))
175 def test_argsparse(self):
176 from functools import partial
178 assertErr = partial(self.assertRaises, ArgError, p.argsparse)
179 assertErr('', ['foo'])
180 assertErr('string', [])
181 assertErr('string string', ['foo'])
182 self.assertEqual(p.argsparse('string', ('foo',)), ['foo'])
183 self.assertEqual(p.argsparse('string string', ('foo', 'bar')),
185 assertErr('int:nonneg', [''])
186 assertErr('int:nonneg', ['x'])
187 assertErr('int:nonneg', ['-1'])
188 assertErr('int:nonneg', ['0.1'])
189 self.assertEqual(p.argsparse('int:nonneg', ('0',)), [0])
190 assertErr('yx_tuple', ['x'])
191 assertErr('yx_tuple', ['Y:1.1,X:1'])
192 self.assertEqual(p.argsparse('yx_tuple', ('Y:1,X:-2',)), [(1, -2)])
193 assertErr('yx_tuple:nonneg', ['Y:0,X:-1'])
194 assertErr('yx_tuple:nonneg', ['Y:-1,X:0'])
195 assertErr('yx_tuple:nonneg', ['Y:1,X:1.1'])
196 self.assertEqual(p.argsparse('yx_tuple:nonneg', ('Y:1,X:2',)),
198 assertErr('yx_tuple:pos', ['Y:0,X:1'])
199 assertErr('yx_tuple:pos', ['Y:1,X:0'])
200 assertErr('seq:int:nonneg', [''])
201 self.assertEqual(p.argsparse('seq:int:nonneg', [',']), [[]])
202 assertErr('seq:int:nonneg', ['a'])
203 assertErr('seq:int:nonneg', ['a,1'])
204 assertErr('seq:int:nonneg', [',1'])
205 assertErr('seq:int:nonneg', ['1,'])
206 self.assertEqual(p.argsparse('seq:int:nonneg', ('1,2,3',)),