X-Git-Url: https://plomlompom.com/repos/?a=blobdiff_plain;f=plomrogue%2Fparser.py;h=51f5cc20390ac71c50b5b1baae7f53fcd7c12bdd;hb=f3e107445e4de3f4e79c3d369dd70f5bab8b7d0d;hp=a043bde4615f80474aaab11b974ddb2a87a48b0b;hpb=df9a8d0a788b29913dae3eec4ef8113e2d8e9a41;p=plomrogue2 diff --git a/plomrogue/parser.py b/plomrogue/parser.py index a043bde..51f5cc2 100644 --- a/plomrogue/parser.py +++ b/plomrogue/parser.py @@ -6,6 +6,7 @@ class Parser: def __init__(self, game=None): self.game = game + self.string_options = {} def tokenize(self, msg): """Parse msg string into tokens. @@ -73,11 +74,23 @@ class Parser: x = get_axis_position_from_argument('X', tokens[1]) return YX(y, x) - def parse(self, msg): + def parse(self, msg, replace_newline=True): """Parse msg as call to function, return function with args tuple. Respects function signature defined in function's .argtypes attribute. + + Refuses messages with any but a small list of acceptable characters. + """ + import string + if replace_newline: + msg = msg.replace('\n', ' ') # Inserted by some tablet keyboards. + legal_chars = string.digits + string.ascii_letters +\ + string.punctuation + ' ' + 'ÄäÖöÜüߧ' + 'éèáàô' + '–…' + for c in msg: + if not c in legal_chars: + raise ArgError('Command/message contains illegal character(s), ' + 'may only contain ones of: %s' % legal_chars) tokens = self.tokenize(msg) if len(tokens) == 0: return None, () @@ -116,6 +129,15 @@ class Parser: if not arg.isdigit() or int(arg) < 1: raise ArgError('Argument must be positive integer.') args += [int(arg)] + elif tmpl == 'int': + try: + args += [int(arg)] + except ValueError: + raise ArgError('Argument must be integer.') + elif tmpl == 'bool': + if not arg.isdigit() or int(arg) not in (0, 1): + raise ArgError('Argument must be 0 or 1.') + args += [bool(int(arg))] elif tmpl == 'char': try: ord(arg) @@ -131,12 +153,10 @@ class Parser: elif tmpl == string_string: args += [arg] elif tmpl[:len(string_string) + 1] == string_string + ':': - if not hasattr(self.game, 'get_string_options'): - raise ArgError('No string option directory.') string_option_type = tmpl[len(string_string) + 1:] - options = self.game.get_string_options(string_option_type) - if options is None: - raise ArgError('Unknown string option type.') + if not string_option_type in self.string_options.keys(): + raise ArgError('Unknown string option type: %s' % string_option_type) + options = self.string_options[string_option_type] if arg not in options: msg = 'Argument #%s must be one of: %s' % (i + 1, options) raise ArgError(msg)