from compiler import ast ### Simple tools used by the parser # # XXX: Remove in favor of the logging framework def printdebug(msg): """ """ print 'parser: %s' % msg def list_strip(seq): """ Remove all None element from a list. """ ret = [] for item in seq: if item: ret.append(item) return ret def list_flatten(seq): """ Pulls up multi-level lists into a single level list. Example: [[a,b],c,[[d]]] -> [a,b,c,d] """ ret = [] for item in seq: if isinstance(item, list): ret += list_flatten(item) else: ret.append(item) return ret ### AST Functions # def ast_make_dict(seq): """ Function that takes a sequence and returns an ast making a dictionnary. Example ASTs: {'a':1, 'b':2} Dict([(Const('a'), Const(1)), (Const('b'), Const(2))]) dict(a=1,b=2) CallFunc(Name('dict'), [Keyword('a', Const(1)), Keyword('b', Const(2))], None, None) dict(d1,c=3) CallFunc(Name('dict'), [Name('d1')], None, Dict([(Const('c'), Const(3))])) """ seq = list_strip(seq) if True in [isinstance(item, ast.Name) for item in seq]: # We have a Name in the seq, use the dict construtor. args = [] name = [] for item in seq: if isinstance(item, ast.Name): name.append(item) else: args.append(item) # print name, ast.Dict(args) ret = ast.CallFunc(ast.Name('dict'), name, None, ast.Dict(args)) else: ret = ast.Dict(seq) # print seq, '->', ret return ret