lexer.html


001| '''Text Source and Lexer Classes.
001| 
001| classes:
001|     Datum           - String to bool/long/float/date class
001| 
001|     Lexer           - Tokenizing Lexer
001|     LexerLine       - Sub-class for parsing name=value pairs
001| 
001|     SourceText      - Lexer text source
001|     SourceFile      - Lexer file source
001| 
001| Developer@Sonnack.com
001| February 2014
001| '''

002| ####################################################################################################
003| from datetime import datetime
004| from goodies import comp
005| ####################################################################################################
006| 
007| 
008| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
009| class Datum (object):
010|     '''Datum class. Given a string, convert to a binary value if possible.'''
011|     TextTrue  = ['true' ,'t', 'yes','y', 'on' ]
012|     TextFalse = ['false','f', 'no' ,'n', 'off']
013| 
014|     STRING  = 'string'
015|     LONG    = 'long'
016|     FLOAT   = 'float'
017|     DATE    = 'date'
018|     BOOLEAN = 'bool'
019| 
020|     DateFormats = ['%m-%d-%Y','%m-%d-%y', '%m/%d/%Y','%m/%d/%y', '%Y-%m-%d','%Y/%m/%d']
021| 
022|     def __init__ (self, value):
023|         '''Create a new instance.'''
024|         if isinstance(value, str):
025|             self.s = value
026|             self.t = type(self).STRING
027|             self.v = None
028|             # Try to convert string into some kind of binary value:
029|             # First, see if it's a boolean...
030|             s = str(self.s).lower()
031|             if s in type(self).TextTrue:
032|                 self.v = True
033|                 self.t = type(self).BOOLEAN
034|                 return
035|             if s in type(self).TextFalse:
036|                 self.v = False
037|                 self.t = type(self).BOOLEAN
038|                 return
039|             # First, see if it's a plain old integer...
040|             try:
041|                 self.v = int(self.s)
042|                 self.t = type(self).LONG
043|                 return
044|             except:
045|                 pass
046|             # Nope, so next try a float...
047|             try:
048|                 self.v = float(self.s)
049|                 self.t = type(self).FLOAT
050|                 return
051|             except:
052|                 pass
053|             # Neither of the above, so maybe it's a date...
054|             for fmt in type(self).DateFormats:
055|                 try:
056|                     self.v = datetime.strptime(self.s, fmt)
057|                     self.t = type(self).DATE
058|                     return
059|                 except:
060|                     pass
061|             # All failed! Apparently, it's just a string.
062|             self.v = self.s
063|             return
064|         if isinstance(value, bool):
065|             self.s = str(value)
066|             self.v = value
067|             self.t = type(self).BOOLEAN
068|             return
069|         if isinstance(value, float):
070|             self.s = str(value)
071|             self.v = value
072|             self.t = type(self).FLOAT
073|             return
074|         if isinstance(value, int):
075|             self.s = str(value)
076|             self.v = value
077|             self.t = type(self).LONG
078|             return
079|         if isinstance(value, datetime):
080|             self.s = str(value)
081|             self.v = value
082|             self.t = type(self).LONG
083|             return
084| 
085|     def __call__ (self):
086|         '''The function value of a Datum is the value (or string).'''
087|         return self.v if self.v is not None else self.s
088| 
089|     def __len__ (self):
090|         '''Datum length is length of its string.'''
091|         return len(self.s)
092| 
093|     def __eq__ (self, other): return (self.s == other.s)
094|     def __lt__ (self, other): return (self.s < other.s)
095|     def __gt__ (self, other): return not ((self == other) or (self < other))
096|     def __le__ (self, other): return not (other < self)
097|     def __ge__ (self, other): return not (self < other)
098|     def __ne__ (self, other): return not (self == other)
099| 
100|     def __bool__ (self):
101|         '''Datum is True if string converted to something binary.'''
102|         return True if self.v else False
103| 
104|     def __int__ (self):
105|         '''Return integer if possible.'''
106|         if self.t == type(self).LONG:
107|             return self.v
108|         if self.t == type(self).FLOAT:
109|             return int(self.v)
110|         if self.t == type(self).DATE:
111|             return self.v.toordinal()
112|         raise ValueError('Datum is not a number!')
113| 
114|     def __float__ (self):
115|         '''Return float if possible.'''
116|         if self.t == type(self).FLOAT:
117|             return self.v
118|         if self.t == type(self).LONG:
119|             return float(self.v)
120|         if self.t == type(self).DATE:
121|             return self.v.timestamp()
122|         raise ValueError('Datum is not a number!')
123| 
124|     def __str__ (self):
125|         '''String version (includes type).'''
126|         return f'{self.s} ({self.t})'
127| 
128|     def __repr__ (self):
129|         '''Debug string.'''
130|         return f'<{type(self).__name__} {self.s}:{self.t} @{id(self):08x}>'
131| 
132| 
133| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
134| class SourceText (object):
135|     '''\
135| Source Text base class.
135| 
135| methods:
135|     .get_char       - consume next character
135|     .unget_char     - unget; buffer a single char to be got next
135|     .more           - ready; true if more characters available
135|     .reset          - rewind; return Source to initial state
135| 
135| properties:
135|     .cs         - source text
135|     .cp         - current character pointer
135|     .unget_ch   - ungot char | None
135|     .nl_lf      - newline flag: LF  {false converts LF to SPC}
135|     .nl_cr      - newline flag: CR  { " }
135|     .nl_ff      - newline flag: FF  { " }
135| 
135| '''

136|     SPC = ' '
137|     EOL = '\n'
138|     LF = '\n'
139|     CR = '\r'
140|     FF = '\f'
141|     NewlineChars = [CR, LF, FF]
142| 
143|     def __init__ (self, s):
144|         '''Create a new Source instance.'''
145|         self.cs = s
146|         self.reset()
147|         self.filename = '<text>'
148| 
149|     def __iter__ (self):
150|         '''Iterating a Source iterates its text.'''
151|         return iter(self.cs)
152| 
153|     def __bool__ (self):
154|         '''Source object is "true" when it has length.'''
155|         return (0 < len(self))
156| 
157|     def __len__ (self):
158|         '''Length of Source object is length of the text.'''
159|         return len(self.cs)
160| 
161|     def __getitem__ (self, ix):
162|         '''Get value of one char. (Cheating!)'''
163|         return self.cs[ix]
164| 
165|     def reset (self):
166|         '''Reset. Make full text available again.'''
167|         self.cp = 0
168|         self.chars = 0
169|         self.lines = 1
170|         self.unget_ch = None
171|         self.nl_lf = type(self).LF in self.cs
172|         self.nl_cr = type(self).CR in self.cs
173|         self.nl_ff = True
174| 
175|     def more (self):
176|         '''More characters are available.'''
177|         return self.cp < len(self)
178| 
179|     def get_char (self):
180|         '''Get Character. (Includes unget function.)'''
181|         if self.unget_ch:
182|             ch = self.unget_ch
183|             self.unget_ch = None
184|             return ch
185|         # Next char...
186|         try:
187|             ch = self._next_ch()
188|             self.chars += 1
189|             if ch == type(self).EOL:
190|                 self.lines += 1
191|             return ch
192|         except IndexError:
193|             return None
194| 
195|     def unget_char (self, ch):
196|         '''Unget Character.'''
197|         if self.unget_ch:
198|             raise RuntimeError('Multiple UNGET not allowed!')
199|         self.unget_ch = ch
200| 
201|     def _next_ch (self):
202|         '''Next Character. (Includes special EOL handling.)'''
203|         if self.more():
204|             ch = self.cs[self.cp]
205|             self.cp += 1
206|             # Carriage Return (CR) is treated specially...
207|             if ch == type(self).CR:
208|                 # If we've got LF chars, CR chars are just whitespace...
209|                 # Plus, the NL-CR flag controls whether CR does return EOL or SPC...
210|                 return type(self).SPC if (self.nl_lf or (not self.nl_cr)) else type(self).EOL
211|             # Line Feed (LF) is treated specially...
212|             if ch == type(self).LF:
213|                 # The NL-LF flag controls whether LF returns EOL or SPC...
214|                 return type(self).SPC if (not self.nl_lf) else type(self).EOL
215|             # Form Feed (FF) is treated specially...
216|             if ch == type(self).FF:
217|                 # The NL-FF flag controls whether FF returns EOL or SPC...
218|                 return type(self).SPC if (not self.nl_ff) else type(self).EOL
219|             return ch
220|         raise IndexError
221| 
222|     def __str__ (self):
223|         '''String version.'''
224|         return '\n'.join(['| "%s"' % line for line in self.cs.splitlines()])
225| 
226|     def __repr__ (self):
227|         '''Debug string.'''
228|         return f'<{type(self).__name__} {self.filename} @{id(self):08x}>'
229| 
230| 
231| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
232| class SourceFile (SourceText):
233|     '''Source File base class.'''
234| 
235|     def __init__ (self, filename):
236|         '''Create a new File Source instance.'''
237|         super(SourceFile,self).__init__('')
238|         self.filename = filename
239|         # Open file...
240|         fp = open(self.filename, mode='r', encoding='utf-8')
241|         try:
242|             # Read all the text...
243|             self.cs = fp.read()
244|             self.reset()
245|         except:
246|             raise
247|         finally:
248|             fp.close()
249| 
250|     def __str__ (self):
251|         '''String version.'''
252|         r = super(SourceFile,self).__str__()
253|         s = 'file: %s\n%s'
254|         t = (self.filename, r)
255|         return s % t
256| 
257|     def __repr__ (self):
258|         '''JSON-ish version.'''
259|         r = super(SourceFile,self).__repr__()
260|         s = '{SourceFile:{parent:%s, file:"%s", id:%s}}'
261|         t = (r, self.filename, hex(id(self)))
262|         return s % t
263| 
264| 
265| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
266| class Lexer (object):
267|     '''\
267| Tokenizing Lexer class.
267| 
267| Tokens are tuples with the form: ( toktype, toktext, tokvalue, extvalue, line-no, char-no )
267| 
267| Possible Token Types (toktype) are:
267|     Name        - N; not one of the other types; typically an identifier
267|     String      - $; quoted string (single- or double-quote)
267|     Number      - #; string of digits (or other recognized number format)
267|     Date        - D; recognized date string
267|     Boolean     - B; recognized boolean value
267|     Symbol      - ?; punctuation character
267|     Newline     - _; end of line
267| 
267| The Token value is the text length or numeric value (in which case the fourth member
267| of the tuple is 'long' or 'float' or other type specifier). For String Tokens, the
267| fourth item is the string's quote character (or the newline char for "rest of line"
267| strings). (Name Tokens put the first character of the name in the fourth slot.)
267| 
267| methods:
267|     .get_token          - returns (consumes) next token
267|     .unget_token        -
267| 
267| properties:
267|     .src        - original source text object
267|     .nl_flag    - newline flag; FALSE suppresses newlines
267|     .rem_chars  - characters that begin a comment line
267|     .sdq_chars  - single and double quote characters
267|     .sym_chars  - punctuation characters
267| 
267| '''

268|     NameToken       = 'N'
269|     StringToken     = '$'
270|     NumberToken     = '#'
271|     DateToken       = 'D'
272|     BooleanToken    = 'B'
273|     SymbolToken     = '?'
274|     NewlineToken    = '_'
275| 
276|     def __init__ (self, src, nl_flag=True):
277|         '''Create a new Lexer instance.'''
278|         self.src = src
279|         self.unget_tok = None
280|         self.nl_flag = nl_flag
281|         self.rem_chars = ['#', ';']
282|         self.sdq_chars = ['"', "'"]
283|         self.sym_chars = [',','!','?',':', '=','+','-','*','/','@','$','%','&', '(',')', '[',']', '<','>', '{','}']
284| 
285|     def get_token (self):
286|         '''Get next token. (Includes unget function.)'''
287|         if self.unget_tok:
288|             tok = self.unget_tok
289|             self.unget_tok = None
290|         else:
291|             # Next Token...
292|             tok = self._next_token()
293|         return tok
294| 
295|     def unget_token (self, tok):
296|         '''Unget token.'''
297|         if self.unget_tok:
298|             raise RuntimeError('Multiple UNGET not allowed!')
299|         self.unget_tok = tok
300| 
301|     def _next_token (self):
302|         '''Return the next token (back end for get_token).'''
303|         # Get a character (could be anything!)...
304|         ch = self.src.get_char()
305|         # Consume text until we have a token to return...
306|         while ch:
307|             # A comment invalidates remainder of line...
308|             if ch in self.rem_chars:
309|                 # Consume the rest of the line...
310|                 self._eat_rest_of_line()
311|                 # (And keep going! -->>)
312|             else:
313|                 # Recognize EOL as a token if NL-FLAG is set...
314|                 # (If flag not set, EOL is treated as WS.)
315|                 if (ch == SourceText.EOL) and self.nl_flag:
316|                     # Return NewLine Token...
317|                     return (Lexer.NewlineToken, ch, 0, SourceText.EOL, self.src.lines, self.src.chars)
318|                 # Recognize punctuation symbols as tokens...
319|                 if ch in self.sym_chars:
320|                     # Return Symbol Token...
321|                     return (Lexer.SymbolToken, ch, len(ch), ch, self.src.lines, self.src.chars)
322|                 # Recognize beginning of a quoted string...
323|                 # (Either double- or single-quoted.)
324|                 if ch in self.sdq_chars:
325|                     # Return String Token...
326|                     return self._get_quoted_token(ch)
327|                 # Recognize beginning of a word...
328|                 if not ch.isspace():
329|                     # Return Name Token...
330|                     return self._get_word_token(ch)
331|             # Get another character...
332|             ch = self.src.get_char()
333|             # Loop! -->>
334| 
335|     def _get_word_token (self, first_ch):
336|         '''Return a string of contiguous non-space characters.'''
337|         tok = first_ch
338|         # Get a character (next token char or something else)...
339|         ch = self.src.get_char()
340|         # Consume characters until hitting a newline...
341|         while ch:
342|             # A comment ends the token (EOL will be next get)...
343|             if ch in self.rem_chars:
344|                 # Consume the rest of the line...
345|                 self._eat_rest_of_line()
346|                 break
347|             # Symbol ends the token (preserve char for next get)...
348|             if ch in self.sym_chars:
349|                 # Unget the symbol char...
350|                 self.src.unget_char(ch)
351|                 break
352|             # EOL ends the token (need to preserve EOL)...
353|             if ch == SourceText.EOL:
354|                 # Unget the newline...
355|                 self.src.unget_char(ch)
356|                 break
357|             # Whitespace ends the token (character can be discarded)...
358|             if ch.isspace():
359|                 break
360|             # Add character to token...
361|             tok += ch
362|             # Get another character...
363|             ch = self.src.get_char()
364|             # Loop! -->>
365|         # If it looks like it might be a number...
366|         if first_ch.isdigit() or first_ch in ['+', '-', '.']:
367|             d = Datum(tok)
368|             # If Datum converts to a value, Token is not (just) a string...
369|             if d.t:
370|                 # If it was a string anyway,...
371|                 if d.t == Datum.String:
372|                     return (Lexer.NameToken, tok, len(tok), first_ch, self.src.lines, self.src.chars)
373|                 # It could be a date...
374|                 if d.t == Datum.Date:
375|                     return (Lexer.DateToken, tok, d.v, d.t, self.src.lines, self.src.chars)
376|                 # Otherwise, it's a number...
377|                 return (Lexer.NumberToken, tok, d.v, d.t, self.src.lines, self.src.chars)
378|             # Datum didn't convert, wasn't a number, so continue...
379|         if tok.lower() == 'false':
380|             return (Lexer.BooleanToken, 'False', False, Datum.Boolean, self.src.lines, self.src.chars)
381|         if tok.lower() == 'true':
382|             return (Lexer.BooleanToken, 'True', True, Datum.Boolean, self.src.lines, self.src.chars)
383|         # Return Name Token...
384|         return (Lexer.NameToken, tok, len(tok), first_ch, self.src.lines, self.src.chars)
385| 
386|     def _get_quoted_token (self, quote_ch):
387|         '''Given a quote-char, return the string up to that char.'''
388|         tok = ''
389|         # Get a character (first char in string)...
390|         ch = self.src.get_char()
391|         # Consume characters until hitting a quote char...
392|         while ch != quote_ch:
393|             # Need to escape quoted quote-char...
394|             if ch == '\\':
395|                 # Get another character...
396|                 ch = self.src.get_char()
397|                 # Recognize basic escaped control chars...
398|                 if ch == 't': ch = '\t'
399|                 elif ch == 'n': ch = '\n'
400|                 elif ch == 'r': ch = '\r'
401|                 elif ch == 'f': ch = '\f'
402|                 elif ch == 's': ch = ' '
403|             # Add character to token...
404|             tok += ch
405|             # Get another character...
406|             ch = self.src.get_char()
407|             # Loop! -->>
408|         # Return String Token...
409|         return (Lexer.StringToken, tok, len(tok), quote_ch, self.src.lines, self.src.chars)
410| 
411|     def _eat_rest_of_line (self):
412|         '''Consume rest of line no matter what it contains.'''
413|         # Get a character...
414|         ch = self.src.get_char()
415|         # Eat characters until hitting a newline...
416|         while ch != SourceText.EOL:
417|             # Get another character...
418|             ch = self.src.get_char()
419|             # Loop! -->>
420|         # Unget the newline...
421|         self.src.unget_char(ch)
422| 
423|     def __len__ (self):
424|         '''Length of a Lexer is the length of its Source.'''
425|         return len(self.src)
426| 
427|     def __str__ (self):
428|         '''String version is the string version of the Source.'''
429|         return str(self.src)
430| 
431|     def __repr__ (self):
432|         '''JSON-ish version.'''
433|         s = '{Lexer:{src:%s, nl:%s, id:%s}}'
434|         t = (repr(self.src), self.nl_flag, hex(id(self)))
435|         return s % t
436| 
437| 
438| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
439| class LexerLine (Lexer):
440|     '''Lexer sub-class for parsing line-oriented text.'''
441| 
442|     def skip_whitespace (self):
443|         '''Skip remaining whitespace. Returns (and ungets) char.'''
444|         # Get a character...
445|         ch = self.src.get_char()
446|         # Consume non-whitespace characters...
447|         while ch:
448|             # EOL stops the skip (peek is an EOL)...
449|             if ch == SourceText.EOL:
450|                 # Unget the newline...
451|                 self.src.unget_char(ch)
452|                 break
453|             # A comment also stops the skip (also peeks an EOL)...
454|             if ch in self.rem_chars:
455|                 self._eat_rest_of_line()
456|                 break
457|             # If it's not a space, we're done skipping (peek is the char)...
458|             if not ch.isspace():
459|                 # Unget the non-WS character...
460|                 self.src.unget_char(ch)
461|                 # And return it!
462|                 return ch
463|                 ## BUG? ^^^^ ATTN ATTN ATTN
464|             # Get another character (and try again)...
465|             ch = self.src.get_char()
466|             # Loop! -->>
467|         # Breaking out of the loop peeks an EOL...
468|         return (Lexer.NewlineToken, SourceText.EOL, 0, ch, self.src.lines, self.src.chars)
469| 
470|     def get_rest_of_line (self):
471|         '''Return remainder of line (trimmed) as a single token.'''
472|         tok = ''
473|         # Get a character...
474|         ch = self.src.get_char()
475|         # Consume characters until hitting a newline...
476|         while ch:
477|             if ch == SourceText.EOL:
478|                 # Unget the newline...
479|                 self.src.unget_char(ch)
480|                 break
481|             if ch in self.rem_chars:
482|                 self._eat_rest_of_line()
483|                 break
484|             # Add character to token...
485|             tok += ch
486|             # Get another character...
487|             ch = self.src.get_char()
488|         # Trim whitespace from the right side...
489|         tok = tok.rstrip()
490|         # Return String Token...
491|         return (Lexer.StringToken, tok, len(tok), SourceText.EOL, self.src.lines, self.src.chars)
492| 
493| 
494| 
495| ####################################################################################################
496| '''eof'''
497|