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_):
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':
122 sub_tokens = arg.split(',')
123 if len(sub_tokens) < 1:
124 raise ArgError('Argument must be non-empty sequence.')
126 for tok in sub_tokens:
127 if not tok.isdigit():
128 raise ArgError('Argument sequence must only contain '
129 'non-negative integers.')
132 elif tmpl == string_string:
134 elif tmpl[:len(string_string) + 1] == string_string + ':':
135 if not hasattr(self.game, 'get_string_options'):
136 raise ArgError('No string option directory.')
137 string_option_type = tmpl[len(string_string) + 1:]
138 options = self.game.get_string_options(string_option_type)
140 raise ArgError('Unknown string option type.')
141 if arg not in options:
142 msg = 'Argument #%s must be one of: %s' % (i + 1, options)
146 raise ArgError('Unknown argument type.')
150 class TestParser(unittest.TestCase):
152 def test_tokenizer(self):
154 self.assertEqual(p.tokenize(''), [])
155 self.assertEqual(p.tokenize(' '), [])
156 self.assertEqual(p.tokenize('abc'), ['abc'])
157 self.assertEqual(p.tokenize('a b\nc "d"'), ['a', 'b', 'c', 'd'])
158 self.assertEqual(p.tokenize('a "b\nc d"'), ['a', 'b\nc d'])
159 self.assertEqual(p.tokenize('a"b"c'), ['abc'])
160 self.assertEqual(p.tokenize('a\\b'), ['a\\b'])
161 self.assertEqual(p.tokenize('"a\\b"'), ['ab'])
162 self.assertEqual(p.tokenize('a"b'), ['ab'])
163 self.assertEqual(p.tokenize('a"\\"b'), ['a"b'])
165 def test_unhandled(self):
167 self.assertEqual(p.parse(''), None)
168 self.assertEqual(p.parse(' '), None)
169 self.assertEqual(p.parse('x'), None)
171 def test_argsparse(self):
172 from functools import partial
174 assertErr = partial(self.assertRaises, ArgError, p.argsparse)
175 assertErr('', ['foo'])
176 assertErr('string', [])
177 assertErr('string string', ['foo'])
178 self.assertEqual(p.argsparse('string', ('foo',)),
180 self.assertEqual(p.argsparse('string string', ('foo', 'bar')),
181 (['foo', 'bar'], {}))
182 assertErr('int:nonneg', [''])
183 assertErr('int:nonneg', ['x'])
184 assertErr('int:nonneg', ['-1'])
185 assertErr('int:nonneg', ['0.1'])
186 self.assertEqual(p.argsparse('int:nonneg', ('0',)),
188 assertErr('yx_tuple:nonneg', ['x'])
189 assertErr('yx_tuple:nonneg', ['Y:0,X:-1'])
190 assertErr('yx_tuple:nonneg', ['Y:-1,X:0'])
191 assertErr('yx_tuple:nonneg', ['Y:1.1,X:1'])
192 assertErr('yx_tuple:nonneg', ['Y:1,X:1.1'])
193 self.assertEqual(p.argsparse('yx_tuple:nonneg', ('Y:1,X:2',)),
195 assertErr('yx_tuple:pos', ['Y:0,X:1'])
196 assertErr('yx_tuple:pos', ['Y:1,X:0'])
197 assertErr('seq:int:nonneg', [''])
198 assertErr('seq:int:nonneg', [','])
199 assertErr('seq:int:nonneg', ['a'])
200 assertErr('seq:int:nonneg', ['a,1'])
201 assertErr('seq:int:nonneg', [',1'])
202 assertErr('seq:int:nonneg', ['1,'])
203 self.assertEqual(p.argsparse('seq:int:nonneg', ('1,2,3',)),