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"]
24
from . import grammar, parse, token, tokenize, pgen
29
def __init__(self, grammar, convert=None, logger=None):
30
self.grammar = grammar
32
logger = logging.getLogger()
34
self.convert = convert
36
def parse_tokens(self, tokens, debug=False):
37
"""Parse a series of tokens and return the syntax tree."""
38
# XXX Move the prefix computation into a wrapper around tokenize.
39
p = parse.Parser(self.grammar, self.convert)
43
type = value = start = end = line_text = None
45
for quintuple in tokens:
46
type, value, start, end, line_text = quintuple
47
if start != (lineno, column):
48
assert (lineno, column) <= start, ((lineno, column), start)
49
s_lineno, s_column = start
51
prefix += "\n" * (s_lineno - lineno)
55
prefix += line_text[column:s_column]
57
if type in (tokenize.COMMENT, tokenize.NL):
60
if value.endswith("\n"):
65
type = grammar.opmap[value]
67
self.logger.debug("%s %r (prefix=%r)",
68
token.tok_name[type], value, prefix)
69
if p.addtoken(type, value, (prefix, start)):
71
self.logger.debug("Stop.")
75
if value.endswith("\n"):
79
# We never broke out -- EOF is too soon (how can this happen???)
80
raise parse.ParseError("incomplete input",
81
type, value, (prefix, start))
84
def parse_stream_raw(self, stream, debug=False):
85
"""Parse a stream and return the syntax tree."""
86
tokens = tokenize.generate_tokens(stream.readline)
87
return self.parse_tokens(tokens, debug)
89
def parse_stream(self, stream, debug=False):
90
"""Parse a stream and return the syntax tree."""
91
return self.parse_stream_raw(stream, debug)
93
def parse_file(self, filename, debug=False):
94
"""Parse a file and return the syntax tree."""
95
stream = open(filename)
97
return self.parse_stream(stream, debug)
101
def parse_string(self, text, debug=False):
102
"""Parse a string and return the syntax tree."""
103
tokens = tokenize.generate_tokens(generate_lines(text).__next__)
104
return self.parse_tokens(tokens, debug)
107
def generate_lines(text):
108
"""Generator that behaves like readline without using StringIO."""
109
for line in text.splitlines(True):
115
def load_grammar(gt="Grammar.txt", gp=None,
116
save=True, force=False, logger=None):
117
"""Load the grammar (maybe from a pickle)."""
119
logger = logging.getLogger()
121
head, tail = os.path.splitext(gt)
124
gp = head + tail + ".".join(map(str, sys.version_info)) + ".pickle"
125
if force or not _newer(gp, gt):
126
logger.info("Generating grammar tables from %s", gt)
127
g = pgen.generate_grammar(gt)
129
logger.info("Writing grammar tables to %s", gp)
133
logger.info("Writing failed:"+str(e))
135
g = grammar.Grammar()
141
"""Inquire whether file a was written since file b."""
142
if not os.path.exists(a):
144
if not os.path.exists(b):
146
return os.path.getmtime(a) >= os.path.getmtime(b)