2 from plomrogue.errors import ArgError
7 def __init__(self, game=None):
10 def tokenize(self, msg):
11 """Parse msg string into tokens.
13 Separates by ' ' and '\n', but allows whitespace in tokens quoted by
14 '"', and allows escaping within quoted tokens by a prefixed backslash.
33 elif c in {' ', '\n'}:
44 """Parse msg as call to function, return function with args tuple.
46 Respects function signature defined in function's .argtypes attribute.
48 tokens = self.tokenize(msg)
51 func = self.game.get_command(tokens[0])
53 if hasattr(func, 'argtypes'):
54 argtypes = func.argtypes
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_=None):
68 """Parse yx_string as yx_tuple, return result.
70 The range_ argument may be 'nonneg' (non-negative, including
71 0) 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() or token[2] == '-'):
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', '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 == 'yx_tuple':
120 args += [self.parse_yx_tuple(arg)]
121 elif tmpl == 'seq:int:nonneg':
125 sub_tokens = arg.split(',')
126 if len(sub_tokens) < 1:
127 raise ArgError('Argument must be non-empty sequence.')
129 for tok in sub_tokens:
130 if not tok.isdigit():
131 raise ArgError('Argument sequence must only contain '
132 'non-negative integers.')
135 elif tmpl == string_string:
137 elif tmpl[:len(string_string) + 1] == string_string + ':':
138 if not hasattr(self.game, 'get_string_options'):
139 raise ArgError('No string option directory.')
140 string_option_type = tmpl[len(string_string) + 1:]
141 options = self.game.get_string_options(string_option_type)
143 raise ArgError('Unknown string option type.')
144 if arg not in options:
145 msg = 'Argument #%s must be one of: %s' % (i + 1, options)
149 raise ArgError('Unknown argument type.')
153 class TestParser(unittest.TestCase):
155 def test_tokenizer(self):
157 self.assertEqual(p.tokenize(''), [])
158 self.assertEqual(p.tokenize(' '), [])
159 self.assertEqual(p.tokenize('abc'), ['abc'])
160 self.assertEqual(p.tokenize('a b\nc "d"'), ['a', 'b', 'c', 'd'])
161 self.assertEqual(p.tokenize('a "b\nc d"'), ['a', 'b\nc d'])
162 self.assertEqual(p.tokenize('a"b"c'), ['abc'])
163 self.assertEqual(p.tokenize('a\\b'), ['a\\b'])
164 self.assertEqual(p.tokenize('"a\\b"'), ['ab'])
165 self.assertEqual(p.tokenize('a"b'), ['ab'])
166 self.assertEqual(p.tokenize('a"\\"b'), ['a"b'])
168 def test_unhandled(self):
170 self.assertEqual(p.parse(''), (None, ()))
171 self.assertEqual(p.parse(' '), (None, ()))
172 #self.assertEqual(p.parse('x'), (None, ()))
174 def test_argsparse(self):
175 from functools import partial
177 assertErr = partial(self.assertRaises, ArgError, p.argsparse)
178 assertErr('', ['foo'])
179 assertErr('string', [])
180 assertErr('string string', ['foo'])
181 self.assertEqual(p.argsparse('string', ('foo',)), ['foo'])
182 self.assertEqual(p.argsparse('string string', ('foo', 'bar')),
184 assertErr('int:nonneg', [''])
185 assertErr('int:nonneg', ['x'])
186 assertErr('int:nonneg', ['-1'])
187 assertErr('int:nonneg', ['0.1'])
188 self.assertEqual(p.argsparse('int:nonneg', ('0',)), [0])
189 assertErr('yx_tuple', ['x'])
190 assertErr('yx_tuple', ['Y:1.1,X:1'])
191 self.assertEqual(p.argsparse('yx_tuple', ('Y:1,X:-2',)), [(1, -2)])
192 assertErr('yx_tuple:nonneg', ['Y:0,X:-1'])
193 assertErr('yx_tuple:nonneg', ['Y:-1,X:0'])
194 assertErr('yx_tuple:nonneg', ['Y:1,X:1.1'])
195 self.assertEqual(p.argsparse('yx_tuple:nonneg', ('Y:1,X:2',)),
197 assertErr('yx_tuple:pos', ['Y:0,X:1'])
198 assertErr('yx_tuple:pos', ['Y:1,X:0'])
199 assertErr('seq:int:nonneg', [''])
200 self.assertEqual(p.argsparse('seq:int:nonneg', [',']), [[]])
201 assertErr('seq:int:nonneg', ['a'])
202 assertErr('seq:int:nonneg', ['a,1'])
203 assertErr('seq:int:nonneg', [',1'])
204 assertErr('seq:int:nonneg', ['1,'])
205 self.assertEqual(p.argsparse('seq:int:nonneg', ('1,2,3',)),