Skip to content

Instantly share code, notes, and snippets.

@stormbrew
Created March 3, 2011 21:59
Show Gist options
  • Save stormbrew/853705 to your computer and use it in GitHub Desktop.
Save stormbrew/853705 to your computer and use it in GitHub Desktop.
# 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