Parser Base.
| 77 | |
| 78 | |
| 79 | class Parser: |
| 80 | """Parser Base.""" |
| 81 | |
| 82 | def __init__(self): |
| 83 | self.statement_nodes = STATEMENT_NODES |
| 84 | self.keywords = KEYWORDS |
| 85 | |
| 86 | def parse(self, text, name="<template>"): |
| 87 | self.text = text |
| 88 | self.name = name |
| 89 | |
| 90 | defwith, text = self.read_defwith(text) |
| 91 | suite = self.read_suite(text) |
| 92 | return DefwithNode(defwith, suite) |
| 93 | |
| 94 | def read_defwith(self, text): |
| 95 | if text.startswith("$def with"): |
| 96 | defwith, text = splitline(text) |
| 97 | defwith = defwith[1:].strip() # strip $ and spaces |
| 98 | return defwith, text |
| 99 | else: |
| 100 | return "", text |
| 101 | |
| 102 | def read_section(self, text): |
| 103 | r"""Reads one section from the given text. |
| 104 | |
| 105 | section -> block | assignment | line |
| 106 | |
| 107 | >>> read_section = Parser().read_section |
| 108 | >>> read_section('foo\nbar\n') |
| 109 | (<line: [t'foo\n']>, 'bar\n') |
| 110 | >>> read_section('$ a = b + 1\nfoo\n') |
| 111 | (<assignment: 'a = b + 1'>, 'foo\n') |
| 112 | |
| 113 | read_section('$for in range(10):\n hello $i\nfoo) |
| 114 | """ |
| 115 | if text.lstrip(" ").startswith("$"): |
| 116 | index = text.index("$") |
| 117 | begin_indent, text2 = text[:index], text[index + 1 :] |
| 118 | ahead = self.python_lookahead(text2) |
| 119 | |
| 120 | if ahead == "var": |
| 121 | return self.read_var(text2) |
| 122 | elif ahead in self.statement_nodes: |
| 123 | return self.read_block_section(text2, begin_indent) |
| 124 | elif ahead in self.keywords: |
| 125 | return self.read_keyword(text2) |
| 126 | elif ahead.strip() == "": |
| 127 | # assignments starts with a space after $ |
| 128 | # ex: $ a = b + 2 |
| 129 | return self.read_assignment(text2) |
| 130 | return self.readline(text) |
| 131 | |
| 132 | def read_var(self, text): |
| 133 | r"""Reads a var statement. |
| 134 | |
| 135 | >>> read_var = Parser().read_var |
| 136 | >>> read_var('var x=10\nfoo') |
no outgoing calls