-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathCSV.rakumod
2053 lines (1778 loc) · 71.6 KB
/
CSV.rakumod
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
#!raku
use Slang::Tuxic;
use File::Temp;
use Text::IO::String;
my $VERSION = "0.022";
my constant $opt_v = %*ENV<RAKU_VERBOSE> // 1;
my constant %errors =
# Success
0 => "",
# Generic errors
1000 => "INI - constructor failed",
1001 => "INI - separator is equal to quote- or escape sequence",
1002 => "INI - allow_whitespace with escape or quoter SP or TAB",
1003 => "INI - \r or \n in main attr not allowed",
1004 => "INI - callbacks should be Hash or undefined",
# 1005 => "INI - EOL too long",
# 1006 => "INI - SEP too long",
# 1007 => "INI - QUOTE too long",
1008 => "INI - SEP undefined",
1010 => "INI - the header is empty",
1011 => "INI - the header contains more than one valid separator",
1012 => "INI - the header contains an empty field",
1013 => "INI - the header contains nun-unique fields",
# 1014 => "INI - header called on undefined stream",
# Syntax errors
1500 => "PRM - Invalid/unsupported argument(s)",
# For perl5 compatability. Due to strict typing, these do not apply
1501 => "PRM - The key attribute is passed as an unsupported type",
# Parse errors
2010 => "ECR - QUO char inside quotes followed by CR not part of EOL", # 5
2011 => "ECR - Characters after end of quoted field",
2012 => "EOF - End of data in parsing input stream",
2013 => "ESP - Specification error for fragments RFC7111",
2014 => "ENF - Inconsistent number of fields",
2015 => "ERW - Empty row",
# EIQ - Error Inside Quotes
2021 => "EIQ - NL or EOL inside quotes, binary off",
2022 => "EIQ - CR char inside quotes, binary off",
2023 => "EIQ - QUO sequence not allowed",
2024 => "EIQ - EOF cannot be escaped, not even inside quotes",
2025 => "EIQ - Loose unescaped escape",
2026 => "EIQ - Binary character inside quoted field, binary off",
2027 => "EIQ - Quoted field not terminated",
# EIF - Error Inside Field
# 2030 => "EIF - NL char inside unquoted verbatim, binary off",
2031 => "EIF - CR char is first char of field, not part of EOL",
2032 => "EIF - CR char inside unquoted, not part of EOL",
2034 => "EIF - Loose unescaped quote",
2035 => "EIF - Escaped EOF in unquoted field",
2036 => "EIF - ESC error",
2037 => "EIF - Binary character in unquoted field, binary off",
# Combine errors
2110 => "ECB - Binary character in Combine, binary off",
# IO errors
2200 => "EIO - print to IO failed. See errno",
# Hash-Ref errors
3001 => "EHR - Unsupported syntax for column_names ()",
3002 => "EHR - getline_hr () called before column_names ()",
3003 => "EHR - bind_columns () and column_names () fields count mismatch",
3004 => "EHR - bind_columns () only accepts refs to scalars",
3006 => "EHR - bind_columns () did not pass enough refs for parsed fields",
3007 => "EHR - bind_columns needs refs to writable scalars",
3008 => "EHR - unexpected error in bound fields",
3009 => "EHR - print (Hash) called before column_names ()",
3010 => "EHR - print (Hash) called with invalid arguments",
3100 => "EHK - Unsupported callback",
# Content errors
4001 => "PRM - The key does not exist as field in the data",
# csv CI
5000 => "CSV - Unsupported type for in",
5001 => "CSV - Unsupported type for out",
;
sub progress (*@y) {
my Str $x;
my @x = @y.map ( -> \x --> Str { x.Str } );
my $line = callframe (1).annotations<line>;
for (@x) {
s{^(\d+)$} = sprintf "%3d -", $_;
s:g{"True,"} = "True, ";
s:g{"new("} = "new (";
$x ~= $_ ~ " ";
}
$x.say;
} # progress
class RangeSet {
has Pair @!ranges;
method new (**@ranges) {
self.bless (:@ranges);
}
multi method add (Pair:D $p) { @!ranges.push: $p; }
multi method add (Range:D $r) { @!ranges.push: $r.min => $r.max; }
multi method add (Int:D $from) { @!ranges.push: $from => $from; }
multi method add (Int:D $from, Num:D $to) { @!ranges.push: $from => $to; }
multi method add (Int:D $from, Any:D $to) { @!ranges.push: $from => $to.Num; }
method min () { @!ranges>>.key.min }
method max () { @!ranges>>.value.max }
method in (Int:D $i) returns Bool {
for @!ranges -> $r {
$i >= $r.key && $i <= $r.value and return True;
}
False;
}
method to_list () {
gather {
my Int $max = -1;
for sort @!ranges -> $r {
my $from = ($r.key, $max + 1).max.Int;
my $to = $r.value == Inf ?? 65535 !! $r.value;
take (($from .. $to).Slip);
$r.value == Inf and last;
$max = ($max, $r.value).max.Int;
}
}
}
multi method list (Int $last) {
my Int @x;
my Int $max = -1;
for sort @!ranges -> $r {
my $from = ($r.key, $max + 1).max.Int;
my $to = ($r.value, $last - 1).min.Int;
$from > $to and next;
@x.append: $from .. $to;
$to >= $last || $r.value == Inf and last;
$max = ($max, $r.value).max.Int;
}
@x;
}
multi method list () {
my @x;
my Int $max = -1;
for sort @!ranges -> $r {
my $from = ($r.key, $max + 1).max.Int;
$from > $r.value and next;
@x.plan: $from .. $r.value;
$r.value == Inf and last;
$max = ($max, $r.value).max.Int;
}
@x.elems ?? @x !! ($.min .. $.max).grep (self);
}
}
class CellSet {
class CellRange {
has RangeSet $.row;
has RangeSet $.col;
method in (Int $row, Int $col) {
$!row && $!col && $!row.in ($row) && $!col.in ($col);
}
method show {
say "Row: ", $.row.to_list.raku;
say "Col: ", $.col.to_list.raku;
}
}
has CellRange @!cr;
method add (Int:D $tlr, Int:D $tlc,
Num $brr = $tlr.Num, Num $brc = $tlc.Num) {
my $row = RangeSet.new; $row.add ($tlr, $brr);
my $col = RangeSet.new; $col.add ($tlc, $brc);
@!cr.push: CellRange.new (:$row, :$col);
}
method in (Int:D $row, Int:D $col) returns Bool {
#return @!cr.any (*.in ($row, $col));
for @!cr -> $c {
$c.in ($row, $col) and return True;
}
False;
}
method show {
say "This CellSet contains there ranges:";
.show for @!cr;
say "-----------------------------------";
}
}
class CSV::Field {
has Bool $.is_quoted is rw is default(False);
has Str $.text is rw;
has Bool $!is_binary is default(False);
has Bool $!is_utf8 is default(False);
has Bool $!is_missing is default(False);
has Bool $!is_formula is default(False);
has Bool $!analysed is default(False);
multi method new (Str(Cool) $str) {
$str.defined ?? self.bless.add ($str) !! self.bless;
}
method Bool {
$!text.defined && $!text ne "0" && $!text ne "";
}
method Str {
# ?$!text ?? $!text !! $Text::CSV::undef_str
$!text;
}
method chars {
$!text.chars;
}
method Buf {
Buf.new ($!text.encode ("utf8-c8").list);
}
method Numeric {
$!text.defined
?? $!text ~~ m{^ <[0..9]> } ?? +$!text
!! $!text.unival.Int
!! Num;
}
method Real {
$!text.defined
?? $!text ~~ m{^ <[0..9]> } ?? +$!text
!! $!text.unival.Int
!! Real;
}
method gist {
$!text.defined or return "<undef>";
$!analysed or self.analyse;
my $s = $!is_quoted ?? "Q" !! "q";
$s ~= $!is_binary ?? "B" !! "b";
$s ~= $!is_utf8 ?? "8" !! "7";
$s ~= $!is_missing ?? "M" !! "m";
$s ~= $!is_formula ?? "=" !! "-";
$s ~ ":" ~ $!text.raku;
}
method add (Str $chunk) {
$!text ~= $chunk;
self;
}
method set_quoted () {
$!is_quoted = True;
$!text = "";
}
method undefined () {
!$!text.defined;
}
method analyse (Bool $force = !$!analysed) {
$force or return;
$!analysed = True;
!$!text.defined || $!text eq "" and
return; # Default is False for the rest
$!text.starts-with ("=") and
$!is_formula = True;
$!text ~~ m:m{^ <[ \x09, \x20 .. \x7E ]>+ $} or
$!is_binary = True;
$!text ~~ m:m{^ <[ \x00 .. \x7F ]>+ $} or
$!is_utf8 = True;
}
method is_binary () returns Bool {
$!analysed or self.analyse;
$!is_binary;
}
method is_utf8 () returns Bool {
$!analysed or self.analyse;
$!is_utf8;
}
method is_missing () returns Bool {
$!analysed or self.analyse;
$!is_missing;
}
method is_formula () returns Bool {
$!analysed or self.analyse;
$!is_formula;
}
method is-quoted () returns Bool { $.is_quoted; }
method is-binary () returns Bool { self.is_binary; }
method is-utf8 () returns Bool { self.is_utf8; }
method is-missing () returns Bool { self.is_missing; }
method is-formula () returns Bool { self.is_formula; }
method set-quoted () { self.set_quoted; }
} # CSV::Field
class Text::CSV { ... }
class CSV::Row does Iterable does Positional does Associative {
has Text::CSV $.csv;
has CSV::Field @.fields;
multi method new (@f) { @!fields = @f.map ( -> \x --> CSV::Field { CSV::Field.new (x) }); }
method Str () { $!csv ?? $!csv.string (@!fields) !! Str; }
method iterator () { @.fields.iterator; }
method hash () { hash $!csv.column_names Z=> @!fields».Str; }
method of () { CSV::Field; }
method AT-KEY (Str $k) { %($!csv.column_names Z=> @!fields){$k}; }
method strings () { @!fields».Str; }
method AT-POS (int $i) { @!fields.AT-POS ($i); }
method elems { @!fields.elems; }
method splice (*@args) { @!fields.splice (@args); }
method keys () { $!csv.column_names; }
method ASSIGN-POS (int $i, $v) {
@!fields.AT-POS ($i).text = $v.Str;
}
method ASSIGN-KEY (Str:D $k, $v) {
$!csv.column_names and
%($!csv.column_names Z=> @!fields){$k}.text = $v.Str;
}
multi method push (CSV::Field $f) { @!fields.push: $f; }
multi method push (Cool $f) { @!fields.push: CSV::Field.new ($f); }
multi method push (CSV::Row $r) { @!fields.append: $r.fields; }
method pop returns CSV::Field { @!fields.pop; }
}
class Text::CSV {
# Defaults are set in BUILD!
has Str $!eol;
has Str $!sep;
has Str $!quo;
has Str $!esc;
has Bool $!binary;
has Bool $!strict;
has Bool $!decode_utf8;
has Bool $!auto_diag;
has Int $!diag_verbose;
has Bool $!keep_meta;
has Int $!skip_empty_rows;
has Any $!skip_empty_rows_cb;
has Bool $!blank_is_undef;
has Bool $!empty_is_undef;
has Bool $!allow_whitespace;
has Bool $!allow_loose_quotes;
has Bool $!allow_loose_escapes;
has Bool $!allow_unquoted_escape;
has Bool $!always_quote;
has Bool $!quote_space;
has Bool $!escape_null;
has Bool $!quote_empty;
has Bool $!quote_binary;
has Bool $!build;
has Int $!record_number;
has Str $!formula;
has Str $!undef_str;
has Str $!comment_str;
has CSV::Row $!csv-row;
has Str @!ahead;
has Str @!cnames;
has IO::Handle $!io;
has Bool $!eof;
has Int @!types;
has Int @!crange;
has RangeSet $!rrange;
has Int $!strict_n;
has %!callbacks;
has Int $!errno;
has Int $!error_pos;
has Int $!error_field;
has Str $!error_input;
has Str $!error_message;
class CSV::Diag does Iterable does Positional is Exception is export {
has Int $.error is readonly = 0;
has Str $.message is readonly = %errors{$!error};
has Int $.pos is readonly;
has Int $.field is readonly;
has Int $.record is readonly;
has Str $.buffer is readonly;
method sink {
# See also src/core/Exception.pm - role X::Comp method gist
my $p = ($!pos // "Unknown").Str;
my $f = ($!field // "Unknown").Str;
my $r = ($!record // "Unknown").Str;
my $m =
"\e[34m" ~ $!message
~ "\e[0m" ~ " : error $!error @ record $r, field $f, position $p\n";
$!buffer.defined && $!buffer.chars && $!pos.defined &&
$!pos >= 0 && $!pos < $!buffer.chars and $m ~=
"\e[32m" ~ substr ($!buffer, 0, $!pos - 1)
~ "\e[33m" ~ "\x[23CF]"
~ "\e[31m" ~ substr ($!buffer, $!pos - 1)
~ "\e[0m\n";
# I do not want the "in method sink at ..." here, but there
# is no way yet to suppress that, so print instead of warn for now
print $m;
}
method Numeric { $!error; }
method Str { $!message; }
method iterator { $[ $!error, $!message, $!pos, $!field, $!record, $!buffer ].iterator; }
method hash { { errno => $!error,
error => $!message,
pos => $!pos,
field => $!field,
recno => $!record,
buffer => $!buffer,
}; }
# method AT-KEY (Str $k) { } NYI
method AT-POS (int $i) {
$i == 0 ?? $!error
!! $i == 1 ?? $!message
!! $i == 2 ?? $!pos
!! $i == 3 ?? $!field
!! $i == 4 ?? $!record
!! $i == 5 ?? $!buffer
!! Any;
}
}
# We need this to support aliasses and to catch unsupported attributes
submethod BUILD (*%init) {
# Defaults are disabled when BUILD is defined!
$!sep = ',';
$!quo = '"';
$!esc = '"';
$!binary = True;
$!decode_utf8 = True;
$!auto_diag = False;
$!strict = False;
$!diag_verbose = 0;
$!keep_meta = False;
$!skip_empty_rows = 0;
$!skip_empty_rows_cb = Any;
$!blank_is_undef = False;
$!empty_is_undef = False;
$!allow_whitespace = False;
$!allow_loose_quotes = False;
$!allow_loose_escapes = False;
$!allow_unquoted_escape = False;
$!always_quote = False;
$!quote_empty = False;
$!quote_space = True;
$!escape_null = False;
$!quote_binary = True;
$!formula = "none";
$!errno = 0;
$!error_pos = 0;
$!error_field = 0;
$!error_input = "";
$!error_message = "";
$!record_number = 0;
$!io = IO::Handle;
$!eof = False;
$!csv-row = CSV::Row.new (csv => self);
self!set-attributes (%init);
}
method !set-attributes (%init) {
$!build = True;
for keys %init -> $attr {
my @can = self.can (lc $attr) or self!fail (1000, "Unknown attribute '$attr'");
.(self, %init{$attr}) for @can;
}
$!build = False;
self!check_sanity;
}
method !fail (Int:D $errno, Int :$field, Str :$input, *@s) {
$!errno = $errno;
$!error_pos = 0;
$!error_message = %errors{$errno};
$!error_message ~= (":", @s).join (" ") if @s.elems;
$!error_field = $field // ($!csv-row.fields.elems + 1);
$!error_input = $input;
$!auto_diag and self.error_diag; # Void context
die self.error_diag; # Exception object
}
method set_diag (Int:D $errno, Int :$pos, Int :$fieldno, Int :$recno) {
$!errno = $errno;
$!error_message = %errors{$errno} // "";
$!error_input = "";
$pos.defined and $!error_pos = $pos;
$fieldno.defined and $!error_field = $fieldno;
$recno.defined and $!record_number = $recno;
}
method !check_sanity () {
$!build and return;
#say "Sanity check: S:"~$!sep~" Q:"~($!quo//"<undef>")~" E:"~($!esc//"<undef>")~" WS:"~$!allow_whitespace;
$!sep.defined or self!fail (1008);
$!sep eq "" and self!fail (1008);
$!quo.defined and $!quo eq $!sep and self!fail (1001);
$!esc.defined and $!esc eq $!sep and self!fail (1001);
$!sep ~~ m{<[\r\n]>} and self!fail (1003);
$!quo.defined and $!quo ~~ m{<[\r\n]>} and self!fail (1003);
$!esc.defined and $!esc ~~ m{<[\r\n]>} and self!fail (1003);
$!allow_whitespace or return;
$!sep ~~ m{ <[\ \t]> } and self!fail (1002);
$!quo.defined and $!quo ~~ m{ <[\ \t]> } and self!fail (1002);
$!esc.defined and $!esc ~~ m{ <[\ \t]> } and self!fail (1002);
$!esc.defined or $!escape_null = False;
}
# String attributes
method !a_str ($attr is rw, *@s) returns Str {
if (@s.elems == 1) {
my $x = @s[0];
$x.defined && $x ~~ Str && $x eq "" and $x = Str;
$attr = $x;
self!check_sanity;
}
$attr;
}
method sep (*@s) returns Str { self!a_str ($!sep, @s); }
method quo (*@s) returns Str { self!a_str ($!quo, @s); }
method esc (*@s) returns Str { self!a_str ($!esc, @s); }
method eol (*@s) returns Str {
@s[0] ~~ Array and @s = |@s[0]; # Allow *OUT.nl-out
self!a_str ($!eol, @s);
}
# Boolean attributes
method !a_bool ($attr is rw, *@s) returns Bool {
if (@s.elems == 1) {
$attr = ?@s[0];
self!check_sanity;
}
$attr;
}
method binary (*@s) returns Bool { self!a_bool ($!binary, @s); }
method always_quote (*@s) returns Bool { self!a_bool ($!always_quote, @s); }
method quote_empty (*@s) returns Bool { self!a_bool ($!quote_empty, @s); }
method quote_space (*@s) returns Bool { self!a_bool ($!quote_space, @s); }
method escape_null (*@s) returns Bool { self!a_bool ($!escape_null, @s); }
method quote_binary (*@s) returns Bool { self!a_bool ($!quote_binary, @s); }
method allow_loose_quotes (*@s) returns Bool { self!a_bool ($!allow_loose_quotes, @s); }
method allow_loose_escapes (*@s) returns Bool { self!a_bool ($!allow_loose_escapes, @s); }
method allow_unquoted_escape (*@s) returns Bool { self!a_bool ($!allow_unquoted_escape, @s); }
method allow_whitespace (*@s) returns Bool { self!a_bool ($!allow_whitespace, @s); }
method blank_is_undef (*@s) returns Bool { self!a_bool ($!blank_is_undef, @s); }
method empty_is_undef (*@s) returns Bool { self!a_bool ($!empty_is_undef, @s); }
method keep_meta (*@s) returns Bool { self!a_bool ($!keep_meta, @s); }
method auto_diag (*@s) returns Bool { self!a_bool ($!auto_diag, @s); }
method strict (*@s) returns Bool { self!a_bool ($!strict, @s); }
method eof () returns Bool { $!eof || $!errno == 2012; }
# Numeric attributes
method !a_num ($attr is rw, *@s) returns Int {
@s.elems == 1 and $attr = +@s[0];
$attr;
}
method record_number (*@s) returns Int { self!a_num ($!record_number, @s); }
# Numeric attributes, boolean allowed
method !a_bool_int ($attr is rw, *@s) returns Int {
if (@s.elems == 1) {
my $v = @s[0];
$attr = $v ~~ Bool ?? +$v !! $v.defined ?? $v eq "" ?? 0 !! +$v !! 0;
}
$attr;
}
method diag_verbose (*@s) returns Int { self!a_bool_int ($!diag_verbose, @s); }
method header (IO::Handle:D $fh,
Array :$sep-set = [< , ; >],
Any :$munge-column-names = "fc",
Bool :$set-column-names = True,
Bool :$detect-bom = True) { # unused for now
my Str $hdr = $fh.get or self!fail (1010);
# Determine separator conflicts
my %sep = $hdr.comb.Bag{$sep-set.list}:kv;
%sep.elems > 1 and self!fail (1011);
self.sep (%sep.keys);
given $munge-column-names {
when Callable | "none" { }
when "lc" { $hdr .= lc; }
when "uc" { $hdr .= uc; }
default { $hdr .= fc; }
}
self.getline ($hdr) or self!fail ($!errno);
my @row = self.strings or self!fail (1010);
$munge-column-names ~~ Callable and @row = @row.map ($munge-column-names);
@row.grep ("") and self!fail (1012);
if (my @dup = @row.repeated) { self!fail (1013, @dup.Bag.map ({ "{$_.key}({$_.value+1})" }).join: ", "); }
$set-column-names and self.column-names: @row;
self;
}
multi method formula () returns Str { $!formula; };
multi method formula (Str:U) returns Str { $!formula = "undef"; };
multi method formula (Str:D $x) returns Str {
my Str $f = $x.lc;
$f eq "" and $f = "empty";
$f ~~ "none" | "die" | "croak" | "diag" | "empty" | "undef" or self!fail (1500);
$!formula = $f;
};
multi method skip_empty_rows () returns Int { $!skip_empty_rows; };
multi method skip_empty_rows (Any:U) returns Int { self.skip_empty_rows ("false"); };
multi method skip_empty_rows (Bool $x) returns Int { self.skip_empty_rows (lc $x); };
multi method skip_empty_rows (Int:D $x
where 0 <= * <= 5) returns Int { self.skip_empty_rows (~$x); };
multi method skip_empty_rows (Callable:D $x) returns Int { $!skip_empty_rows_cb = $x; return $!skip_empty_rows = 6; }
multi method skip_empty_rows (Routine:D $x) returns Int { $!skip_empty_rows_cb = $x; return $!skip_empty_rows = 6; }
multi method skip_empty_rows (Str:D $x) returns Int {
my Str $f = $x.lc;
$!skip_empty_rows_cb = Any;
$f ~~ "0" | "" | "false" and return $!skip_empty_rows = 0;
$f ~~ "1" | "skip" | "true" and return $!skip_empty_rows = 1;
$f ~~ "2" | "stop" | "eof" and return $!skip_empty_rows = 2;
$f ~~ "3" | "die" and return $!skip_empty_rows = 3;
$f ~~ "4" | "croak" and return $!skip_empty_rows = 4;
$f ~~ "5" | "error" and return $!skip_empty_rows = 5;
self!fail (1500);
};
multi method undef_str () returns Str { $!undef_str; };
multi method undef_str (Any:U) returns Str { $!undef_str = Str; };
multi method undef_str (Str:D $x) returns Str { $!undef_str = $x };
multi method comment_str () returns Str { $!comment_str; };
multi method comment_str (Any:U) returns Str { $!comment_str = Str; };
multi method comment_str (Str:D $x) returns Str { $!comment_str = $x };
multi method column_names (Bool:D $ where *.not) returns Array[Str] { @!cnames = (); }
multi method column_names (Any:U) returns Array[Str] { @!cnames = (); }
multi method column_names (0) returns Array[Str] { @!cnames = (); }
multi method column_names (*@c) returns Array[Str] {
@c.elems and @!cnames = @c.map (*.Str);
@!cnames;
}
my %predef-hooks =
not_blank => { $^row.elems > 1 or $^row[0].defined && $^row[0] ne "" or $^row[0].is-quoted },
not_empty => { $^row.first: { .defined && $_ ne "" }},
filled => { $^row.first: { .defined && $_ ~~ /\S/ }};
%predef-hooks<not-blank> = %predef-hooks<not_blank>;
%predef-hooks<not-empty> = %predef-hooks<not_empty>;
method callbacks (*@cb is copy) {
if (@cb.elems == 1) {
my $b = @cb[0];
if ($b ~~ Hash || $b ~~ Pair) {
@cb = $b.kv;
}
else {
!$b.defined or
($b ~~ Bool || $b ~~ Int and !?$b) or
($b ~~ Str && $b ~~ m:i/^( reset | clear | none | 0 )$/) or
self!fail (1004);
%!callbacks = %();
@cb = ();
}
}
if (@cb.elems % 2) {
self!fail (1004);
}
if (@cb.elems) {
my %hooks;
for @cb -> $name, $callback {
my $hook = $callback;
$hook.defined && $hook ~~ Str && %predef-hooks{$hook}.defined and
$hook = %predef-hooks{$hook};
$name.defined && $name ~~ Str &&
$hook.defined && ($hook ~~ Routine || $hook ~~ Callable) or
self!fail (1004);
my Str $cb_name = $name;
$cb_name ~~ s{"-"} = "_";
$cb_name ~~ /^ after_parse
| before_print
| filter
| error
$/ or self!fail (3100, $name);
%hooks{$cb_name} = $hook;
}
%!callbacks = %hooks;
}
%!callbacks;
}
method !rfc7111ranges (Str:D $spec) returns RangeSet {
$spec eq "" and self!fail (2013);
my RangeSet $range = RangeSet.new;
for $spec.split (";") -> $r {
$r ~~ /^ (<[0..9]>+)["-"[(<[0..9]>+)||("*")]]? $/ or self!fail (2013);
my Int $from = +$0;
$from == 0 and self!fail (2013);
my Str $tos = ($1 // $from).Str;
$tos eq "0" and self!fail (2013);
my Num $to = $tos eq "*" ?? Inf !! (+$tos - 1).Num;
--$from <= $to or self!fail (2013);
$range.add ($from, $to);
}
$range;
}
multi method colrange (@cr) {
if (@cr.elems) {
my RangeSet $range = RangeSet.new;
$range.add ($_) for @cr;
@!crange = $range.to_list;
}
@!crange;
}
multi method colrange (Str $range) {
@!crange = ();
$range.defined and @!crange = self!rfc7111ranges ($range).to_list.flat;
@!crange;
}
multi method colrange () {
@!crange;
}
multi method rowrange (Str $range) returns RangeSet {
$!rrange = RangeSet;
$range.defined and $!rrange = self!rfc7111ranges ($range);
$!rrange;
}
multi method rowrange () returns RangeSet {
$!rrange;
}
method version () returns Str {
$VERSION;
}
method status () returns Bool {
!?$!errno;
}
method error_input () returns Str {
$!errno ?? $!error_input !! Str
}
method error_diag () returns CSV::Diag {
CSV::Diag.new (
error => $!errno,
message => $!error_message,
pos => $!error_pos,
field => $!error_field,
record => $!record_number,
buffer => $!error_input // "", # // for 2012
);
}
method is_quoted (Int:D $i) returns Bool {
$i >= 0 && $i < $!csv-row.fields.elems && $!csv-row.fields[$i].is_quoted;
}
method is_binary (Int:D $i) returns Bool {
$i >= 0 && $i < $!csv-row.fields.elems && $!csv-row.fields[$i].is_binary;
}
method is_utf8 (Int:D $i) returns Bool {
$i >= 0 && $i < $!csv-row.fields.elems && $!csv-row.fields[$i].is_utf8;
}
method is_missing (Int:D $i) returns Bool {
$i >= 0 && $i < $!csv-row.fields.elems && $!csv-row.fields[$i].is_missing;
}
method !accept-field (CSV::Field $f) returns Bool {
$!csv-row.push: $f;
True;
}
# combine : direction = 0
# parse : direction = 1
method !ready (Int:D $direction, CSV::Field $f) returns Bool {
if ($f.undefined) {
if ($direction) {
$!blank_is_undef || $!empty_is_undef or $f.add ("");
}
#return self!accept-field ($f);
}
elsif ($f.Str eq "") {
$!empty_is_undef and $f.text = Str;
#return self!accept-field ($f);
}
elsif ($!formula ne "none" && $f.is-formula) {
given $!formula {
when "die" { die "Formulas are forbidden"; }
when "croak" { die "Formulas are forbidden"; }
when "empty" { $f.text = ""; }
when "undef" { $f.text = Str; }
when "diag" {
my $fnum = $!csv-row.fields.elems + 1;
@!cnames.elems and $fnum ~= " (column: '@!cnames[$fnum - 1]')";
my $recn = $direction ?? " in record $!record_number" !! "";
warn "Field $fnum$recn contains formula '$f'\n";
}
}
$f.analyse (True);
}
# Postpone all other field attributes like is_binary and is_utf8
# till it is actually asked for unless it is required right now
# to fail
elsif (!$!binary and $f.Str ~~ m{ <[ \x00..\x08 \x0A..\x1F ]> }) {
$!error_pos = $/.from + 1 + $f.is_quoted;
$!errno = $f.is_quoted ??
$f.Str ~~ m{<[ \r ]>} ?? 2022 !!
$f.Str ~~ m{<[ \n ]>} ?? 2021 !! 2026 !! 2037;
$!error_field = $!csv-row.fields.elems + 1;
$!error_message = %errors{$!errno};
$!error_input = $f.Str;
$!auto_diag and self.error_diag;
return False;
}
self!accept-field ($f);
} # ready
method fields () {
@!crange ?? ($!csv-row.fields[@!crange]:v) !! $!csv-row.fields;
}
method strings () {
self.fields».Str.Array;
}
multi method string () returns Str {
#progress (0, $!csv-row.fields);
self.string ($!csv-row.fields);
}
multi method string (CSV::Field:D @fld) returns Str {
%!callbacks<before_print>.defined and
%!callbacks<before_print>.($!csv-row);
@fld or return Str;
my Str $s = $!sep;
my Str $q = $!quo;
my Str $e = $!esc;
my Str @f;
for @fld -> $f {
if (!$f.defined || $f.undefined) {
@f.push: "";
next;
}
my Str $t = $f.Str;
if ($t eq "") {
@f.push: $!always_quote || $!quote_empty ?? "$!quo$!quo" !! "";
next;
}
$t.subst-mutate (/( $q | $e )/, { "$e$0" }, :g);
$t.subst-mutate (/ \x[0] /, { $e ~ 0 }, :g) if $!escape_null;
$!always_quote
|| $t ~~ / $e | $s | \r | \n /
|| ($!quote_space && $t ~~ / " " | \t /)
|| ($!quote_binary && $t ~~ / <[ \x00..\x08 \x0a..\x1f \x7f..\xa0 ]> /)
and $t = "$q$t$q";
@f.push: $t;
}
#progress (0, @f);
#progress (1, my $x =
defined ($!eol)
?? join ( $!sep, @f ) ~ $!eol
!! join ( $!sep, @f )
#); $x
} # string
multi method combine (Capture $c) returns Bool {
self.combine ($c.list);
}
multi method combine (*@f) returns Bool {
self.combine (@f);
}
multi method combine (@f) returns Bool {
$!csv-row.fields = ();
my int $i = 0;
for flat @f -> $f {
$i = $i + 1;
my CSV::Field $cf;
if ($f.isa (CSV::Field)) {
$cf = $f;
}
else {
$cf = CSV::Field.new;
defined $f and $cf.add ($f.Str);
}
unless (self!ready (0, $cf)) {
$!errno = 2110;
$!error_input = $f.Str;
$!error_field = $i;
return False;
}
}
True;
}
method parse (Str $buffer) returns Bool {
my int $skip = 0;
my int $pos = 0;
my int $ppos = 0;
$!errno = 0;
my sub parse_error (Int $errno, Int :$fpos) {
$!errno = $errno;
$!error_pos = $fpos // $pos;
$!error_field = $!csv-row.fields.elems + 1;
$!error_message = %errors{$errno};
$!error_input = $buffer;
$!eof = $errno == 2012;
$!auto_diag && !($!io && $!eof) and self.error_diag;
False;
}
my sub chunks (Str $str, @re) {
$str.defined
?? $str.chars
?? $str.split (@re, :v, :skip-empty) # :ignoremark
!! ("")
!! ()
}
$!record_number = $!record_number + 1;
$opt_v > 4 and progress ($!record_number, $buffer.raku);
my CSV::Field $f = CSV::Field.new;
my $eol = $!eol // rx{ \r\n || \r || \n };
my Str $sep = $!sep;
my Str $quo = $!quo;
my Str $esc = $!esc;
my Bool $noe = !$esc.defined || ($quo.defined && $esc eq $quo);
my @eox = $!eol.defined ?? $eol !! ("\r\n", "\r", "\n");