All patches and comments are welcome. Please squash your changes to logical
commits before using git-format-patch and git-send-email to
patches@git.madduck.net.
If you'd read over the Git project's submission guidelines and adhered to them,
I'd be especially grateful.
1 # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2 # Licensed to PSF under a Contributor Agreement.
5 # Copyright 2006 Google, Inc. All Rights Reserved.
6 # Licensed to PSF under a Contributor Agreement.
10 This provides a high-level interface to parse a file into a syntax tree.
14 __author__ = "Guido van Rossum <guido@python.org>"
16 __all__ = ["Driver", "load_grammar"]
27 from . import grammar, parse, token, tokenize, pgen
37 tokenizer_config=tokenize.TokenizerConfig(),
39 self.grammar = grammar
41 logger = logging.getLogger(__name__)
43 self.convert = convert
44 self.tokenizer_config = tokenizer_config
46 def parse_tokens(self, tokens, debug=False):
47 """Parse a series of tokens and return the syntax tree."""
48 # XXX Move the prefix computation into a wrapper around tokenize.
49 p = parse.Parser(self.grammar, self.convert)
54 type = value = start = end = line_text = None
56 for quintuple in tokens:
57 type, value, start, end, line_text = quintuple
58 if start != (lineno, column):
59 assert (lineno, column) <= start, ((lineno, column), start)
60 s_lineno, s_column = start
62 prefix += "\n" * (s_lineno - lineno)
66 prefix += line_text[column:s_column]
68 if type in (tokenize.COMMENT, tokenize.NL):
71 if value.endswith("\n"):
76 type = grammar.opmap[value]
78 self.logger.debug("%s %r (prefix=%r)",
79 token.tok_name[type], value, prefix)
80 if type == token.INDENT:
81 indent_columns.append(len(value))
82 _prefix = prefix + value
85 elif type == token.DEDENT:
86 _indent_col = indent_columns.pop()
87 prefix, _prefix = self._partially_consume_prefix(prefix, _indent_col)
88 if p.addtoken(type, value, (prefix, start)):
90 self.logger.debug("Stop.")
93 if type in {token.INDENT, token.DEDENT}:
96 if value.endswith("\n"):
100 # We never broke out -- EOF is too soon (how can this happen???)
101 raise parse.ParseError("incomplete input",
102 type, value, (prefix, start))
105 def parse_stream_raw(self, stream, debug=False):
106 """Parse a stream and return the syntax tree."""
107 tokens = tokenize.generate_tokens(stream.readline, config=self.tokenizer_config)
108 return self.parse_tokens(tokens, debug)
110 def parse_stream(self, stream, debug=False):
111 """Parse a stream and return the syntax tree."""
112 return self.parse_stream_raw(stream, debug)
114 def parse_file(self, filename, encoding=None, debug=False):
115 """Parse a file and return the syntax tree."""
116 with io.open(filename, "r", encoding=encoding) as stream:
117 return self.parse_stream(stream, debug)
119 def parse_string(self, text, debug=False):
120 """Parse a string and return the syntax tree."""
121 tokens = tokenize.generate_tokens(
122 io.StringIO(text).readline,
123 config=self.tokenizer_config,
125 return self.parse_tokens(tokens, debug)
127 def _partially_consume_prefix(self, prefix, column):
136 if current_line.strip() and current_column < column:
138 return res, prefix[len(res):]
140 lines.append(current_line)
147 # unexpected empty line
152 return ''.join(lines), current_line
155 def _generate_pickle_name(gt, cache_dir=None):
156 head, tail = os.path.splitext(gt)
159 name = head + tail + ".".join(map(str, sys.version_info)) + ".pickle"
161 return os.path.join(cache_dir, os.path.basename(name))
166 def load_grammar(gt="Grammar.txt", gp=None,
167 save=True, force=False, logger=None):
168 """Load the grammar (maybe from a pickle)."""
170 logger = logging.getLogger(__name__)
171 gp = _generate_pickle_name(gt) if gp is None else gp
172 if force or not _newer(gp, gt):
173 logger.info("Generating grammar tables from %s", gt)
174 g = pgen.generate_grammar(gt)
176 logger.info("Writing grammar tables to %s", gp)
180 logger.info("Writing failed: %s", e)
182 g = grammar.Grammar()
188 """Inquire whether file a was written since file b."""
189 if not os.path.exists(a):
191 if not os.path.exists(b):
193 return os.path.getmtime(a) >= os.path.getmtime(b)
196 def load_packaged_grammar(package, grammar_source, cache_dir=None):
197 """Normally, loads a pickled grammar by doing
198 pkgutil.get_data(package, pickled_grammar)
199 where *pickled_grammar* is computed from *grammar_source* by adding the
200 Python version and using a ``.pickle`` extension.
202 However, if *grammar_source* is an extant file, load_grammar(grammar_source)
203 is called instead. This facilitates using a packaged grammar file when needed
204 but preserves load_grammar's automatic regeneration behavior when possible.
207 if os.path.isfile(grammar_source):
208 gp = _generate_pickle_name(grammar_source, cache_dir) if cache_dir else None
209 return load_grammar(grammar_source, gp=gp)
210 pickled_name = _generate_pickle_name(os.path.basename(grammar_source), cache_dir)
211 data = pkgutil.get_data(package, pickled_name)
212 g = grammar.Grammar()
218 """Main program, when run as a script: produce grammar pickle files.
220 Calls load_grammar for each argument, a path to a grammar text file.
224 logging.basicConfig(level=logging.INFO, stream=sys.stdout,
225 format='%(message)s')
227 load_grammar(gt, save=True, force=True)
230 if __name__ == "__main__":
231 sys.exit(int(not main()))