Skip to content

Commit ef04c44

Browse files
committed
Merged revisions 61596-61597 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk ........ r61596 | martin.v.loewis | 2008-03-18 23:43:46 -0500 (Di, 18 Mär 2008) | 2 lines Import lib2to3. ........ r61597 | martin.v.loewis | 2008-03-18 23:58:04 -0500 (Di, 18 Mär 2008) | 3 lines Initialized merge tracking via "svnmerge" with revisions "1-61595" from svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3 ........
1 parent c42bcbb commit ef04c44

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

67 files changed

+11990
-0
lines changed

Lib/lib2to3/Grammar.txt

+153
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
# Grammar for Python
2+
3+
# Note: Changing the grammar specified in this file will most likely
4+
# require corresponding changes in the parser module
5+
# (../Modules/parsermodule.c). If you can't make the changes to
6+
# that module yourself, please co-ordinate the required changes
7+
# with someone who can; ask around on python-dev for help. Fred
8+
# Drake <fdrake@acm.org> will probably be listening there.
9+
10+
# NOTE WELL: You should also follow all the steps listed in PEP 306,
11+
# "How to Change Python's Grammar"
12+
13+
# Commands for Kees Blom's railroad program
14+
#diagram:token NAME
15+
#diagram:token NUMBER
16+
#diagram:token STRING
17+
#diagram:token NEWLINE
18+
#diagram:token ENDMARKER
19+
#diagram:token INDENT
20+
#diagram:output\input python.bla
21+
#diagram:token DEDENT
22+
#diagram:output\textwidth 20.04cm\oddsidemargin 0.0cm\evensidemargin 0.0cm
23+
#diagram:rules
24+
25+
# Start symbols for the grammar:
26+
# file_input is a module or sequence of commands read from an input file;
27+
# single_input is a single interactive statement;
28+
# eval_input is the input for the eval() and input() functions.
29+
# NB: compound_stmt in single_input is followed by extra NEWLINE!
30+
file_input: (NEWLINE | stmt)* ENDMARKER
31+
single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
32+
eval_input: testlist NEWLINE* ENDMARKER
33+
34+
decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
35+
decorators: decorator+
36+
decorated: decorators (classdef | funcdef)
37+
funcdef: 'def' NAME parameters ['->' test] ':' suite
38+
parameters: '(' [typedargslist] ')'
39+
typedargslist: ((tfpdef ['=' test] ',')*
40+
('*' [tname] (',' tname ['=' test])* [',' '**' tname] | '**' tname)
41+
| tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
42+
tname: NAME [':' test]
43+
tfpdef: tname | '(' tfplist ')'
44+
tfplist: tfpdef (',' tfpdef)* [',']
45+
varargslist: ((vfpdef ['=' test] ',')*
46+
('*' [vname] (',' vname ['=' test])* [',' '**' vname] | '**' vname)
47+
| vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
48+
vname: NAME
49+
vfpdef: vname | '(' vfplist ')'
50+
vfplist: vfpdef (',' vfpdef)* [',']
51+
52+
stmt: simple_stmt | compound_stmt
53+
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
54+
small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
55+
import_stmt | global_stmt | exec_stmt | assert_stmt)
56+
expr_stmt: testlist (augassign (yield_expr|testlist) |
57+
('=' (yield_expr|testlist))*)
58+
augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
59+
'<<=' | '>>=' | '**=' | '//=')
60+
# For normal assignments, additional restrictions enforced by the interpreter
61+
print_stmt: 'print' ( [ test (',' test)* [','] ] |
62+
'>>' test [ (',' test)+ [','] ] )
63+
del_stmt: 'del' exprlist
64+
pass_stmt: 'pass'
65+
flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
66+
break_stmt: 'break'
67+
continue_stmt: 'continue'
68+
return_stmt: 'return' [testlist]
69+
yield_stmt: yield_expr
70+
raise_stmt: 'raise' [test ['from' test | ',' test [',' test]]]
71+
import_stmt: import_name | import_from
72+
import_name: 'import' dotted_as_names
73+
import_from: ('from' ('.'* dotted_name | '.'+)
74+
'import' ('*' | '(' import_as_names ')' | import_as_names))
75+
import_as_name: NAME ['as' NAME]
76+
dotted_as_name: dotted_name ['as' NAME]
77+
import_as_names: import_as_name (',' import_as_name)* [',']
78+
dotted_as_names: dotted_as_name (',' dotted_as_name)*
79+
dotted_name: NAME ('.' NAME)*
80+
global_stmt: ('global' | 'nonlocal') NAME (',' NAME)*
81+
exec_stmt: 'exec' expr ['in' test [',' test]]
82+
assert_stmt: 'assert' test [',' test]
83+
84+
compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated
85+
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
86+
while_stmt: 'while' test ':' suite ['else' ':' suite]
87+
for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]
88+
try_stmt: ('try' ':' suite
89+
((except_clause ':' suite)+
90+
['else' ':' suite]
91+
['finally' ':' suite] |
92+
'finally' ':' suite))
93+
with_stmt: 'with' test [ with_var ] ':' suite
94+
with_var: 'as' expr
95+
# NB compile.c makes sure that the default except clause is last
96+
except_clause: 'except' [test [(',' | 'as') test]]
97+
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
98+
99+
# Backward compatibility cruft to support:
100+
# [ x for x in lambda: True, lambda: False if x() ]
101+
# even while also allowing:
102+
# lambda x: 5 if x else 2
103+
# (But not a mix of the two)
104+
testlist_safe: old_test [(',' old_test)+ [',']]
105+
old_test: or_test | old_lambdef
106+
old_lambdef: 'lambda' [varargslist] ':' old_test
107+
108+
test: or_test ['if' or_test 'else' test] | lambdef
109+
or_test: and_test ('or' and_test)*
110+
and_test: not_test ('and' not_test)*
111+
not_test: 'not' not_test | comparison
112+
comparison: expr (comp_op expr)*
113+
comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
114+
expr: xor_expr ('|' xor_expr)*
115+
xor_expr: and_expr ('^' and_expr)*
116+
and_expr: shift_expr ('&' shift_expr)*
117+
shift_expr: arith_expr (('<<'|'>>') arith_expr)*
118+
arith_expr: term (('+'|'-') term)*
119+
term: factor (('*'|'/'|'%'|'//') factor)*
120+
factor: ('+'|'-'|'~') factor | power
121+
power: atom trailer* ['**' factor]
122+
atom: ('(' [yield_expr|testlist_gexp] ')' |
123+
'[' [listmaker] ']' |
124+
'{' [dictsetmaker] '}' |
125+
'`' testlist1 '`' |
126+
NAME | NUMBER | STRING+ | '.' '.' '.')
127+
listmaker: test ( comp_for | (',' test)* [','] )
128+
testlist_gexp: test ( comp_for | (',' test)* [','] )
129+
lambdef: 'lambda' [varargslist] ':' test
130+
trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
131+
subscriptlist: subscript (',' subscript)* [',']
132+
subscript: test | [test] ':' [test] [sliceop]
133+
sliceop: ':' [test]
134+
exprlist: expr (',' expr)* [',']
135+
testlist: test (',' test)* [',']
136+
dictsetmaker: ( (test ':' test (comp_for | (',' test ':' test)* [','])) |
137+
(test (comp_for | (',' test)* [','])) )
138+
139+
classdef: 'class' NAME ['(' [arglist] ')'] ':' suite
140+
141+
arglist: (argument ',')* (argument [',']| '*' test [',' '**' test] | '**' test)
142+
argument: test [comp_for] | test '=' test # Really [keyword '='] test
143+
144+
comp_iter: comp_for | comp_if
145+
comp_for: 'for' exprlist 'in' testlist_safe [comp_iter]
146+
comp_if: 'if' old_test [comp_iter]
147+
148+
testlist1: test (',' test)*
149+
150+
# not used in grammar, but may appear in "node" passed from Parser to Compiler
151+
encoding_decl: NAME
152+
153+
yield_expr: 'yield' [testlist]

Lib/lib2to3/PatternGrammar.txt

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Copyright 2006 Google, Inc. All Rights Reserved.
2+
# Licensed to PSF under a Contributor Agreement.
3+
4+
# A grammar to describe tree matching patterns.
5+
# Not shown here:
6+
# - 'TOKEN' stands for any token (leaf node)
7+
# - 'any' stands for any node (leaf or interior)
8+
# With 'any' we can still specify the sub-structure.
9+
10+
# The start symbol is 'Matcher'.
11+
12+
Matcher: Alternatives ENDMARKER
13+
14+
Alternatives: Alternative ('|' Alternative)*
15+
16+
Alternative: (Unit | NegatedUnit)+
17+
18+
Unit: [NAME '='] ( STRING [Repeater]
19+
| NAME [Details] [Repeater]
20+
| '(' Alternatives ')' [Repeater]
21+
| '[' Alternatives ']'
22+
)
23+
24+
NegatedUnit: 'not' (STRING | NAME [Details] | '(' Alternatives ')')
25+
26+
Repeater: '*' | '+' | '{' NUMBER [',' NUMBER] '}'
27+
28+
Details: '<' Alternatives '>'

Lib/lib2to3/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
#empty

Lib/lib2to3/fixes/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Dummy file to make this directory a package.

Lib/lib2to3/fixes/basefix.py

+165
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
# Copyright 2006 Google, Inc. All Rights Reserved.
2+
# Licensed to PSF under a Contributor Agreement.
3+
4+
"""Base class for fixers (optional, but recommended)."""
5+
6+
# Python imports
7+
import logging
8+
import itertools
9+
10+
# Get a usable 'set' constructor
11+
try:
12+
set
13+
except NameError:
14+
from sets import Set as set
15+
16+
# Local imports
17+
from ..patcomp import PatternCompiler
18+
from .. import pygram
19+
20+
class BaseFix(object):
21+
22+
"""Optional base class for fixers.
23+
24+
The subclass name must be FixFooBar where FooBar is the result of
25+
removing underscores and capitalizing the words of the fix name.
26+
For example, the class name for a fixer named 'has_key' should be
27+
FixHasKey.
28+
"""
29+
30+
PATTERN = None # Most subclasses should override with a string literal
31+
pattern = None # Compiled pattern, set by compile_pattern()
32+
options = None # Options object passed to initializer
33+
filename = None # The filename (set by set_filename)
34+
logger = None # A logger (set by set_filename)
35+
numbers = itertools.count(1) # For new_name()
36+
used_names = set() # A set of all used NAMEs
37+
order = "post" # Does the fixer prefer pre- or post-order traversal
38+
explicit = False # Is this ignored by refactor.py -f all?
39+
40+
# Shortcut for access to Python grammar symbols
41+
syms = pygram.python_symbols
42+
43+
def __init__(self, options, log):
44+
"""Initializer. Subclass may override.
45+
46+
Args:
47+
options: an optparse.Values instance which can be used
48+
to inspect the command line options.
49+
log: a list to append warnings and other messages to.
50+
"""
51+
self.options = options
52+
self.log = log
53+
self.compile_pattern()
54+
55+
def compile_pattern(self):
56+
"""Compiles self.PATTERN into self.pattern.
57+
58+
Subclass may override if it doesn't want to use
59+
self.{pattern,PATTERN} in .match().
60+
"""
61+
if self.PATTERN is not None:
62+
self.pattern = PatternCompiler().compile_pattern(self.PATTERN)
63+
64+
def set_filename(self, filename):
65+
"""Set the filename, and a logger derived from it.
66+
67+
The main refactoring tool should call this.
68+
"""
69+
self.filename = filename
70+
self.logger = logging.getLogger(filename)
71+
72+
def match(self, node):
73+
"""Returns match for a given parse tree node.
74+
75+
Should return a true or false object (not necessarily a bool).
76+
It may return a non-empty dict of matching sub-nodes as
77+
returned by a matching pattern.
78+
79+
Subclass may override.
80+
"""
81+
results = {"node": node}
82+
return self.pattern.match(node, results) and results
83+
84+
def transform(self, node, results):
85+
"""Returns the transformation for a given parse tree node.
86+
87+
Args:
88+
node: the root of the parse tree that matched the fixer.
89+
results: a dict mapping symbolic names to part of the match.
90+
91+
Returns:
92+
None, or a node that is a modified copy of the
93+
argument node. The node argument may also be modified in-place to
94+
effect the same change.
95+
96+
Subclass *must* override.
97+
"""
98+
raise NotImplementedError()
99+
100+
def parenthesize(self, node):
101+
"""Wrapper around pygram.parenthesize()."""
102+
return pygram.parenthesize(node)
103+
104+
def new_name(self, template="xxx_todo_changeme"):
105+
"""Return a string suitable for use as an identifier
106+
107+
The new name is guaranteed not to conflict with other identifiers.
108+
"""
109+
name = template
110+
while name in self.used_names:
111+
name = template + str(self.numbers.next())
112+
self.used_names.add(name)
113+
return name
114+
115+
def log_message(self, message):
116+
if self.first_log:
117+
self.first_log = False
118+
self.log.append("### In file %s ###" % self.filename)
119+
self.log.append(message)
120+
121+
def cannot_convert(self, node, reason=None):
122+
"""Warn the user that a given chunk of code is not valid Python 3,
123+
but that it cannot be converted automatically.
124+
125+
First argument is the top-level node for the code in question.
126+
Optional second argument is why it can't be converted.
127+
"""
128+
lineno = node.get_lineno()
129+
for_output = node.clone()
130+
for_output.set_prefix("")
131+
msg = "Line %d: could not convert: %s"
132+
self.log_message(msg % (lineno, for_output))
133+
if reason:
134+
self.log_message(reason)
135+
136+
def warning(self, node, reason):
137+
"""Used for warning the user about possible uncertainty in the
138+
translation.
139+
140+
First argument is the top-level node for the code in question.
141+
Optional second argument is why it can't be converted.
142+
"""
143+
lineno = node.get_lineno()
144+
self.log_message("Line %d: %s" % (lineno, reason))
145+
146+
def start_tree(self, tree, filename):
147+
"""Some fixers need to maintain tree-wide state.
148+
This method is called once, at the start of tree fix-up.
149+
150+
tree - the root node of the tree to be processed.
151+
filename - the name of the file the tree came from.
152+
"""
153+
self.used_names = tree.used_names
154+
self.set_filename(filename)
155+
self.numbers = itertools.count(1)
156+
self.first_log = True
157+
158+
def finish_tree(self, tree, filename):
159+
"""Some fixers need to maintain tree-wide state.
160+
This method is called once, at the conclusion of tree fix-up.
161+
162+
tree - the root node of the tree to be processed.
163+
filename - the name of the file the tree came from.
164+
"""
165+
pass

0 commit comments

Comments
 (0)