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 argsparse(self, signature, args_tokens):
68 tmpl_tokens = signature.split()
69 if len(tmpl_tokens) != len(args_tokens):
70 raise ArgError('Number of arguments (' + str(len(args_tokens)) +
71 ') not expected number (' + str(len(tmpl_tokens))
74 string_string = 'string'
75 for i in range(len(tmpl_tokens)):
78 if tmpl == string_string:
80 elif tmpl[:len(string_string) + 1] == string_string + ':':
81 if not hasattr(self.game, 'get_string_options'):
82 raise ArgError('No string option directory.')
83 string_option_type = tmpl[len(string_string) + 1:]
84 options = self.game.get_string_options(string_option_type)
86 raise ArgError('Unknown string option type.')
87 if arg not in options:
88 msg = 'Argument #%s must be one of: %s' % (i + 1, options)
92 raise ArgError('Unknown argument type: %s' % tmpl)