Declaration of a lexer.
| 108 | |
| 109 | |
| 110 | class LexerDeclaration(object): |
| 111 | ''' Declaration of a lexer. ''' |
| 112 | |
| 113 | def __init__(self, messages, splitter = ' '): |
| 114 | ''' Declares a protocol. |
| 115 | |
| 116 | @param splitter: the character used to separate field in messages |
| 117 | @param messages: the messages declared for this protocol |
| 118 | ''' |
| 119 | |
| 120 | self.__splitter = splitter |
| 121 | self.__messages = {message.tag : message |
| 122 | for message |
| 123 | in messages} |
| 124 | |
| 125 | |
| 126 | def __call__(self, line): |
| 127 | ''' Lex the line. ''' |
| 128 | |
| 129 | # Strip of surrounding white spaces and tailing new line and split the |
| 130 | # message into parts separated by the splitting character |
| 131 | message = line.strip().split(self.__splitter) |
| 132 | |
| 133 | # Split message in tag and values |
| 134 | tag, values = message[0], message[1:] |
| 135 | |
| 136 | # Find message declaration for tag and lex the values using this message |
| 137 | # declaration or return None if the tag is unknown |
| 138 | if tag in self.__messages: |
| 139 | return self.__messages[tag].lex(values) |
| 140 | |
| 141 | else: |
| 142 | return None |
| 143 | |
| 144 | |
| 145 | def __getattr__(self, key): |
| 146 | ''' Returns a message declaration for the given key. ''' |
| 147 | |
| 148 | return self.__messages[key] |
| 149 | |
| 150 | |
| 151 |