Repository navigation
Expand file tree
/
Copy pathnl-reader-test.cc
More file actions
2032 lines (1747 loc) · 68.8 KB
/
Copy pathnl-reader-test.cc
File metadata and controls
2032 lines (1747 loc) · 68.8 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
/*
nl reader tests
Copyright (C) 2013 - 2016 AMPL Optimization Inc
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that the copyright notice and this permission notice and warranty
disclaimer appear in supporting documentation.
The author and AMPL Optimization Inc disclaim all warranties with
regard to this software, including all implied warranties of
merchantability and fitness. In no event shall the author be liable
for any special, indirect or consequential damages or any damages
whatsoever resulting from loss of use, data or profits, whether in an
action of contract, negligence or other tortious action, arising out
of or in connection with the use or performance of this software.
Author: Victor Zverovich
*/
#include "test-assert.h"
// Include the source file to test the implementation.
#include "../src/nl-reader.cc"
#include <cmath>
#include <climits>
#include <cstring>
#include "gmock/gmock.h"
#include "gtest-extra.h"
#include "mock-file.h"
#include "mock-problem-builder.h"
#include "util.h"
using mp::NLHeader;
using mp::ReadError;
using mp::ReadNLString;
using mp::internal::BinaryReader;
using mp::internal::EndiannessConverter;
using mp::internal::NLProblemBuilder;
namespace expr = mp::expr;
typedef mp::internal::TextReader<> TextReader;
using testing::_;
using testing::Field;
using testing::Return;
using testing::ReturnRef;
using testing::StrictMock;
using testing::Throw;
// Suppress a spurious warning
// "'<anonymous>' may be used uninitialized in this function" in GCC 4.4.
#if FMT_GCC_VERSION == 404
# pragma GCC diagnostic ignored "-Wuninitialized"
#endif
class MockNLHandler : public mp::NLHandler<MockNLHandler, TestExpr> {
public:
MOCK_METHOD1(OnUnhandled, void (const char *name));
MOCK_METHOD1(OnHeader, void (const NLHeader &h));
MOCK_METHOD3(OnVarBounds, void (int index, double lb, double ub));
MOCK_METHOD3(OnObj, void (int index, mp::obj::Type type, NumericExpr expr));
MOCK_CONST_METHOD1(NeedObj, bool (int obj_index));
MOCK_METHOD2(OnLinearObjExpr,
LinearObjHandler (int obj_index, int num_linear_terms));
MOCK_METHOD0(EndInput, void ());
};
TEST(NLStringRefTest, ConstructFromCString) {
const char *data = "foo";
const mp::NLStringRef s(data);
EXPECT_EQ(data, s.c_str());
EXPECT_EQ(3u, s.size());
}
TEST(NLStringRefTest, ConstructFromCStringAndSize) {
const char *data = "foo\0bar";
const mp::NLStringRef s(data, 7);
EXPECT_EQ(data, s.c_str());
EXPECT_EQ(7u, s.size());
EXPECT_ASSERT(mp::NLStringRef("foo", 2), "string not null-terminated");
}
TEST(NLStringRefTest, ConstructFromStdString) {
std::string str = "foo";
const mp::NLStringRef s(str);
EXPECT_EQ(0, s.c_str()[str.size()]);
EXPECT_EQ(str.c_str(), s.c_str());
EXPECT_EQ(str.size(), s.size());
}
TEST(ReaderBaseTest, ReadChar) {
struct TestReaderBase : mp::internal::ReaderBase {
TestReaderBase(mp::NLStringRef data, fmt::CStringRef name)
: ReaderBase(data, name) {}
};
TestReaderBase rb(" b", "test");
EXPECT_EQ(' ', rb.ReadChar());
EXPECT_EQ('b', rb.ReadChar());
EXPECT_EQ(0, rb.ReadChar());
TextReader reader("abc\nd", "test");
reader.ReadTillEndOfLine();
// ReadTillEndOfLine doesn't change token location
EXPECT_THROW_MSG(reader.ReportError("oops"), mp::ReadError,
"test:1:1: oops");
// while ReadChar does.
reader.ReadChar();
EXPECT_THROW_MSG(reader.ReportError("oops"), mp::ReadError,
"test:2:1: oops");
}
TEST(TextReaderTest, ReportError) {
TextReader reader("x\n", "test");
EXPECT_THROW_MSG(reader.ReportError("a{}c", 'b'), mp::ReadError,
"test:1:1: abc");
}
TEST(TextReaderTest, ReadTillEndOfLine) {
TextReader reader("ab cde\nfg h", "test");
reader.ReadTillEndOfLine();
EXPECT_THROW_MSG(reader.ReadTillEndOfLine(), mp::ReadError,
"test:2:5: expected newline");
}
TEST(TextReaderTest, ReadInt) {
TextReader reader(" 11 -22 ", "test");
EXPECT_EQ(11, reader.ReadInt<int>());
EXPECT_EQ(-22, reader.ReadInt<long>());
EXPECT_THROW_MSG(reader.ReadInt<int>(), mp::ReadError,
"test:1:12: expected integer");
}
TEST(TextReaderTest, ReadUInt) {
TextReader reader(" 11 -22 ", "test");
EXPECT_EQ(11, reader.ReadUInt());
EXPECT_THROW_MSG(reader.ReadUInt(), mp::ReadError,
"test:1:8: expected unsigned integer");
}
TEST(TextReaderTest, ReadDouble) {
TextReader reader(" 11 -2.2 ", "test");
EXPECT_EQ(11, reader.ReadDouble());
EXPECT_EQ(-2.2, reader.ReadDouble());
EXPECT_THROW_MSG(reader.ReadDouble(), mp::ReadError,
"test:1:13: expected double");
}
class MockLocale {
public:
MOCK_METHOD1(strtod, double (const char *&str));
};
TEST(TextReaderTest, ReadDoubleUsesCLocale) {
const char *str = "4.2";
mp::internal::TextReader<MockLocale> reader(str, "test.nl");
EXPECT_CALL(reader.locale(), strtod(str))
.WillOnce(testing::DoAll(testing::SetArgReferee<0>(str + 1), Return(1.23)));
EXPECT_EQ(1.23, reader.ReadDouble());
#ifdef FMT_LOCALE
TextReader default_reader(str, "test.nl");
fmt::Locale &locale = default_reader.locale();
mp::internal::Unused(&locale);
#endif
}
TEST(TextReaderTest, ReadName) {
TextReader reader(" abc \n ", "test");
fmt::StringRef name = reader.ReadName();
EXPECT_EQ("abc", name.to_string());
EXPECT_THROW_MSG(reader.ReadName(), mp::ReadError, "test:1:8: expected name");
reader.ReadTillEndOfLine();
EXPECT_THROW_MSG(reader.ReadName(), mp::ReadError, "test:2:3: expected name");
}
TEST(TextReaderTest, ReadString) {
TextReader reader(" 3:a\nb\nc\n2x\n2:de \n2:fg", "test");
fmt::StringRef name = reader.ReadString();
EXPECT_EQ("a\nb", name.to_string());
EXPECT_THROW_MSG(reader.ReadString(), mp::ReadError,
"test:3:1: expected unsigned integer");
reader.ReadTillEndOfLine();
EXPECT_THROW_MSG(reader.ReadString(), mp::ReadError,
"test:4:2: expected ':'");
reader.ReadTillEndOfLine();
EXPECT_THROW_MSG(reader.ReadString(), mp::ReadError,
"test:5:5: expected newline");
reader.ReadTillEndOfLine();
EXPECT_THROW_MSG(reader.ReadString(), mp::ReadError,
"test:6:5: expected newline");
}
// Formats header and variable bounds as a string.
std::string FormatTextHeader(const NLHeader &h, bool var_bounds = true) {
NLHeader text_header = h;
text_header.format = NLHeader::TEXT;
fmt::MemoryWriter w;
w << text_header;
if (var_bounds) {
w << "b\n";
for (int i = 0; i < h.num_vars; ++i)
w << "1 0\n";
}
return w.str();
}
// Reads a header from the specified string.
NLHeader ReadHeader(const std::string &s) {
TextReader reader(s, "(input)");
NLHeader header = NLHeader();
// These optional-field tests start with explicitly empty options.
header.num_ampl_options = 0;
std::fill(std::begin(header.ampl_options), std::end(header.ampl_options), 0);
reader.ReadHeader(header);
return header;
}
// Reads a zero header with one modified line.
NLHeader ReadHeader(int line_index, fmt::StringRef line) {
return ReadHeader(ReplaceLine(FormatTextHeader(NLHeader()), line_index, line));
}
TEST(TextReaderTest, InvalidFormat) {
EXPECT_THROW_MSG(ReadHeader(0, "x"),
ReadError, "(input):1:1: expected format specifier");
}
TEST(TextReaderTest, InvalidNumOptions) {
EXPECT_EQ(0, ReadHeader(0, "ga").num_ampl_options);
EXPECT_EQ(0, ReadHeader(0, "g-1").num_ampl_options);
EXPECT_THROW_MSG(ReadHeader(0, "g10"),
ReadError, "(input):1:2: too many options");
EXPECT_THROW_MSG(ReadHeader(0,
fmt::format("g{}", static_cast<unsigned>(INT_MAX) + 1)),
ReadError, "(input):1:2: number is too big");
}
void CheckReadOptions(int num_options,
int num_options_to_write, const int *options) {
fmt::MemoryWriter w;
w << 'g' << num_options;
for (int i = 0; i < num_options_to_write; ++i)
w << ' ' << options[i];
NLHeader header = ReadHeader(0, w.c_str());
ASSERT_EQ(num_options, header.num_ampl_options);
int min_num_options = std::min(num_options, num_options_to_write);
for (int i = 0; i < min_num_options; ++i)
EXPECT_EQ(options[i], header.ampl_options[i]);
for (int i = min_num_options; i < num_options_to_write; ++i)
EXPECT_EQ(0, header.ampl_options[i]);
}
TEST(TextReaderTest, ReadOptions) {
const int options[mp::MAX_AMPL_OPTIONS + 1] = {
3, 5, 7, 11, 13, 17, 19, 23, 29, 31
};
for (int i = 0; i < mp::MAX_AMPL_OPTIONS; ++i) {
for (int j = 0; j < mp::MAX_AMPL_OPTIONS + 1; ++j)
CheckReadOptions(i, j, options);
}
EXPECT_EQ(0, ReadHeader(0, "g").num_ampl_options);
}
TEST(TextReaderTest, ReadAMPLVBTol) {
EXPECT_EQ(4.2, ReadHeader(0, "g2 0 3 4.2").ampl_vbtol);
EXPECT_EQ(0, ReadHeader(0, "g2 0 0 4.2").ampl_vbtol);
EXPECT_EQ(0, ReadHeader(0, "g2 0 3").ampl_vbtol);
}
TEST(TextReaderTest, NumComplDblIneq) {
EXPECT_EQ(42, ReadHeader(2, " 0 0 0 0 42").num_compl_dbl_ineqs);
EXPECT_EQ(-1, ReadHeader(2, " 0 0 70 0 42").num_compl_dbl_ineqs);
}
TEST(TextReaderTest, ReadArithKind) {
EXPECT_EQ(NLHeader::TEXT, ReadHeader(5, " 0 0").format);
EXPECT_EQ(NLHeader::TEXT, ReadHeader(5, " 0 0 0").format);
EXPECT_EQ(NLHeader::TEXT,
ReadHeader(5, fmt::format(" 0 0 {}", mp::arith::LAST)).format);
EXPECT_THROW_MSG(
ReadHeader(5, fmt::format(" 0 0 {}", mp::arith::LAST + 1)),
ReadError, "(input):6:6: unknown floating-point arithmetic kind");
}
TEST(TextReaderTest, IncompleteHeader) {
ReadHeader(0, "g");
EXPECT_THROW_MSG(
ReadHeader(0, "\n"),
ReadError, "(input):1:1: expected format specifier");
ReadHeader(1, " 1 0 0");
EXPECT_THROW_MSG(
ReadHeader(1, " 1 0"),
ReadError, "(input):2:5: expected unsigned integer");
for (int i = 2; i <= 8; ++i) {
if (i == 6)
continue;
ReadHeader(i, " 0 0");
EXPECT_THROW_MSG(
ReadHeader(i, " 0"), ReadError,
fmt::format("(input):{}:3: expected unsigned integer", i + 1));
}
for (int i = 6; i <= 9; i += 3) {
ReadHeader(1, " 0 0 0 0 0");
EXPECT_THROW_MSG(
ReadHeader(i, " 0 0 0 0"), ReadError,
fmt::format("(input):{}:9: expected unsigned integer", i + 1));
}
std::string input = ReplaceLine(FormatTextHeader(NLHeader()), 4, " 0 0");
ReadHeader(ReplaceLine(input, 6, " 0 0"));
EXPECT_THROW_MSG(
ReadHeader(ReplaceLine(input, 6, " 0")),
ReadError, "(input):7:3: expected unsigned integer");
}
#define CHECK_INT_OVERFLOW(field, col) { \
NLHeader h = NLHeader(); \
h.format = NLHeader::TEXT; \
h.num_vars = INT_MAX; \
h.field = 1; \
fmt::MemoryWriter w; \
w << h; \
NLHeader actual = NLHeader(); \
EXPECT_THROW_MSG(TextReader(w.str(), "in").ReadHeader(actual), \
ReadError, fmt::format("in:10:{}: integer overflow", col)); \
}
TEST(TextReaderTest, ReadHeaderIntegerOverflow) {
CHECK_INT_OVERFLOW(num_common_exprs_in_both, 2);
CHECK_INT_OVERFLOW(num_common_exprs_in_cons, 4);
CHECK_INT_OVERFLOW(num_common_exprs_in_objs, 6);
CHECK_INT_OVERFLOW(num_common_exprs_in_single_cons, 8);
CHECK_INT_OVERFLOW(num_common_exprs_in_single_objs, 10);
}
class TestReaderBase : public mp::internal::ReaderBase {
public:
TestReaderBase(mp::NLStringRef data, fmt::CStringRef name)
: ReaderBase(data, name) {}
TestReaderBase &get() { return *this; }
};
template <typename Converter = mp::internal::IdentityConverter>
class TestBinaryReader :
private TestReaderBase, public BinaryReader<Converter> {
public:
TestBinaryReader(mp::NLStringRef data, fmt::CStringRef name = "test")
: TestReaderBase(data, name), BinaryReader<Converter>(get()) {}
};
TEST(BinaryReaderTest, ReportError) {
TestBinaryReader<> reader("x");
EXPECT_THROW_MSG(reader.ReportError("a{}c", 'b'), mp::BinaryReadError,
"test:offset 0: abc");
}
template <typename T>
void ChangeEndianness(T &value) {
char *data = reinterpret_cast<char*>(&value);
std::reverse(data, data + sizeof(T));
}
TEST(BinaryReaderTest, ReadInt) {
int data[] = {11, -22, 0};
std::size_t size = sizeof(data) - sizeof(int);
mp::NLStringRef str(reinterpret_cast<char*>(data), size);
TestBinaryReader<> reader(str);
EXPECT_EQ(11, reader.ReadInt<int>());
EXPECT_EQ(-22, reader.ReadInt<int>());
EXPECT_THROW_MSG(reader.ReadInt<int>(), mp::BinaryReadError,
fmt::format("test:offset {}: unexpected end of file", size));
ChangeEndianness(data[0]);
EXPECT_EQ(11, TestBinaryReader<EndiannessConverter>(str).ReadInt<int>());
}
TEST(BinaryReaderTest, ReadLong) {
long data[] = {42, 0};
mp::NLStringRef str(reinterpret_cast<char*>(data), sizeof(data) - 1);
TestBinaryReader<> reader(str);
EXPECT_EQ(42, reader.ReadInt<long>());
ChangeEndianness(data[0]);
EXPECT_EQ(42, TestBinaryReader<EndiannessConverter>(str).ReadInt<long>());
}
TEST(BinaryReaderTest, ReadUInt) {
int data[] = {11, -22, 0};
mp::NLStringRef str(reinterpret_cast<char*>(data), sizeof(data) - 1);
TestBinaryReader<> reader(str);
EXPECT_EQ(11, reader.ReadUInt());
std::string message =
fmt::format("test:offset {}: expected unsigned integer", sizeof(int));
EXPECT_THROW_MSG(reader.ReadUInt(), mp::BinaryReadError, message);
ChangeEndianness(data[0]);
EXPECT_EQ(11, TestBinaryReader<EndiannessConverter>(str).ReadUInt());
}
TEST(BinaryReaderTest, ReadDouble) {
double data[] = {11, -2.2, 0};
std::size_t size = sizeof(data) - 1;
mp::NLStringRef str(reinterpret_cast<char*>(data), size);
TestBinaryReader<> reader(str);
EXPECT_EQ(11, reader.ReadDouble());
EXPECT_EQ(-2.2, reader.ReadDouble());
EXPECT_THROW_MSG(reader.ReadDouble(), mp::BinaryReadError,
fmt::format("test:offset {}: unexpected end of file", size));
ChangeEndianness(data[0]);
EXPECT_EQ(11, TestBinaryReader<EndiannessConverter>(str).ReadDouble());
}
template <typename Converter>
void TestReadString(fmt::StringRef (BinaryReader<Converter>::*read)(),
bool change_endianness = false) {
int data[] = {3, 0, 0};
if (change_endianness)
ChangeEndianness(data[0]);
char *str = reinterpret_cast<char*>(data + 1);
std::strcpy(str, "abc");
{
TestBinaryReader<Converter> reader(
mp::NLStringRef(reinterpret_cast<char*>(data), sizeof(int) + 3));
fmt::StringRef name = (reader.*read)();
EXPECT_EQ("abc", name.to_string());
}
{
str[2] = 0;
std::size_t size = sizeof(int) + 2;
TestBinaryReader<Converter> reader(
mp::NLStringRef(reinterpret_cast<char*>(data), size));
std::string message =
fmt::format("test:offset {}: unexpected end of file", size);
EXPECT_THROW_MSG((reader.*read)(), mp::BinaryReadError, message);
}
data[0] = -1;
if (change_endianness)
ChangeEndianness(data[0]);
{
TestBinaryReader<Converter> reader(
mp::NLStringRef(reinterpret_cast<char*>(data), sizeof(int) + 3));
EXPECT_THROW_MSG((reader.*read)(), mp::BinaryReadError,
"test:offset 0: expected unsigned integer");
}
}
TEST(BinaryReaderTest, ReadName) {
TestReadString(&BinaryReader<>::ReadName);
TestReadString(&BinaryReader<EndiannessConverter>::ReadName, true);
}
TEST(BinaryReaderTest, ReadString) {
TestReadString(&BinaryReader<>::ReadString);
TestReadString(&BinaryReader<EndiannessConverter>::ReadString, true);
}
TEST(NLReaderTest, ArithKind) {
namespace arith = mp::arith;
EXPECT_GE(arith::GetKind(), arith::UNKNOWN);
EXPECT_LE(arith::GetKind(), arith::LAST);
EXPECT_TRUE(arith::IsIEEE(arith::IEEE_LITTLE_ENDIAN));
EXPECT_TRUE(arith::IsIEEE(arith::IEEE_BIG_ENDIAN));
EXPECT_FALSE(arith::IsIEEE(arith::UNKNOWN));
EXPECT_FALSE(arith::IsIEEE(arith::IBM));
EXPECT_FALSE(arith::IsIEEE(arith::VAX));
EXPECT_FALSE(arith::IsIEEE(arith::CRAY));
}
class TestNLHandler {
private:
// Writes a comma-separated list.
template <typename Array>
static void WriteList(fmt::Writer &w, const Array &values) {
for (std::size_t i = 0, n = values.size(); i < n; ++i) {
if (i != 0)
w << ", ";
w << values[i];
}
}
std::string MakeVarArg(std::string op, const std::vector<std::string> &args) {
fmt::MemoryWriter w;
w << op << '(';
WriteList(w, args);
w << ')';
return w.str();
}
fmt::Writer &WriteSep() {
if (log.size() != 0)
log << ' ';
return log;
}
void WriteBounds(char type, int index, double lb, double ub) {
WriteSep();
double infinity = INFINITY;
if (lb != -infinity && lb != ub)
log << lb << " <= ";
log << type << index;
if (lb == ub)
log << " = " << ub;
else if (ub != infinity)
log << " <= " << ub;
log << ';';
}
public:
fmt::MemoryWriter log; // Call log.
typedef std::string Expr;
typedef std::string NumericExpr;
typedef std::string LogicalExpr;
typedef std::string CountExpr;
typedef std::string Reference;
void OnHeader(const NLHeader &) { log.clear(); }
bool NeedObj(int) const { return true; }
int resulting_obj_index(int obj_index) const { return obj_index; }
void OnVarBounds(int index, double lb, double ub) {
WriteBounds('v', index, lb, ub);
}
void OnConBounds(int index, double lb, double ub) {
WriteBounds('c', index, lb, ub);
}
void OnComplementarity(int con_index, int var_index, mp::ComplInfo info) {
WriteSep().write("{} <= c{} <= {} complements v{};",
info.con_lb(), con_index, info.con_ub(), var_index);
}
class LinearExprHandler {
private:
std::string str_;
fmt::Writer &log_;
bool terminate_;
public:
explicit LinearExprHandler(fmt::Writer &log, bool terminate = true)
: log_(log), terminate_(terminate) {}
~LinearExprHandler() {
log_ << str_;
if (terminate_)
log_ << ';';
}
void AddTerm(int var_index, double coef) {
if (!str_.empty())
str_ += " + ";
str_ += fmt::format("{} * v{}", coef, var_index);
}
};
typedef LinearExprHandler LinearObjHandler;
typedef LinearExprHandler LinearConHandler;
LinearExprHandler OnLinearObjExpr(int index, int num_terms) {
WriteSep().write("o{} {}: ", index, num_terms);
return LinearExprHandler(log);
}
LinearExprHandler OnLinearConExpr(int index, int num_terms) {
WriteSep().write("c{} {}: ", index, num_terms);
return LinearExprHandler(log);
}
class ColumnSizeHandler {
private:
fmt::Writer &log_;
public:
explicit ColumnSizeHandler(fmt::Writer &log) : log_(log) {}
~ColumnSizeHandler() { log_ << ';'; }
void Add(int offset) { log_ << ' ' << offset; }
};
ColumnSizeHandler OnColumnSizes() {
WriteSep() << "sizes:";
return ColumnSizeHandler(log);
}
void OnObj(int index, mp::obj::Type type, std::string expr) {
WriteSep() << (type == mp::obj::MAX ? "maximize" : "minimize")
<< " o" << index << ": " << expr << ";";
}
void OnAlgebraicCon(int index, std::string expr) {
WriteSep() << "c" << index << ": " << expr << ";";
}
void OnLogicalCon(int index, std::string expr) {
WriteSep() << "l" << index << ": " << expr << ";";
}
LinearExprHandler BeginCommonExpr(int index, int num_terms) {
WriteSep().write("e{} {}: ", index, num_terms);
return LinearExprHandler(log, false);
}
void EndCommonExpr(int, std::string expr, int position) {
log.write(" + {} {};", expr, position);
}
void OnInitialValue(int var_index, double value) {
WriteSep().write("v{} := {};", var_index, value);
}
void OnInitialDualValue(int con_index, double value) {
WriteSep().write("c{} := {};", con_index, value);
}
void OnFunction(
int index, fmt::StringRef name, int num_args, mp::func::Type type) {
WriteSep().write("f{}: {} {} {};", index, name, num_args, type);
}
template <typename T>
class SuffixHandler {
private:
fmt::Writer &log_;
bool first_;
public:
explicit SuffixHandler(fmt::Writer &log) : log_(log), first_(true) {}
~SuffixHandler() { log_ << ';'; }
void SetValue(int index, T value) {
if (!first_)
log_ << ',';
first_ = false;
log_.write(" i{} = {}", index, value);
}
};
typedef SuffixHandler<int> IntSuffixHandler;
IntSuffixHandler OnIntSuffix(fmt::StringRef name, int kind, int num_values) {
WriteSep().write("suffix {}:{}:{}:", name, kind, num_values);
return IntSuffixHandler(log);
}
typedef SuffixHandler<double> DblSuffixHandler;
DblSuffixHandler OnDblSuffix(fmt::StringRef name, int kind, int num_values) {
WriteSep().write("suffix {}:{}:{}:", name, kind, num_values);
return DblSuffixHandler(log);
}
std::string OnNumber(double value) {
return fmt::format("{}", value);
}
std::string OnVariableRef(int index) {
return fmt::format("v{}", index);
}
std::string OnCommonExprRef(int index) {
return fmt::format("e{}", index);
}
std::string OnUnary(expr::Kind kind, std::string arg) {
return fmt::format("u{}({})", nl_opcode(kind), arg);
}
std::string OnBinary(expr::Kind kind, std::string lhs, std::string rhs) {
return fmt::format("b{}({}, {})", nl_opcode(kind), lhs, rhs);
}
std::string OnIf(std::string condition,
std::string then_expr, std::string else_expr) {
return fmt::format("if {} then {} else {}",
condition, then_expr, else_expr);
}
class PLTermHandler {
private:
std::vector<double> slopes_;
std::vector<double> breakpoints_;
friend class TestNLHandler;
public:
void AddSlope(double slope) { slopes_.push_back(slope); }
void AddBreakpoint(double breakpoint) {
breakpoints_.push_back(breakpoint);
}
};
PLTermHandler BeginPLTerm(int) {
return PLTermHandler();
}
std::string EndPLTerm(PLTermHandler h, std::string var) {
fmt::MemoryWriter w;
w << "<<";
WriteList(w, h.breakpoints_);
w << "; ";
WriteList(w, h.slopes_);
w << ">> " << var;
return w.str();
}
class CallArgHandler {
private:
int func_index_;
std::vector<std::string> args_;
friend class TestNLHandler;
public:
explicit CallArgHandler(int func_index) : func_index_(func_index) {}
void AddArg(std::string arg) { args_.push_back(arg); }
};
CallArgHandler BeginCall(int func_index, int) {
return CallArgHandler(func_index);
}
std::string EndCall(CallArgHandler h) {
fmt::MemoryWriter w;
w << 'f' << h.func_index_ << '(';
WriteList(w, h.args_);
w << ')';
return w.str();
}
class ArgHandler {
private:
std::string name_;
std::vector<std::string> args_;
friend class TestNLHandler;
public:
explicit ArgHandler(std::string name) : name_(name) {}
void AddArg(std::string arg) { args_.push_back(arg); }
};
typedef ArgHandler NumericArgHandler;
typedef ArgHandler VarArgHandler;
VarArgHandler BeginVarArg(expr::Kind kind, int) {
return VarArgHandler(fmt::format("v{}", nl_opcode(kind)));
}
std::string EndVarArg(VarArgHandler h) {
return MakeVarArg(h.name_, h.args_);
}
ArgHandler BeginSum(int) { return ArgHandler("sum"); }
std::string EndSum(ArgHandler h) { return MakeVarArg(h.name_, h.args_); }
typedef ArgHandler NumberOfArgHandler;
ArgHandler BeginNumberOf(int, std::string arg0) {
return ArgHandler("numberof " + arg0 + " in ");
}
std::string EndNumberOf(ArgHandler h) { return MakeVarArg(h.name_, h.args_); }
typedef ArgHandler SymbolicArgHandler;
ArgHandler BeginSymbolicNumberOf(int, std::string arg0) {
return ArgHandler("numberof " + arg0 + " in ");
}
std::string EndSymbolicNumberOf(ArgHandler h) {
return MakeVarArg(h.name_, h.args_);
}
typedef ArgHandler CountArgHandler;
ArgHandler BeginCount(int) { return ArgHandler("count"); }
std::string EndCount(ArgHandler h) { return MakeVarArg(h.name_, h.args_); }
std::string OnBool(bool value) { return fmt::format("l{:d}", value); }
std::string OnNot(std::string arg) { return fmt::format("not {}", arg); }
std::string OnBinaryLogical(
expr::Kind kind, std::string lhs, std::string rhs) {
return fmt::format("bl{}({}, {})", nl_opcode(kind), lhs, rhs);
}
std::string OnRelational(expr::Kind kind, std::string lhs, std::string rhs) {
return fmt::format("r{}({}, {})", nl_opcode(kind), lhs, rhs);
}
std::string OnLogicalCount(
expr::Kind kind, std::string lhs, std::string rhs) {
return fmt::format("lc{}({}, {})", nl_opcode(kind), lhs, rhs);
}
std::string OnImplication(std::string condition,
std::string then_expr, std::string else_expr) {
return fmt::format("{} ==> {} else {}", condition, then_expr, else_expr);
}
typedef ArgHandler LogicalArgHandler;
ArgHandler BeginIteratedLogical(expr::Kind kind, int) {
return ArgHandler(fmt::format("il{}", nl_opcode(kind)));
}
std::string EndIteratedLogical(ArgHandler h) {
return MakeVarArg(h.name_, h.args_);
}
typedef ArgHandler PairwiseArgHandler;
ArgHandler BeginPairwise(expr::Kind kind, int) {
return ArgHandler(kind == expr::ALLDIFF ? "alldiff" : "!alldiff");
}
std::string EndPairwise(ArgHandler h) { return MakeVarArg(h.name_, h.args_); }
std::string OnString(fmt::StringRef value) {
return fmt::format("'{}'", value.data() ? value : "");
}
std::string OnSymbolicIf(std::string condition,
std::string then_expr, std::string else_expr) {
return OnIf(condition, then_expr, else_expr);
}
void EndInput() {}
};
TEST(NLReaderTest, WriteTextHeader) {
NLHeader h = MakeTestHeader();
fmt::MemoryWriter w;
w << h;
EXPECT_EQ(
"g9 2 3 5 7 11 13 17 19 23 1.23\n"
" 29 47 37 41 43 31\n"
" 53 59 6 61 71 73\n"
" 79 83\n"
" 89 97 101\n"
" 103 107 0 109\n"
" 113 127 131 137 139\n"
" 149 151\n"
" 157 163\n"
" 167 173 179 181 191\n",
w.str());
}
TEST(NLReaderTest, WriteBinaryHeader) {
NLHeader header = NLHeader();
header.format = NLHeader::BINARY;
header.flags = 0;
header.num_ampl_options = 3;
for (int i = 0; i < header.num_ampl_options; ++i)
header.ampl_options[i] = 11 * (i + 1);
header.arith_kind = (NLArithKind)mp::arith::CRAY;
fmt::MemoryWriter w;
w << header;
EXPECT_EQ(
"b3 11 22 33\n"
" 0 0 0 0 0 0\n"
" 0 0 0 0 0 0\n"
" 0 0\n"
" 0 0 0\n"
" 0 0 5 0\n"
" 0 0 0 0 0\n"
" 0 0\n"
" 0 0\n"
" 0 0 0 0 0\n",
w.str());
}
struct TestNLHandler2 {
typedef struct TestExpr {} Expr;
typedef struct TestNumericExpr : TestExpr {} NumericExpr;
typedef struct TestReference : TestNumericExpr {} Reference;
typedef struct TestCountExpr : TestNumericExpr {} CountExpr;
typedef struct TestLogicalExpr : TestExpr {} LogicalExpr;
void OnHeader(const NLHeader &) {}
bool NeedObj(int) const { return true; }
int resulting_obj_index(int obj_index) const { return obj_index; }
void OnVarBounds(int, double, double) {}
void OnConBounds(int, double, double) {}
void OnComplementarity(int, int, mp::ComplInfo) {}
struct LinearObjHandler {
void AddTerm(int, double) {}
};
LinearObjHandler OnLinearObjExpr(int, int) {
return LinearObjHandler();
}
struct LinearConHandler {
void AddTerm(int, double) {}
};
LinearConHandler OnLinearConExpr(int, int) {
return LinearConHandler();
}
struct LinearExprHandler {
void AddTerm(int, double) {}
};
LinearExprHandler BeginCommonExpr(int, int) {
return LinearExprHandler();
}
void EndCommonExpr(int, TestNumericExpr, int) {}
struct ColumnSizeHandler {
void Add(int) {}
};
ColumnSizeHandler OnColumnSizes() { return ColumnSizeHandler(); }
void OnObj(int, mp::obj::Type, TestNumericExpr) {}
void OnAlgebraicCon(int, TestNumericExpr) {}
void OnLogicalCon(int, TestLogicalExpr) {}
void OnInitialValue(int, double) {}
void OnInitialDualValue(int, double) {}
void OnFunction(int, fmt::StringRef, int, mp::func::Type) {}
template <typename T>
struct SuffixHandler {
void SetValue(int, T) {}
};
typedef SuffixHandler<int> IntSuffixHandler;
IntSuffixHandler OnIntSuffix(fmt::StringRef, int, int) {
return IntSuffixHandler();
}
typedef SuffixHandler<double> DblSuffixHandler;
DblSuffixHandler OnDblSuffix(fmt::StringRef, int, int) {
return DblSuffixHandler();
}
TestNumericExpr OnNumber(double) { return TestNumericExpr(); }
TestReference OnVariableRef(int) { return TestReference(); }
TestReference OnCommonExprRef(int) { return TestReference(); }
TestNumericExpr OnUnary(expr::Kind, TestNumericExpr) {
return TestNumericExpr();
}
TestNumericExpr OnBinary(expr::Kind, TestNumericExpr, TestNumericExpr) {
return TestNumericExpr();
}
TestNumericExpr OnIf(TestLogicalExpr, TestNumericExpr, TestNumericExpr) {
return TestNumericExpr();
}
struct PLTermHandler {
void AddSlope(double) {}
void AddBreakpoint(double) {}
};
PLTermHandler BeginPLTerm(int) { return PLTermHandler(); }
TestNumericExpr EndPLTerm(PLTermHandler, TestNumericExpr) {
return TestNumericExpr();
}
struct CallArgHandler {
void AddArg(TestNumericExpr) {}
void AddArg(TestExpr) {}
};
CallArgHandler BeginCall(int, int) { return CallArgHandler(); }
TestNumericExpr EndCall(CallArgHandler) { return TestNumericExpr(); }
struct NumericArgHandler {
void AddArg(NumericExpr) {}
};
struct VarArgHandler {
void AddArg(NumericExpr) {}
};
VarArgHandler BeginVarArg(expr::Kind, int) { return VarArgHandler(); }
TestNumericExpr EndVarArg(VarArgHandler) { return TestNumericExpr(); }
NumericArgHandler BeginSum(int) { return NumericArgHandler(); }
TestNumericExpr EndSum(NumericArgHandler) { return TestNumericExpr(); }
struct NumberOfArgHandler {
void AddArg(NumericExpr) {}
};
NumberOfArgHandler BeginNumberOf(int, TestNumericExpr) {
return NumberOfArgHandler();
}
TestNumericExpr EndNumberOf(NumberOfArgHandler) { return TestNumericExpr(); }
struct SymbolicArgHandler {
void AddArg(TestExpr) {}
};
SymbolicArgHandler BeginSymbolicNumberOf(int, TestExpr) {
return SymbolicArgHandler();
}
TestNumericExpr EndSymbolicNumberOf(SymbolicArgHandler) {
return TestNumericExpr();
}