Repository navigation
Expand file tree
/
Copy pathreader.cpp
More file actions
1418 lines (1362 loc) · 44.7 KB
/
Copy pathreader.cpp
File metadata and controls
1418 lines (1362 loc) · 44.7 KB
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
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Mikael Zayenz Lagerkvist <lagerkvist@gecode.dev>
*
* Copyright:
* Mikael Zayenz Lagerkvist, 2026
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.dev
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
// Ported from gecode/instance/reader.cpp at Gecode commit
// 599f977b7855dba2a1a5f67db1892722372067d3.
#include "reader.hpp"
#include "eval.hpp"
#include "numbers.hpp"
#include "text.hpp"
#include <algorithm>
#include <climits>
#include <cstdint>
#include <optional>
#include <utility>
namespace iris::detail {
namespace {
/**
* Return the first column of row `i` of a stored triangle
*
* The triangle is upper if `upper` and includes the diagonal if `diag`.
*/
std::size_t triangle_from(bool upper, bool diag, std::size_t i) {
if (!upper)
return 0;
return diag ? i : i + 1;
}
/// Return the column after the last of row `i` of a stored triangle of an
/// `n` by `n` matrix (see triangle_from)
std::size_t triangle_to(bool upper, bool diag, std::size_t n, std::size_t i) {
if (upper)
return n;
return diag ? i + 1 : i;
}
/// Return a description of what read type `t` reads, for messages
String describe(ReadType t) {
switch (t) {
case ReadType::Int:
return "int";
case ReadType::Float:
return "float";
case ReadType::Num:
return "a number";
case ReadType::Word:
return "a word";
case ReadType::Rest:
return "the rest of the line";
case ReadType::Symbol:
return "a symbol";
}
std::unreachable();
}
/// Test whether values of read type `t` are strings
bool reads_strings(ReadType t) {
return (t == ReadType::Word) || (t == ReadType::Rest);
}
/// The bounds of a range type, evaluated
struct Range {
/// Lower bound, if any
std::optional<std::int64_t> lo;
/// Upper bound, included, if any
std::optional<std::int64_t> hi;
/// Test whether `v` is in the range
[[nodiscard]] bool contains(std::int64_t v) const {
return (!lo || (v >= *lo)) && (!hi || (v <= *hi));
}
/// Test whether there are bounds
[[nodiscard]] bool bounded() const { return lo || hi; }
};
/// A type with its range evaluated
struct Domain {
/// The type
const Type &type;
/// The range
Range range;
/// Return a description of the values, for messages
[[nodiscard]] String describe() const {
String d = detail::describe(type.read);
if (range.bounded())
d = "an int in " + (range.lo ? to_string(*range.lo) : "") + ".." +
(range.hi ? to_string(*range.hi) : "");
return type.name.empty() ? d : type.name + " (" + d + ")";
}
};
/// A value captured from a line
struct Capture {
/// The capture
const Pattern::Item *item;
/// The value
Value value;
/// Where its text starts in the line
std::size_t from;
/// Where its text ends in the line
std::size_t to;
};
/// What an interpreter returns
enum class Mode {
/// The data read (Specification §9.4)
Read,
/// The catalog of the instances (Specification §9.6)
Catalog
};
/// What a catalog keeps of an instance
struct Listing {
/// The name, or empty
String name;
/// The summary of the first rejection, or empty
String summary;
};
/// Interpreter running a reader spec on an input
class Interpreter : public Evaluator {
public:
/// Initialize to return `mode`
Interpreter(const SpecImpl &s, std::string_view text, String origin,
const ParamsImpl &p, Mode mode)
: Evaluator(s, text, std::move(origin)), params_(p), mode_(mode) {}
/// Add the names of the param statements in `b` to `out`
static void declared_params(const Block &b, Seq<String> &out) {
for (const Node<Stmt> &s : b) {
if (s->kind == Stmt::Kind::Param)
out.push_back(s->name);
if (s->kind == Stmt::Kind::Instances)
out.emplace_back("instance");
declared_params(s->body, out);
declared_params(s->orelse, out);
for (const Arm &a : s->arms)
declared_params(a.body, out);
}
}
/// Run the reader spec and return the data, or the catalog
DataImpl run() {
// A misspelt parameter would otherwise be ignored silently
Seq<String> known;
declared_params(spec.body, known);
for (const String &n : params_.names)
if (std::ranges::find(known, n) == known.end())
throw spec_error(ErrorCode::ParamUnknown,
"the spec has no parameter '" + n + "'", spec.origin);
// The whole input must be valid UTF-8 (Specification §4.10)
if (std::optional<std::size_t> bad = find_invalid_utf8(in.text)) {
in.advance(*bad);
throw input_error(ErrorCode::Utf8, "input is not valid UTF-8", in);
}
exec(spec.body);
spec_line = 0;
owner_line = 0;
// Reading stops after the selected instance
if (!trailing_ && !selected_ && in.skip_to_data())
throw input_error(ErrorCode::TrailingInput,
"unexpected input after the end of the spec: " +
quote(in.rest()),
in);
if (mode_ == Mode::Catalog)
return catalog_data();
DataImpl d;
for (Entry &e : frames[0])
if (!is_internal(e.name))
d.entries.push_back(std::move(e));
return d;
}
private:
/**
* Return the catalog (Specification §9.6): the number of instances, their
* names if all have one, and their first rejections if there are any
*
* Without an instances statement, the input is one instance.
*/
[[nodiscard]] DataImpl catalog_data() const {
DataImpl d;
const std::size_t n = listings_ ? listings_->size() : 1;
d.entries.push_back(
Entry{.name = "instances",
.value = Value::integer(static_cast<std::int64_t>(n))});
if (!listings_)
return d;
const Seq<Listing> &l = *listings_;
if (!l.empty() && std::ranges::none_of(
l, [](const Listing &x) { return x.name.empty(); }))
d.entries.push_back(
Entry{.name = "name", .value = strings(l, &Listing::name)});
if (std::ranges::any_of(
l, [](const Listing &x) { return !x.summary.empty(); }))
d.entries.push_back(
Entry{.name = "failed", .value = strings(l, &Listing::summary)});
return d;
}
/// Return the list of the `field` of each of `l`
static Value strings(const Seq<Listing> &l, String Listing::*field) {
Value v;
v.type = ValueType::String;
for (const Listing &x : l)
v.strings.push_back(x.*field);
v.end_list();
return v;
}
/// The parameters
const ParamsImpl ¶ms_;
/// What run returns
const Mode mode_;
/// The instances read for a catalog, or nothing without an instances
/// statement
std::optional<Seq<Listing>> listings_;
/// Row numbers of the active repeats
Seq<std::size_t> rows_;
/// Whether input after the reader spec is allowed
bool trailing_ = false;
/// Whether the parameter instance selects an instance
bool select_ = false;
/// The value of the parameter instance
String want_;
/// The number of the instance selected, unless selected by name
std::optional<std::int64_t> number_;
/// Number of the instance being read (0 if none)
std::size_t current_ = 0;
/// Frame of the instance being read
std::size_t instance_frame_ = 0;
/// The first rejection of the instance being read
std::optional<Error> deferred_;
/// The summary of that rejection, for a catalog
String deferred_summary_;
/// Whether the selected instance has been read
bool selected_ = false;
/// The ranges of the named types, by type statement
Seq<std::pair<const Stmt *, Range>> type_ranges_;
/// Where the last token read as a value starts
std::size_t token_start_ = 0;
/// Lists of finished repeat iterations, kept for their memory
Seq<Value> spare_;
/// Most lists kept in spare
static constexpr std::size_t max_spare = 8;
/// Account for `k` units of work that read no input, failing if that is
/// too much (Specification §10.2)
void work(std::uint64_t k) {
if (!budget.charge_idle(k))
fail(ErrorCode::Budget,
"too many repetitions or empty rows without reading input");
}
/*
* Reading
*/
/// Store `t` read as `type` in `v`, and return whether it fits
static bool convert(ReadType type, std::string_view t, Value &v) {
if (reads_strings(type)) {
v = Value::string(t);
return !t.empty();
}
if (type != ReadType::Float)
if (std::optional<std::int64_t> i = parse_int(t)) {
v = Value::integer(*i);
return true;
}
if (type != ReadType::Int)
if (std::optional<double> f = parse_float(t)) {
v = Value::real(*f);
return true;
}
return false;
}
/// Fail unless the string `t` read at position `from` of the input is
/// valid UTF-8 (Specification §4.10)
void valid(std::string_view t, std::size_t from) {
if (std::optional<std::size_t> bad = find_invalid_utf8(t)) {
// The value is on the current line
in.pos = from + *bad;
fail(ErrorCode::Utf8, "string value is not valid UTF-8");
}
}
/// Fail for want of `what` at the end of the input or the token there
[[noreturn]] void expected(const String &what) {
if (!in.skip_to_data())
fail(ErrorCode::ExpectedValue,
"expected " + what + ", found end of input");
fail(ErrorCode::ExpectedValue,
"expected " + what + ", found " + quote(in.peek()));
}
/**
* Read one value of `type` into `v`, and return whether there is one
*
* At the end of the input or a token that is not of the type, the
* position stays before it.
*/
bool scan(ReadType type, Value &v) {
if (!in.skip_to_data())
return false;
token_start_ = in.pos;
if (type == ReadType::Rest) {
std::string_view t = in.rest();
valid(t, token_start_);
v = Value::string(t);
in.to_eol();
return true;
}
std::string_view t = in.token();
if (convert(type, t, v)) {
if (type == ReadType::Word)
valid(t, token_start_);
return true;
}
in.pos = token_start_;
return false;
}
/// Read one value of `type`, described by `what`
Value scalar(ReadType type, const String &what) {
Value v(ValueType::Int);
if (!scan(type, v))
expected(what);
return v;
}
/// Read one value of domain `d`, without checking its range
Value scalar(const Domain &d) {
Value v(ValueType::Int);
if (!scan(d.type.read, v))
expected(d.describe());
return v;
}
/// Read an integer of domain `d`, which reads integers, without checking
/// its range
std::int64_t int_scalar(const Domain &d) {
std::int64_t x = 0;
if (!in.skip_to_data())
expected(d.describe());
token_start_ = in.pos;
if (!in.int_token(x))
expected(d.describe());
return x;
}
/// Test whether value `v` is in the range of domain `d`
static bool fits(const Domain &d, const Value &v) {
return (v.type != ValueType::Int) || d.range.contains(v.ints[0]);
}
/// Fail for the value from position `from` to `to` on the current line,
/// which is not in domain `d`
[[noreturn]] void outside(const Domain &d, std::size_t from, std::size_t to) {
std::string_view t = in.text.substr(from, to - from);
in.pos = from;
fail(ErrorCode::ExpectedValue,
"expected " + d.describe() + ", found " + quote(t));
}
/// Read one value of domain `d`
Value value(const Domain &d) {
Value v = scalar(d);
if (!fits(d, v))
outside(d, token_start_, in.pos);
return v;
}
/// Read one value of domain `d` and append it to the list `v`
void push(const Domain &d, Value &v) {
if ((d.type.read == ReadType::Int) && (v.type == ValueType::Int)) {
std::int64_t x = int_scalar(d);
if (!d.range.contains(x))
outside(d, token_start_, in.pos);
v.ints.push_back(x);
} else {
v.push(value(d));
}
}
/// Return the range of type `t`
Range range(const Type &t) {
if (t.named != nullptr) {
for (const auto &[s, r] : type_ranges_)
if (s == t.named)
return r;
fail(ErrorCode::TypeUndefined,
"the type '" + t.name + "' is not defined yet");
}
Range r;
if (t.lo)
r.lo = bound(*t.lo);
if (t.hi) {
r.hi = bound(*t.hi);
if (t.exclusive) {
r.hi = checked_sub(*r.hi, 1);
if (!r.hi)
fail(ErrorCode::IntegerOverflow,
"integer overflow in the upper bound of a range");
}
}
return r;
}
/// Return the value of the bound `e` of a range
std::int64_t bound(const Expr &e) {
// Ranges are evaluated for every value read, so common bounds such as 0
// and -n avoid making a value
if (e.kind == Expr::Kind::Int)
return e.int_value;
if ((e.kind == Expr::Kind::Unary) && (e.op == Expr::Op::Neg)) {
std::optional<std::int64_t> x = checked_neg(bound(*e.args[0]));
if (!x)
fail(ErrorCode::IntegerOverflow, "integer overflow in '-'");
return *x;
}
Value tmp(ValueType::Int);
const Value &v = ref(e, tmp);
if ((v.depth() > 0) || (v.type != ValueType::Int))
fail(ErrorCode::RangeBounds, "the bounds of a range must be integers");
return v.ints[0];
}
/// Read an array of domain `d` with dimensions `dims`
Value array(const Domain &d, const Seq<std::size_t> &dims) {
// Each factor is at most INT_MAX, so the product cannot overflow
std::uint64_t size = 1;
for (std::size_t n : dims) {
size *= n;
if (size > INT_MAX)
fail(ErrorCode::SizeLimit, "array is too large");
}
// Rows before an empty dimension cost memory without reading any input
if (size == 0) {
std::uint64_t rows = 1;
for (std::size_t k = 0; (k < dims.size()) && (dims[k] > 0); k++) {
rows *= dims[k];
work(rows);
}
}
Value v;
if (d.type.read == ReadType::Float)
v.type = ValueType::Float;
else if (d.type.read == ReadType::Word)
v.type = ValueType::String;
// Read the values before making the structure, so that a wrong count
// fails at the end of the input rather than on allocation
for (std::uint64_t i = 0; i < size; i++)
try {
push(d, v);
} catch (const ShapeError &e) {
fail(e, context.back().text);
}
v.shape(dims);
return v;
}
/**
* Read a symmetric `n` by `n` matrix of domain `d` stored in TSPLIB layout
* `f` with offset `o`
*
* The offset applies to the numbers read, not to the cells that only
* exist after mirroring.
*/
Value layout(const Domain &d, std::size_t n, std::size_t m, const String &f,
std::int64_t o) {
if (f == "FULL_MATRIX") {
Value v = array(d, {n, m});
offset(v, o);
return v;
}
if (n != m)
fail(ErrorCode::Layout, "layout " + f + " needs a square matrix");
// Column-wise upper equals row-wise lower for symmetric matrices
bool upper = false;
bool diag = false;
if ((f == "UPPER_ROW") || (f == "LOWER_COL")) {
upper = true;
} else if ((f == "LOWER_ROW") || (f == "UPPER_COL")) {
} else if ((f == "UPPER_DIAG_ROW") || (f == "LOWER_DIAG_COL")) {
upper = true;
diag = true;
} else if ((f == "LOWER_DIAG_ROW") || (f == "UPPER_DIAG_COL")) {
diag = true;
} else {
fail(ErrorCode::Layout, "unknown matrix layout " + quote(f));
}
if (static_cast<std::uint64_t>(n) * n > INT_MAX)
fail(ErrorCode::SizeLimit, "matrix is too large");
// Read the stored triangle, then mirror it into a full matrix
Value t;
if (d.type.read == ReadType::Float)
t.type = ValueType::Float;
for (std::size_t i = 0; i < n; i++)
for (std::size_t j = triangle_from(upper, diag, i);
j < triangle_to(upper, diag, n, i); j++)
push(d, t);
offset(t, o);
Value v;
v.type = t.type;
v.shape({n, n});
if (v.type == ValueType::Int)
v.ints.resize(n * n);
else
v.floats.resize(n * n);
std::size_t k = 0;
for (std::size_t i = 0; i < n; i++)
for (std::size_t j = triangle_from(upper, diag, i);
j < triangle_to(upper, diag, n, i); j++, k++)
if (v.type == ValueType::Int) {
v.ints[(i * n) + j] = t.ints[k];
v.ints[(j * n) + i] = t.ints[k];
} else {
v.floats[(i * n) + j] = t.floats[k];
v.floats[(j * n) + i] = t.floats[k];
}
return v;
}
/// Add `o` to every number in `v`
void offset(Value &v, std::int64_t o) {
for (std::int64_t &x : v.ints) {
std::optional<std::int64_t> r = checked_add(x, o);
if (!r)
fail(ErrorCode::IntegerOverflow,
"integer overflow when applying offset");
x = *r;
}
for (double &x : v.floats)
x += static_cast<double>(o);
}
/// Return the offset of statement `s` (0 if none)
std::int64_t offset(const Stmt &s) {
if (!s.offset)
return 0;
Value o = eval(*s.offset);
if ((o.depth() > 0) || (o.type != ValueType::Int))
fail(ErrorCode::OffsetType, "offset must be an integer");
return o.ints[0];
}
/// Store value `v` read by statement `s`, unless its name is _
void store(const Stmt &s, Value &&v) {
if (s.name != "_")
set(s.name, std::move(v));
}
/// Match pattern `p` against the rest of the current line, consuming it
bool match(const Pattern &p) {
Seq<Capture> caps;
if (!matches(p, caps))
return false;
take(caps);
return true;
}
/// Test whether `p` matches the rest of the current line, giving the
/// captures `caps`
bool matches(const Pattern &p, Seq<Capture> &caps) {
in.skip();
if (in.pos >= in.text.size())
return false;
std::string_view l = in.rest();
std::size_t c = 0;
for (std::size_t k = 0; k < p.items.size(); k++)
if (!match_item(p, k, l, c, caps))
return false;
while ((c < l.size()) && is_blank(l[c]))
c++;
return c == l.size();
}
/// Define the values `caps` captured from the current line, and consume
/// it
void take(const Seq<Capture> &caps) {
// Every string captured must be valid, even if it is not kept
for (const Capture &x : caps)
if (reads_strings(x.item->type.read))
valid(x.value.strings[0], in.pos + x.from);
// The captures can use each other in their ranges
for (const Capture &x : caps)
if (!x.item->text.empty() && (x.item->text != "_"))
set(x.item->text, Value(x.value));
for (const Capture &x : caps)
if (x.item->type.ranged()) {
Domain d{.type = x.item->type, .range = range(x.item->type)};
if (!fits(d, x.value))
outside(d, in.pos + x.from, in.pos + x.to);
}
in.to_eol();
}
/// Match item `k` of `p` at position `c` of line `l`
bool match_item(const Pattern &p, std::size_t k, std::string_view l,
std::size_t &c, Seq<Capture> &caps) {
using Item = Pattern::Item;
const Item &it = p.items[k];
switch (it.kind) {
case Item::Kind::Space: {
std::size_t c0 = c;
while ((c < l.size()) && is_blank(l[c]))
c++;
return !it.required || (c > c0) || (c == l.size());
}
case Item::Kind::Lit:
if (!l.substr(c).starts_with(it.text))
return false;
c += it.text.size();
return true;
case Item::Kind::Any:
c = l.size();
return true;
case Item::Kind::Var: {
String want = variable(it.text);
if (want.empty() || !l.substr(c).starts_with(want))
return false;
c += want.size();
return true;
}
case Item::Kind::Cap: {
// A word ends before a literal that follows it directly
char stop = 0;
if ((k + 1 < p.items.size()) && (p.items[k + 1].kind == Item::Kind::Lit))
stop = p.items[k + 1].text[0];
std::size_t c0 = c;
c = capture_end(it.type.read, l, c, stop);
std::string_view t = l.substr(c0, c - c0);
while (!t.empty() && is_blank(t.back()))
t.remove_suffix(1);
Capture x{.item = &it,
.value = Value(ValueType::Int),
.from = c0,
.to = c0 + t.size()};
if (!convert(it.type.read, t, x.value))
return false;
caps.push_back(std::move(x));
return true;
}
}
return false;
}
/// Return the value of variable `n` as text, for {$n} in a pattern
String variable(const String &n) {
const Value *v = lookup(n);
if (v == nullptr)
fail(ErrorCode::NameUndefined, "'" + n + "' is not defined yet");
if ((v->depth() == 0) && (v->type == ValueType::String))
return v->strings[0];
if ((v->depth() == 0) && (v->type == ValueType::Int))
return to_string(v->ints[0]);
fail(ErrorCode::PatternReference,
"'" + n + "' must be a string or an integer");
}
/// Return where a capture of `type` starting at `c` of `l` ends
static std::size_t capture_end(ReadType type, std::string_view l,
std::size_t c, char stop) {
switch (type) {
case ReadType::Rest:
return l.size();
case ReadType::Word:
while ((c < l.size()) && !is_blank(l[c]) && (l[c] != stop))
c++;
return c;
default:
// Numbers end where a following literal starts
return number_end(l, c, true, type != ReadType::Int);
}
}
void exec(const Block &b) {
for (const Node<Stmt> &s : b)
exec(*s);
}
void exec(const Stmt &s) {
spec_line = s.line;
owner_line = 0;
switch (s.kind) {
case Stmt::Kind::Comment:
in.comments.insert(in.comments.end(), s.words.begin(), s.words.end());
break;
case Stmt::Kind::Stop:
in.stops.insert(in.stops.end(), s.words.begin(), s.words.end());
break;
case Stmt::Kind::Tokens:
in.add_split(s.chars);
break;
case Stmt::Kind::Separators:
in.add_separators(s.chars);
break;
case Stmt::Kind::Trailing:
trailing_ = true;
break;
case Stmt::Kind::Param:
param(s);
break;
case Stmt::Kind::Read:
read(s);
break;
case Stmt::Kind::List:
list(s);
break;
case Stmt::Kind::Line:
line(s);
break;
case Stmt::Kind::Find:
find(s);
break;
case Stmt::Kind::Skip:
skip_lines(s);
break;
case Stmt::Kind::Expect:
expect(s);
break;
case Stmt::Kind::Index:
index(s);
break;
case Stmt::Kind::Repeat:
repeat(s);
break;
case Stmt::Kind::Sections:
sections(s);
break;
case Stmt::Kind::Instances:
instances(s);
break;
case Stmt::Kind::Type:
define_type(s);
break;
case Stmt::Kind::Let:
set(s.name, eval(*s.expr));
break;
case Stmt::Kind::If:
exec(truth(eval(*s.expr)) ? s.body : s.orelse);
break;
case Stmt::Kind::Check:
check(s);
break;
case Stmt::Kind::Each:
break;
}
}
/// type T = ...: fix the range of the type
void define_type(const Stmt &s) {
Range r = range(s.type);
for (auto &[t, x] : type_ranges_)
if (t == &s) {
x = r;
return;
}
type_ranges_.emplace_back(&s, r);
}
/**
* param x [= default]
*
* A given value has the type of the default. Without a default, it is an
* integer if possible, otherwise a float or a string.
*/
void param(const Stmt &s) {
Value d;
if (s.expr)
d = eval(*s.expr);
std::optional<std::string_view> v = params_.get(s.name);
if (!v) {
if (!s.expr)
fail(ErrorCode::ParamMissing,
"parameter '" + s.name + "' must be given");
set(s.name, std::move(d));
return;
}
if (s.expr && (d.type == ValueType::String)) {
set(s.name, Value::string(*v));
return;
}
if (!s.expr || (d.type == ValueType::Int))
if (std::optional<std::int64_t> i = parse_int(*v)) {
set(s.name, Value::integer(*i));
return;
}
if (!s.expr || (d.type == ValueType::Float))
if (std::optional<double> f = parse_float(*v)) {
set(s.name, Value::real(*f));
return;
}
if (!s.expr) {
set(s.name, Value::string(*v));
return;
}
fail(ErrorCode::ParamType,
"parameter '" + s.name + "' must be " +
(d.type == ValueType::Int ? "an integer" : "a number") + ", not " +
quote(*v));
}
/// x: type and x[d1][d2]...: type
void read(const Stmt &s) {
context.push_back(
Context{.text = s.name, .iteration = 0, .iterations = std::nullopt});
std::int64_t o = offset(s);
Domain d{.type = s.type, .range = range(s.type)};
if (s.dims.empty()) {
Value v = value(d);
offset(v, o);
store(s, std::move(v));
} else {
Seq<std::size_t> dims;
for (const Node<Expr> &e : s.dims)
dims.push_back(count(*e, "array size"));
if (s.type.read == ReadType::Symbol) {
store(s, symbols(s.type, dims[0], dims[1]));
} else if (s.expr) {
Value f = eval(*s.expr);
if ((f.depth() > 0) || (f.type != ValueType::String))
fail(ErrorCode::Layout, "matrix layout must be a string");
store(s, layout(d, dims[0], dims[1], f.strings[0], o));
} else {
Value v = array(d, dims);
offset(v, o);
store(s, std::move(v));
}
}
context.pop_back();
}
/// list x: type until (eol | terminator)
void list(const Stmt &s) {
context.push_back(
Context{.text = s.name, .iteration = 0, .iterations = std::nullopt});
Value v(ValueType::Int);
if (!spare_.empty()) {
v = std::move(spare_.back());
spare_.pop_back();
}
v.clear_list(s.type.read == ReadType::Float ? ValueType::Float
: s.type.read == ReadType::Word ? ValueType::String
: ValueType::Int);
Domain d{.type = s.type, .range = range(s.type)};
try {
if (s.until_eol)
list_line(d, v);
else
list_until(s, d, v);
} catch (const ShapeError &e) {
fail(e, s.name);
}
v.end_list();
offset(v, offset(s));
context.pop_back();
store(s, std::move(v));
}
/// Read the values of domain `d` on the rest of the line into `v`
void list_line(const Domain &d, Value &v) {
// The rest of the current line, or the next line if the current one is
// used up (skip_to_data() moves there)
if (!in.skip_to_line_data() && !in.skip_to_data())
fail(ErrorCode::ExpectedValue,
"expected a line of values, found end of input");
while (in.skip_to_line_data())
push(d, v);
}
/// Test whether the scalars `x` and `y` are numbers that are equal
static bool same_number(const Value &x, const Value &y) {
if ((x.type == ValueType::Int) && (y.type == ValueType::Int))
return x.ints[0] == y.ints[0];
if ((x.type == ValueType::String) || (y.type == ValueType::String))
return false;
return x.as_double() == y.as_double();
}
/// Read integers of domain `d` into `v` up to the terminator `stop`
void ints_until(const Domain &d, std::int64_t stop, Value &v) {
for (;;) {
// The terminator need not be in the range
std::int64_t x = int_scalar(d);
if (x == stop)
return;
if (!d.range.contains(x))
outside(d, token_start_, in.pos);
v.ints.push_back(x);
}
}
/// Read values of domain `d` into `v` up to the terminator of `s`
void list_until(const Stmt &s, const Domain &d, Value &v) {
if ((d.type.read == ReadType::Int) &&
(s.sentinel->kind == Expr::Kind::Int)) {
ints_until(d, s.sentinel->int_value, v);
return;
}
Value stop = eval(*s.sentinel);
if (stop.depth() > 0)
fail(ErrorCode::ListTerminator, "list terminator must be a single value");
// Words end at the token spelling an integer terminator
if ((s.type.read == ReadType::Word) && (stop.type == ValueType::Int))
stop = Value::string(to_string(stop.ints[0]));
if ((s.type.read == ReadType::Word) && (stop.type == ValueType::Float))
fail(ErrorCode::ListTerminator,
"a list of words needs a string or integer terminator");
if ((d.type.read == ReadType::Int) && (stop.type == ValueType::Int)) {
ints_until(d, stop.ints[0], v);
return;
}
for (;;) {
// A string terminator is compared before the token is read as a
// value, so "EOF" can end a list of numbers
if (stop.type == ValueType::String) {
if (!in.skip_to_data())
fail(ErrorCode::ExpectedToken,
"expected " + quote(stop.strings[0]) + ", found end of input");
if (in.peek() == stop.strings[0]) {
(void)in.token();
return;
}
}
// The terminator need not be in the range
Value x = scalar(d);
if (same_number(x, stop))
return;
if (!fits(d, x))
outside(d, token_start_, in.pos);
v.push(x);
}
}
/// line "pattern": the rest of the current line, or the next line if the
/// current one is used up, must match
void line(const Stmt &s) {
if (match(s.pattern))
return;
fail(ErrorCode::LineMatch,
"expected a line matching \"" + s.pattern.source + "\"" +
(in.pos >= in.text.size() ? ", found end of input" : ""));
}
/// find "pattern": skip lines until one matches
void find(const Stmt &s) {
while (!match(s.pattern)) {
if (!in.skip_to_data())
fail(ErrorCode::FindMatch,
"no line matching \"" + s.pattern.source + "\" found");
in.to_eol();
}
}
/// skip e lines
void skip_lines(const Stmt &s) {
std::size_t n = count(*s.expr, "number of lines");
for (std::size_t k = 0; k < n; k++) {
if (!in.skip_to_data())
fail(ErrorCode::SkipEof, "cannot skip a line at end of input");
in.to_eol();
}
}
/// expect "a" "b" ...: literal tokens
void expect(const Stmt &s) {
for (const String &w : s.words) {
if (!in.skip_to_data())
fail(ErrorCode::ExpectedToken,
"expected " + quote(w) + ", found end of input");
std::size_t p0 = in.pos;
std::string_view t = in.token();
if (t != w) {
in.pos = p0;
fail(ErrorCode::ExpectedToken,
"expected " + quote(w) + ", found " + quote(t));
}
}
}
/// index b: the row number of the innermost repeat, counted from b
void index(const Stmt &s) {
if (rows_.empty())
fail(ErrorCode::IndexContext, "'index' must be inside a repeat");