File: ast_renderer.py

package info (click to toggle)
python-mistletoe 1.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 828 kB
  • sloc: python: 5,663; sh: 66; makefile: 40
file content (53 lines) | stat: -rw-r--r-- 1,475 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""
Abstract syntax tree renderer for mistletoe.
"""

import json
from mistletoe.base_renderer import BaseRenderer


class AstRenderer(BaseRenderer):
    def render(self, token):
        """
        Returns the string representation of the AST.

        Overrides super().render. Delegates the logic to get_ast.
        """
        return json.dumps(get_ast(token), indent=2) + '\n'

    def __getattr__(self, name):
        return lambda token: ''


def get_ast(token):
    """
    Recursively unrolls token attributes into dictionaries (token.children
    into lists).

    Returns:
        a dictionary of token's attributes.
    """
    node = {}
    # Python 3.6 uses [ordered dicts] [1].
    # Put in 'type' entry first to make the final tree format somewhat
    # similar to [MDAST] [2].
    #
    #   [1]: https://docs.python.org/3/whatsnew/3.6.html
    #   [2]: https://github.com/syntax-tree/mdast
    node['type'] = token.__class__.__name__
    for attrname in ['content', 'footnotes']:
        if attrname in vars(token):
            node[attrname] = getattr(token, attrname)
    for attrname in token.repr_attributes:
        node[attrname] = getattr(token, attrname)
    if 'header' in vars(token):
        node['header'] = get_ast(getattr(token, 'header'))
    if token.children is not None:
        node['children'] = [get_ast(child) for child in token.children]
    return node


ASTRenderer = AstRenderer
"""
Deprecated name of the `AstRenderer` class.
"""