Skip to content

Instantly share code, notes, and snippets.

@moritz
Created July 15, 2012 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moritz/3116493 to your computer and use it in GitHub Desktop.
Save moritz/3116493 to your computer and use it in GitHub Desktop.
Walking Perl 6 Pod trees, combining list items into Lists
use v6;
sub pod-gist(Pod::Block $pod, $level = 0) {
my $leading = ' ' x $level;
my %confs;
my @chunks;
for <config name level caption type> {
my $thing = $pod.?"$_"();
if $thing {
%confs{$_} = $thing ~~ Iterable ?? $thing.perl !! $thing.Str;
}
}
@chunks = $leading, $pod.^name, (%confs.perl if %confs), "\n";
for $pod.content.list -> $c {
if $c ~~ Pod::Block {
@chunks.push: pod-gist($c, $level + 2);
}
else {
@chunks.push: $c.indent($level + 2), "\n";
}
}
@chunks.join;
}
sub visit($root, :&pre, :&post, :&assemble = -> *%{ Nil }) {
my ($pre, $post);
$pre = pre($root) if defined &pre;
my @content = $root.?content.map: {visit $_, :&pre, :&post, :&assemble};
$post = post($root, :@content) if defined &post;
return assemble(:$pre, :$post, :@content, :node($root));
}
my $pod = eval(slurp('lib/Hash.pod') ~ "\n\$=pod")[0];
say pod-gist($pod);
class Pod::List is Pod::Block { }
sub assemble(:@content, :$node, *% ) {
my @current;
my @result;
my $found;
for @content -> $c {
if $c ~~ Pod::Item {
@current.push: $c;
$found = True;
}
elsif @current {
@result.push: Pod::List.new(content => @current);
@current = ();
@result.push: $c;
}
else {
@result.push: $c;
}
}
@result.push: Pod::List.new(content => @current) if @current;
@current = ();
return $found ?? $node.clone(content => @result) !! $node;
}
say pod-gist(visit($pod, :&assemble));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment