2021-11-10_a-simple-dl-parser.html


001| #:name::A Simple DL Parser
002| #:link::https://thehardcorecoder.com/2021/11/10/a-simple-dl-parser/
003| #:date::2021-11-10
004| #:code::
005| class InputToken (object):
006|     '''DL File Input Token class.'''
007|     def __init__ (self, char, char_index, char_line):
008|         self.word = char
009|         self.cpos = char_index
010|         self.lnbr = char_line
011| 
012|     def add (self, char): self.word += char
013| 
014|     def __bool__ (self): return True
015|     def __call__ (self): return self.word
016|     def __len__ (self): return len(self.word)
017|     def __iter__ (self): return iter(self.word)
018|     def __getitem__ (self, ix): return self.word[ix]
019| 
020|     def __str__ (self):
021|         t = (self.lnbr, self.cpos, self.word)
022|         s = '[%4d,%6d] %s'
023|         return s%t
024| 
025| #:code::
026| def dl_parser (srcfile):
027|     '''DL Parser. Reads "srcfile" and returns InputTokens.'''
028|     attribute_char = ':'    # attribute ends with
029|     terminal_char = ';'     # alternate END {tag} character
030|     comment_char = '-'      # comments begin with two
031|     cdata_sot = '<<<'       # CDATA begins with
032|     cdata_eot = '>>>'       # CDATA ends with
033|     EOL = '\n'              # End Of Line character
034| 
035|     tokens = []             # buffer for InputTokens
036|     curr_token = None       # current InputToken
037|     line_nbr = 1            # current line number
038|     comment_flag = 0        # in-comment state flag
039|     string_flag = ''        # in-string state flag
040|     cdata_flag = 0          # in-CDATA state flag
041| 
042|     # Read the source file...
043|     src = textfile(srcfile)
044|     src.load()
045| 
046|     # Parse the source file...
047|     for ix,ch in enumerate(src):
048|         #
049|         #
050|         # ... the DL parser guts ...
051|         #
052|         #
053|         # Otherwise, start a new token...
054|         curr_token = InputToken(ch, ix, line_nbr)
055|     # Return list of InputTokens...
056|     return tokens
057| 
058| #:code::
059| # If we see an end of line char, bump the line number...
060| if ch == EOL:
061|     line_nbr += 1
062| 
063| # Special handling if in STRING mode...
064| if string_flag:
065|     curr_token.add(ch)
066|     if curr_token[-1] == string_flag:
067|         string_flag = ''
068|         tokens.append(curr_token)
069|         curr_token = None
070|         Log.trace('string-exit: %s' % ch)
071|     continue
072| 
073| # Special handling if in CDATA mode...
074| if cdata_flag:
075|     curr_token.add(ch)
076|     if curr_token().endswith(cdata_eot):
077|         cdata_flag = 0
078|         tokens.append(curr_token)
079|         curr_token = None
080|     continue
081| 
082| #:code::
083| # If we're in comment mode,...
084| if comment_flag == 2:
085|     # If we've found the end of line, exit comment mode...
086|     if ch == EOL:
087|         comment_flag = 0
088|     # Otherwise stay in comment mode...
089|     continue
090| 
091| # If we've seen one comment char,...
092| if comment_flag == 1:
093|     # Another one puts us in comment mode...
094|     if ch == comment_char:
095|         comment_flag = 2
096|         continue
097|     # Otherwise reset the flag and emit the buffered char...
098|     comment_flag = 0
099|     if not curr_token:
100|         # Start a new token if necessary...
101|         curr_token = InputToken('', ix, line_nbr)
102|     curr_token.add(comment_char)
103|     curr_token.add(ch)
104|     continue
105| 
106| # If we're not in comment mode at all,...
107| if comment_flag == 0:
108|     # Seeing a comment char puts us in comment mode...
109|     if ch == comment_char:
110|         # Set the flag and next char...
111|         comment_flag = 1
112|         continue
113| 
114| #:code::
115| # Whitespace ends any token we're building...
116| if ch.isspace():
117|     # If we're building a token, add it to the list...
118|     if curr_token:
119|         tokens.append(curr_token)
120|         curr_token = None
121|     # Next char...
122|     continue
123| 
124| # Special handling for special END char...
125| if ch == terminal_char:
126|     # If we're building a token, add it to the list...
127|     if curr_token:
128|         tokens.append(curr_token)
129|         curr_token = None
130|     # Create special END token...
131|     tok = InputToken(terminal_char, ix, line_nbr)
132|     tokens.append(tok)
133|     continue
134| 
135| # If we're building a token...
136| if curr_token:
137|     # Add character to token...
138|     curr_token.add(ch)
139|     # Special handling for start of strings...
140|     if curr_token[0] in ['"', "'"]:
141|         string_flag = curr_token[0]
142|         continue
143|     # Special handling for start of CDATA...
144|     if curr_token().startswith(cdata_sot):
145|         cdata_flag = 1
146|         continue
147|     # Special handling for attribute names...
148|     if ch == attribute_char:
149|         tokens.append(curr_token)
150|         curr_token = None
151|         continue
152|     # In any event, next char...
153|     continue
154| 
155| #:code::
156| def dl_definition (toks):
157|     # Tag, Name...
158|     tok1 = toks.pop(0)
159|     tok2 = toks.pop(0)
160|     define_obj = dlDefinition(tok1(), tok2())
161| 
162|     # Content...
163|     dl_content(toks, define_obj)
164| 
165|     # END keyword...
166|     tok3 = toks.pop(0)
167|     if tok3() == ';':
168|         Log.trace('definition: %s' % define_obj)
169|         return define_obj
170|     if tok3().upper() != 'END':
171|         raise SyntaxError(E_NO_END_KEY % (tok3(), tok3.lnbr))
172| 
173|     # End Tag...
174|     tok4 = toks.pop(0)
175|     if tok4().upper() != tok1().upper():
176|         raise SyntaxError(E_NO_END_TAG % (tok4(), tok4.lnbr))
177| 
178|     # Return the definition object...
179|     Log.trace('definition: %s' % define_obj)
180|     return define_obj
181| 
182| #:code::
183| def dl_content (toks, define_obj):
184|     # Peek at the first token...
185|     while 0 < len(toks):
186|         tok = toks[0]
187|         # If it's the end of a def, there's no more content...
188|         if tok().upper() in ['END', ';']:
189|             Log.trace('content: END')
190|             return
191| 
192|         # Handle Attributes...
193|         if tok().endswith(':'):
194|             dl_attribute(toks, define_obj)
195|             continue
196| 
197|         # It's a nested definition...
198|         nested_def = dl_definition(toks)
199|         define_obj.children.append(nested_def)
200| 
201| #:code::
202| def dl_attribute (toks, define_obj):
203|     # Name, Value...
204|     tok1 = toks.pop(0)
205|     tok2 = toks.pop(0)
206| 
207|     # Add property...
208|     define_obj.props[tok1()] = tok2()
209| 
210| #:code::
211| class dlDefinition (object):
212|     '''DL Definition class.'''
213|     def __init__ (self, tag, name):
214|         self.tag = tag
215|         self.name = name
216|         self.props = {}
217|         self.children = []
218| 
219|     def __str__ (self):
220|         return f'{self.tag} {self.name}'
221| 
222| #:code::
223| datafile = path.join(BasePath, FileName)
224| tokens = dl_parser(datafile)
225| define_obj = dl_definition(tokens)
226| 
227| #:end:code::
228|