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"]
26
from . import grammar, parse, token, tokenize, pgen
31
def __init__(self, grammar, convert=None, logger=None):
32
self.grammar = grammar
34
logger = logging.getLogger()
36
self.convert = convert
38
def parse_tokens(self, tokens, debug=False):
39
"""Parse a series of tokens and return the syntax tree."""
40
# XXX Move the prefix computation into a wrapper around tokenize.
41
p = parse.Parser(self.grammar, self.convert)
45
type = value = start = end = line_text = None
47
for quintuple in tokens:
48
type, value, start, end, line_text = quintuple
49
if start != (lineno, column):
50
assert (lineno, column) <= start, ((lineno, column), start)
51
s_lineno, s_column = start
53
prefix += "\n" * (s_lineno - lineno)
57
prefix += line_text[column:s_column]
59
if type in (tokenize.COMMENT, tokenize.NL):
62
if value.endswith("\n"):
67
type = grammar.opmap[value]
69
self.logger.debug("%s %r (prefix=%r)",
70
token.tok_name[type], value, prefix)
71
if p.addtoken(type, value, (prefix, start)):
73
self.logger.debug("Stop.")
77
if value.endswith("\n"):
81
# We never broke out -- EOF is too soon (how can this happen???)
82
raise parse.ParseError("incomplete input",
83
type, value, (prefix, start))
86
def parse_stream_raw(self, stream, debug=False):
87
"""Parse a stream and return the syntax tree."""
88
tokens = tokenize.generate_tokens(stream.readline)
89
return self.parse_tokens(tokens, debug)
91
def parse_stream(self, stream, debug=False):
92
"""Parse a stream and return the syntax tree."""
93
return self.parse_stream_raw(stream, debug)
95
def parse_file(self, filename, encoding=None, debug=False):
96
"""Parse a file and return the syntax tree."""
97
stream = codecs.open(filename, "r", encoding)
99
return self.parse_stream(stream, debug)
103
def parse_string(self, text, debug=False):
104
"""Parse a string and return the syntax tree."""
105
tokens = tokenize.generate_tokens(io.StringIO(text).readline)
106
return self.parse_tokens(tokens, debug)
109
def load_grammar(gt="Grammar.txt", gp=None,
110
save=True, force=False, logger=None):
111
"""Load the grammar (maybe from a pickle)."""
113
logger = logging.getLogger()
115
head, tail = os.path.splitext(gt)
118
gp = head + tail + ".".join(map(str, sys.version_info)) + ".pickle"
119
if force or not _newer(gp, gt):
120
logger.info("Generating grammar tables from %s", gt)
121
g = pgen.generate_grammar(gt)
123
logger.info("Writing grammar tables to %s", gp)
127
logger.info("Writing failed:"+str(e))
129
g = grammar.Grammar()
135
"""Inquire whether file a was written since file b."""
136
if not os.path.exists(a):
138
if not os.path.exists(b):
140
return os.path.getmtime(a) >= os.path.getmtime(b)
144
"""Main program, when run as a script: produce grammar pickle files.
146
Calls load_grammar for each argument, a path to a grammar text file.
150
logging.basicConfig(level=logging.INFO, stream=sys.stdout,
151
format='%(message)s')
153
load_grammar(gt, save=True, force=True)
156
if __name__ == "__main__":
157
sys.exit(int(not main()))