# Path: hq/hquery/evaluation_error.py
# class HqueryEvaluationError(RuntimeError):
# 
#     @classmethod
#     def must_be_node_set(cls, obj):
#         if not is_node_set(obj):
#             raise HqueryEvaluationError('Expected a node set, but found a(n) {0}'.format(obj.__class__.__name__))
# 
#     @classmethod
#     def must_be_node_set_or_sequence(cls, obj):
#         if not (is_node_set(obj) or is_sequence(obj)):
#             raise HqueryEvaluationError('Expected a node set or sequence, but found a(n) {0}'.format(
#                 obj.__class__.__name__
#             ))
# 
# Path: hq/hquery/hquery_processor.py
# def _is_name_test_predecessor(token):
# def _pick_token_based_on_numeric_context(parse_interface, value, previous_token, numeric_class, other_class):
# def _pick_token_for_and_or_or(parse_interface, value, previous_token):
# def _pick_token_for_asterisk(parse_interface, value, previous_token):
# def _pick_token_for_div_or_mod(parse_interface, value, previous_token):
# def _pick_token_for_computed_constructor_reserved_word(parse_interface, value, previous_token):
# def _pick_token_for_if_or_else(parse_interface, value, previous_token):
# def _pick_token_for_flwor_reserved_word(parse_interface, value, previous_token):
# def _pick_token_for_to(parse_interface, value, previous_token):
#     def __init__(self, processor):
#     def advance(self, *expected_classes):
#     def advance_if(self, *expected_classes):
#     def computed_constructor(self, first_token):
#     def expression(self, rbp=0):
#     def flwor(self, first_token):
#     def if_then_else(self):
#     def is_on(self, *token_classes):
#     def location_path(self, first_token, root_expression=None):
#     def parse_in_new_processor(self, source):
#     def peek(self):
#     def __init__(self, source, preserve_space=False):
#     def query(self, starting_node):
#     def tokenize(self):
#     def token_is(self, *token_classes):
#     def advance_if(self, *expected_classes):
#     def advance_over_name(self):
#     def advance(self, *expected_classes):
#     def parse(self):
#     def parse_computed_array_constructor(self):
#     def parse_computed_attribute_constructor(self):
#     def parse_computed_constructor(self, first_token):
#     def parse_computed_element_constructor(self):
#     def parse_computed_hash_constructor(self):
#     def parse_if_then_else(self):
#         def evaluate():
#     def parse_flwor(self, first_token):
#     def parse_flwor_for(self, flwor):
#     def parse_flwor_let(self, flwor):
#     def parse_flwor_return(self, flwor):
#     def parse_location_path(self, first_token, root_expression=None):
#     def parse_location_path_node_test(self):
#     def parse_location_path_predicates(self, already_inside_brace=False):
#     def expression(self, rbp=LBP.nothing):
#     def _cannot_eat_else_same_as_then_because_else_needs_lower_lbp_so_then_expr_knows_when_to_stop(self):
# class ParseInterface:
# class HqueryProcessor():
# 
# Path: hq/output.py
# def convert_results_to_output_text(results, pretty=True, preserve_space=False):
#     if is_sequence(results):
#         return '\n'.join(value_object_to_text(object, pretty, preserve_space) for object in results)
#     else:
#         return value_object_to_text(results, pretty, preserve_space)
# 
# Path: hq/soup_util.py
# def make_soup(source):
#     soup = BeautifulSoup(source, 'html.parser')
#     counter = [0]
# 
#     def visit_node(node):
#         node.hq_doc_index = counter[0]
#         counter[0] += 1
#         if is_tag_node(node):
#             attr_names = sorted(node.attrs.keys(), key=lambda name: name.lower())
#             node.hq_attrs = [AttributeNode(name, node.attrs[name]) for name in attr_names]
#             for attr in node.hq_attrs:
#                 visit_node(attr)
# 
#     preorder_traverse_node_tree(soup, visit_node, filter=is_any_node)
#     verbose_print('Loaded HTML document containing {0} indexed nodes.'.format(counter[0]))
#     return soup
# 
# Path: hq/verbosity.py
# def verbose_print(text, indent_after=False, outdent_before=False):
#     if settings.VERBOSE:
#         if outdent_before:
#             pop_indent()
#         if not is_a_string(text):
#             text = text()
#         print(u'{0}{1}'.format(' ' * indent_level, text), file=sys.stderr)
#         if indent_after:
#             push_indent()
# 
# def set_verbosity(verbose):
#     setattr(settings, 'VERBOSE', verbose)


from docopt import docopt
from .hquery.evaluation_error import HqueryEvaluationError
from .hquery.hquery_processor import HqueryProcessor, HquerySyntaxError
from .output import convert_results_to_output_text
from .soup_util import make_soup
from .verbosity import verbose_print, set_verbosity
    from sys import stderr, stdin   # So py.tests have a chance to hook stdout & stderr
"""

from __future__ import print_function



__version__ = '0.0.4'


def main():

    args = docopt(__doc__, version='HQ {0}'.format(__version__))
    preserve_space = bool(args['--preserve'])
    set_verbosity(bool(args['--verbose']))

    try:
        if args['--file']:
            with open(args['--file']) as file:
                source = file.read()
        else:
            source = stdin.read()
        verbose_print('Read {0} characters of input'.format(len(source)))
        soup = make_soup(source)

        if args['--program']:
            with open(args['--program']) as file:
                expression = file.read()
        else:
            expression = args['<expression>']
        if len(expression) > 0:

# Path: hq/hquery/evaluation_error.py
# class HqueryEvaluationError(RuntimeError):
# 
#     @classmethod
#     def must_be_node_set(cls, obj):
#         if not is_node_set(obj):
#             raise HqueryEvaluationError('Expected a node set, but found a(n) {0}'.format(obj.__class__.__name__))
# 
#     @classmethod
#     def must_be_node_set_or_sequence(cls, obj):
#         if not (is_node_set(obj) or is_sequence(obj)):
#             raise HqueryEvaluationError('Expected a node set or sequence, but found a(n) {0}'.format(
#                 obj.__class__.__name__
#             ))
# 
# Path: hq/hquery/hquery_processor.py
# def _is_name_test_predecessor(token):
# def _pick_token_based_on_numeric_context(parse_interface, value, previous_token, numeric_class, other_class):
# def _pick_token_for_and_or_or(parse_interface, value, previous_token):
# def _pick_token_for_asterisk(parse_interface, value, previous_token):
# def _pick_token_for_div_or_mod(parse_interface, value, previous_token):
# def _pick_token_for_computed_constructor_reserved_word(parse_interface, value, previous_token):
# def _pick_token_for_if_or_else(parse_interface, value, previous_token):
# def _pick_token_for_flwor_reserved_word(parse_interface, value, previous_token):
# def _pick_token_for_to(parse_interface, value, previous_token):
#     def __init__(self, processor):
#     def advance(self, *expected_classes):
#     def advance_if(self, *expected_classes):
#     def computed_constructor(self, first_token):
#     def expression(self, rbp=0):
#     def flwor(self, first_token):
#     def if_then_else(self):
#     def is_on(self, *token_classes):
#     def location_path(self, first_token, root_expression=None):
#     def parse_in_new_processor(self, source):
#     def peek(self):
#     def __init__(self, source, preserve_space=False):
#     def query(self, starting_node):
#     def tokenize(self):
#     def token_is(self, *token_classes):
#     def advance_if(self, *expected_classes):
#     def advance_over_name(self):
#     def advance(self, *expected_classes):
#     def parse(self):
#     def parse_computed_array_constructor(self):
#     def parse_computed_attribute_constructor(self):
#     def parse_computed_constructor(self, first_token):
#     def parse_computed_element_constructor(self):
#     def parse_computed_hash_constructor(self):
#     def parse_if_then_else(self):
#         def evaluate():
#     def parse_flwor(self, first_token):
#     def parse_flwor_for(self, flwor):
#     def parse_flwor_let(self, flwor):
#     def parse_flwor_return(self, flwor):
#     def parse_location_path(self, first_token, root_expression=None):
#     def parse_location_path_node_test(self):
#     def parse_location_path_predicates(self, already_inside_brace=False):
#     def expression(self, rbp=LBP.nothing):
#     def _cannot_eat_else_same_as_then_because_else_needs_lower_lbp_so_then_expr_knows_when_to_stop(self):
# class ParseInterface:
# class HqueryProcessor():
# 
# Path: hq/output.py
# def convert_results_to_output_text(results, pretty=True, preserve_space=False):
#     if is_sequence(results):
#         return '\n'.join(value_object_to_text(object, pretty, preserve_space) for object in results)
#     else:
#         return value_object_to_text(results, pretty, preserve_space)
# 
# Path: hq/soup_util.py
# def make_soup(source):
#     soup = BeautifulSoup(source, 'html.parser')
#     counter = [0]
# 
#     def visit_node(node):
#         node.hq_doc_index = counter[0]
#         counter[0] += 1
#         if is_tag_node(node):
#             attr_names = sorted(node.attrs.keys(), key=lambda name: name.lower())
#             node.hq_attrs = [AttributeNode(name, node.attrs[name]) for name in attr_names]
#             for attr in node.hq_attrs:
#                 visit_node(attr)
# 
#     preorder_traverse_node_tree(soup, visit_node, filter=is_any_node)
#     verbose_print('Loaded HTML document containing {0} indexed nodes.'.format(counter[0]))
#     return soup
# 
# Path: hq/verbosity.py
# def verbose_print(text, indent_after=False, outdent_before=False):
#     if settings.VERBOSE:
#         if outdent_before:
#             pop_indent()
#         if not is_a_string(text):
#             text = text()
#         print(u'{0}{1}'.format(' ' * indent_level, text), file=sys.stderr)
#         if indent_after:
#             push_indent()
# 
# def set_verbosity(verbose):
#     setattr(settings, 'VERBOSE', verbose)


# Path: hq/hq.py
from docopt import docopt
from .hquery.evaluation_error import HqueryEvaluationError
from .hquery.hquery_processor import HqueryProcessor, HquerySyntaxError
from .output import convert_results_to_output_text
from .soup_util import make_soup
from .verbosity import verbose_print, set_verbosity
    from sys import stderr, stdin   # So py.tests have a chance to hook stdout & stderr

"""

from __future__ import print_function



__version__ = '0.0.4'


def main():

    args = docopt(__doc__, version='HQ {0}'.format(__version__))
    preserve_space = bool(args['--preserve'])
    set_verbosity(bool(args['--verbose']))

    try:
        if args['--file']:
            with open(args['--file']) as file:
                source = file.read()
        else:
            source = stdin.read()
        verbose_print('Read {0} characters of input'.format(len(source)))
        soup = make_soup(source)

        if args['--program']:
            with open(args['--program']) as file:
                expression = file.read()
        else:
            expression = args['<expression>']
        if len(expression) > 0:

            result = HqueryProcessor(expression, preserve_space).query(soup)