home · contact · privacy
Fix various minor, mostly "unused" flake8 complaints.
[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         tokens = self.tokenize(msg)
82         if len(tokens) == 0:
83             return None, ()
84         func = self.game.get_command(tokens[0])
85         argtypes = ''
86         if hasattr(func, 'argtypes'):
87             argtypes = func.argtypes
88         if func is None:
89             return None, ()
90         if len(argtypes) == 0:
91             if len(tokens) > 1:
92                 raise ArgError('Command expects no argument(s).')
93             return func, ()
94         if len(tokens) == 1:
95             raise ArgError('Command expects argument(s).')
96         args_candidates = tokens[1:]
97         args = self.argsparse(argtypes, args_candidates)
98         return func, args
99
100     def argsparse(self, signature, args_tokens):
101         tmpl_tokens = signature.split()
102         if len(tmpl_tokens) != len(args_tokens):
103             raise ArgError('Number of arguments (' + str(len(args_tokens)) +
104                            ') not expected number (' + str(len(tmpl_tokens))
105                            + ').')
106         args = []
107         string_string = 'string'
108         for i in range(len(tmpl_tokens)):
109             tmpl = tmpl_tokens[i]
110             arg = args_tokens[i]
111             if tmpl == 'int:nonneg':
112                 if not arg.isdigit():
113                     raise ArgError('Argument must be non-negative integer.')
114                 args += [int(arg)]
115             elif tmpl == 'int:pos':
116                 if not arg.isdigit() or int(arg) < 1:
117                     raise ArgError('Argument must be positive integer.')
118                 args += [int(arg)]
119             elif tmpl == 'char':
120                 try:
121                     ord(arg)
122                 except TypeError:
123                     raise ArgError('Argument must be single character.')
124                 args += [arg]
125             elif tmpl == 'yx_tuple:nonneg':
126                 args += [self.parse_yx_tuple(arg, 'nonneg')]
127             elif tmpl == 'yx_tuple:pos':
128                 args += [self.parse_yx_tuple(arg, 'pos')]
129             elif tmpl == 'yx_tuple':
130                 args += [self.parse_yx_tuple(arg, 'all')]
131             elif tmpl == string_string:
132                 args += [arg]
133             elif tmpl[:len(string_string) + 1] == string_string + ':':
134                 if not hasattr(self.game, 'get_string_options'):
135                     raise ArgError('No string option directory.')
136                 string_option_type = tmpl[len(string_string) + 1:]
137                 options = self.game.get_string_options(string_option_type)
138                 if options is None:
139                     raise ArgError('Unknown string option type.')
140                 if arg not in options:
141                     msg = 'Argument #%s must be one of: %s' % (i + 1, options)
142                     raise ArgError(msg)
143                 args += [arg]
144             else:
145                 raise ArgError('Unknown argument type: %s' % tmpl)
146         return args