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
98 strings 'bool', 'int:nonneg', 'yx_tuple', 'yx_tuple:nonneg',
99 'yx_tuple:pos', 'string', 'seq:int:nonneg', 'string:' + an
100 option type string accepted by self.game.get_string_options,
101 defining the respective argument types.
104 tmpl_tokens = signature.split()
105 if len(tmpl_tokens) != len(args_tokens):
106 raise ArgError('Number of arguments (' + str(len(args_tokens)) +
107 ') not expected number (' + str(len(tmpl_tokens))
110 string_string = 'string'
111 for i in range(len(tmpl_tokens)):
112 tmpl = tmpl_tokens[i]
115 if arg not in {'True', 'False'}:
116 raise ArgError('Argument must be "True" or "False".')
117 args += [True if arg == 'True' else False]
118 elif tmpl == 'int:nonneg':
119 if not arg.isdigit():
120 raise ArgError('Argument must be non-negative integer.')
122 elif tmpl == 'yx_tuple:nonneg':
123 args += [self.parse_yx_tuple(arg, 'nonneg')]
124 elif tmpl == 'yx_tuple:pos':
125 args += [self.parse_yx_tuple(arg, 'pos')]
126 elif tmpl == 'yx_tuple':
127 args += [self.parse_yx_tuple(arg)]
128 elif tmpl == 'seq:int:nonneg':
132 sub_tokens = arg.split(',')
133 if len(sub_tokens) < 1:
134 raise ArgError('Argument must be non-empty sequence.')
136 for tok in sub_tokens:
137 if not tok.isdigit():
138 raise ArgError('Argument sequence must only contain '
139 'non-negative integers.')
142 elif tmpl == string_string:
144 elif tmpl[:len(string_string) + 1] == string_string + ':':
145 if not hasattr(self.game, 'get_string_options'):
146 raise ArgError('No string option directory.')
147 string_option_type = tmpl[len(string_string) + 1:]
148 options = self.game.get_string_options(string_option_type)
150 raise ArgError('Unknown string option type.')
151 if arg not in options:
152 msg = 'Argument #%s must be one of: %s' % (i + 1, options)
156 raise ArgError('Unknown argument type: %s' % tmpl)
160 class TestParser(unittest.TestCase):
162 def test_tokenizer(self):
164 self.assertEqual(p.tokenize(''), [])
165 self.assertEqual(p.tokenize(' '), [])
166 self.assertEqual(p.tokenize('abc'), ['abc'])
167 self.assertEqual(p.tokenize('a b\nc "d"'), ['a', 'b', 'c', 'd'])
168 self.assertEqual(p.tokenize('a "b\nc d"'), ['a', 'b\nc d'])
169 self.assertEqual(p.tokenize('a"b"c'), ['abc'])
170 self.assertEqual(p.tokenize('a\\b'), ['a\\b'])
171 self.assertEqual(p.tokenize('"a\\b"'), ['ab'])
172 self.assertEqual(p.tokenize('a"b'), ['ab'])
173 self.assertEqual(p.tokenize('a"\\"b'), ['a"b'])
175 def test_unhandled(self):
177 self.assertEqual(p.parse(''), (None, ()))
178 self.assertEqual(p.parse(' '), (None, ()))
179 #self.assertEqual(p.parse('x'), (None, ()))
181 def test_argsparse(self):
182 from functools import partial
184 assertErr = partial(self.assertRaises, ArgError, p.argsparse)
185 assertErr('', ['foo'])
186 assertErr('string', [])
187 assertErr('string string', ['foo'])
188 self.assertEqual(p.argsparse('string', ('foo',)), ['foo'])
189 self.assertEqual(p.argsparse('string string', ('foo', 'bar')),
191 assertErr('int:nonneg', [''])
192 assertErr('int:nonneg', ['x'])
193 assertErr('int:nonneg', ['-1'])
194 assertErr('int:nonneg', ['0.1'])
195 self.assertEqual(p.argsparse('int:nonneg', ('0',)), [0])
196 assertErr('yx_tuple', ['x'])
197 assertErr('yx_tuple', ['Y:1.1,X:1'])
198 self.assertEqual(p.argsparse('yx_tuple', ('Y:1,X:-2',)), [(1, -2)])
199 assertErr('yx_tuple:nonneg', ['Y:0,X:-1'])
200 assertErr('yx_tuple:nonneg', ['Y:-1,X:0'])
201 assertErr('yx_tuple:nonneg', ['Y:1,X:1.1'])
202 self.assertEqual(p.argsparse('yx_tuple:nonneg', ('Y:1,X:2',)),
204 assertErr('yx_tuple:pos', ['Y:0,X:1'])
205 assertErr('yx_tuple:pos', ['Y:1,X:0'])
206 assertErr('seq:int:nonneg', [''])
207 self.assertEqual(p.argsparse('seq:int:nonneg', [',']), [[]])
208 assertErr('seq:int:nonneg', ['a'])
209 assertErr('seq:int:nonneg', ['a,1'])
210 assertErr('seq:int:nonneg', [',1'])
211 assertErr('seq:int:nonneg', ['1,'])
212 self.assertEqual(p.argsparse('seq:int:nonneg', ('1,2,3',)),