home · contact · privacy
302733d0322a69c9592276b94239b626debcb4c3
[plomrogue2] / plomrogue / parser.py
1 from plomrogue.errors import ArgError
2 from plomrogue.mapping import YX
3
4
5 class Parser:
6
7     def __init__(self, game=None):
8         self.game = game
9
10     def tokenize(self, msg):
11         """Parse msg string into tokens.
12
13         Separates by ' ' and '\n', but allows whitespace in tokens quoted by
14         '"', and allows escaping within quoted tokens by a prefixed backslash.
15         """
16         tokens = []
17         token = ''
18         quoted = False
19         escaped = False
20         for c in msg:
21             if quoted:
22                 if escaped:
23                     token += c
24                     escaped = False
25                 elif c == '\\':
26                     escaped = True
27                 elif c == '"':
28                     quoted = False
29                 else:
30                     token += c
31             elif c == '"':
32                 quoted = True
33             elif c in {' ', '\n'}:
34                 if len(token) > 0:
35                     tokens += [token]
36                     token = ''
37             else:
38                 token += c
39         if len(token) > 0:
40             tokens += [token]
41         return tokens
42
43     def parse_yx_tuple(self, yx_string, range_=None):
44         """Parse yx_string as yx_tuple, return result.
45
46         The range_ argument may be 'nonneg' (non-negative, including
47         0) or 'pos' (positive, excluding 0) or 'all'.
48
49         """
50
51         def get_axis_position_from_argument(axis, token):
52             if token[:2] != axis + ':':
53                 raise ArgError('invalid YX tuple formatting')
54             n_string = token[2:]
55             if n_string.strip() != n_string:
56                 raise ArgError('invalid YX tuple formatting')
57             try:
58                 n = int(n_string)
59             except ValueError:
60                 raise ArgError('non-int value for ' + axis + ' position')
61             if range_ == 'all':
62                 return n
63             if n < 1 and range == 'pos':
64                 raise ArgError('Arg for ' + axis + ' position < 1.')
65             elif n < 0 and range_ == 'nonneg':
66                 raise ArgError('Arg for ' + axis + ' position < 0.')
67             return n
68
69         tokens = yx_string.split(',')
70         if len(tokens) != 2:
71             raise ArgError('Wrong number of yx-tuple arguments.')
72         y = get_axis_position_from_argument('Y', tokens[0])
73         x = get_axis_position_from_argument('X', tokens[1])
74         return YX(y, x)
75
76     def parse(self, msg):
77         """Parse msg as call to function, return function with args tuple.
78
79         Respects function signature defined in function's .argtypes attribute.
80
81         Throws out messages with any but a small list of acceptable characters.
82
83         """
84         import string
85         msg = msg.replace('\n', ' ')  # Inserted by some tablet keyboards.
86         legal_chars = string.digits + string.ascii_letters +\
87             string.punctuation + ' ' + 'ÄäÖöÜüߧ' + 'éèáàô' + '–…'
88         for c in msg:
89             if not c in legal_chars:
90                 raise ArgError('Command/message contains illegal character(s), '
91                                'may only contain ones of: %s' % legal_chars)
92         tokens = self.tokenize(msg)
93         if len(tokens) == 0:
94             return None, ()
95         func = self.game.get_command(tokens[0])
96         argtypes = ''
97         if hasattr(func, 'argtypes'):
98             argtypes = func.argtypes
99         if func is None:
100             return None, ()
101         if len(argtypes) == 0:
102             if len(tokens) > 1:
103                 raise ArgError('Command expects no argument(s).')
104             return func, ()
105         if len(tokens) == 1:
106             raise ArgError('Command expects argument(s).')
107         args_candidates = tokens[1:]
108         args = self.argsparse(argtypes, args_candidates)
109         return func, args
110
111     def argsparse(self, signature, args_tokens):
112         tmpl_tokens = signature.split()
113         if len(tmpl_tokens) != len(args_tokens):
114             raise ArgError('Number of arguments (' + str(len(args_tokens)) +
115                            ') not expected number (' + str(len(tmpl_tokens)) +
116                            ').')
117         args = []
118         string_string = 'string'
119         for i in range(len(tmpl_tokens)):
120             tmpl = tmpl_tokens[i]
121             arg = args_tokens[i]
122             if tmpl == 'int:nonneg':
123                 if not arg.isdigit():
124                     raise ArgError('Argument must be non-negative integer.')
125                 args += [int(arg)]
126             elif tmpl == 'int:pos':
127                 if not arg.isdigit() or int(arg) < 1:
128                     raise ArgError('Argument must be positive integer.')
129                 args += [int(arg)]
130             elif tmpl == 'int':
131                 try:
132                     args += [int(arg)]
133                 except ValueError:
134                     raise ArgError('Argument must be integer.')
135             elif tmpl == 'bool':
136                 if not arg.isdigit() or int(arg) not in (0, 1):
137                     raise ArgError('Argument must be 0 or 1.')
138                 args += [bool(int(arg))]
139             elif tmpl == 'char':
140                 try:
141                     ord(arg)
142                 except TypeError:
143                     raise ArgError('Argument must be single character.')
144                 args += [arg]
145             elif tmpl == 'yx_tuple:nonneg':
146                 args += [self.parse_yx_tuple(arg, 'nonneg')]
147             elif tmpl == 'yx_tuple:pos':
148                 args += [self.parse_yx_tuple(arg, 'pos')]
149             elif tmpl == 'yx_tuple':
150                 args += [self.parse_yx_tuple(arg, 'all')]
151             elif tmpl == string_string:
152                 args += [arg]
153             elif tmpl[:len(string_string) + 1] == string_string + ':':
154                 if not hasattr(self.game, 'get_string_options'):
155                     raise ArgError('No string option directory.')
156                 string_option_type = tmpl[len(string_string) + 1:]
157                 options = self.game.get_string_options(string_option_type)
158                 if options is None:
159                     raise ArgError('Unknown string option type.')
160                 if arg not in options:
161                     msg = 'Argument #%s must be one of: %s' % (i + 1, options)
162                     raise ArgError(msg)
163                 args += [arg]
164             else:
165                 raise ArgError('Unknown argument type: %s' % tmpl)
166         return args