Created
March 3, 2011 21:59
-
-
Save stormbrew/853705 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A tree structure that contains parse error messages. This can be used to | |
# give the user a detailed report on what went wrong during a parse. | |
# | |
class(Parslet) ErrorTree: { | |
# The parslet that caused the error stored here. | |
attr_reader(parslet) | |
# All errors that were encountered when parsing part of this +parslet+. | |
attr_reader(children) | |
def initialize:(parslet, *children) { # :nodoc: | |
@parslet = $parslet | |
@children = $children.compact | |
} | |
def nodes: { | |
1 + @children.inject(0) do:(sum, node) { $sum + $node.nodes } | |
} | |
def cause: { | |
@parslet.cause || "Unknown error in #{parslet.inspect}" | |
} | |
# Returns an ascii tree representation of the causes of this node and its | |
# children. | |
# | |
def ascii_tree: { | |
StringIO.new.tap do:(io) { | |
recursive_ascii_tree(@, $io, [true]) | |
}.string | |
} | |
alias(to_s, ascii_tree) | |
def(private) recursive_ascii_tree:(node, stream, curved) {# :nodoc: | |
append_prefix($stream, $curved) | |
$stream.puts($node.cause) | |
$node.children.each do:(child) { | |
$last_child = ($node.children.last == $child) | |
recursive_ascii_tree($child, $stream, $curved + [$last_child]) | |
} | |
} | |
def append_prefix:(stream, curved) { # :nodoc: | |
$curved[0..-2].each do:(c) { | |
$stream.print(if(c) do: { " " } else: { "| " }) | |
} | |
$stream.print(if ($curved.last) do: { "`- " } else: { "|- " }) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment