Permalink
Browse files

Now parses program code correctly

Essentially wrote a state machine to make this work.
  • Loading branch information...
1 parent 4c4499a commit 567371bf39a6278a76fa407bcba528477f8207f9 @masak masak committed Aug 31, 2009
Showing with 65 additions and 2 deletions.
  1. +52 −1 lib/Perl6/Literate.pm
  2. +1 −1 t/01-comment-only.t
  3. +12 −0 t/02-program-code-only.t
View
@@ -1,5 +1,56 @@
module Perl6::Literate;
sub convert($text) {
- return "=begin Comment\n" ~ $text ~ "\n=end Comment";
+ # There are six modes, 'start', 'code', 'comment', 'empty line after code'
+ # and 'empty line after comment'. The latter two are abbreviated '_code'
+ # and '_comment', respectively. All given-statements looping over $mode
+ # should treat all four modes somehow.
+ my $mode = 'start';
+
+ return [~] gather {
+ for $text.comb(/\N*\n|\N+\n?/).kv -> $n, $line {
+ given $line {
+ when /^ '>'/ {
+ given $mode {
+ when 'code'|'_code'|'start'|'_start' {
+ take ' ' ~ $line.substr(1);
+ }
+ when '_comment' {
+ take "=end Comment\n";
+ take $line;
+ }
+ when 'comment' {
+ die "Must have empty line before code paragraph "
+ ~ "on line $n";
+ }
+ }
+ $mode = 'code';
+ }
+ when /^ \s* $/ {
+ take $line;
+ $mode.=subst(/^_?/, '_');
+ }
+ default {
+ given $mode {
+ when 'comment'|'_comment' {
+ take $line;
+ }
+ when 'start'|'_start'|'_code' {
+ take "=begin Comment\n";
+ take $line;
+ }
+ when 'code' {
+ die "Must have empty line after code paragraph "
+ ~ "on line $n";
+ }
+ }
+ $mode = 'comment'
+ }
+ }
+ }
+ # RAKUDO: Would rather have this in a LAST block.
+ if $mode ~~ /comment/ {
+ take "\n=end Comment\n";
+ }
+ }
}
View
@@ -4,5 +4,5 @@ use Test;
use Perl6::Literate;
is Perl6::Literate::convert("A\nB\n\nC"),
- "=begin Comment\nA\nB\n\nC\n=end Comment",
+ "=begin Comment\nA\nB\n\nC\n=end Comment\n",
'a program consisting only of a comment gets converted into Pod';
View
@@ -0,0 +1,12 @@
+use v6;
+use Test;
+
+use Perl6::Literate;
+
+is Perl6::Literate::convert(q[[[> my $a = "OH ";
+> $a ~= "HAI";
+> say $a;]]]),
+ q[[[ my $a = "OH ";
+ $a ~= "HAI";
+ say $a;]]],
+ 'a program consisting only of code has all its ">" chars stripped';

0 comments on commit 567371b

Please sign in to comment.