| 1 | package Blatte::Compiler; | ||
| 2 | |||
| 3 | use Blatte::Parser; | ||
| 4 | |||
| 5 | use constant CHUNK_SIZE => 8192; | ||
| 6 | |||
| 7 | my $parser; | ||
| 8 | |||
| 9 | sub compile { | ||
| 10 | my($fh, $cb) = @_; | ||
| 11 | |||
| 12 | my $content = ''; | ||
| 13 | |||
| 14 | $parser = new Blatte::Parser() unless defined($parser); | ||
| 15 | |||
| 16 | my $line = 1; | ||
| 17 | |||
| 18 | while (1) { | ||
| 19 | if ($content eq '') { | ||
| 20 | return undef if $fh->eof(); | ||
| 21 | $fh->read($content, CHUNK_SIZE); | ||
| 22 | } | ||
| 23 | |||
| 24 | my $source = $content; | ||
| 25 | my $result = $parser->parse(\$content); | ||
| 26 | |||
| 27 | if (defined($result)) { | ||
| 28 | if ($content eq '') { | ||
| 29 | if ($fh->eof()) { | ||
| 30 | &$cb($result, | ||
| 31 | substr($source, 0, (length($source) - length($content)))); | ||
| 32 | } else { | ||
| 33 | # don't trust the result | ||
| 34 | $content = $source; | ||
| 35 | $fh->read($content, CHUNK_SIZE, length($content)); | ||
| 36 | } | ||
| 37 | } else { | ||
| 38 | &$cb($result, | ||
| 39 | substr($source, 0, (length($source) - length($content)))); | ||
| 40 | } | ||
| 41 | } elsif ($fh->eof()) { | ||
| 42 | return undef if ($parser->eof($content)); | ||
| 43 | return $line; | ||
| 44 | } else { | ||
| 45 | $content = $source; | ||
| 46 | $fh->read($content, CHUNK_SIZE, length($content)); | ||
| 47 | } | ||
| 48 | } | ||
| 49 | } | ||
| 50 | |||
| 51 | sub compile_sparse { | ||
| 52 | my($fh, $cb) = @_; | ||
| 53 | |||
| 54 | my $content = ''; | ||
| 55 | |||
| 56 | $parser = new Blatte::Parser() unless defined($parser); | ||
| 57 | |||
| 58 | my $line = 1; | ||
| 59 | |||
| 60 | while (1) { | ||
| 61 | if ($content eq '') { | ||
| 62 | return undef if $fh->eof(); | ||
| 63 | $fh->read($content, CHUNK_SIZE); | ||
| 64 | } | ||
| 65 | |||
| 66 | if ($content =~ /^([^\\\{]*)[\\\{]/s) { | ||
| 67 | my $plain = $1; | ||
| 68 | if ($plain ne '') { | ||
| 69 | $content = substr($content, length($plain)); | ||
| 70 | &$cb($plain); | ||
| 71 | while ($plain =~ /\n/g) { | ||
| 72 | ++$line; | ||
| 73 | } | ||
| 74 | } | ||
| 75 | my $source = $content; | ||
| 76 | my $result = $parser->parse(\$content); | ||
| 77 | if (defined($result)) { | ||
| 78 | $source = substr($source, 0, (length($source) - length($content))); | ||
| 79 | &$cb($result, $source); | ||
| 80 | while ($source =~ /\n/g) { | ||
| 81 | ++$line; | ||
| 82 | } | ||
| 83 | } elsif ($fh->eof()) { | ||
| 84 | return $line; | ||
| 85 | } else { | ||
| 86 | $fh->read($content, CHUNK_SIZE, length($content)); | ||
| 87 | } | ||
| 88 | } else { | ||
| 89 | &$cb($content); | ||
| 90 | $content = ''; | ||
| 91 | while ($content =~ /\n/g) { | ||
| 92 | ++$line; | ||
| 93 | } | ||
| 94 | } | ||
| 95 | } | ||
| 96 | } | ||
| 97 | |||
| 98 | 1; | ||
| 99 | |||
| 100 | __END__ |