/
HeaderParser.pm
1840 lines (1657 loc) · 60.8 KB
/
HeaderParser.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package HeaderParser;
use strict;
use warnings;
use v5.10; # Needs named capture groups
# these are required below in BEGIN statements, we cant have a
# hard dependency on them as they might not be available when
# we run as part of autodoc.pl
#
# use Data::Dumper;
# use Storable qw(dclone);
#
use Carp qw(confess);
use Text::Tabs qw(expand unexpand);
use Text::Wrap qw(wrap);
# The style of this file is determined by:
#
# perltidy -w -ple -bbb -bbc -bbs -nolq -l=80 -noll -nola -nwls='=' \
# -isbc -nolc -otr -kis -ci=4 -se -sot -sct -nsbl -pt=2 -fs \
# -fsb='#start-no-tidy' -fse='#end-no-tidy' -cpb -bfvt=2
my (
%unop, # unary operators and their precedence
%binop, # binary operators and their precedence
%is_right_assoc, # operators which are right associative
%precedence, # precedence of all operators.
%associative, # associative operators
%commutative, # commutative operators
%cmpop, # comparison operators
$unop_pat, # pattern to match unary operators
$binop_pat, # pattern to match binary operators
%op_names, # map of op to description, used in error messages
$tokenize_pat # a pattern which can tokenize an expression
);
BEGIN {
# this is initialization for the operator precedence expression parser
# we use for handling preprocessor conditions.
%op_names= (
'==' => 'equality',
'!=' => 'inequality',
'<<' => 'bit-shift-left',
'>>' => 'bit-shift-right',
'+' => 'addition',
'-' => 'subtraction',
'*' => 'multiplication',
'/' => 'division',
'%' => 'modulo',
'||' => 'logical-or', # Lowest precedence
'&&' => 'logical-and',
'|' => 'binary-or',
'^' => 'binary-xor',
'&' => 'binary-and',
'<' => 'less-than', # split on spaces, all with equal precedence
'>' => 'greater-than',
'<=' => 'less-than-or-equal',
'>=' => 'greater-than-or-equal',
);
my @cmpop= (
'== !=', # listed in lowest to highest precedence
'< > <= >=', # split on spaces, all with equal precedence
);
my @binop= (
'||', # Lowest precedence
'&&',
'|',
'^',
'&',
@cmpop, # include the numerical comparison operators.
'<< >>',
'+ -',
'* / %', # highest prcedence operators.
);
my @unop= qw( ! ~ + - );
%unop= map { $_ => 1 } @unop;
%cmpop= map { $_ => 1 } map { split /\s+/, $_ } @cmpop;
%binop= map { $_ => 1 } map { split /\s+/, $_ } @binop;
my $make_pat= sub {
my $pat= join "|", sort { length($b) <=> length($a) || $a cmp $b }
map quotemeta($_), @_;
return qr/$pat/;
};
$unop_pat= $make_pat->(@unop);
foreach my $ix (0 .. $#binop) {
my $sym= $binop[$ix];
$precedence{$_}= (1 + $ix) * 10 for split /\s+/, $sym;
}
$is_right_assoc{"?"}= 1;
$is_right_assoc{":"}= 1;
$precedence{"?"}= 1;
$precedence{":"}= 0;
$associative{$_}++
for qw( || && + *); # we leave '==' out so we don't reorder terms
$commutative{$_}++ for qw( || && + *);
$binop_pat= $make_pat->(keys %precedence);
$tokenize_pat= qr/
^(?:
(?<comment> \/\*.*?\*\/ )
| (?<ws> \s+ )
| (?<term>
(?<literal>
(?<define> defined\(\w+\) )
| (?<func> \w+\s*\(\s*\w+(?:\s*,\s*\w+)*\s*\) )
| (?<const> (?:0x[a-fA-F0-9]+|\d+[LU]*|'.') )
| (?<sym> \w+ )
)
| (?<op> $binop_pat | $unop_pat )
| (?<paren> [\(\)] )
)
)
/xs;
}
# dump the arguments with dump. wraps loading Dumper
# as we are executed by miniperl where Dumper isnt available
sub dd {
my $self= shift;
local $self->{orig_content};
my $ret= "(dump not available)";
eval {
require Data::Dumper;
$ret= Data::Dumper->new(\@_)->Indent(1)->Sortkeys(1)->Useqq(1)->Dump();
};
return $ret;
}
my $has_storable;
# same story here, in miniperl we use slow perl code,
# in real perl we can use Storable and speed things up.
BEGIN { eval "use Storable; \$has_storable=1;" }
# recursively copy an AoAoA...
sub copy_aoa {
my ($aoa)= @_;
if ($has_storable) {
return Storable::dclone($aoa);
}
else {
return _copy_aoa($aoa);
}
}
sub _copy_aoa {
my ($thing)= @_;
if (ref $thing) {
return [ map { ref($_) ? _copy_aoa($_) : $_ } @$thing ];
}
else {
return $thing;
}
}
# return the number characters that should go in between a '#' and
# the name of a c preprocessor directive. Returns 0 spaces for level
# 0, and 2 * ($level - 1) + 1 spaces for the rest. (1,3,5, etc)
# This might sound weird, but consider these are tab *stops* and the
# '#' is included in the total. which means indents of 2, 4, 6 etc.
sub indent_chars {
my ($self, $level)= @_;
my $ind= "";
$ind .= " " if $level;
$ind .= " " x ($level - 1) if $level > 1;
return $ind;
}
# we use OO to store state, etc.
sub new {
my ($class, %args)= @_;
$args{add_commented_expr_after} //= 10;
$args{max_width} //= 78;
$args{min_break_width} //= 70;
return bless \%args,;
}
# this parses the expression into an array of tokens
# this is somewhat crude, we could do this incrementally
# if we wanted and avoid the overhead. but it makes it
# easier to debug the tokenizer.
sub _tokenize_expr {
my ($self, $expr)= @_;
delete $self->{tokens};
delete $self->{parse_tree};
$self->{original_expr}= $expr;
my @tokens;
while ($expr =~ s/$tokenize_pat//xs) {
push @tokens, {%+} if defined $+{'term'};
}
$self->{tokens}= \@tokens;
warn $self->dd($self) if $self->{debug};
if (length $expr) {
confess "Failed to tokenize_expr: $expr\n";
}
return \@tokens;
}
sub _count_ops {
my ($self, $term)= @_;
my $count= 0;
$count++ while $term =~ m/(?: \|\| | \&\& | \? )/gx;
return $count;
}
# sort terms in an expression in a way that puts things
# in a sensible order. Anything starting with PERL_IN_
# should be on the left in alphabetical order. Digits
# should be on the right (eg 0), and ties are resolved
# by stripping non-alpha-numerc, thus removing underbar
# parens, spaces, logical operators, etc, and then by
# lc comparison of the result.
sub _sort_terms {
my $self= shift;
my (@terms)= map {
[
$_, # 0: raw
lc($_) =~ s/[^a-zA-Z0-9]//gr, # 1: "_" stripped and caseless
$_ =~ m/PERL_IN_/ ? 1 : 0, # 2: PERL_IN_ labeled define
$_ =~ m/^\d/ ? 1 : 0, # 3: digit
$_ =~ m/DEBUGGING/ ? 1 : 0, # 4: DEBUGGING?
$self->_count_ops($_), # 5: Number of ops (||, &&)
]
} @_;
my %seen;
#start-no-tidy
@terms= map { $seen{ $_->[0] }++ ? () : $_->[0] }
sort {
$a->[5] <=> $b->[5] || # least number of ops
$b->[2] <=> $a->[2] || # PERL_IN before others
$a->[3] <=> $b->[3] || # digits after others
$a->[4] <=> $b->[4] || # DEBUGGING after all else
$a->[1] cmp $b->[1] || # stripped caseless cmp
lc($a->[0]) cmp lc($b->[0]) || # caseless cmp
$a->[0] cmp $b->[0] || # exact cmp
0
} @terms;
#end-no-tidy
return @terms;
}
# normalize a condition expression by parsing it and then stringifying
# the parse tree.
sub tidy_cond {
my ($self, $expr)= @_;
my $ret= $self->{_tidy_cond_cache}{$expr} //= do {
$self->parse_expr($expr) if defined $expr;
my $text= $self->_pt_as_str();
$text;
};
$self->{last_expr}= $ret;
return $ret;
}
# convert a parse tree structure to a string recursively.
#
# Parse trees are currently made up of arrays, with the count
# of items in the object determining the type of op it represents.
# 1 argument: literal value of some sort.
# 2 arguments: unary operator: 0 slot is the operator, 1 is a parse tree
# : ternary: 0 slot holds '?', 1 is an array holding three
# parse trees: cond, true, false
# 3 arguments or more: binary operator. 0 slot is the op. 1..n are parse trees
# : note, this is multigate for commutative operators like
# : "+", "*", "&&" and "||", so an expr
# : like "A && B && !C" would be represented as:
# : [ "&&", ["A"], ["B"], [ "!",["C"] ] ]
#
sub _pt_as_str {
my ($self, $node, $parent_op, $depth)= @_;
$node ||= $self->{parse_tree}
or confess "No parse tree?";
$depth ||= 0;
if (@$node == 1) {
# its a literal
return $node->[0];
}
elsif (@$node == 2) {
# is this a ternary or an unop?
if ($node->[0] eq '?') {
# ternary, the three "parts" are tucked away in
# an array in the payload slot
my $expr=
$self->_pt_as_str($node->[1][0], "?", $depth + 1) . " ? "
. $self->_pt_as_str($node->[1][1], "?", $depth + 1) . " : "
. $self->_pt_as_str($node->[1][2], "?", $depth + 1);
# stick parens on if this is a subexpression
$expr= "( " . $expr . " )" if $depth;
return $expr;
}
else {
if ( $node->[0] eq "!"
and @{ $node->[1] } == 2
and $node->[1][0] eq "!")
{
# normalize away !! in expressions.
return $self->_pt_as_str($node->[1][1], $parent_op, $depth);
}
# unop - the payload is a optree
return $node->[0]
. $self->_pt_as_str($node->[1], $node->[0], $depth + 1);
}
}
# if we get here we are dealing with a binary operator
# the nodes are not necessarily binary, as we "collect"
# the terms into a list, thus: A && B && C && D -> ['&&',A,B,C,D]
my ($op, @terms)= @$node;
# convert the terms to strings
@terms= map { $self->_pt_as_str($_, $op, $depth + 1) } @terms;
# sort them to normalize the subexpression
my $expr=
join " $op ", $associative{$op}
? $self->_sort_terms(@terms)
: @terms;
# stick parens on if this is a subexpression
$expr= "( " . $expr . " )" if $depth and !$cmpop{$op};
# and we are done.
return $expr;
}
# Returns the precedence of an operator, returns 0 if there is no token
# or the next token is not an op, or confesss if it encounters an op it does not
# know.
sub _precedence {
my $self= shift;
my $token= shift // return 0;
my $op= (ref $token ? $token->{op} : $token) // return 0;
return $precedence{$op} // confess "Unknown op '$op'";
}
# entry point into parsing the tokens, checks that we actually parsed everything
# and didnt leave anything in the token stream (possible from a malformed expression)
# Performs some minor textual cleanups using regexes, but then does a proper parse
# of the expression.
sub parse_expr {
my ($self, $expr)= @_;
if (defined $expr) {
$expr =~ s/\s*\\\n\s*/ /g;
$expr =~ s/defined\s+(\w+)/defined($1)/g;
$self->_tokenize_expr($expr);
}
my $ret= $self->_parse_expr();
if (@{ $self->{tokens} }) {
# if all was well with parsing we should not get here.
confess "Unparsed tokens: ", $self->dd($self->{tokens});
}
$self->{parse_tree}= $ret;
return $ret;
}
# this is just a wrapper around _parse_expr_assoc() which handles
# parsing an arbitrary expression.
sub _parse_expr {
my ($self)= @_;
return $self->_parse_expr_assoc($self->_parse_expr_primary(), 1);
}
# This handles extracting from the token stream
# - simple literals
# - unops (assumed to be right associative)
# - parens (which reset the precedence acceptable to the parser)
#
sub _parse_expr_primary {
my ($self)= @_;
my $tokens= $self->{tokens}
or confess "No tokens in _parse_expr_primary?";
my $first= $tokens->[0]
or confess "No primary?";
if ($first->{paren} and $first->{paren} eq "(") {
shift @$tokens;
my $expr= $self->_parse_expr();
$first= $tokens->[0];
if (!$first->{paren} or $first->{paren} ne ")") {
confess "Expecting close paren", $self->dd($tokens);
}
shift @$tokens;
return $expr;
}
elsif ($first->{op} and $unop{ $first->{op} }) {
my $op_token= shift @$tokens;
return [ $op_token->{op}, $self->_parse_expr_primary() ];
}
elsif (defined $first->{literal}) {
shift @$tokens;
return [ $first->{literal} ];
}
else {
die sprintf
"Unexpected token '%s', expecting literal, unary, or expression.\n",
$first->{term};
}
}
# This is the heart of the expression parser. It uses
# a pair of nested loops to avoid excessive recursion during parsing,
# which should be a bit faster than other strategies. It only should
# recurse when the precedence level changes.
sub _parse_expr_assoc {
my ($self, $lhs, $min_precedence)= @_;
my $tokens= $self->{tokens}
or confess "No tokens in _parse_expr_assoc";
my $la= $tokens->[0]; # lookahead
my $la_pr= $self->_precedence($la); # lookahead precedence
while ($la && $la_pr >= $min_precedence) {
my $op_token= shift @$tokens;
my $op_pr= $la_pr; # op precedence
if ($op_token->{op} eq "?") {
my $mid= $self->_parse_expr();
if (@$tokens and $tokens->[0]{op} and $tokens->[0]{op} eq ":") {
shift @$tokens;
my $tail= $self->_parse_expr();
return [ '?', [ $lhs, $mid, $tail ] ];
}
confess "Panic: expecting ':'", $self->dd($tokens);
}
my $rhs;
eval { $rhs= $self->_parse_expr_primary(); }
or die "Error in $op_names{$op_token->{op}} expression: $@";
$la= $tokens->[0];
$la_pr= $self->_precedence($la);
while (
$la_pr > $op_pr || # any and larger
( $is_right_assoc{ $op_token->{op} }
and $la_pr == $op_pr) # right and equal
) {
my $new_precedence= $op_pr + ($la_pr > $op_pr ? 1 : 0);
$rhs= $self->_parse_expr_assoc($rhs, $new_precedence);
$la= $tokens->[0];
$la_pr= $self->_precedence($la);
}
if ( @$lhs >= 3
&& $lhs->[0] eq $op_token->{op}
&& $commutative{ $op_token->{op} })
{
push @$lhs, $rhs;
}
else {
my @lt= ($lhs);
my @rt= ($rhs);
# if we have '( a && b ) && ( c && d)'
# turn it into 'a && b && c && d'
if (@$lhs > 2 && $lhs->[0] eq $op_token->{op}) {
(undef,@lt)= @$lhs; # throw away op.
}
if (@$rhs > 2 && $rhs->[0] eq $op_token->{op}) {
(undef,@rt)= @$rhs; # throw away op.
}
$lhs= [ $op_token->{op}, @lt, @rt ];
}
}
return $lhs;
}
#entry point for normalizing and if/elif statements
#returns the line and condition in normalized form.
sub normalize_if_elif {
my ($self, $line, $line_info)= @_;
if (my $dat= $self->{cache_normalize_if_elif}{$line}) {
return $dat->{line}, $dat->{cond};
}
my ($cond);
eval {
($line, $cond)= $self->_normalize_if_elif($line);
1;
} or die sprintf "Error at line %d\nLine %d: %s\n%s",
($line_info->start_line_num()) x 2, $line, $@;
$self->{cache_normalize_if_elif}{$line}= { line => $line, cond => $cond };
return ($line, $cond);
}
#guts of the normalize_if_elif() - cleans up the line, extracts
#the condition, and then tidies it with tidy_cond().
sub _normalize_if_elif {
my ($self, $line)= @_;
my $nl= "";
$nl= $1 if $line =~ s/(\n+)\z//;
$line =~ s/\s+\z//;
my @comment;
push @comment, $1 while $line =~ s!\s*(/\*.*?\*/)\z!!;
$line =~ s/defined\s*\(\s*(\w+)\s*\)/defined($1)/g;
$line =~ s/!\s+defined/!defined/g;
if ($line =~ /^#((?:el)?if)(n?)def\s+(\w+)/) {
my $if= $1;
my $not= $2 ? "!" : "";
$line= "#$if ${not}defined($3)";
}
$line =~ s/#((?:el)?if)\s+//
or confess "Bad cond: $line";
my $if= $1;
$line =~ s/!\s+/!/g;
my $old_cond= $line;
my $cond= $self->tidy_cond($old_cond);
warn "cond - $old_cond\ncond + $cond\n"
if $old_cond ne $cond and $self->{debug};
$line= "#$if $cond";
$line .= " " . join " ", reverse @comment if @comment;
$line .= $nl;
return ($line, $cond);
}
# parses a text buffer as though it was a file on disk
# calls parse_fh()
sub parse_text {
my ($self, $text)= @_;
local $self->{parse_source}= "(buffer)";
open my $fh, "<", \$text
or die "Failed to open buffer for read: $!";
return $self->parse_fh($fh);
}
# takes a readable filehandle and parses whatever contents is
# returned by reading it. Returns an array of HeaderLine objects.
# this is the main routing for parsing a header file.
sub parse_fh {
my ($self, $fh)= @_;
my @lines;
my @cond;
my @cond_line;
my $last_cond;
local $self->{parse_source}= $self->{parse_source} || "(unknown)";
my $cb= $self->{pre_process_content};
$self->{orig_content}= "";
my $line_num= 1;
while (defined(my $line= readline($fh))) {
my $start_line_num= $line_num++;
$self->{orig_content} .= $line;
while ($line =~ /\\\n\z/ or $line =~ m</\*(?:(?!\*/).)*\s*\z>s) {
defined(my $read_line= readline($fh))
or last;
$self->{orig_content} .= $read_line;
$line_num++;
$line .= $read_line;
}
while ($line =~ m!/\*(.*?)(\*/|\z)!gs) {
my ($inner, $tail)= ($1, $2);
if ($tail ne "*/") {
confess
"Unterminated comment starting at line $start_line_num\n";
}
elsif ($inner =~ m!/\*!) {
confess
"Nested/broken comment starting at line $start_line_num\n";
}
}
my $raw= $line;
my $type= "content";
my $sub_type= "text";
my $level= @cond;
my $do_pop= 0;
my $flat= $line;
$flat =~ s/\s*\\\n\s*/ /g;
$flat =~ s!/\*.*?\*/! !gs;
$flat =~ s/\s+/ /g;
$flat =~ s/\s+\z//;
$flat =~ s/^\s*#\s*/#/g;
my $line_info=
HeaderLine->new(start_line_num => $start_line_num, raw => $raw);
my $do_cond_line;
if ($flat =~ /^#/) {
if ($flat =~ m/^(#(?:el)?if)(n?)def\s+(\w+)/) {
my $if= $1;
my $not= $2 ? "!" : "";
my $sym= $3;
$flat =~
s/^(#(?:el)?if)(n?)def\s+(\w+)/$if ${not}defined($sym)/;
}
my $cond; # used in various expressions below
if ($flat =~ /^#endif/) {
if (!@cond) {
confess "Not expecting $flat";
}
$do_pop= 1;
$level--;
$type= "cond";
$sub_type= "#endif";
}
elsif ($flat =~ /^#if\b/) {
($flat, $cond)= $self->normalize_if_elif($flat, $line_info);
push @cond, [$cond];
push @cond_line, $line_info;
$type= "cond";
$sub_type= "#if";
}
elsif ($flat =~ /^#elif\b/) {
if (!@cond) {
confess "No if for $flat";
}
$level--;
($flat, $cond)= $self->normalize_if_elif($flat, $line_info);
$cond[-1][-1]= $self->tidy_cond("!($cond[-1][-1])");
$cond_line[-1]= $line_info;
push @{ $cond[-1] }, $cond;
$type= "cond";
$sub_type= "#elif";
}
elsif ($flat =~ /^#else\b/) {
if (!@cond) {
confess "No if for $flat";
}
$level--;
$cond[-1][-1]= $self->tidy_cond("!($cond[-1][-1])");
$cond_line[-1]= $line_info;
$type= "cond";
$sub_type= "#else";
}
elsif ($flat =~ /#undef/) {
$type= "content";
$sub_type= "#undef";
}
elsif ($flat =~ /#pragma\b/) {
$type= "content";
$sub_type= "#pragma";
}
elsif ($flat =~ /#include\b/) {
$type= "content";
$sub_type= "#include";
}
elsif ($flat =~ /#define\b/) {
$type= "content";
$sub_type= "#define";
}
elsif ($flat =~ /#error\b/) {
$type= "content";
$sub_type= "#error";
}
else {
confess "Do not know what to do with $line";
}
if ($type eq "cond") {
# normalize conditional lines
$line= $flat;
$last_cond= $line_info;
}
}
$line =~ s/\n?\z/\n/;
%$line_info= (
cond => copy_aoa(\@cond),
type => $type,
sub_type => $sub_type,
raw => $raw,
flat => $flat,
line => $line,
level => $level,
source => $self->{parse_source},
start_line_num => $start_line_num,
n_lines => $line_num - $start_line_num,
);
push @lines, $line_info;
if ($do_pop) {
$line_info->{inner_lines}=
$line_info->start_line_num - $cond_line[-1]->start_line_num;
pop @cond;
pop @cond_line;
}
if ($type eq "content" and $cb) {
$cb->($self, $lines[-1]);
}
}
if (@cond_line) {
my $msg= "Unterminated conditional block starting line "
. $cond_line[-1]->start_line_num();
$msg .=
" with last conditional operation at line "
. $last_cond->start_line_num()
if $cond_line[-1] != $last_cond;
confess $msg;
}
$self->{lines}= \@lines;
return \@lines;
}
# returns the last lines we parsed.
sub lines { $_[0]->{lines} }
# assuming a line looks like an embed.fnc entry parse it
# and normalize it, and create and EmbedLine object from it.
sub tidy_embed_fnc_entry {
my ($self, $line_data)= @_;
my $line= $line_data->{line};
return $line if $line =~ /^\s*:/;
return $line unless $line_data->{type} eq "content";
return $line unless $line =~ /\|/;
$line =~ s/\s*\\\n/ /g;
$line =~ s/\s+\z//;
($line)= expand($line);
my ($flags, $ret, $name, @args)= split /\s*\|\s*/, $line;
my %flag_seen;
$flags= join "", grep !$flag_seen{$_}++, sort split //, $flags;
if ($flags =~ s/^#//) {
$flags .= "#";
}
if ($flags eq "#") {
die "Not allowed to use only '#' for flags"
. "in 'embed.fnc' at line $line_data->{start_line_num}";
}
if (!$flags) {
die "Missing flags in function definition"
. " in 'embed.fnc' at line $line_data->{start_line_num}\n"
. "Did you a forget a line continuation on the previous line?\n";
}
for ($ret, @args) {
s/(\w)\*/$1 */g;
s/\*\s+(\w)/*$1/g;
s/\*const/* const/g;
}
my $head= sprintf "%-8s|%-7s", $flags, $ret;
$head .= sprintf "|%*s", -(31 - length($head)), $name;
if (@args and length($head) > 32) {
$head .= "\\\n";
$head .= " " x 32;
}
foreach my $ix (0 .. $#args) {
my $arg= $args[$ix];
$head .= "|$arg";
$head .= "\\\n" . (" " x 32) if $ix < $#args;
}
$line= $head . "\n";
if ($line =~ /\\\n/) {
my @lines= split /\s*\\\n/, $line;
my $len= length($lines[0]);
$len < length($_) and $len= length($_) for @lines;
$len= int(($len + 7) / 8) * 8;
$len= 72 if $len < 72;
$line= join("\\\n",
(map { sprintf "%*s", -$len, $_ } @lines[ 0 .. $#lines - 1 ]),
$lines[-1]);
}
($line)= unexpand($line);
$line_data->{embed}= EmbedLine->new(
flags => $flags,
return_type => $ret,
name => $name,
args => \@args,
);
$line =~ s/\s+\z/\n/;
$line_data->{line}= $line;
return $line;
}
# line up the text in a multiline string by a given $fragment
# of text, inserting whitespace in front or behind the $fragment
# to get the text to line up. Returns the text. This is wrapped
# by line_up() and is used to wrap long conditions and comments
# in the generated code.
sub _line_up_frag {
my ($self, $str, $fragment)= @_;
die "has tabs?!" if $str =~ /\t/;
my @lines= split /\n/, $str;
my $changed= 1;
while ($changed) {
$changed= 0;
foreach my $ix (0 .. $#lines - 1) {
my $f_index= 0;
my $n_index= 0;
while (1) {
$f_index= index($lines[$ix], $fragment, $f_index);
$n_index= index($lines[ $ix + 1 ], $fragment, $n_index);
if ($f_index == -1 or $n_index == -1) {
last;
}
if ($f_index < $n_index) {
my $f_idx= $f_index;
$f_idx-- while substr($lines[$ix], $f_idx, 1) ne " ";
substr($lines[$ix], $f_idx, 0, " " x ($n_index - $f_index));
$changed++;
last;
}
elsif ($n_index < $f_index) {
my $n_idx= $n_index;
$n_idx-- while substr($lines[ $ix + 1 ], $n_idx, 1) ne " ";
substr($lines[ $ix + 1 ],
$n_idx, 0, " " x ($f_index - $n_index));
$changed++;
last;
}
$f_index++;
$n_index++;
}
}
}
my $ret= join "", map { "$_\n" } @lines;
return $ret;
}
sub _fixup_indent {
my ($self, $line)= @_;
my @lines= split /\n/, $line;
if ($lines[0]=~/^(#\s*\w+(?:\s*\/\*)?\s)(\s+)/) {
my $first_left_len = length $1;
while (1) {
my $ok = 1;
for (@lines) {
/^.{$first_left_len} /
or do { $ok = 0; last; };
}
if ($ok) {
s/^(.{$first_left_len}) /$1/ for @lines;
} else {
last;
}
}
}
if ($lines[0]=~/^(#\s*\w+\s+)\(/) {
my $len = length($1);
for my $idx (1..$#lines) {
$lines[$idx]=~s/^([ ]{$len})(\s+)(\()/$1$3$2/;
}
}
my $ret= join "", map { "$_\n" } @lines;
return $ret;
}
# this is the workhorse for _break_line_at_op().
sub __break_line_at_op {
my ($self, $limit, $line, $blank_prefix)= @_;
my @lines= ("");
while (length $line) {
my $part;
if ($line =~ s/^(.*?(?:\|\||&&)\s+)//) {
$part= $1;
}
else {
$part= $line;
$line= "";
}
if (length($lines[-1]) + length($part) < $limit) {
$lines[-1] .= $part;
}
else {
push @lines, $blank_prefix . $part;
}
}
return \@lines;
}
# Break a condition line into parts, while trying to keep the last
# token on each line being an operator like || or && or ? or : We try
# to keep each line at $limit characters, however, we also try to
# ensure that each line has the same number of operators on it such
# that across all the lines there are only two counts of operators (eg,
# we either way each line to have two operators on it, or 0, or 1 or 0,
# or 2 or 1, and so on.) If we cannot meet this requirement we reduce
# the limit by 1 and try again, until we meet the objective, or the
# limit ends up at 70 chars or less.
sub _break_line_at_op {
my ($self, $limit, $line, $blank_prefix)= @_;
my $lines;
while (1) {
$lines= $self->__break_line_at_op($limit, $line, $blank_prefix);
my %op_counts;
foreach my $line_idx (0 .. $#$lines) {
my $line= $lines->[$line_idx];
my $count= 0;
$count++ while $line =~ /(\|\||&&|\?|:)/g;
$op_counts{$count}++;
}
if ($limit <= $self->{min_break_width} || keys(%op_counts) <= 2) {
last;
}
$limit--;
}
s/\s*\z/\n/ for @$lines;
return join "", @$lines;
}
sub _max { # cant use Scalar::Util so we roll our own
my $max= shift;
$max < $_ and $max= $_ for @_;
return $max;
}
# take a condition, split into $type and $rest
# wrap it, and try to line up operators and defined() functions
# that it contains. This is rather horrible code, but it does a
# reasonable job applying the heuristics we need to lay our the
# conditions in a reasonable way.
sub _wrap_and_line_up_cond {
my ($self, $type, $rest)= @_;
my $limit= $self->{max_width};
# extract the expression part of the line, and normalize it, we do
# this here even though it might be duplicative as it is possible
# that the caller code has munged the expression in some way, and we
# might want to simplify the expression first. Eg:
# 'defined(FOO) && (defined(BAR) && defined(BAZ))' should be turned into
# 'defined(FOO) && defined(BAR) && defined(BAZ)' if possible.
my $rest_head= "";
my $rest_tail= "";
if ($rest =~ s!(if\s+)!!) {
$rest_head= $1;
}
if ($rest =~ s!(\s*/\*.*?\*/)\s*\z!! || $rest =~ s!(\s*\*/\s*)\z!!) {
$rest_tail= $1;
}
if ($rest) {
$rest= $self->tidy_cond($rest);
$rest= $rest_head . $rest . $rest_tail;
}
my $l= length($type);
my $line= $type;
$line .= $rest if length($rest);
my $blank_prefix= " " x $l;
# at this point we have a single line with the entire expression on it
# if it fits on one line we are done, we can return it right away.
if (length($line) <= $limit) {
$line =~ s/\s*\z/\n/;
return $line;
}
my $rest_copy= $rest;
my @fragments;
my $op_pat= qr/(?:\|\||&&|[?:])/;
# does the $rest contain a parenthesized group? If it does then
# there are a mixture of different ops being used, as if it was all
# the same opcode there would not be a parenthesized group.
# If it does then we handle it differently, and try to put the
# different parts of the expression on their own line.
if ($rest_copy =~ /$op_pat\s*\(/) {
my @parts;
while (length $rest_copy) {
if ($rest_copy =~ s/^(.*?$op_pat)(\s*!?\()/$2/) {
push @parts, $1;
} else {
#$rest_copy=~s/^\s+//;
push @parts, $rest_copy;
last;
}
}
$parts[0]= $type . $parts[0];
$parts[$_]= $blank_prefix . $parts[$_] for 1 .. $#parts;
foreach my $line (@parts) {
if (length($line) > $limit) {
$line= $self->_break_line_at_op($limit, $line, $blank_prefix);
}
}
s/\s*\z/\n/ for @parts;
$line= join "", @parts;
@fragments= ("defined", "||");
}
else {
# the expression consists of just one opcode type, so we can use
# simpler logic to break it apart with the objective of ensuring
# that the lines are similarly formed with trailing operators on
# each line but the last.
@fragments= ("||", "defined");
$line= $self->_break_line_at_op($limit, $type . $rest, $blank_prefix);
}
# try to line up the text on different lines. We stop after
# the first $fragment that modifies the text. The order
# of fragments we try is determined above based on the type
# of condition this is.
my $pre_line= $line;
foreach my $fragment (@fragments) {
$line= $self->_line_up_frag($line, $fragment);
last if $line ne $pre_line;
}
# if we have lined up by "defined" in _line_up_frag()
# then we may have " || defined(...)" type expressions