Exemple #1
0
    def raise_open_without_close(formula, stack):
        """
        Called when un-closed opening brackets remain at the end of scan, for
        example: "(1 + 2) + ( 3 + (".
        - stack is the remaining stack
        """
        bracket_registry = BracketValidator.bracket_registry
        still_open = {}
        for key in sorted(bracket_registry):
            if bracket_registry[key].is_closer:
                continue
            num_opened = sum([entry.bracket.char == bracket_registry[key].char for entry in stack])
            if num_opened:
                still_open[key] = num_opened

        # sort so error messages come in definite order, for testing purposes
        sorted_still_open = sorted(still_open.keys(), key=lambda x: bracket_registry[x].name)

        if still_open:
            message = "Invalid Input:\n"
            for key in sorted_still_open:
                if still_open[key] == 1:
                    message += ('{count} {name} was opened without being closed '
                                '(highlighted below)\n'
                                .format(count=still_open[key], name=bracket_registry[key].name))
                else:
                    message += ('{count} {plural} were opened without being closed '
                                '(highlighted below)\n'
                                .format(count=still_open[key], plural=bracket_registry[key].plural))

        indices = [entry.index for entry in stack]
        highlight = BracketValidator.highlight_formula(formula, indices)
        message += highlight
        raise UnbalancedBrackets(message)
Exemple #2
0
    def raise_close_without_open(formula, current):
        """
        Called when scan encounters a closing bracket without matching opener,
        for example: "1, 2, 3]".
        - current is the offending StackEntry
        """
        msg = ("Invalid Input: a {current.bracket.name} was closed without ever "
               "being opened, highlighted below.\n{highlight}")

        indices = [current.index]
        highlight = BracketValidator.highlight_formula(formula, indices)
        formatted = msg.format(current=current, highlight=highlight)
        raise UnbalancedBrackets(formatted)
Exemple #3
0
    def raise_wrong_closing_bracket(formula, current, previous):
        """
        Called when scan encounters a closing bracket that does not match the
        previous opening bracket, for example: "[(1, 2, 3])"
        - current and previous are the offending StackEntry pairs
        """
        msg = ("Invalid Input: a {previous.bracket.name} was opened and then "
               "closed by a {current.bracket.name}, highlighted below.\n"
               "{highlight}")

        indices = [previous.index, current.index]
        highlight = BracketValidator.highlight_formula(formula, indices)
        formatted = msg.format(current=current, previous=previous, highlight=highlight)
        raise UnbalancedBrackets(formatted)