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'}:
44 def parse_yx_tuple(self, yx_string, range_=None):
45 """Parse yx_string as yx_tuple, return result.
47 The range_ argument may be 'nonneg' (non-negative, including
48 0) or 'pos' (positive, excluding 0).
52 def get_axis_position_from_argument(axis, token):
53 if len(token) < 3 or token[:2] != axis + ':' or \
54 not (token[2:].isdigit() or token[2] == '-'):
55 raise ArgError('Non-int arg for ' + axis + ' position.')
57 if n < 1 and range_ == 'pos':
58 raise ArgError('Arg for ' + axis + ' position < 1.')
59 elif n < 0 and range_ == 'nonneg':
60 raise ArgError('Arg for ' + axis + ' position < 0.')
63 tokens = yx_string.split(',')
65 raise ArgError('Wrong number of yx-tuple arguments.')
66 y = get_axis_position_from_argument('Y', tokens[0])
67 x = get_axis_position_from_argument('X', tokens[1])
71 """Parse msg as call to function, return function with args tuple.
73 Respects function signature defined in function's .argtypes attribute.
75 tokens = self.tokenize(msg)
78 func = self.game.get_command(tokens[0])
80 if hasattr(func, 'argtypes'):
81 argtypes = func.argtypes
84 if len(argtypes) == 0:
86 raise ArgError('Command expects no argument(s).')
89 raise ArgError('Command expects argument(s).')
90 args_candidates = tokens[1:]
91 args = self.argsparse(argtypes, args_candidates)
94 def argsparse(self, signature, args_tokens):
95 tmpl_tokens = signature.split()
96 if len(tmpl_tokens) != len(args_tokens):
97 raise ArgError('Number of arguments (' + str(len(args_tokens)) +
98 ') not expected number (' + str(len(tmpl_tokens))
101 string_string = 'string'
102 for i in range(len(tmpl_tokens)):
103 tmpl = tmpl_tokens[i]
105 if tmpl == 'int:nonneg':
106 if not arg.isdigit():
107 raise ArgError('Argument must be non-negative integer.')
109 elif tmpl == 'yx_tuple:nonneg':
110 args += [self.parse_yx_tuple(arg, 'nonneg')]
111 elif tmpl == 'yx_tuple:pos':
112 args += [self.parse_yx_tuple(arg, 'pos')]
113 elif tmpl == string_string:
115 elif tmpl[:len(string_string) + 1] == string_string + ':':
116 if not hasattr(self.game, 'get_string_options'):
117 raise ArgError('No string option directory.')
118 string_option_type = tmpl[len(string_string) + 1:]
119 options = self.game.get_string_options(string_option_type)
121 raise ArgError('Unknown string option type.')
122 if arg not in options:
123 msg = 'Argument #%s must be one of: %s' % (i + 1, options)
127 raise ArgError('Unknown argument type: %s' % tmpl)