def getboolean(self, section, option):
states = {'1': 1, 'yes': 1, 'true': 1, 'on': 1,
'0': 0, 'no': 0, 'false': 0, 'off': 0}
- v = self.get(section, option)
+ v = self.get(section, option)
if not states.has_key(v.lower()):
raise ValueError, 'Not a boolean: %s' % v
return states[v.lower()]
See compiler.visitor for details.
compile(source, filename, mode, flags=None, dont_inherit=None)
- Returns a code object. A replacement for the builtin compile() function.
+ Returns a code object. A replacement for the builtin compile() function.
compileFile(filename)
Generates a .pyc file by compiling filename.
from transformer import parse, parseFile
from visitor import walk
from pycodegen import compile, compileFile
-
self.varargs = 1
if flags & CO_VARKEYWORDS:
self.kwargs = 1
-
+
def getChildren(self):
class FutureParser:
features = ("nested_scopes", "generators", "division")
-
+
def __init__(self):
self.found = {} # set
walk(tree, v)
print v.found
print
-
node = worklist.pop(0)
node.filename = filename
worklist.extend(node.getChildNodes())
-
# these edges to get the blocks emitted in the right order,
# however. :-( If a client needs to remove these edges, call
# pruneEdges().
-
+
self.current.addNext(block)
self.startBlock(block)
# XXX This is a total mess. There must be a better way to get
# the code blocks in the right order.
-
+
self.fixupOrderHonorNext(blocks, default_next)
self.fixupOrderForward(blocks, default_next)
def fixupOrderHonorNext(self, blocks, default_next):
"""Fix one problem with DFS.
-
+
The DFS uses child block, but doesn't know about the special
"next" block. As a result, the DFS can order blocks so that a
block isn't next to the right block for implicit control
for c in chains:
for b in c:
blocks.append(b)
-
+
def getBlocks(self):
return self.blocks.elements()
def getRoot(self):
"""Return nodes appropriate for use with dominator"""
return self.entry
-
+
def getContainedGraphs(self):
l = []
for b in self.getBlocks():
def __str__(self):
insts = map(str, self.insts)
return "<block %s %d:\n%s>" % (self.label, self.bid,
- string.join(insts, '\n'))
+ string.join(insts, '\n'))
def emit(self, inst):
op = inst[0]
self.argcount = getArgCount(args)
self.klass = klass
if optimized:
- self.flags = CO_OPTIMIZED | CO_NEWLOCALS
+ self.flags = CO_OPTIMIZED | CO_NEWLOCALS
else:
self.flags = 0
self.consts = []
for name, obj in locals().items():
if name[:9] == "_convert_":
opname = name[9:]
- _converters[opname] = obj
+ _converters[opname] = obj
del name, obj, opname
def makeByteCode(self):
elt = elt.getCode()
l.append(elt)
return tuple(l)
-
+
def isJump(opname):
if opname[:4] == 'JUMP':
return 1
class LineAddrTable:
"""lnotab
-
+
This class builds the lnotab, which is documented in compile.c.
Here's a brief recap:
def getTable(self):
return string.join(map(chr, self.lnotab), '')
-
+
class StackDepthTracker:
# XXX 1. need to keep track of stack depth on jumps
# XXX 2. at least partly as a result, this code is broken
('BINARY_', -1),
('LOAD_', 1),
]
-
+
def UNPACK_SEQUENCE(self, count):
return count-1
def BUILD_TUPLE(self, count):
return -2
def DUP_TOPX(self, argc):
return argc
-
+
findDepth = StackDepthTracker().findDepth
class BlockStack(misc.Stack):
__super_init = misc.Stack.__init__
-
+
def __init__(self):
self.__super_init(self)
self.loop = None
"""Replacement for builtin compile() function"""
if flags is not None or dont_inherit is not None:
raise RuntimeError, "not implemented yet"
-
+
if mode == "single":
gen = Interactive(source, filename)
elif mode == "exec":
NameFinder, FunctionGen, and ClassGen. These attributes can be
defined in the initClass() method, which is a hook for
initializing these methods after all the classes have been
- defined.
+ defined.
"""
optimized = 0 # is namespace access optimized?
self.emit(prefix + '_NAME', name)
def set_lineno(self, node, force=0):
- """Emit SET_LINENO if node has lineno attribute and it is
+ """Emit SET_LINENO if node has lineno attribute and it is
different than the last lineno emitted.
Returns true if SET_LINENO was emitted.
self.emit('CONTINUE_LOOP', loop_block)
self.nextBlock()
elif kind == END_FINALLY:
- msg = "'continue' not allowed inside 'finally' clause (%s, %d)"
+ msg = "'continue' not allowed inside 'finally' clause (%s, %d)"
raise SyntaxError, msg % (node.filename, node.lineno)
def visitTest(self, node, jump):
# list comprehensions
__list_count = 0
-
+
def visitListComp(self, node):
self.set_lineno(node)
# setup list
self.emit('DUP_TOP')
self.emit('LOAD_ATTR', 'append')
self._implicitNameOp('STORE', append)
-
+
stack = []
for i, for_ in zip(range(len(node.quals)), node.quals):
start, anchor = self.visit(for_)
self.visit(node.expr)
self.emit('CALL_FUNCTION', 1)
self.emit('POP_TOP')
-
+
for start, cont, anchor in stack:
if cont:
skip_one = self.newBlock()
self.emit('JUMP_ABSOLUTE', start)
self.startBlock(anchor)
self._implicitNameOp('DELETE', append)
-
+
self.__list_count = self.__list_count - 1
def visitListCompFor(self, node):
self.setups.pop()
self.emit('JUMP_FORWARD', lElse)
self.startBlock(handlers)
-
+
last = len(node.handlers) - 1
for i in range(len(node.handlers)):
expr, target, body = node.handlers[i]
self.nextBlock(lElse)
self.visit(node.else_)
self.nextBlock(end)
-
+
def visitTryFinally(self, node):
body = self.newBlock()
final = self.newBlock()
def visitName(self, node):
self.set_lineno(node)
self.loadName(node.name)
-
+
def visitPass(self, node):
self.set_lineno(node)
__super_init = CodeGenerator.__init__
scopes = None
-
+
def __init__(self, tree):
self.graph = pyassem.PyFlowGraph("<module>", tree.filename)
self.futures = future.find_futures(tree)
scopes = None
futures = ()
-
+
def __init__(self, tree):
self.graph = pyassem.PyFlowGraph("<expression>", tree.filename)
self.__super_init()
scopes = None
futures = ()
-
+
def __init__(self, tree):
self.graph = pyassem.PyFlowGraph("<interactive>", tree.filename)
self.__super_init()
else:
name = func.name
args, hasTupleArg = generateArgList(func.argnames)
- self.graph = pyassem.PyFlowGraph(name, func.filename, args,
- optimized=1)
+ self.graph = pyassem.PyFlowGraph(name, func.filename, args,
+ optimized=1)
self.isLambda = isLambda
self.super_init()
if type(arg) == types.TupleType:
self.emit('LOAD_FAST', '.%d' % (i * 2))
self.unpackSequence(arg)
-
+
def unpackSequence(self, tup):
if VERSION > 1:
self.emit('UNPACK_SEQUENCE', len(tup))
unpackTuple = unpackSequence
class FunctionCodeGenerator(NestedScopeMixin, AbstractFunctionCode,
- CodeGenerator):
+ CodeGenerator):
super_init = CodeGenerator.__init__ # call be other init
scopes = None
rather than free.
Be careful to stop if a child does not think the name is
- free.
+ free.
"""
self.globals[name] = 1
if self.frees.has_key(name):
class ModuleScope(Scope):
__super_init = Scope.__init__
-
+
def __init__(self):
self.__super_init("global", self)
__super_init = Scope.__init__
__counter = 1
-
+
def __init__(self, module, klass=None):
i = self.__counter
self.__counter += 1
def __init__(self):
self.scopes = {}
self.klass = None
-
+
# node that define new scopes
def visitModule(self, node):
self._do_args(scope, node.argnames)
self.visit(node.code, scope)
self.handle_free_vars(scope, parent)
-
+
def visitLambda(self, node, parent):
for n in node.defaults:
self.visit(n, parent)
self.visit(node.lower, scope, 0)
if node.upper:
self.visit(node.upper, scope, 0)
-
+
def visitAugAssign(self, node, scope):
# If the LHS is a name, then this counts as assignment.
# Otherwise, it's just use.
def get_names(syms):
return [s for s in [s.get_name() for s in syms.get_symbols()]
- if not (s.startswith('_[') or s.startswith('.'))]
-
+ if not (s.startswith('_[') or s.startswith('.'))]
+
for file in sys.argv[1:]:
print file
f = open(file)
n = Backquote(self.com_node(nodelist[1]))
n.lineno = nodelist[0][2]
return n
-
+
def atom_number(self, nodelist):
### need to verify this matches compile.c
k = eval(nodelist[0][1])
n = Const(k)
n.lineno = nodelist[0][2]
return n
-
+
def atom_string(self, nodelist):
### need to verify this matches compile.c
k = ''
# here, Render it harmless. (genc discards ('discard',
# ('const', xxxx)) Nodes)
return Discard(Const(None))
-
+
def com_arglist(self, nodelist):
# varargslist:
# (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME]
return node[1][1]
def com_fplist(self, node):
- # fplist: fpdef (',' fpdef)* [',']
+ # fplist: fpdef (',' fpdef)* [',']
if len(node) == 2:
return self.com_fpdef(node[1])
list = []
def com_try_finally(self, nodelist):
# try_fin_stmt: "try" ":" suite "finally" ":" suite
n = TryFinally(self.com_node(nodelist[2]),
- self.com_node(nodelist[5]))
+ self.com_node(nodelist[5]))
n.lineno = nodelist[0][2]
return n
raise SyntaxError, "can't assign to operator"
primary = self.com_apply_trailer(primary, ch)
return self.com_assign_trailer(primary, node[-1],
- assigning)
+ assigning)
node = node[1]
elif t == symbol.atom:
t = node[1][0]
# list_if: 'if' test [list_iter]
# XXX should raise SyntaxError for assignment
-
+
lineno = node[1][2]
fors = []
while node:
for i in range(1, len_nodelist, 2):
node = nodelist[i]
if node[0] == token.STAR or node[0] == token.DOUBLESTAR:
- break
+ break
kw, result = self.com_argument(node, kw)
args.append(result)
else:
def com_subscriptlist(self, primary, nodelist, assigning):
# slicing: simple_slicing | extended_slicing
# simple_slicing: primary "[" short_slice "]"
- # extended_slicing: primary "[" slice_list "]"
+ # extended_slicing: primary "[" slice_list "]"
# slice_list: slice_item ("," slice_item)* [","]
# backwards compat slice for '[i:j]'
you still have to do.
"""
examples = {}
-
+
def dispatch(self, node, *args):
self.node = node
meth = self._cache.get(node.__class__, None)
'\x00\x80J\x00\x00\x00\x80(U\x03abcq\x04h\x04(c__main__\n' + \
'C\nq\x05oq\x06}q\x07(U\x03fooq\x08K\x01U\x03barq\tK\x02ubh' + \
'\x06tq\nh\nK\x05e.'
-
+
def create_data():
c = C()
c.foo = 1
good.sort()
bad.sort()
skipped.sort()
-
+
if good and not quiet:
if not bad and not skipped and len(good) > 1:
print "All",
# Verify the treatment of Unicode strings
verify(binascii.hexlify(u'a') == '61', "hexlify failed for Unicode")
-
from test_support import run_unittest
class cPickleTests(AbstractPickleTests, AbstractPickleModuleTests):
-
+
def setUp(self):
self.dumps = cPickle.dumps
self.loads = cPickle.loads
self.assertEqual(sfp.getvalue(), """\
From: test@dom.ain
References: <0@dom.ain> <1@dom.ain> <2@dom.ain> <3@dom.ain> <4@dom.ain>
- <5@dom.ain> <6@dom.ain> <7@dom.ain> <8@dom.ain> <9@dom.ain>
+\t<5@dom.ain> <6@dom.ain> <7@dom.ain> <8@dom.ain> <9@dom.ain>
Test""")
f = open(self.fname, 'wb')
f.write("ABC")
f.close()
-
+
def tearDown(self):
os.unlink(self.fname)
os.rmdir(TESTFN)
except TypeError:
pass
-
+
def test_statvfs_attributes(self):
if not hasattr(os, "statvfs"):
return
def setUp(self):
self.dumps = pickle.dumps
self.loads = pickle.loads
-
+
module = pickle
error = KeyError
f = urllib.urlopen('https://sf.net')
buf = f.read()
f.close()
-
-
-
print "max_length decompressobj failed"
else:
print "max_length decompressobj succeeded"
-
+
# Misc tests of max_length
deco = zlib.decompressobj(-12)
try: