Debian Codegraph @

mallard/ducktype/parser.py

raw
1 # Copyright (c) 2014-2019 Shaun McCance <[email protected]>
2 #
3 # Permission is hereby granted, free of charge, to any person obtaining a copy
4 # of this software and associated documentation files (the "Software"), to deal
5 # in the Software without restriction, including without limitation the rights
6 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 # copies of the Software, and to permit persons to whom the Software is
8 # furnished to do so, subject to the following conditions:
9 #
10 # The above copyright notice and this permission notice shall be included in
11 # all copies or substantial portions of the Software.
12 #
13 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 # THE SOFTWARE.
20
21 import collections
22 import importlib
23 import inspect
24 import os
25 import sys
26 import urllib.parse
27
28 from . import entities
29
30
31 def FIXME(msg=None):
32 if msg is not None:
33 print('FIXME: %s' % msg)
34 else:
35 print('FIXME')
36
37 def _escape_xml_attr(s):
38 return s.replace('&', '&amp;').replace('<', '&lt;').replace('"', '&quot;')
39
40 def _escape_xml(s):
41 return s.replace('&', '&amp;').replace('<', '&lt;')
42
43 _escaped_chars = '$*=-.@[]()"\''
44
45
46 class Attributes:
47 def __init__(self):
48 self._attrlist = []
49 self._attrvals = {}
50
51 def add_attribute(self, key, value):
52 if key not in self._attrlist:
53 self._attrlist.append(key)
54 if key in ('style', 'type'):
55 self._attrvals.setdefault(key, [])
56 self._attrvals[key].append(value)
57 else:
58 self._attrvals[key] = value
59
60 def get_attribute(self, key):
61 val = self._attrvals.get(key)
62 if isinstance(val, list):
63 return ' '.join(val)
64 else:
65 return val
66
67 def get_attributes(self):
68 return self._attrlist
69
70 def __contains__(self, item):
71 return item in self._attrlist
72
73 def _write_xml(self, fd):
74 for attr in self._attrlist:
75 fd.write(' ' + attr + '="')
76 val = self._attrvals[attr]
77 if isinstance(val, list):
78 fd.write(' '.join([_escape_xml_attr(s) for s in val]))
79 else:
80 fd.write(_escape_xml_attr(val))
81 fd.write('"')
82
83
84 class Directive:
85 def __init__(self, name):
86 self.name = name
87 self.content = ''
88
89 def set_content(self, content):
90 self.content = content
91
92 @staticmethod
93 def parse_line(line, parser):
94 i = 1
95 while i < len(line):
96 if line[i].isspace():
97 break
98 i += 1
99 if i == 1:
100 raise SyntaxError('Directive must start with a name', parser)
101 directive = Directive(line[1:i])
102 directive.set_content(line[i:].lstrip().rstrip('\n'))
103 return directive
104
105
106 class Node:
107 def __init__(self, name, outer=0, inner=None, parser=None, linenum=None, extensions=False):
108 self.name = name
109 self.nsprefix = None
110 self.nsuri = None
111 self.localname = name
112 self.default_namespace = None
113 self.extension = None
114 self.is_external = False
115 if ':' in name:
116 self.nsprefix = name[:name.index(':')]
117 self.nsuri = parser.document.get_namespace(self.nsprefix)
118 self.localname = self.name[len(self.nsprefix)+1:]
119 if self.nsuri is not None and not self.nsuri.startswith('http://projectmallard.org/'):
120 self.is_external = True
121 if extensions and parser is not None:
122 if self.nsprefix in parser.extensions_by_module:
123 self.extension = self.nsprefix
124 if self.extension is None:
125 if self.nsuri is None:
126 if self.nsprefix == 'xml':
127 pass
128 elif self.nsprefix == 'its':
129 parser.document.add_namespace('its', 'http://www.w3.org/2005/11/its')
130 else:
131 raise SyntaxError('Unrecognized namespace prefix: ' + self.nsprefix,
132 parser)
133 else:
134 self.localname = name
135 self.outer = outer
136 if inner is None:
137 self.inner = outer
138 else:
139 self.inner = inner
140 self.info = None
141 self.children = []
142 self.attributes = None
143 self.is_verbatim = (name in ('screen', 'code'))
144 self.is_list = (name in ('list', 'steps', 'terms', 'tree'))
145 self.is_greedy = self.is_name((
146 'list', 'steps', 'terms', 'tree',
147 'table', 'thead', 'tfoot', 'tbody', 'tr'))
148 self._is_leaf = None
149 self.linenum = linenum
150 if self.linenum is None and parser is not None:
151 self.linenum = parser.linenum
152 self._namespaces = collections.OrderedDict()
153 self._definitions = {}
154 self._parent = None
155 self._softbreak = False # Help keep out pesky trailing newlines
156
157 def is_name(self, localname, nsuri=None):
158 if nsuri in (None, 'http://projectmallard.org/1.0/'):
159 if self.nsuri not in (None, 'http://projectmallard.org/1.0/'):
160 return False
161 else:
162 if nsuri != self.nsuri:
163 return False
164
165 if isinstance(localname, (list, tuple)):
166 for name in localname:
167 if name == self.localname:
168 return True
169 return False
170 else:
171 return localname == self.localname
172
173 @property
174 def is_leaf(self):
175 if self._is_leaf is not None:
176 return self._is_leaf
177 leafs = ('p', 'screen', 'code', 'title', 'subtitle', 'desc', 'cite', 'name', 'email', 'years')
178 if self.is_name(leafs):
179 return True
180 if self.nsprefix is not None:
181 if self.nsuri is None:
182 return False
183 if self.nsuri == 'http://projectmallard.org/1.0/':
184 return self.localname in leafs
185 return False
186
187 @is_leaf.setter
188 def is_leaf(self, is_leaf):
189 self._is_leaf = is_leaf
190
191 @property
192 def is_tree_item(self):
193 if not self.is_name('item'):
194 return False
195 cur = self
196 while cur.is_name('item'):
197 cur = cur.parent
198 if cur.is_name('tree'):
199 return True
200 return False
201
202 @property
203 def has_tree_items(self):
204 if self.is_tree_item:
205 for item in self.children:
206 if isinstance(item, Node) and item.is_name('item'):
207 return True
208 return False
209
210 @property
211 def is_external_leaf(self):
212 if not self.is_external:
213 return False
214 if len(self.children) == 0:
215 return False
216 if isinstance(self.children[0], str) or isinstance(self.children[0], Inline):
217 return True
218 return False
219
220 @property
221 def is_empty(self):
222 return len(self.children) == 0 and self.info is None
223
224 @property
225 def available(self):
226 for child in self.children:
227 if not child.is_name(('info', 'title', 'desc', 'cite')):
228 return False
229 return True
230
231 @property
232 def parent(self):
233 return self._parent
234
235 @parent.setter
236 def parent(self, node):
237 self._parent = node
238
239 def add_child(self, child):
240 if isinstance(child, str):
241 self.add_text(child)
242 return
243 if self._softbreak:
244 if len(self.children) > 0:
245 self.children[-1] += '\n'
246 self._softbreak = False
247 self.children.append(child)
248 child.parent = self
249
250 def insert_child(self, index, child):
251 self.children.insert(index, child)
252 child.parent = self
253
254 def add_text(self, text):
255 # We don't add newlines when we see them. Instead, we record that
256 # we saw one with _softbreak and output the newline if we add
257 # something afterwards. This prevents pesky trailing newlines on
258 # text in block elements. But we only do newline mangling at the
259 # block parse phase, so don't bother if self is an Inline.
260 if self._softbreak:
261 if len(self.children) > 0:
262 self.children[-1] += '\n'
263 self._softbreak = False
264 if not isinstance(self, Inline) and text.endswith('\n'):
265 text = text[:-1]
266 self._softbreak = True
267 if len(self.children) > 0 and isinstance(self.children[-1], str):
268 self.children[-1] += text
269 else:
270 self.children.append(text)
271
272 def add_namespace(self, prefix, uri):
273 self._namespaces[prefix] =uri
274
275 def get_namespace(self, prefix):
276 uri = self._namespaces.get(prefix)
277 if uri is not None:
278 return uri
279 if self._parent is not None:
280 return self._parent.get_namespace(prefix)
281 return None
282
283 def add_definition(self, name, value):
284 self._definitions[name] = value
285
286 def write_xml(self, outfile=None):
287 close = False
288 if outfile is None:
289 fd = sys.stdout
290 elif isinstance(outfile, str):
291 close = True
292 fd = open(outfile, 'w', encoding='utf-8')
293 else:
294 fd = outfile
295 self._write_xml(fd)
296 if close:
297 fd.close()
298
299 def _write_xml(self, fd, *, depth=0, verbatim=False):
300 verbatim = verbatim or self.is_verbatim
301 if not isinstance(self, Inline):
302 fd.write(' ' * depth)
303 fd.write('<' + self.name)
304 if self.default_namespace is not None:
305 fd.write(' xmlns="' + self.default_namespace + '"')
306 for prefix in self._namespaces:
307 fd.write(' xmlns:' + prefix + '="' + self._namespaces[prefix] + '"')
308 if self.attributes is not None:
309 self.attributes._write_xml(fd)
310 if self.is_empty:
311 if isinstance(self, Inline):
312 fd.write('/>')
313 else:
314 fd.write('/>\n')
315 elif (isinstance(self.children[0], Block) or
316 isinstance(self.children[0], Info) ):
317 fd.write('>\n')
318 else:
319 fd.write('>')
320
321 for i in range(len(self.children)):
322 child = self.children[i]
323 if isinstance(child, Inline):
324 child._write_xml(fd, depth=depth, verbatim=verbatim)
325 elif isinstance(child, Fence):
326 child._write_xml(fd, depth=depth, verbatim=verbatim)
327 if i + 1 < len(self.children):
328 fd.write('\n')
329 elif isinstance(child, Node):
330 child._write_xml(fd, depth=depth+1, verbatim=verbatim)
331 else:
332 if i > 0 and isinstance(self.children[i-1], Fence) and not verbatim:
333 fd.write(' ' * depth)
334 if '\n' in child:
335 nl = child.find('\n')
336 while nl >= 0:
337 if nl + 1 == len(child) and i + 1 == len(self.children):
338 fd.write(_escape_xml(child[:nl]))
339 elif verbatim or (nl + 1 < len(child) and child[nl + 1] == '\n'):
340 fd.write(_escape_xml(child[:nl]) + '\n')
341 elif self.is_tree_item:
342 fd.write(_escape_xml(child[:nl]) + '\n')
343 if nl + 1 < len(child):
344 fd.write(' ' * (depth + 1))
345 else:
346 fd.write(_escape_xml(child[:nl]) + '\n' + (' ' * depth))
347 child = child[nl + 1:]
348 nl = child.find('\n')
349 if child != '':
350 fd.write(_escape_xml(child))
351 else:
352 fd.write(_escape_xml(child))
353 if not self.is_empty:
354 leafy = self.is_leaf or self.is_external_leaf
355 for child in self.children:
356 if isinstance(child, (Block, Info)):
357 leafy = False
358 break
359 if isinstance(self, Inline):
360 fd.write('</' + self.name + '>')
361 elif leafy:
362 fd.write('</' + self.name + '>\n')
363 elif self.is_tree_item:
364 if self.has_tree_items:
365 fd.write((' ' * depth) + '</' + self.name + '>\n')
366 else:
367 fd.write('</' + self.name + '>\n')
368 else:
369 fd.write((' ' * depth) + '</' + self.name + '>\n')
370
371
372 class Document(Node):
373 def __init__(self, parser=None):
374 Node.__init__(self, '_', parser=parser)
375 self.divdepth = 0
376 self.default_namespace = 'http://projectmallard.org/1.0/'
377
378 def _write_xml(self, fd, *args, depth=0, verbatim=False):
379 if len(self.children) == 1:
380 fd.write('<?xml version="1.0" encoding="utf-8"?>\n')
381 for child in self.children:
382 if child.default_namespace is None:
383 child.default_namespace = self.default_namespace
384 for ns in self._namespaces:
385 child.add_namespace(ns, self._namespaces[ns])
386 child._write_xml(fd)
387
388
389 class Division(Node):
390 def __init__(self, name, depth, **kwargs):
391 Node.__init__(self, name, **kwargs)
392 self.divdepth = depth
393
394
395 class Block(Node):
396 pass
397
398
399 class Info(Node):
400 pass
401
402
403 class Inline(Node):
404 pass
405
406
407 class Fence(Node):
408 def add_line(self, line):
409 self.add_text(line)
410 return
411 indent = DuckParser.get_indent(line)
412 if len(self.children) == 0:
413 self.inner = indent
414 self.children.append('')
415 self.children[0] += line[min(indent, self.inner):]
416 if not line.endswith('\n'):
417 self.children[0] += '\n'
418
419 def _write_xml(self, fd, *, depth=0, verbatim=False):
420 lines = self.children[0].split('\n')
421 trim = min(self.inner, DuckParser.get_indent(lines[0]))
422 for i in range(len(lines)):
423 line = lines[i]
424 indent = DuckParser.get_indent(line)
425 if i != 0:
426 fd.write('\n')
427 fd.write(_escape_xml(line[min(indent, trim):]))
428
429
430 class NodeFactory:
431 def __init__(self, parser):
432 self.parser = parser
433 self.id_attribute = 'id'
434
435 def create_info_node(self, name, outer):
436 node = Info(name, outer=outer, parser=self.parser, extensions=True)
437 return node
438
439 def create_info_paragraph_node(self, outer):
440 node = Info('p', outer=outer, parser=self.parser)
441 return node
442
443 def create_block_node(self, name, outer):
444 node = Block(name, outer=outer, parser=self.parser, extensions=True)
445 return node
446
447 def create_block_paragraph_node(self, outer):
448 node = Block('p', outer=outer, parser=self.parser)
449 return node
450
451 def handle_division_title(self, depth, inner):
452 name = 'page' if (depth == 1) else 'section'
453 page = Division(name, depth=depth, parser=self.parser)
454 title = Block('title', inner=inner, parser=self.parser)
455 self.parser.current.add_child(page)
456 page.add_child(title)
457 self.parser.current = title
458
459 def handle_division_subtitle(self, depth, inner):
460 node = Block('subtitle', inner=inner, parser=self.parser)
461 self.parser.current.add_child(node)
462 self.parser.current = node
463
464 def handle_info_container(self, outer):
465 info = Block('info', outer=outer, parser=self.parser)
466 self.parser.current.insert_child(0, info)
467 self.parser.current.info = info
468 info.parent = self.parser.current
469
470 def handle_block_title(self, outer, inner):
471 # For lines starting with '. '. Creates a block title.
472 title = Block('title', outer, inner, parser=self.parser)
473 self.parser.current.add_child(title)
474 self.parser.current = title
475
476 def handle_block_item_title(self, outer, inner):
477 # For lines starting with '- '. It might be a th element,
478 # or it might be a title in a terms item. It might also
479 # start a terms element.
480 if self.parser.current.is_name('tr'):
481 node = Block('th', outer, inner, parser=self.parser)
482 self.parser.current.add_child(node)
483 self.parser.current = node
484 return
485
486 if not self.parser.current.is_name('terms'):
487 node = Block('terms', outer, parser=self.parser)
488 self.parser.current.add_child(node)
489 self.parser.current = node
490 # By now we've unwound to the terms element. If the preceding
491 # block was a title, then the last item will have only title
492 # elements, and we just keep appending there.
493 if (not self.parser.current.is_empty
494 and isinstance(self.parser.current.children[-1], Block)
495 and self.parser.current.children[-1].is_name('item')):
496 item = self.parser.current.children[-1]
497 if (not item.is_empty
498 and isinstance(self.parser.current.children[-1], Block)
499 and item.children[-1].is_name('title')):
500 self.parser.current = item
501 if not self.parser.current.is_name('item'):
502 item = Block('item', outer, inner, parser=self.parser)
503 self.parser.current.add_child(item)
504 self.parser.current = item
505 title = Block('title', outer, inner, parser=self.parser)
506 self.parser.current.add_child(title)
507 self.parser.current = title
508
509 def handle_block_item_content(self, outer, inner):
510 # For lines starting with '* '. It might be a td element,
511 # it might be an item element in a list or steps, it might
512 # be a tree item, or it might start the content of an item
513 # in a terms. It might also start a list element.
514 if self.parser.current.is_name('tr'):
515 node = Block('td', outer=outer, inner=inner, parser=self.parser)
516 self.parser.current.add_child(node)
517 self.parser.current = node
518 return node
519 elif self.parser.current.is_name('terms'):
520 # All the logic above will have unraveled us from the item
521 # created by the title, so we have to step back into it.
522 if self.parser.current.is_empty or not self.parser.current.children[-1].is_name('item'):
523 raise SyntaxError('Missing item title in terms', self.parser)
524 self.parser.current = self.parser.current.children[-1]
525 return self.parser.current
526 elif self.parser.current.is_name('tree') or self.parser.current.is_tree_item:
527 item = Block('item', outer=outer, inner=inner, parser=self.parser)
528 self.parser.current.add_child(item)
529 self.parser.current = item
530 return item
531 elif self.parser.current.is_name(('list', 'steps')):
532 item = Block('item', outer=outer, inner=inner, parser=self.parser)
533 self.parser.current.add_child(item)
534 self.parser.current = item
535 return item
536 else:
537 node = Block('list', outer=outer, parser=self.parser)
538 self.parser.current.add_child(node)
539 item = Block('item', outer=outer, inner=inner, parser=self.parser)
540 node.add_child(item)
541 self.parser.current = item
542 return item
543
544
545 class SyntaxError(Exception):
546 def __init__(self, message, parser):
547 self.message = message
548 self.parser = parser
549 self.filename = parser.filename if parser else None
550 self.linenum = parser.linenum if parser else None
551 self.fullmessage = ''
552 if self.filename is not None:
553 self.fullmessage += os.path.basename(self.filename)
554 if self.linenum is not None:
555 self.fullmessage += ':' + str(self.linenum)
556 self.fullmessage += ': '
557 self.fullmessage += self.message
558
559
560 class ParserExtension:
561 def __init__(self, parser, prefix, version):
562 pass
563
564 def parse_line_block(self, line):
565 return False
566
567 def take_directive(self, directive):
568 return False
569
570 def take_block_node(self, node):
571 return False
572
573
574 class InlineParser:
575 def __init__(self, parent, linenum=1):
576 # Dummy node just to hold children while we parse
577 self.current = Inline('_', linenum=linenum)
578 self.document = parent.document
579 self.filename = parent.filename
580 self.linenum = linenum
581 self._parent = parent
582
583 def lookup_entity(self, entity):
584 return self._parent.lookup_entity(entity)
585
586 def parse_text(self, text):
587 self._parse_text(text)
588 while self.current.parent is not None:
589 self.current = self.current.parent
590 return self.current.children
591
592 def _parse_text(self, text):
593 start = cur = 0
594 parens = []
595 while cur < len(text):
596 if self.current.parent is not None and text[cur] == ')':
597 if len(parens) > 0 and parens[-1] > 0:
598 parens[-1] -= 1
599 cur += 1
600 else:
601 self.current.add_text(text[start:cur])
602 self.current = self.current.parent
603 parens.pop()
604 cur += 1
605 start = cur
606 elif self.current.parent is not None and text[cur] == '(':
607 parens[-1] += 1
608 cur += 1
609 elif cur == len(text) - 1:
610 cur += 1
611 self.current.add_text(text[start:cur])
612 elif text[cur] == '$' and text[cur + 1] in _escaped_chars:
613 self.current.add_text(text[start:cur])
614 self.current.add_text(text[cur + 1])
615 cur += 2
616 start = cur
617 elif text[cur] == '$' and _isnmtoken(text[cur + 1]):
618 end = cur + 1
619 while end < len(text):
620 if not _isnmtoken(text[end]):
621 break
622 end += 1
623 if end == len(text):
624 self.current.add_text(text[start:end])
625 cur = end
626 elif text[end] == ';':
627 self.current.add_text(text[start:cur])
628 entname = text[cur + 1:end]
629 entval = self._parent.lookup_entity(entname)
630 if entval is not None:
631 parser = InlineParser(self,
632 linenum=self.current.linenum)
633 for child in parser.parse_text(entval):
634 if isinstance(child, str):
635 self.current.add_text(child)
636 else:
637 self.current.add_child(child)
638 else:
639 raise SyntaxError('Unrecognized entity: ' + entname, self)
640 start = cur = end + 1
641 elif text[end] == '[':
642 self.current.add_text(text[start:cur])
643 node = Inline(text[cur + 1:end], parser=self)
644 self.current.add_child(node)
645 attrparser = AttributeParser(self)
646 attrparser.parse_line(text[end + 1:])
647 if not attrparser.finished:
648 # We know we have all the text there could be,
649 # so this an unclosed attribute list. Do we make
650 # that an error, auto-close, or decide this was
651 # never really markup after all?
652 FIXME('unclosed attribute list')
653 node.attributes = attrparser.attributes
654 self.linenum = attrparser.linenum
655 start = cur = len(text) - len(attrparser.remainder)
656 if cur < len(text) and text[cur] == '(':
657 self.current = node
658 parens.append(0)
659 start = cur = cur + 1
660 elif text[end] == '(':
661 self.current.add_text(text[start:cur])
662 node = Inline(text[cur + 1:end], parser=self)
663 self.current.add_child(node)
664 self.current = node
665 parens.append(0)
666 start = cur = end + 1
667 else:
668 cur = end
669 else:
670 if text[cur] == '\n':
671 self.linenum += 1
672 cur += 1
673
674
675 class AttributeParser:
676 def __init__(self, parent, node=None):
677 self.remainder = ''
678 self.node = node
679 self.attributes = Attributes()
680 self.finished = False
681 self.filename = parent.filename
682 self.linenum = parent.linenum
683 self._quote = None
684 self._value = ''
685 self._attrname = None
686 self._parent = parent
687
688 def lookup_entity(self, entity):
689 return self._parent.lookup_entity(entity)
690
691 def parse_value(self, text):
692 retval = ''
693 start = cur = 0
694 while cur < len(text):
695 if text[cur] == '$':
696 if cur == len(text) - 1:
697 cur += 1
698 retval += text[start:cur]
699 start = cur
700 elif text[cur] == '$' and text[cur + 1] in _escaped_chars:
701 retval += text[start:cur]
702 retval += text[cur + 1]
703 cur += 2
704 start = cur
705 elif text[cur] == '$' and _isnmtoken(text[cur + 1]):
706 end = cur + 1
707 while end < len(text):
708 if not _isnmtoken(text[end]):
709 break
710 end += 1
711 if end == len(text):
712 retval += text[start:end]
713 start = cur = end
714 elif text[end] == ';':
715 retval += text[start:cur]
716 start = cur
717 entname = text[cur + 1:end]
718 entval = self.lookup_entity(entname)
719 if entval is not None:
720 parser = AttributeParser(self)
721 retval += parser.parse_value(entval)
722 else:
723 raise SyntaxError('Unrecognized entity: ' + entname, self)
724 start = cur = end + 1
725 else:
726 cur = end
727 else:
728 cur += 1
729 else:
730 if text[cur] == '\n':
731 self.linenum += 1
732 cur += 1
733 if cur != start:
734 retval += text[start:cur]
735 return retval
736
737 def parse_line(self, line):
738 i = 0
739 while i < len(line) and not self.finished:
740 if self._quote is not None:
741 j = i
742 while j < len(line):
743 if line[j] == '$':
744 # Will be parsed later. Just skip the escaped quote
745 # char so it doesn't close the attribute value.
746 if j + 1 < len(line) and line[j] in _escaped_chars:
747 j += 2
748 else:
749 j += 1
750 elif line[j] == self._quote:
751 self._value += line[i:j]
752 self._value = self.parse_value(self._value)
753 self.attributes.add_attribute(self._attrname, self._value)
754 self._value = ''
755 self._quote = None
756 i = j
757 break
758 else:
759 j += 1
760 if self._quote is not None:
761 self._value += line[i:j]
762 i = j + 1
763 elif line[i].isspace():
764 if line[i] == '\n':
765 self.linenum += 1
766 i += 1
767 elif line[i] == ']':
768 self.finished = True
769 self.remainder = line[i + 1:]
770 elif line[i] in ('.', '#', '>'):
771 j = i + 1
772 while j < len(line):
773 if line[j].isspace() or line[j] == ']':
774 break
775 j += 1
776 word = self.parse_value(line[i + 1:j])
777 if line[i] == '>':
778 if len(line) > i + 1 and line[i + 1] == '>':
779 self.attributes.add_attribute('href', word[1:])
780 else:
781 self.attributes.add_attribute('xref', word)
782 elif line[i] == '.':
783 self.attributes.add_attribute('style', word)
784 else:
785 self.attributes.add_attribute('id', word)
786 i = j
787 else:
788 j = i
789 while j < len(line) and _isnmtoken(line[j]):
790 j += 1
791 word = line[i:j]
792 if line[j] == '=' and word != '':
793 if ':' in word:
794 nsprefix, localname = word.split(':', maxsplit=1)
795 nsuri = self._parent.document.get_namespace(nsprefix)
796 if nsuri is None:
797 if nsprefix == 'xml':
798 pass
799 elif nsprefix == 'its':
800 self._parent.document.add_namespace('its', 'http://www.w3.org/2005/11/its')
801 else:
802 raise SyntaxError('Unrecognized namespace prefix: ' + nsprefix,
803 self)
804 if line[j + 1] in ('"', "'"):
805 self._quote = line[j + 1]
806 self._value = ''
807 i = j + 2
808 self._attrname = word
809 else:
810 k = j + 1
811 while k < len(line):
812 if line[k].isspace() or line[k] == ']':
813 break
814 k += 1
815 value = self.parse_value(line[j + 1:k])
816 self.attributes.add_attribute(word, value)
817 i = k
818 elif line[j].isspace() or line[j] == ']':
819 value = self.parse_value(line[i:j])
820 self.attributes.add_attribute('type', value)
821 i = j
822 else:
823 raise SyntaxError('Invalid character ' + line[j] +
824 ' in attribute list', self)
825
826
827 class DirectiveIncludeParser:
828 def __init__(self, parent):
829 self.parent = parent
830 self.document = parent.document
831 self.extensions = []
832 self.extensions_by_module = {}
833 self._start = True
834 self._comment = False
835
836 def parse_file(self, filename):
837 self.filename = filename
838 self.absfilename = os.path.join(os.path.dirname(self.parent.absfilename),
839 filename)
840 if isinstance(self.parent, DuckParser):
841 self._parentfiles = [self.parent.absfilename, self.absfilename]
842 else:
843 self._parentfiles = self.parent._parentfiles + [self.absfilename]
844 self.linenum = 0
845 try:
846 fd = open(self.absfilename, encoding='utf-8')
847 except:
848 raise SyntaxError('Missing included file ' + filename, self.parent)
849 for line in fd:
850 self.parse_line(line)
851 fd.close()
852
853 def parse_line(self, line):
854 self.linenum += 1
855
856 if self._comment:
857 if line.strip() == '--]':
858 self._comment = False
859 return
860 indent = DuckParser.get_indent(line)
861 iline = line[indent:]
862 if iline.startswith('[-]'):
863 return
864 elif iline.startswith('[--'):
865 self._comment = True
866 return
867
868 if line.strip() == '':
869 return
870 if not(line.startswith('@')):
871 raise SyntaxError('Directive includes can only include directives', self)
872 self._parse_line(line)
873
874 def take_directive(self, directive):
875 if directive.name.startswith('ducktype/'):
876 if not self._start:
877 raise SyntaxError('Ducktype declaration must be first', self)
878 if directive.name != 'ducktype/1.0':
879 raise SyntaxError(
880 'Unsupported ducktype version: ' + directive.name ,
881 self)
882 for value in directive.content.split():
883 try:
884 prefix, version = value.split('/', maxsplit=1)
885 extmod = importlib.import_module('mallard.ducktype.extensions.' + prefix)
886 for extclsname, extcls in inspect.getmembers(extmod, inspect.isclass):
887 if issubclass(extcls, ParserExtension):
888 extension = extcls(self, prefix, version)
889 self.extensions.append(extension)
890 self.extensions_by_module.setdefault(prefix, [])
891 self.extensions_by_module[prefix].append(extension)
892 except SyntaxError as e:
893 raise e
894 except:
895 raise SyntaxError(
896 'Unsupported ducktype extension: ' + value,
897 self)
898 elif ':' in directive.name:
899 prefix, name = directive.name.split(':', maxsplit=1)
900 if prefix not in self.extensions_by_module:
901 raise SyntaxError('Unrecognized directive prefix: ' + prefix, self)
902 for extension in self.extensions_by_module[prefix]:
903 if extension.take_directive(directive):
904 return
905 raise SyntaxError('Unrecognized directive: ' + directive.name, self)
906 elif directive.name == 'define':
907 try:
908 self.parent.take_directive(directive)
909 except SyntaxError as e:
910 raise SyntaxError(e.message, self)
911 elif directive.name == 'encoding':
912 FIXME('encoding')
913 elif directive.name == 'include':
914 if ' ' in directive.content:
915 raise SyntaxError('Multiple values in include. URL encode file name?', self)
916 relfile = urllib.parse.unquote(directive.content)
917 absfile = os.path.join(os.path.dirname(self.absfilename), relfile)
918 if absfile in self._parentfiles:
919 raise SyntaxError('Recursive include detected: ' + directive.content, self)
920 incparser = DirectiveIncludeParser(self)
921 incparser.parse_file(relfile)
922 elif directive.name == 'namespace':
923 try:
924 self.parent.take_directive(directive)
925 except SyntaxError as e:
926 raise SyntaxError(e.message, self)
927 else:
928 raise SyntaxError('Unrecognized directive: ' + directive.name, self)
929 self._start = False
930
931 def _parse_line(self, line):
932 directive = Directive.parse_line(line, self)
933 self.take_directive(directive)
934
935
936 class DuckParser:
937 STATE_START = 1
938 STATE_TOP = 2
939 STATE_HEADER = 3
940 STATE_HEADER_POST = 4
941 STATE_SUBHEADER = 5
942 STATE_SUBHEADER_POST = 6
943 STATE_HEADER_ATTR = 7
944 STATE_HEADER_ATTR_POST = 8
945 STATE_HEADER_INFO = 9
946 STATE_BLOCK = 10
947 STATE_BLOCK_ATTR = 11
948 STATE_BLOCK_READY = 12
949 STATE_BLOCK_INFO = 13
950
951 INFO_STATE_NONE = 101
952 INFO_STATE_INFO = 102
953 INFO_STATE_READY = 103
954 INFO_STATE_BLOCK = 104
955 INFO_STATE_ATTR = 105
956
957 def __init__(self):
958 self.state = DuckParser.STATE_START
959 self.info_state = DuckParser.INFO_STATE_NONE
960 self.linenum = 0
961 self.document = Document(parser=self)
962 self.current = self.document
963 self.curinfo = None
964 self.extensions = []
965 self.extensions_by_module = {}
966 self.factory = NodeFactory(self)
967
968 self._text = ''
969 self._attrparser = None
970 self._defaultid = None
971 self._comment = False
972 self._fenced = False
973 self._fragments = False
974
975 @staticmethod
976 def get_indent(line):
977 for i in range(len(line)):
978 if line[i] != ' ':
979 return i
980 return 0
981
982 def lookup_entity(self, entity):
983 cur = self.current
984 while cur is not None:
985 if entity in cur._definitions:
986 return cur._definitions[entity]
987 cur = cur.parent
988 if entity in entities.entities:
989 return entities.entities[entity]
990 else:
991 # Try to treat it as a hex numeric reference
992 hexnum = 0
993 for c in entity:
994 if c in '0123456789':
995 hexnum = hexnum * 16 + (ord(c) - 48)
996 elif c in 'abcdef':
997 hexnum = hexnum * 16 + (ord(c) - 87)
998 elif c in 'ABCDEF':
999 hexnum = hexnum * 16 + (ord(c) - 55)
1000 else:
1001 hexnum = None
1002 break
1003 if hexnum is not None:
1004 return chr(hexnum)
1005 return None
1006
1007 def parse_file(self, filename):
1008 self.filename = filename
1009 self.absfilename = os.path.abspath(filename)
1010 self._defaultid = os.path.basename(filename)
1011 if self._defaultid.endswith('.duck'):
1012 self._defaultid = self._defaultid[:-5]
1013 fd = open(filename, encoding='utf-8')
1014 for line in fd:
1015 self.parse_line(line)
1016 fd.close()
1017
1018 def parse_inline(self, node=None):
1019 if node is None:
1020 node = self.document
1021 oldchildren = node.children
1022 node.children = []
1023 if node.info is not None:
1024 self.parse_inline(node.info)
1025 for child in oldchildren:
1026 if isinstance(child, str):
1027 parser = InlineParser(self, linenum=node.linenum)
1028 for c in parser.parse_text(child):
1029 node.add_child(c)
1030 elif isinstance(child, Fence):
1031 node.add_child(child)
1032 else:
1033 self.parse_inline(child)
1034 node.add_child(child)
1035
1036 def take_directive(self, directive):
1037 if directive.name.startswith('ducktype/'):
1038 if self.state != DuckParser.STATE_START:
1039 raise SyntaxError('Ducktype declaration must be first', self)
1040 if directive.name != 'ducktype/1.0':
1041 raise SyntaxError(
1042 'Unsupported ducktype version: ' + directive.name ,
1043 self)
1044 for value in directive.content.split():
1045 if value == '__future__/fragments':
1046 self._fragments = True
1047 continue
1048 try:
1049 prefix, version = value.split('/', maxsplit=1)
1050 extmod = importlib.import_module('mallard.ducktype.extensions.' + prefix)
1051 for extclsname, extcls in inspect.getmembers(extmod, inspect.isclass):
1052 if issubclass(extcls, ParserExtension):
1053 extension = extcls(self, prefix, version)
1054 self.extensions.append(extension)
1055 self.extensions_by_module.setdefault(prefix, [])
1056 self.extensions_by_module[prefix].append(extension)
1057 except SyntaxError as e:
1058 raise e
1059 except:
1060 raise SyntaxError(
1061 'Unsupported ducktype extension: ' + value,
1062 self)
1063 elif ':' in directive.name:
1064 prefix, name = directive.name.split(':', maxsplit=1)
1065 if prefix not in self.extensions_by_module:
1066 raise SyntaxError('Unrecognized directive prefix: ' + prefix, self)
1067 for extension in self.extensions_by_module[prefix]:
1068 if extension.take_directive(directive):
1069 return
1070 raise SyntaxError('Unrecognized directive: ' + directive.name, self)
1071 elif directive.name == 'define':
1072 values = directive.content.split(maxsplit=1)
1073 if len(values) != 2:
1074 raise SyntaxError(
1075 'Entity definition takes exactly two values',
1076 self)
1077 self.current.add_definition(*values)
1078 elif directive.name == 'encoding':
1079 FIXME('encoding')
1080 elif directive.name == 'include':
1081 if ' ' in directive.content:
1082 raise SyntaxError('Multiple values in include. URL encode file name?', self)
1083 relfile = urllib.parse.unquote(directive.content)
1084 incparser = DirectiveIncludeParser(self)
1085 incparser.parse_file(relfile)
1086 elif directive.name == 'namespace':
1087 values = directive.content.split(maxsplit=1)
1088 if len(values) != 2:
1089 raise SyntaxError(
1090 'Namespace declaration takes exactly two values',
1091 self)
1092 if values[0] == 'xml':
1093 if values[1] != 'http://www.w3.org/XML/1998/namespace':
1094 raise SyntaxError('Wrong value of xml namespace prefix', self)
1095 if values[0] == 'its':
1096 if values[1] != 'http://www.w3.org/2005/11/its':
1097 raise SyntaxError('Wrong value of its namespace prefix', self)
1098 self.current.add_namespace(*values)
1099 else:
1100 raise SyntaxError('Unrecognized directive: ' + directive.name, self)
1101
1102 def finish(self):
1103 if (self.state in (DuckParser.STATE_HEADER_ATTR, DuckParser.STATE_BLOCK_ATTR) or
1104 self.info_state == DuckParser.INFO_STATE_ATTR):
1105 raise SyntaxError('Unterminated block declaration', self)
1106 self.push_text()
1107 if self._defaultid is not None and len(self.document.children) == 1:
1108 root = self.document.children[0]
1109 if isinstance(root, Division):
1110 if root.attributes is None:
1111 root.attributes = Attributes()
1112 idattr = self.factory.id_attribute
1113 if idattr not in root.attributes:
1114 root.attributes.add_attribute(idattr, self._defaultid)
1115 self.parse_inline()
1116
1117 def parse_line(self, line):
1118 self.linenum += 1
1119 self._parse_line(line)
1120
1121 def _parse_line(self, line):
1122 # If we're inside a comment or a no-parse fence, nothing else matters.
1123 if self._comment:
1124 if line.strip() == '--]':
1125 self._comment = False
1126 return
1127 if self._fenced:
1128 if line.strip() == ']]]':
1129 self._fenced = False
1130 self.current = self.current.parent
1131 else:
1132 self.current.add_line(line)
1133 return
1134
1135 indent = DuckParser.get_indent(line)
1136 iline = line[indent:]
1137
1138 if iline.startswith('[-]'):
1139 return
1140 elif iline.startswith('[--'):
1141 self._comment = True
1142 return
1143 elif self.info_state == DuckParser.INFO_STATE_INFO:
1144 self._parse_line_info(line)
1145 elif self.info_state == DuckParser.INFO_STATE_READY:
1146 self._parse_line_info(line)
1147 elif self.info_state == DuckParser.INFO_STATE_BLOCK:
1148 self._parse_line_info(line)
1149 elif self.info_state == DuckParser.INFO_STATE_ATTR:
1150 self._parse_line_info_attr(line)
1151 elif self.state == DuckParser.STATE_START:
1152 self._parse_line_top(line)
1153 elif self.state == DuckParser.STATE_TOP:
1154 self._parse_line_top(line)
1155 elif self.state == DuckParser.STATE_HEADER:
1156 self._parse_line_header(line)
1157 elif self.state == DuckParser.STATE_HEADER_POST:
1158 self._parse_line_header_post(line)
1159 elif self.state == DuckParser.STATE_SUBHEADER:
1160 self._parse_line_subheader(line)
1161 elif self.state == DuckParser.STATE_SUBHEADER_POST:
1162 self._parse_line_subheader_post(line)
1163 elif self.state == DuckParser.STATE_HEADER_ATTR:
1164 self._parse_line_header_attr(line)
1165 elif self.state == DuckParser.STATE_HEADER_ATTR_POST:
1166 self._parse_line_header_attr_post(line)
1167 elif self.state == DuckParser.STATE_HEADER_INFO:
1168 self._parse_line_header_info(line)
1169 elif self.state == DuckParser.STATE_BLOCK:
1170 self._parse_line_block(line)
1171 elif self.state == DuckParser.STATE_BLOCK_ATTR:
1172 self._parse_line_block_attr(line)
1173 elif self.state == DuckParser.STATE_BLOCK_READY:
1174 self._parse_line_block_ready(line)
1175 else:
1176 FIXME('unknown state')
1177
1178 def _parse_line_top(self, line):
1179 if line.strip() == '':
1180 self.state = DuckParser.STATE_TOP
1181 elif line.startswith('@'):
1182 self._parse_line_directive(line)
1183 elif line.startswith('= '):
1184 self.factory.handle_division_title(depth=1, inner=2)
1185 self.set_text(line[2:])
1186 self.state = DuckParser.STATE_HEADER
1187 elif line.strip().startswith('[') or line.startswith('=='):
1188 if self._fragments == False:
1189 raise SyntaxError('Missing page header', self)
1190 self.state = DuckParser.STATE_BLOCK
1191 self._parse_line(line)
1192 else:
1193 raise SyntaxError('Missing page header', self)
1194
1195 def _parse_line_directive(self, line):
1196 directive = Directive.parse_line(line, self)
1197 self.take_directive(directive)
1198 if self.state == DuckParser.STATE_START:
1199 self.state == DuckParser.STATE_TOP
1200
1201 def _parse_line_header(self, line):
1202 indent = DuckParser.get_indent(line)
1203 iline = line[indent:]
1204 if iline.startswith('@'):
1205 self.push_text()
1206 self.current = self.current.parent
1207 self.state = DuckParser.STATE_BLOCK
1208 self.info_state = DuckParser.INFO_STATE_INFO
1209 self._parse_line(line)
1210 elif indent > 0 and iline.startswith('['):
1211 self._parse_line_header_attr_start(line)
1212 elif indent >= self.current.inner:
1213 self.add_text(line[self.current.inner:])
1214 else:
1215 self.push_text()
1216 self.current = self.current.parent
1217 self.state = DuckParser.STATE_HEADER_POST
1218 self._parse_line(line)
1219
1220 def _parse_line_header_post(self, line):
1221 depth = self.current.divdepth
1222 if line.startswith(('-' * depth) + ' '):
1223 self.factory.handle_division_subtitle(depth=depth, inner=depth+1)
1224 self.set_text(line[depth + 1:])
1225 self.state = DuckParser.STATE_SUBHEADER
1226 elif line.lstrip().startswith('@'):
1227 self.state = DuckParser.STATE_BLOCK
1228 self.info_state = DuckParser.INFO_STATE_INFO
1229 self._parse_line(line)
1230 elif line.strip() == '':
1231 self.state = DuckParser.STATE_HEADER_INFO
1232 else:
1233 self.state = DuckParser.STATE_BLOCK
1234 self._parse_line(line)
1235
1236 def _parse_line_subheader(self, line):
1237 indent = DuckParser.get_indent(line)
1238 iline = line[indent:]
1239 if iline.startswith('@'):
1240 self.push_text()
1241 self.current = self.current.parent
1242 self.state = DuckParser.STATE_BLOCK
1243 self.info_state = DuckParser.INFO_STATE_INFO
1244 self._parse_line(line)
1245 elif indent > 0 and iline.startswith('['):
1246 self._parse_line_header_attr_start(line)
1247 elif indent >= self.current.inner:
1248 self.add_text(line[self.current.inner:])
1249 else:
1250 self.push_text()
1251 self.current = self.current.parent
1252 self.state = DuckParser.STATE_SUBHEADER_POST
1253 self._parse_line(line)
1254
1255 def _parse_line_subheader_post(self, line):
1256 if line.lstrip().startswith('@'):
1257 self.state = DuckParser.STATE_BLOCK
1258 self.info_state = DuckParser.INFO_STATE_INFO
1259 self._parse_line(line)
1260 elif line.strip() == '':
1261 self.state = DuckParser.STATE_HEADER_INFO
1262 else:
1263 self.state = DuckParser.STATE_BLOCK
1264 self._parse_line(line)
1265
1266 def _parse_line_header_attr_start(self, line):
1267 indent = DuckParser.get_indent(line)
1268 if indent > 0 and line[indent:].startswith('['):
1269 self.push_text()
1270 self.current = self.current.parent
1271 self._attrparser = AttributeParser(self)
1272 self._attrparser.parse_line(line[indent + 1:])
1273 if self._attrparser.finished:
1274 self.current.attributes = self._attrparser.attributes
1275 self.state = DuckParser.STATE_HEADER_ATTR_POST
1276 self._attrparser = None
1277 else:
1278 self.state = DuckParser.STATE_HEADER_ATTR
1279 else:
1280 self.push_text()
1281 self.current = self.current.parent
1282 self.state = DuckParser.STATE_HEADER_ATTR_POST
1283 self._parse_line(line)
1284
1285 def _parse_line_header_attr(self, line):
1286 self._attrparser.parse_line(line)
1287 if self._attrparser.finished:
1288 self.current.attributes = self._attrparser.attributes
1289 self.state = DuckParser.STATE_HEADER_ATTR_POST
1290 self._attrparser = None
1291
1292 def _parse_line_header_attr_post(self, line):
1293 if line.lstrip().startswith('@'):
1294 self.state = DuckParser.STATE_BLOCK
1295 self.info_state = DuckParser.INFO_STATE_INFO
1296 self._parse_line(line)
1297 elif line.strip() == '':
1298 self.state = DuckParser.STATE_HEADER_INFO
1299 else:
1300 self.state = DuckParser.STATE_BLOCK
1301 self._parse_line(line)
1302
1303 def _parse_line_header_info(self, line):
1304 if line.lstrip().startswith('@'):
1305 self.state = DuckParser.STATE_BLOCK
1306 self.info_state = DuckParser.INFO_STATE_INFO
1307 self._parse_line(line)
1308 elif line.strip() == '':
1309 self.state = DuckParser.STATE_HEADER_INFO
1310 else:
1311 self.state = DuckParser.STATE_BLOCK
1312 self._parse_line(line)
1313
1314 def _parse_line_info(self, line):
1315 if line.strip() == '':
1316 # If the info elements weren't indented past the indent
1317 # level of the parent and the parent is a block, blank
1318 # line terminates info, because it must terminate the
1319 # block according to block processing rules.
1320 if (self.current.outer == self.current.inner and not isinstance(self.current, Division)):
1321 self.push_text()
1322 self.info_state = DuckParser.INFO_STATE_NONE
1323 self._parse_line(line)
1324 return
1325 # If we're inside a leaf element like a paragraph, break
1326 # out of that. Unless it's an indented verbatim element,
1327 # in which case the newline is just part of the content.
1328 if self.curinfo.is_leaf:
1329 if (self.curinfo.is_verbatim and
1330 self.curinfo.inner > self.curinfo.outer):
1331 self.add_text('\n')
1332 else:
1333 self.push_text()
1334 self.curinfo = self.curinfo.parent
1335 self.info_state = DuckParser.INFO_STATE_INFO
1336 return
1337
1338 indent = DuckParser.get_indent(line)
1339 if self.current.info is None:
1340 self.factory.handle_info_container(indent)
1341 self.curinfo = self.current.info
1342 if indent < self.current.info.outer:
1343 self.push_text()
1344 self.info_state = DuckParser.INFO_STATE_NONE
1345 self._parse_line(line)
1346 return
1347 iline = line[indent:]
1348 if iline.startswith('@'):
1349 self._parse_line_info_info(iline, indent)
1350 else:
1351 # Block content at the same (or less) indent level as the
1352 # info elements doesn't belong to info. It starts the body.
1353 if indent <= self.current.info.outer:
1354 self.push_text()
1355 self.info_state = DuckParser.INFO_STATE_NONE
1356 self._parse_line(line)
1357 return
1358 self._parse_line_info_block(iline, indent)
1359
1360 def _parse_line_info_info(self, iline, indent):
1361 # Unlike block elements, info elements are never children of
1362 # preceding info elements at the same indent level. Unravel
1363 # as long as the current info's outer indent is the same.
1364 if indent <= self.curinfo.outer:
1365 self.push_text()
1366 while indent <= self.curinfo.outer:
1367 if self.curinfo == self.current.info:
1368 break
1369 self.curinfo = self.curinfo.parent
1370 # First line after an @info declaration? Set inner indent.
1371 if self.info_state == DuckParser.INFO_STATE_READY:
1372 self.curinfo.inner = indent
1373 self.info_state = DuckParser.INFO_STATE_INFO
1374
1375 for j in range(1, len(iline)):
1376 if not _isnmtoken(iline[j]):
1377 break
1378 name = iline[1:j]
1379 node = self.factory.create_info_node(name, indent)
1380 self.curinfo.add_child(node)
1381 self.curinfo = node
1382
1383 if iline[j] == '[':
1384 self.info_state = DuckParser.INFO_STATE_ATTR
1385 self._attrparser = AttributeParser(self)
1386 self._parse_line_info_attr(iline[j + 1:])
1387 else:
1388 remainder = iline[j:].lstrip()
1389 if remainder != '':
1390 if not self.curinfo.is_leaf:
1391 pnode = self.factory.create_info_paragraph_node(self.curinfo.outer)
1392 self.curinfo.add_child(pnode)
1393 self.curinfo = pnode
1394 self.set_text(remainder)
1395 else:
1396 self.info_state = DuckParser.INFO_STATE_READY
1397
1398 def _parse_line_info_block(self, iline, indent):
1399 # If we're already inside a leaf element, we only break out
1400 # if the indent is less than the inner indent. For example:
1401 # @p
1402 # Inside of p
1403 if self.curinfo.is_leaf or self.curinfo.is_external:
1404 if indent < self.curinfo.inner:
1405 self.push_text()
1406 self.curinfo = self.curinfo.parent
1407 # If we're not in a leaf, we need to create an implicit
1408 # info paragraph, but only after breaking out to the
1409 # level of the outer indent. For example:
1410 # @foo
1411 # Not inside of foo, and in implicit p
1412 else:
1413 if indent <= self.curinfo.outer:
1414 self.push_text()
1415 while indent <= self.curinfo.outer:
1416 if self.curinfo == self.current.info:
1417 break
1418 self.curinfo = self.curinfo.parent
1419
1420 # After all that unraveling, if we're not in a leaf or external,
1421 # and only if we have real text to add, create an implicit p.
1422 if iline.strip() != '' and not (
1423 self.curinfo.is_leaf or self.curinfo.is_external):
1424 node = self.factory.create_info_paragraph_node(indent)
1425 self.curinfo.add_child(node)
1426 self.curinfo = node
1427
1428 # First line after an @info declaration? Set inner indent.
1429 if self.info_state == DuckParser.INFO_STATE_READY:
1430 self.curinfo.inner = indent
1431 self.info_state = DuckParser.INFO_STATE_BLOCK
1432
1433 self.info_state = DuckParser.INFO_STATE_BLOCK
1434
1435 self.add_text(iline)
1436
1437 def _parse_line_info_attr(self, line):
1438 self._attrparser.parse_line(line)
1439 if self._attrparser.finished:
1440 self.curinfo.attributes = self._attrparser.attributes
1441
1442 remainder = self._attrparser.remainder.lstrip()
1443 if remainder != '':
1444 if not self.curinfo.is_leaf:
1445 pnode = self.factory.create_info_paragraph_node(self.curinfo.outer)
1446 self.curinfo.add_child(pnode)
1447 self.curinfo = pnode
1448 self.set_text(remainder)
1449 self._attrparser = None
1450 if self._text == '':
1451 self.info_state = DuckParser.INFO_STATE_READY
1452 else:
1453 self.info_state = DuckParser.INFO_STATE_INFO
1454
1455 def _parse_line_block(self, line):
1456 # Blank lines close off elements that have inline content (leaf)
1457 # unless they're verbatim elements that have an inner indent. Only
1458 # decreasing indent can break free of those. They also break out of
1459 # unindented block container elements, except for a set of special
1460 # elements that take lists of things instead of general blocks.
1461 if line.strip() == '':
1462 if self.current.is_leaf:
1463 if (self.current.is_verbatim and
1464 self.current.inner > self.current.outer):
1465 self.add_text('\n')
1466 else:
1467 self.push_text()
1468 self.current = self.current.parent
1469 while self.current.inner == self.current.outer:
1470 if isinstance(self.current, (Division, Document)):
1471 break
1472 if self.current.is_greedy:
1473 break
1474 if self.current.is_leaf:
1475 self.push_text()
1476 self.current = self.current.parent
1477 return
1478
1479 sectd = 0
1480 if line.startswith('=='):
1481 i = 0
1482 while i < len(line) and line[i] == '=':
1483 i += 1
1484 if i < len(line) and line[i] == ' ':
1485 sectd = i
1486 if sectd > 0:
1487 self.push_text()
1488 while not isinstance(self.current, (Division, Document)):
1489 self.current = self.current.parent
1490 while self.current.divdepth >= sectd:
1491 self.current = self.current.parent
1492 if sectd != self.current.divdepth + 1:
1493 if isinstance(self.current, Document) and (
1494 self._fragments and(
1495 len(self.current.children) == 0 or
1496 sectd == self.current.children[0].divdepth)):
1497 pass
1498 else:
1499 raise SyntaxError('Incorrect section depth', self)
1500 self.factory.handle_division_title(depth=sectd, inner=sectd+1)
1501 self.set_text(line[sectd + 1:])
1502 self.state = DuckParser.STATE_HEADER
1503 return
1504
1505 # If the indent is less than what we can append to the current
1506 # node, unravel until we're at the same indent level. Note that
1507 # this still might not be the right level. We may or may not be
1508 # able to add children to a block at the same indent, but we'll
1509 # handle that later, because it depends on stuff. We don't use
1510 # unravel, because that always breaks out of leafs, and at this
1511 # point we might still be adding text to a leaf.
1512 indent = DuckParser.get_indent(line)
1513 if indent < self.current.inner:
1514 self.push_text()
1515 while self.current.inner > indent:
1516 if isinstance(self.current, (Division, Document)):
1517 break
1518 self.current = self.current.parent
1519
1520 if self.current.is_verbatim:
1521 iline = line[self.current.inner:]
1522 else:
1523 iline = line[indent:]
1524
1525 # [[[ starts a no-parse fence that ends with ]]], either at the
1526 # end of this line, or on its own line later. This just suppresses
1527 # block and inline parsing. It has no additional semantics. So if
1528 # we're not already in a leaf element, create a paragraph just as
1529 # we would do if we encountered normal text.
1530 if iline.startswith('[[['):
1531 self.push_text()
1532 node = Fence('_', indent, parser=self)
1533
1534 if not (self.current.is_leaf or self.current.is_external or
1535 (self.current.is_tree_item and not self.current.has_tree_items)):
1536 if self.current.is_tree_item:
1537 while self.current.is_name(('tree', 'item')):
1538 self.current = self.current.parent
1539 while self.current.outer == indent and not self.current.available:
1540 if isinstance(self.current, (Division, Document)):
1541 break
1542 self.current = self.current.parent
1543 pnode = self.factory.create_block_paragraph_node(indent)
1544 self.current.add_child(pnode)
1545 pnode.add_child(node)
1546 else:
1547 self.current.add_child(node)
1548
1549 sline = iline.strip()[3:]
1550 if sline.endswith(']]]'):
1551 node.inner = 0
1552 node.add_line(sline[:-3] + '\n')
1553 else:
1554 if sline.strip() != '':
1555 node.inner = 0
1556 node.add_line(sline + '\n')
1557 self.current = node
1558 self._fenced = True
1559 return
1560
1561 # Give all extensions a shot at this line. If any of them handles
1562 # the line (returns True), we're done.
1563 for extension in self.extensions:
1564 if extension.parse_line_block(line):
1565 return
1566
1567 if iline.startswith('['):
1568 # Start a block with a standard block declaration.
1569 self.push_text()
1570
1571 for j in range(1, len(iline)):
1572 if not _isnmtoken(iline[j]):
1573 break
1574 name = iline[1:j]
1575 node = self.factory.create_block_node(name, indent)
1576
1577 if node.is_name('item'):
1578 self.unravel_for_list_item(indent)
1579 elif node.is_name(('td', 'th')):
1580 self.unravel_for_table_cell(indent)
1581 elif node.is_name('tr'):
1582 self.unravel_for_table_row(indent)
1583 elif node.is_name(('thead', 'tfoot', 'tbody')):
1584 self.unravel_for_table_body(indent)
1585 else:
1586 self.unravel_for_block(indent)
1587
1588 if iline[j] == ']':
1589 self.state = DuckParser.STATE_BLOCK_READY
1590 self._take_block_node(node)
1591 else:
1592 self._attrparser = AttributeParser(self, node=node)
1593 self._attrparser.parse_line(iline[j:])
1594 if self._attrparser.finished:
1595 node.attributes = self._attrparser.attributes
1596 self.state = DuckParser.STATE_BLOCK_READY
1597 self._attrparser = None
1598 self._take_block_node(node)
1599 else:
1600 self.state = DuckParser.STATE_BLOCK_ATTR
1601 elif iline.startswith('. '):
1602 self._parse_line_block_title(iline, indent)
1603 elif iline.startswith('- '):
1604 self._parse_line_block_item_title(iline, indent)
1605 elif iline.startswith('* '):
1606 self._parse_line_block_item_content(iline, indent)
1607 elif not (self.current.is_leaf or self.current.is_external or
1608 (self.current.is_tree_item and not self.current.has_tree_items)):
1609 if self.current.is_tree_item:
1610 while self.current.is_name(('tree', 'item')):
1611 self.current = self.current.parent
1612 while self.current.outer == indent and not self.current.available:
1613 if isinstance(self.current, (Division, Document)):
1614 break
1615 self.current = self.current.parent
1616 node = self.factory.create_block_paragraph_node(indent)
1617 self.current.add_child(node)
1618 self.current = node
1619 self.add_text(iline)
1620 else:
1621 self.add_text(iline)
1622
1623 def _parse_line_block_title(self, iline, indent):
1624 # For lines starting with '. '. Creates a block title.
1625 self.push_text()
1626 self.unravel_for_block(indent)
1627 self.factory.handle_block_title(indent, indent + 2)
1628 self._parse_line((' ' * self.current.inner) + iline[2:])
1629
1630 def _parse_line_block_item_title(self, iline, indent):
1631 # For lines starting with '- '. It might be a th element,
1632 # or it might be a title in a terms item. It might also
1633 # start a terms element.
1634 self.push_text()
1635 self.unravel_for_indent(indent)
1636 self.factory.handle_block_item_title(indent, indent + 2)
1637 self._parse_line((' ' * self.current.inner) + iline[2:])
1638
1639 def _parse_line_block_item_content(self, iline, indent):
1640 # For lines starting with '* '. It might be a td element,
1641 # it might be an item element in a list or steps, it might
1642 # be a tree item, or it might start the content of an item
1643 # in a terms. It might also start a list element.
1644 self.push_text()
1645 self.unravel_for_indent(indent)
1646 node = self.factory.handle_block_item_content(indent, indent + 2)
1647 self._parse_line((' ' * node.inner) + iline[2:])
1648
1649 def _parse_line_block_attr(self, line):
1650 self._attrparser.parse_line(line)
1651 if self._attrparser.finished:
1652 node = self._attrparser.node
1653 node.attributes = self._attrparser.attributes
1654 self.state = DuckParser.STATE_BLOCK_READY
1655 self._attrparser = None
1656 self._take_block_node(node)
1657
1658 def _parse_line_block_ready(self, line):
1659 indent = DuckParser.get_indent(line)
1660 if indent < self.current.outer:
1661 while self.current.outer > indent:
1662 if isinstance(self.current, (Division, Document)):
1663 break
1664 self.current = self.current.parent
1665 else:
1666 if line.lstrip().startswith('@'):
1667 self.info_state = DuckParser.INFO_STATE_INFO
1668 self.current.inner = DuckParser.get_indent(line)
1669 self.state = DuckParser.STATE_BLOCK
1670 self._parse_line(line)
1671
1672 def _take_block_node(self, node):
1673 if node.extension:
1674 for extension in self.extensions_by_module[node.extension]:
1675 if extension.take_block_node(node):
1676 return
1677 # If no extension claimed it, but there's still a namespace
1678 # binding, that's ok. You can have a namespace prefix with
1679 # the same name as an extension, but the extension wins.
1680 if node.nsuri is not None:
1681 self.current.add_child(node)
1682 self.current = node
1683 else:
1684 raise SyntaxError('Unrecognized extension element: ' + node.name, self)
1685 else:
1686 self.current.add_child(node)
1687 self.current = node
1688
1689 def set_text(self, text):
1690 self._text = text
1691
1692 def add_text(self, text):
1693 self._text += text
1694
1695 def push_text(self):
1696 if self._text != '':
1697 if self.info_state != DuckParser.INFO_STATE_NONE:
1698 self.curinfo.add_text(self._text)
1699 else:
1700 self.current.add_text(self._text)
1701 self.set_text('')
1702
1703 # Call this if you have an item to insert
1704 def unravel_for_list_item(self, indent):
1705 self.unravel_for_indent(indent)
1706 while self.current.outer == indent:
1707 if isinstance(self.current, (Division, Document)):
1708 break
1709 if self.current.available:
1710 break
1711 if self.current.is_list:
1712 break
1713 self.current = self.current.parent
1714
1715 # Call this if you have a td or th to insert
1716 def unravel_for_table_cell(self, indent):
1717 self.unravel_for_indent(indent)
1718 while self.current.outer == indent:
1719 if isinstance(self.current, (Division, Document)):
1720 break
1721 if self.current.available:
1722 break
1723 if self.current.is_name('tr'):
1724 break
1725 self.current = self.current.parent
1726 if self.current.is_tree_item:
1727 while self.current.is_name(('tree', 'item')):
1728 self.current = self.current.parent
1729
1730 # Call this if you have a tr to insert
1731 def unravel_for_table_row(self, indent):
1732 self.unravel_for_indent(indent)
1733 while self.current.outer == indent:
1734 if isinstance(self.current, (Division, Document)):
1735 break
1736 if self.current.available:
1737 break
1738 if self.current.is_name(('table', 'thead', 'tfoot', 'tbody')):
1739 break
1740 self.current = self.current.parent
1741 if self.current.is_tree_item:
1742 while self.current.is_name(('tree', 'item')):
1743 self.current = self.current.parent
1744
1745 # Call this if you have a tbody, thead, or tfoot to insert
1746 def unravel_for_table_body(self, indent):
1747 self.unravel_for_indent(indent)
1748 while self.current.outer == indent:
1749 if isinstance(self.current, (Division, Document)):
1750 break
1751 if self.current.available:
1752 break
1753 if self.current.is_name('table'):
1754 break
1755 self.current = self.current.parent
1756 if self.current.is_tree_item:
1757 while self.current.is_name(('tree', 'item')):
1758 self.current = self.current.parent
1759
1760 # Call this if you have any other block to insert
1761 def unravel_for_block(self, indent):
1762 self.unravel_for_indent(indent)
1763 while self.current.outer == indent:
1764 if isinstance(self.current, (Division, Document)):
1765 break
1766 if self.current.available:
1767 break
1768 self.current = self.current.parent
1769 if self.current.is_tree_item:
1770 while self.current.is_name(('tree', 'item')):
1771 self.current = self.current.parent
1772
1773 # This only unravels what indentation absolutely forces.
1774 def unravel_for_indent(self, indent):
1775 while self.current.outer > indent or self.current.is_leaf:
1776 if isinstance(self.current, (Division, Document)):
1777 break
1778 self.current = self.current.parent
1779
1780
1781 def _isnmtoken(c):
1782 i = ord(c)
1783 return (('A' <= c <= 'Z') or ('a' <= c <= 'z') or ('0' <= c <= '9') or
1784 (c == ':' or c == '_' or c == '-' or c == '.' or i == 0xB7) or
1785 (0xC0 <= i <= 0xD6) or (0xD8 <= i <= 0xF6) or
1786 (0xF8 <= i <= 0x2FF) or (0x370 <= i <= 0x37D) or
1787 (0x37F <= i <= 0x1FFF) or (0x200C <= i <= 0x200D) or
1788 (0x2070 <= i <= 0x218F) or (0x2C00 <= i <= 0x2FEF) or
1789 (0x3001 <= i <= 0xD7FF) or (0xF900 <= i <= 0xFDCF) or
1790 (0xFDF0 <= i <= 0xFFFD) or (0x10000 <= i <= 0xEFFFF) or
1791 (0x0300 <= i <= 0x036F) or (0x203F <= i <= 0x2040))