Print the AST in a nicely formatted tree format for debuggin
164856
function printNodes(node, indent) {
    indent = indent || 0;

    // This is hacky, but this is just a debugging function anyway
    function print(str, indent, inline) {
        var lines = str.split('\n');

        for(var i=0; i<lines.length; i++) {
            if(lines[i]) {
                if((inline && i > 0) || !inline) {
                    for(var j=0; j<indent; j++) {
                        process.stdout.write(' ');
                    }
                }
            }

            if(i === lines.length-1) {
                process.stdout.write(lines[i]);
            }
            else {
                process.stdout.write(lines[i] + '\n');
            }
        }
    }

    print(node.typename + ': ', indent);

    if(node instanceof NodeList) {
        print('\n');
        lib.each(node.children, function(n) {
            printNodes(n, indent + 2);
        });
    }
    else if(node instanceof CallExtension) {
        print(node.extName + '.' + node.prop);
        print('\n');

        if(node.args) {
            printNodes(node.args, indent + 2);
        }

        if(node.contentArgs) {
            lib.each(node.contentArgs, function(n) {
                printNodes(n, indent + 2);
            });
        }
    }
    else {
        var nodes = null;
        var props = null;

        node.iterFields(function(val, field) {
            if(val instanceof Node) {
                nodes = nodes || {};
                nodes[field] = val;
            }
            else {
                props = props || {};
                props[field] = val;
            }
        });

        if(props) {
            print(JSON.stringify(props, null, 2) + '\n', null, true);
        }
        else {
            print('\n');
        }

        if(nodes) {
            for(var k in nodes) {
                printNodes(nodes[k], indent + 2);
            }
        }

    }
}
855918
function prettyPrintJson(obj, indent) {
  var result = '';

  if (indent == null) indent = '';

  for (var property in obj) {
    if (property.charAt(0) !== '_') {
      var value = obj[property];

      if (typeof value === 'string') {
        value = '\'' + value + '\'';
      } else if (typeof value === 'object') {
        if (value instanceof Array) {
          value = '[ ' + value + ' ]';
        } else {
          // Recursive dump
          var od = prettyPrintJson(value, indent + '  ');

          value = '{\n' + od + '\n' + indent + '}';
        }
      }
      result += indent + property + ': ' + value + ',\n';
    }
  }
  return result.replace(/,\n$/, '');
}
125562
def print_treemap(self, format=None, output=sys.stdout, **kwargs):
        
        treemap = self.as_treemap()
        treemap.print(format=format, output=output, **kwargs)
1114391
def print_tree(self, ast_obj=None):
        

        if not ast_obj:
            ast_obj = self

        if hasattr(self, "bel_subject"):
            print("Subject:")
            self.bel_subject.print_tree(self.bel_subject, indent=0)

        if hasattr(self, "bel_relation"):
            print("Relation:", self.bel_relation)

        if hasattr(self, "bel_object"):
            if self.bel_object.type == "BELAst":
                if hasattr(self, "bel_subject"):
                    print("Nested Subject:")
                    self.bel_object.bel_subject.print_tree(indent=0)

                if hasattr(self, "bel_relation"):
                    print("Nested Relation:", self.bel_object.bel_relation)

                if hasattr(self, "bel_object"):
                    print("Nested Object:")
                    self.bel_object.bel_object.print_tree(indent=0)
            else:
                print("Object:")
                self.bel_object.print_tree(self.bel_object, indent=0)

        return self
690346
def check_ast(self):
        """"""
        try:
            tree = compile(''.join(self.lines), '', 'exec', PyCF_ONLY_AST)
        except (ValueError, SyntaxError, TypeError):
            return self.report_invalid_syntax()
        for name, cls, __ in self._ast_checks:
            checker = cls(tree, self.filename)
            for lineno, offset, text, check in checker.run():
                if not self.lines or not noqa(self.lines[lineno - 1]):
                    self.report_error(lineno, offset, text, check)
1227532
public void printTree(CommonTree t, int indent) {
        if ( t != null ) {
            StringBuffer sb = new StringBuffer(indent);
            for ( int i = 0; i < indent; i++ )
                sb = sb.append("   ");
            for ( int i = 0; i < t.getChildCount(); i++ ) {
                System.out.println("" + i + sb.toString() + t.getChild(i).toString());
                printTree((CommonTree)t.getChild(i), indent+1);
            }
        }
    }
351166
def debug_reduce(self, rule, tokens, parent, i):
        
        prefix = '           '
        if parent and tokens:
            p_token = tokens[parent]
            if hasattr(p_token, 'line'):
                prefix = 'L.%3d.%03d: ' % (p_token.line, p_token.column)
                pass
            pass
        print("%s%s ::= %s" % (prefix, rule[0], ' '.join(rule[1])))
268007
def dump(self, indentlevel=0, target=sys.stdout):
        
        self.__print(self, indentlevel, target=target)
        indentlevel += 4
        if self.has_arguments():
            for arg in self.args_definition:
                if not arg["name"] in self.arguments:
                    continue
                value = self.arguments[arg["name"]]
                atype = arg["type"]
                if "tag" in atype:
                    self.__print(str(value), indentlevel, target=target)
                    if arg["name"] in self.extra_arguments:
                        value = self.extra_arguments[arg["name"]]
                        atype = arg["extra_arg"]["type"]
                    else:
                        continue
                if type(value) == list:
                    if self.__get_arg_type(arg["name"]) == ["testlist"]:
                        for t in value:
                            t.dump(indentlevel, target)
                    else:
                        self.__print("[" + (",".join(value)) + "]",
                                     indentlevel, target=target)
                    continue
                if isinstance(value, Command):
                    value.dump(indentlevel, target)
                    continue
                self.__print(str(value), indentlevel, target=target)
        for ch in self.children:
            ch.dump(indentlevel, target)
1025944
def dump_autogen_code(fpath, autogen_text, codetype='python', fullprint=None,
                      show_diff=None, dowrite=None):
    
    import utool as ut
    if dowrite is None:
        dowrite = ut.get_argflag(('-w', '--write'))
    if show_diff is None:
        show_diff = ut.get_argflag('--diff')
    num_context_lines = ut.get_argval('--diff', type_=int, default=None)
    show_diff = show_diff or num_context_lines is not None

    num_context_lines = ut.get_argval('--diff', type_=int, default=None)

    if fullprint is None:
        fullprint = True

    if fullprint is False:
        fullprint = ut.get_argflag('--print')

    print('[autogen] Autogenerated %s...\n+---\n' % (fpath,))
    if not dowrite:
        if fullprint:
            ut.print_code(autogen_text, lexer_name=codetype)
            print('\nL___')
        else:
            print('specify --print to write to stdout')
            pass
        print('specify -w to write, or --diff to compare')
        print('...would write to: %s' % fpath)
    if show_diff:
        if ut.checkpath(fpath, verbose=True):
            prev_text = ut.read_from(fpath)
            textdiff = ut.get_textdiff(prev_text, autogen_text,
                                       num_context_lines=num_context_lines)
            try:
                ut.print_difftext(textdiff)
            except UnicodeDecodeError:
                import unicodedata
                textdiff = unicodedata.normalize('NFKD', textdiff).encode('ascii', 'ignore')
                ut.print_difftext(textdiff)

        if dowrite:
            print('WARNING: Not writing. Remove --diff from command line')
    elif dowrite:
        ut.write_to(fpath, autogen_text)
146140
function debugOutputAstAsTypeScript(ast) {
    var /** @type {?} */ converter = new _TsEmitterVisitor();
    var /** @type {?} */ ctx = EmitterVisitorContext.createRoot();
    var /** @type {?} */ asts = Array.isArray(ast) ? ast : [ast];
    asts.forEach(function (ast) {
        if (ast instanceof Statement) {
            ast.visitStatement(converter, ctx);
        }
        else if (ast instanceof Expression) {
            ast.visitExpression(converter, ctx);
        }
        else if (ast instanceof Type$1) {
            ast.visitType(converter, ctx);
        }
        else {
            throw new Error("Don't know how to print debug info for " + ast);
        }
    });
    return ctx.toSource();
}
284667
def debug(self, nest_level=1):
        

        prefix = '  ' * nest_level
        print('%s%s Object #%s' % (prefix, type_name(self), id(self)))
        print('%s  Children:' % (prefix,))
        for child in self._children:
            child.debug(nest_level + 2)
323450
def debug_contents(self, indent=1, file=sys.stdout, _ids=None):
        """"""
        klasses = list(self.__class__.__mro__)
        klasses.reverse()

        # print special attributes "bottom up"
        previous_attrs = ()
        for c in klasses:
            attrs = getattr(c, '_debug_contents', ())

            # if we have seen this list already, move to the next class
            if attrs is previous_attrs:
                continue

            for attr in attrs:
                file.write("%s%s = %s\n" % ("    " * indent, attr, getattr(self, attr)))
            previous_attrs = attrs

        # build a list of property identifiers "bottom up"
        property_names = []
        properties_seen = set()
        for c in klasses:
            for prop in getattr(c, 'properties', []):
                if prop.identifier not in properties_seen:
                    property_names.append(prop.identifier)
                    properties_seen.add(prop.identifier)

        # print out the values
        for property_name in property_names:
            property_value = self._values.get(property_name, None)

            # printing out property values that are None is tedious
            if property_value is None:
                continue

            if hasattr(property_value, "debug_contents"):
                file.write("%s%s\n" % ("    " * indent, property_name))
                property_value.debug_contents(indent+1, file, _ids)
            else:
                file.write("%s%s = %r\n" % ("    " * indent, property_name, property_value))
893440
def dump(self):
        
        for seg in self.seglist:
            print("==== %08x-%08x" % (seg.startea, seg.endea))
            if seg.endea - seg.startea < 30:
                for ea in range(seg.startea, seg.endea):
                    print("    %08x: %08x" % (ea, self.getFlags(ea)))
            else:
                for ea in range(seg.startea, seg.startea + 10):
                    print("    %08x: %08x" % (ea, self.getFlags(ea)))
                print("...")
                for ea in range(seg.endea - 10, seg.endea):
                    print("    %08x: %08x" % (ea, self.getFlags(ea)))
717350
def t(root, children=None, debug=False, root_id=None):
    ""
    if isinstance(root, Tree):
        if children is None:
            return root
        return root.__class__(root, children, root_id)

    elif isinstance(root, basestring):
        root = debug_root_label(root, debug, root_id)

        # Beware: (DGParented)Tree is a subclass of list!
        if isinstance(children, Tree):
            child_trees = [children]

        elif isinstance(children, list):
            child_trees = []
            for child in children:
                if isinstance(child, Tree):
                    child_trees.append(child)
                elif isinstance(child, list):
                    child_trees.extend(child)
                elif isinstance(child, tuple):
                    child_trees.append(t(*child))
                elif isinstance(child, basestring):
                    child_trees.append(child)
                else:
                    raise NotImplementedError

        elif isinstance(children, basestring):
            # this tree does only have one child, a leaf node
            # TODO: this is a workaround for the following problem:
            # Tree('foo', [Tree('bar', [])]) != Tree('foo', ['bar'])
            child_trees = [Tree(children, [])]

        else:
            # this tree only consists of one leaf node
            assert children is None
            child_trees = []

        return DGParentedTree(root, child_trees, root_id)

    else:
        raise NotImplementedError
1148176
def format_python2_stmts(python_stmts, show_tokens=False, showast=False,
                         showgrammar=False, compile_mode='exec'):
    

    parser_debug = {'rules': False, 'transition': False,
                    'reduce': showgrammar,
                    'errorstack': True, 'context': True, 'dups': True }
    parsed = parse_python2(python_stmts, show_tokens=show_tokens,
                           parser_debug=parser_debug)
    assert parsed == 'file_input', 'Should have parsed grammar start'

    formatter = Python2Formatter()

    if showast:
        print(parsed)

    # What we've been waiting for: Generate source from AST!
    python2_formatted_str = formatter.traverse(parsed)

    return python2_formatted_str
917472
def output(s):
    
    p = Parser()
    t = ExpressionsTransformer()

    ast = p.parse(s)
    logging.debug(ast.pretty())
    print(ast.pretty())
    d = t.transform(ast)
    print(json.dumps(d, indent=4))
    return d
593525
def pretty_print(self, obj):
        
        s = repr(obj)
        limit = output_limit()
        if len(s) > limit:
            if self.dom_term:
                s = self.color.py_syntax_highlight(s)
                s = self.dom_term.fold_text_string("", s)
            else:
                s = s[:limit - 3]  # cut before syntax highlighting, to avoid missing color endings
                s = self.color.py_syntax_highlight(s)
                s += "..."
        else:
            s = self.color.py_syntax_highlight(s)
        extra_info = self._pp_extra_info(obj)
        if extra_info != "":
            s += ", " + self.color.py_syntax_highlight(extra_info)
        return s