File Coverage

blib/lib/Text/Fab.pm
Criterion Covered Total %
statement 214 222 96.4
branch 99 124 79.8
condition 16 23 69.5
subroutine 32 33 96.9
pod 9 16 56.2
total 370 418 88.5


line stmt bran cond sub pod time code
1             package Text::Fab;
2            
3 5     5   723911 use 5.022;
  5         20  
4 5     5   29 use strict;
  5         12  
  5         208  
5 5     5   29 use warnings;
  5         8  
  5         505  
6            
7             our $VERSION = '0.01';
8            
9             #use Storable 'dclone'; # For group snapshots (does not support CODE references in data!)
10 5     5   3447 use FreezeThaw qw(safeFreeze thaw); # For group snapshots
  5         30784  
  5         20804  
11            
12 2     2 0 11 sub dclone ($) {(thaw safeFreeze shift)[0]} # return scalar even in scalar content
13            
14             # --- Default Callbacks ---
15             # These are the "smart" components that define the default language.
16             # A user can replace any of these by setting the config hash.
17            
18             # Finds the start of the next directive.
19             sub _default_interleaver {
20 22     22   42 my ($buffer, $offset) = @_;
21             # A directive is a '#' at the beginning of a line.
22             # We search for a newline, then check if it's followed by '#'.
23             # A special case handles a '#' at the very start of the buffer.
24 22 100 66     118 return 0 if $offset == 0 && substr($buffer, 0, 1) eq '#';
25 11         43 my $pos = index($buffer, "\n#", $offset-1);
26 11 50       27 return $pos == -1 ? undef : $pos + 1;
27             }
28            
29             # Parses a directive and calls the corresponding Fab primitive.
30             sub _default_directive_parser {
31 22     22   41 my ($fab, $buffer, $offset) = @_;
32 22         43 my $line_end = index($buffer, "\n", $offset);
33 22 100       48 $line_end = length($buffer) if $line_end == -1;
34            
35 22         47 my $directive_line = substr($buffer, $offset, $line_end - $offset);
36             # warn("Drctv_ln: <<<$directive_line>>>");
37            
38 22 100       124 if ($directive_line =~ /^#(\w+)\s*(.*)/) {
39 20         78 my ($directive, $args) = (lc $1, $2);
40 20         54 $args =~ s/\s+$//; # Trim trailing whitespace
41             # warn("Drctv: <<<$directive>>>, <<<$args>>>");
42            
43             # This dispatch table maps the user-facing syntax to the stable
44             # internal API of primitive operations.
45 20 100       71 if ($directive eq 'target_section') {
    100          
    50          
    100          
    100          
    100          
    100          
46 6         31 my ($basename, $ns) = ($args =~ /(\w+)(?:\s+in\s+(\w+))?/);
47 6         16 $fab->out__target_section($basename, $ns);
48             }
49             elsif ($directive eq 'set') {
50 5         17 my ($key, $value) = split /=/, $args, 2;
51 5         14 $fab->cfg__set($key, $value);
52             }
53             elsif ($directive eq 'append') {
54 0         0 my ($key, @values) = split /\s+/, $args;
55 0         0 $fab->cfg__append($key, @values);
56             }
57             elsif ($directive eq 'set_parents') {
58 2         20 my ($ns, @parents) = split /\s+/, $args;
59             # The inheritance graph is stored in a structured way in the config.
60 2         9 $fab->cfg__set("Fab/inheritance_graph/$ns/parents", \@parents);
61             }
62             elsif ($directive eq 'emb') {
63 2         9 my ($basename, $ns) = ($args =~ /(\w+)(?:\s+in\s+(\w+))?/);
64 2         7 $fab->out__embed($basename, $ns, {});
65             }
66             elsif ($directive eq 'start_group') {
67 1         4 $fab->group__start($args);
68             }
69             elsif ($directive eq 'end_group') {
70 2         7 $fab->group__end($args);
71             }
72             else {
73 2         10 $fab->_handle_error('unknown_directive', { directive => $directive, line => $directive_line });
74             }
75             }
76             else {
77 2         9 $fab->_handle_error('malformed_directive', { line => $directive_line });
78             }
79            
80 19         1470 return $line_end + 1; # Resume processing after this directive line.
81             }
82            
83             # The default "stomach" - processes text chunks between directives.
84             sub _default_chunk_preprocessor {
85 7     7   14 my ($fab, $chunk) = @_;
86             # By default, it does nothing but return the text.
87 7         14 return $chunk;
88             }
89            
90             # The default error handler - fail fast.
91             sub _default_error_handler {
92 2     2   6 my ($fab, $type, $details) = @_;
93 2         32 die "Fab Error ($type): $details->{line}\n";
94             }
95            
96             # --- Core Class ---
97            
98             sub new {
99 36     36 0 972764 my ($class, %args) = @_;
100 36         98 my $self = bless {}, $class;
101            
102             # The entire state of the system is held in these hashes.
103             $self->{config} = {
104             # Meta-configuration: which keys are lists.
105             'Fab/list_keys' => { 'Fab/list_keys' => 1 },
106             'Fab/hash_keys' => {},
107 2     2   8 'Fab/hash_key_sort_order' => sub { $a cmp $b }, # Default sort for hash keys
108             # State for recursive processing.
109 36         581 'Fab/call_stack_prefixes' => ['Fab/'],
110             # The user-configurable components that define the language.
111             'Fab/callbacks' => {
112             interleaver => \&_default_interleaver,
113             directive_parser => \&_default_directive_parser,
114             chunk_preprocessor => \&_default_chunk_preprocessor,
115             error_handler => \&_default_error_handler,
116             },
117             # The inheritance graph is just another part of the configuration.
118             'Fab/inheritance_graph' => {},
119             };
120 36         143 $self->{sections} = {}; # { namespace => { basename => \@chunks } }
121 36         102 $self->{current_target} = ['_main', 'body']; # Default output target.
122 36         114 $self->{group_stack} = [];
123            
124             # Allow user to provide an initial configuration.
125 36 100       134 if ($args{config}) {
126             # A real implementation would merge recursively.
127 11         26 %{$self->{config}} = (%{$self->{config}}, %{$args{config}});
  11         63  
  11         38  
  11         31  
128             }
129            
130 36         205 return $self;
131             }
132            
133             # The main processing loop, driven by the callbacks.
134             sub process_string {
135 12     12 0 90 my ($self, $string) = @_;
136 12         23 my $offset = 0;
137            
138 12         29 my $callbacks = $self->cfg__get_prefixed('Fab/callbacks');
139             my ($interleaver, $parser, $preprocessor) =
140 12         21 @{$callbacks}{qw(interleaver directive_parser chunk_preprocessor)};
  12         32  
141            
142 12         33 while ($offset < length($string)) {
143 24         54 my $directive_start = $interleaver->($string, $offset);
144            
145 24 100       82 if (!defined $directive_start) {
146 1         6 $self->_process_chunk(substr($string, $offset), $preprocessor);
147 1         4 last;
148             }
149            
150 23         53 my $chunk_text = substr($string, $offset, $directive_start - $offset);
151 23         120 $self->_process_chunk($chunk_text, $preprocessor);
152            
153 23         49 $offset = $parser->($self, $string, $directive_start);
154             }
155             }
156            
157             sub _process_chunk {
158 24     24   49 my ($self, $chunk_text, $preprocessor) = @_;
159             # Remove leading newline that results from splitting by `\n#`.
160 24         45 $chunk_text =~ s/^\n//;
161 24 100       54 return unless length $chunk_text;
162            
163 7         10 my ($ns, $basename) = @{$self->{current_target}};
  7         17  
164 7         15 my $processed_chunk = $preprocessor->($self, $chunk_text);
165 7         12 push @{$self->{sections}{$ns}{$basename}}, ['text', $processed_chunk];
  7         32  
166             }
167            
168             sub _handle_error {
169 4     4   9 my ($self, $type, $details) = @_;
170 4         9 my $handler = $self->cfg__get_prefixed('Fab/callbacks')->{error_handler};
171 4         9 $handler->($self, $type, $details);
172             }
173            
174             # --- Primitive API (the stable interface for parsers) ---
175            
176 7   66 7 1 22 sub out__target_section { my ($self, $basename, $namespace) = @_; $namespace //= $self->{current_target}->[0]; $self->{current_target} = [$namespace, $basename]; $self->{sections}{$namespace}{$basename} //= []; }
  7   50     23  
  7         22  
  7         43  
177 2   33 2 1 5 sub out__embed { my ($self, $basename, $namespace, $options) = @_; my ($target_ns, $target_basename) = @{$self->{current_target}}; $namespace //= $target_ns; push @{$self->{sections}{$target_ns}{$target_basename}}, ['embed', $namespace, $basename, $options]; }
  2         3  
  2         5  
  2         5  
  2         2  
  2         13  
178 39     39 1 206 sub cfg__set { my ($self, $key, $value) = @_; $self->{config}{$key} = $value; }
  39         142  
179 7 100   7 1 44 sub cfg__append { my ($self, $key, @values) = @_; if ($self->{config}{'Fab/list_keys'}{$key}) { push @{$self->{config}{$key}}, @values; } else { $self->{config}{$key} .= join('', @values); } }
  7         28  
  5         8  
  5         28  
  2         11  
180 26     26 1 4104 sub cfg__get { my ($self, $key) = @_; return $self->{config}{$key}; }
  26         207  
181 20 100   20 1 55 sub cfg__get_prefixed { my ($self, $key) = @_; for my $prefix (reverse @{$self->{config}{'Fab/call_stack_prefixes'}}) { my $full_key = $prefix . $key; return $self->{config}{$full_key} if exists $self->{config}{$full_key}; } return $self->{config}{$key}; }
  20         35  
  20         56  
  22         59  
  22         93  
  18         63  
182 2     2 1 8 sub group__start { my ($self, $flavor) = @_; push @{$self->{group_stack}}, { config => dclone($self->{config}) }; }
  2         5  
  2         8  
183 3 100   3 1 1283 sub group__end { my ($self, $flavor) = @_; my $snapshot = pop @{$self->{group_stack}} or die; $self->{config} = $snapshot->{config};}
  3         7  
  3         28  
  2         15  
184             sub cfg__pop {
185 11     11 0 297 my ($self, $key, @args) = @_;
186 11         51 my $type = $self->_get_key_type($key);
187            
188 11 100       73 if ($type eq 'list') {
    100          
189 6 100       32 die "cfg__pop on a list key accepts at most one argument (a count)" if @args > 1;
190 5 100       15 my $count = @args ? $args[0] : 1;
191 5 50       45 my $list = $self->{config}{$key} or return;
192 5 50       18 die "cfg__pop expected array reference for key '$key'" unless ref $list eq 'ARRAY';
193 5 100       43 die "cfg__pop cannot pop $count elements from list of size " . scalar(@$list) if $count > @$list;
194 4         16 my @popped = splice @$list, -$count;
195 4 100       36 return wantarray ? @popped : $popped[-1];
196             }
197             elsif ($type eq 'hash') {
198             # Silently a no-op if no keys are provided.
199 2 0       8 return wantarray ? () : undef unless @args;
    50          
200 2         5 my @keys_to_delete = @args;
201 2 50       8 my $hash = $self->{config}{$key} or return;
202 2 50       6 die "cfg__pop expected hash reference for key '$key'" unless ref $hash eq 'HASH';
203 2         5 my @deleted_values = delete @{$hash}{@keys_to_delete};
  2         6  
204 2 100       13 return wantarray ? @deleted_values : $deleted_values[0];
205             }
206             else {
207             # This branch handles scalars. A pop on a scalar is only valid with no args.
208 3 100       23 die "cfg__pop with arguments can only be called on list or hash keys" if @args;
209 2         23 die "cfg__pop called on non-list/non-hash key '$key'";
210             }
211             }
212             sub cfg__prepend_elt {
213 11     11 0 961 my ($self, $key, $offset, $value) = @_;
214 11         32 my $type = $self->_get_key_type($key);
215            
216 11 100       45 if ($type eq 'list') {
    100          
217 3   100     17 $self->{config}{$key} //= [];
218 3         7 my $list = $self->{config}{$key};
219 3 50       13 die "cfg__prepend_elt expected array reference for key '$key'" unless ref $list eq 'ARRAY';
220 3         10 splice @$list, $offset, 0, $value;
221 3         13 return;
222             }
223             elsif ($type eq 'hash') {
224 6 100 100     71 die "cfg__prepend_elt on hash requires value to be an array reference of a [key, value] pair"
225             unless ref $value eq 'ARRAY' && @$value == 2;
226 2   50     8 $self->{config}{$key} //= {};
227 2         5 my $hash = $self->{config}{$key};
228 2 50       6 die "cfg__prepend_elt expected hash reference for key '$key'" unless ref $hash eq 'HASH';
229 2         6 $hash->{$value->[0]} = $value->[1];
230 2         6 return;
231             }
232             else {
233 2         23 die "cfg__prepend_elt called on non-list/non-hash key '$key'";
234             }
235             }
236             sub cfg__get_joined {
237 17     17 1 1019 my ($self, $key, $joiners, $options) = @_;
238 17 100       93 die "cfg__get_joined requires an array reference for joiners"
239             unless ref $joiners eq 'ARRAY';
240 15         47 my $type = $self->_get_key_type($key);
241            
242 15 100       58 if ($type eq 'list') {
    100          
243 6 50       21 my $list = $self->{config}{$key} or return '';
244 6 50       15 die "cfg__get_joined expected array reference for key '$key'" unless ref $list eq 'ARRAY';
245 6         21 return $self->_join_list($list, $joiners, $options);
246             }
247             elsif ($type eq 'hash') {
248 7 50       22 my $hash = $self->{config}{$key} or return '';
249 7         21 my @sorted_keys = $self->_get_sorted_hash_keys($key);
250 7         50 my $intra_pair_joiner = $joiners->[0];
251 7 50       46 my @inter_pair_joiners = @$joiners > 1 ? @$joiners[1..$#$joiners] : ($#$joiners == 0 ? [$joiners->[0]] : []);
    100          
252 7         16 my @joined_pairs = map { $_ . $intra_pair_joiner . $hash->{$_} } @sorted_keys;
  15         47  
253 7         22 return $self->_join_list(\@joined_pairs, \@inter_pair_joiners, $options);
254             }
255             else {
256 2         24 die "cfg__get_joined called on non-list/non-hash key '$key'";
257             }
258             }
259             sub out__get_joined {
260 4     4 0 405 my ($self, $spec, $joiners, $options) = @_;
261 4 100       53 die "out__get_joined requires an array reference for joiners"
262             unless ref $joiners eq 'ARRAY';
263 2         12 my ($ns, $basename) = split /:/, $spec;
264 2 50       12 my $all_chunks = $self->{sections}{$ns}{$basename} or return '';
265 2         7 my @text_parts = map { $_->[1] } grep { $_->[0] eq 'text' } @$all_chunks;
  6         14  
  8         20  
266 2         10 return $self->_join_list(\@text_parts, $joiners, $options);
267             }
268            
269             # --- Private Helpers ---
270             sub _get_key_type {
271 37     37   69 my ($self, $key) = @_;
272 37 100       147 return 'hash' if $self->{config}{'Fab/hash_keys'}{$key};
273 22 100       88 return 'list' if $self->{config}{'Fab/list_keys'}{$key};
274 7         21 return 'scalar';
275             }
276             sub _get_sorted_hash_keys {
277 7     7   13 my ($self, $key) = @_;
278 7 50       19 my $hash = $self->{config}{$key} or return ();
279 7 50       18 die "_get_sorted_hash_keys expected hash reference for key '$key'" unless ref $hash eq 'HASH';
280 7         13 my $sorter = $self->{config}{'Fab/hash_key_sort_order'};
281 7         39 return sort { $sorter->($a, $b) } (keys %$hash);
  12         38  
282             }
283             sub _hash_to_sorted_list {
284 0     0   0 my ($self, $key) = @_;
285 0 0       0 my $hash = $self->{config}{$key} or return [];
286 0         0 my @sorted_keys = $self->_get_sorted_hash_keys($key);
287 0         0 return [ map { $_, $hash->{$_} } @sorted_keys ];
  0         0  
288             }
289             sub _join_list {
290 15     15   38 my ($self, $list, $joiners, $options) = @_;
291 15   100     71 $options //= {};
292 15         26 my $num_elements = scalar @$list;
293 15 100       50 return '' unless $num_elements;
294 13 100       48 return $list->[0] if $num_elements == 1;
295            
296 11         24 my $num_joiners_to_use = $num_elements - 1;
297 11 100       54 if (my $mod = $options->{permitted_joiners_modulo}) {
298 4 100       49 die "Join operation violates permitted_joiners_modulo rule (want multiple of $mod, got $num_joiners_to_use)"
299             if $num_joiners_to_use % $mod != 0;
300             }
301            
302 9         20 my $output = $list->[0];
303 9         32 for my $i (1 .. $num_joiners_to_use) {
304 24         75 $output .= $joiners->[($i - 1) % @$joiners] . $list->[$i];
305             }
306 9         116 return $output;
307             }
308            
309             # --- Assembly Phase ---
310            
311             sub assemble {
312 4     4 0 75 my ($self, $root_spec) = @_;
313 4         11 my ($ns, $basename) = split /:/, $root_spec;
314 4         20 my $output = $self->_expand_section($ns, $basename, {});
315 3         9 chomp($output); # Trim final trailing newline.
316             # $output =~ s/\s+$//; # Maybe better (but what for?!) ???
317 3         16 return $output;
318             }
319            
320             sub _expand_section {
321 6     6   12 my ($self, $ns, $basename, $seen) = @_;
322 6         12 my $id = "$ns:$basename";
323 6 100       30 die "Circular dependency for section '$id'" if $seen->{$id};
324 5         16 local $seen->{$id} = 1;
325            
326 5         12 my $chunks = $self->_resolve_section($ns, $basename);
327 5 50       9 return "" unless $chunks;
328            
329 5         8 my $output = "";
330 5         9 for my $chunk (@$chunks) {
331 6         13 my ($type, @data) = @$chunk;
332 6 100       14 if ($type eq 'text') {
    50          
333 4         11 $output .= $data[0];
334             } elsif ($type eq 'embed') {
335 2         6 $output .= $self->_expand_section($data[0], $data[1], $seen);
336             }
337             }
338 4         11 return $output;
339             }
340            
341             sub _resolve_section {
342 6     6   12 my ($self, $ns, $basename) = @_;
343             return $self->{sections}{$ns}{$basename}
344 6 50 66     62 if exists $self->{sections}{$ns} && exists $self->{sections}{$ns}{$basename};
345            
346 1         4 my $parents_key = "Fab/inheritance_graph/$ns/parents";
347             # FIX: Correctly dereference the array reference of parents.
348 1 50       2 for my $parent_ns (@{$self->{config}{$parents_key} || []}) {
  1         6  
349 1         4 my $chunks = $self->_resolve_section($parent_ns, $basename);
350 1 50       5 return $chunks if $chunks;
351             }
352 0           return undef;
353             }
354            
355             1;
356            
357             __END__