Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 1 | # Copyright 2006 Google, Inc. All Rights Reserved. |
| 2 | # Licensed to PSF under a Contributor Agreement. |
| 3 | |
| 4 | """Export the Python grammar and symbols.""" |
| 5 | |
| 6 | # Python imports |
| 7 | import os |
| 8 | |
| 9 | # Local imports |
| 10 | from .pgen2 import token |
| 11 | from .pgen2 import driver |
| 12 | from . import pytree |
| 13 | |
| 14 | # The grammar file |
| 15 | _GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt") |
| 16 | |
| 17 | |
| 18 | class Symbols(object): |
| 19 | |
| 20 | def __init__(self, grammar): |
| 21 | """Initializer. |
| 22 | |
| 23 | Creates an attribute for each grammar symbol (nonterminal), |
| 24 | whose value is the symbol's type (an int >= 256). |
| 25 | """ |
Martin v. Löwis | 8a5f8ca | 2008-03-19 05:33:36 +0000 | [diff] [blame] | 26 | for name, symbol in grammar.symbol2number.items(): |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 27 | setattr(self, name, symbol) |
| 28 | |
| 29 | |
| 30 | python_grammar = driver.load_grammar(_GRAMMAR_FILE) |
| 31 | python_symbols = Symbols(python_grammar) |
| 32 | |
| 33 | |
| 34 | def parenthesize(node): |
| 35 | return pytree.Node(python_symbols.atom, |
| 36 | (pytree.Leaf(token.LPAR, "("), |
| 37 | node, |
| 38 | pytree.Leaf(token.RPAR, ")"))) |