home · contact · privacy
Add basic multiplayer roguelike chat example.
[plomrogue2-experiments] / new2 / plomrogue / parser.py
1 import unittest
2 from plomrogue.errors import ArgError
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(self, msg):
44         """Parse msg as call to function, return function with args tuple.
45
46         Respects function signature defined in function's .argtypes attribute.
47         """
48         tokens = self.tokenize(msg)
49         if len(tokens) == 0:
50             return None, ()
51         func = self.game.get_command(tokens[0])
52         argtypes = ''
53         if hasattr(func, 'argtypes'):
54             argtypes = func.argtypes
55         if func is None:
56             return None, ()
57         if len(argtypes) == 0:
58             if len(tokens) > 1:
59                 raise ArgError('Command expects no argument(s).')
60             return func, ()
61         if len(tokens) == 1:
62             raise ArgError('Command expects argument(s).')
63         args_candidates = tokens[1:]
64         args = self.argsparse(argtypes, args_candidates)
65         return func, args
66
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))
72                            + ').')
73         args = []
74         string_string = 'string'
75         for i in range(len(tmpl_tokens)):
76             tmpl = tmpl_tokens[i]
77             arg = args_tokens[i]
78             if tmpl == string_string:
79                 args += [arg]
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)
85                 if options is None:
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)
89                     raise ArgError(msg)
90                 args += [arg]
91             else:
92                 raise ArgError('Unknown argument type: %s' % tmpl)
93         return args