Skip to content

Instantly share code, notes, and snippets.

@tony-o
Created June 26, 2013 17:16
Show Gist options
  • Save tony-o/5869361 to your computer and use it in GitHub Desktop.
Save tony-o/5869361 to your computer and use it in GitHub Desktop.
method parse ( Str $templ ) {
my $chopper = '^\s*(' ~ $.open ~ '[\\' ~ %.nestables{'open'} ~ '\\' ~
%.nestables{'close'} ~ '].*?' ~ $.close ~ ')\s*$';
my $template = $templ.subst(/$chopper/, "\$1", :g:m);
my $length = $template.chars;
my @templarr = $template.split('');
my @opener = $.open.split('');
my @closer = $.close.split('');
my $status = 0; # 0=in text, 1=in code
my @nodes;
my ($index, $counter, $start, $nesting, $buffer);
my $isopener = sub{
loop ( $counter = 0; $counter < @opener.elems; $counter++ ) {
if ( @templarr[$counter + $index] ne @opener[$counter] ) {
return 0;
}
}
return 1;
};
my $iscloser = sub{
loop ( $counter = 0; $counter < @closer.elems; $counter++ ) {
if ( @templarr[$counter + $index] ne @closer[$counter] ) {
return 0;
}
}
return 1;
};
loop ( $index = 0, $nesting = 0, $start = 0; $index < $length; $index++ ) {
if ( $isopener() && $status == 0 ) {
$status = 1;
my %d = ( t => substr($template, $start, ($index - $start)), n => $nesting );
@nodes.push( { %d } );
$index += @opener.chars;
$start = $index;
next;
}
if ( $iscloser() && $status == 1 ) {
$status = 0;
$nesting++ if substr($template, $start, 1) eq %.nestables{'open'};
my %d = ( e => substr($template, $start, ($index - $start)), n => $nesting );
@nodes.push( { %d } );
$nesting-- if substr($template, $start, 1) eq %.nestables{'close'};
$index += @closer.chars;
$start = $index;
}
}
my %d = ( ($status > 0 ?? 'e' !! 't') => substr($template, $start), n => $nesting );
@nodes.push( { %d } );
return @nodes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment