Generated on for Gecode by doxygen 1.17.0
instance.cpp
Go to the documentation of this file.
1/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
2/*
3 * Main authors:
4 * Mikael Zayenz Lagerkvist <lagerkvist@gecode.dev>
5 *
6 * Copyright:
7 * Mikael Zayenz Lagerkvist, 2026
8 *
9 * This file is part of Gecode, the generic constraint
10 * development environment:
11 * http://www.gecode.dev
12 *
13 * Permission is hereby granted, free of charge, to any person obtaining
14 * a copy of this software and associated documentation files (the
15 * "Software"), to deal in the Software without restriction, including
16 * without limitation the rights to use, copy, modify, merge, publish,
17 * distribute, sublicense, and/or sell copies of the Software, and to
18 * permit persons to whom the Software is furnished to do so, subject to
19 * the following conditions:
20 *
21 * The above copyright notice and this permission notice shall be
22 * included in all copies or substantial portions of the Software.
23 *
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 *
32 */
33
34#include <gecode/instance.hh>
35#include <gecode/driver.hh>
36
37#include "test/test.hh"
38
39#include <chrono>
40#include <climits>
41#include <cstdio>
42#include <cstdlib>
43#include <cstring>
44#include <fstream>
45#include <functional>
46#include <sstream>
47#include <string>
48
49namespace Test { namespace Instance {
50
51 using Gecode::IntArgs;
56
61
63 Data
64 read(const char* spec, const char* text, const Params& p = Params()) {
65 return Spec::parse(spec, "test.reader").read_text(text, "test.txt", p);
66 }
67
69 bool
70 fails(const std::function<void(void)>& f, const char* what) {
71 try {
72 f();
73 } catch (const Error& e) {
74 if (std::string(e.what()).find(what) != std::string::npos)
75 return true;
76 olog << "unexpected error message:\n" << e.what() << "\n";
77 return false;
78 }
79 olog << "expected an error containing '" << what << "'\n";
80 return false;
81 }
82
84 bool
85 fails(const char* spec, const char* text, const char* what) {
86 return fails([&](void) { (void) read(spec, text); }, what);
87 }
88
90 bool
91 rejects(const char* spec, const char* what) {
92 return fails([&](void) { (void) Spec::parse(spec, "s"); }, what);
93 }
94
96 bool
97 equal(const IntArgs& a, std::initializer_list<int> v) {
98 if (a.size() != static_cast<int>(v.size()))
99 return false;
100 int i = 0;
101 for (int x : v)
102 if (a[i++] != x)
103 return false;
104 return true;
105 }
106
107#define CHECK(c) \
108 if (!(c)) { \
109 olog << "check failed at line " << __LINE__ << ": " #c "\n"; \
110 return false; \
111 }
112
114 class Case : public Base {
115 protected:
117 std::function<bool(void)> f;
118 public:
120 Case(const std::string& n, std::function<bool(void)> f0)
121 : Base("Instance::" + n), f(f0) {}
122
123 virtual bool run(void) {
124 try {
125 return f();
126 } catch (const Error& e) {
127 olog << "unexpected error:\n" << e.what() << "\n";
128 return false;
129 }
130 }
131 };
132
133 Case scalars("Read::Scalars", [](void) {
134 Data d = read("a: int b: float c: num e: num w: word r: rest", " -7 2.5\n 3 4.5e1 hello the rest \n");
135 CHECK(d.integer("a") == -7);
136 CHECK(d.number("b") == 2.5);
137 CHECK(d.integer("c") == 3);
139 CHECK(d.number("e") == 45.0);
140 CHECK(d.text("w") == "hello");
141 CHECK(d.text("r") == "the rest");
142 CHECK(d.entries() == 6);
143 CHECK(d.name(0) == "a");
144 return true;
145 });
146
147 Case arrays("Read::Arrays", [](void) {
148 Data d = read("n: int m: int a[n][m]: int _: int f[2]: float offset 1", "2 3\n1 2\n3 4 5 6\n99 1.5 2");
149 CHECK(d.depth("a") == 2);
150 CHECK(d.size("a") == 2);
151 CHECK(d.size("a", {1}) == 3);
152 CHECK(equal(d.ints("a"), {1,2,3,4,5,6}));
153 CHECK(equal(d.ints("a", {1}), {4,5,6}));
154 CHECK(d.integer("a", {1,2}) == 6);
155 CHECK(!d.has("_"));
156 CHECK(d.numbers("f")[0] == 2.5);
157 CHECK(d.numbers("f")[1] == 3.0);
158 return true;
159 });
160
161 Case layouts("Read::Layouts", [](void) {
162 // The symmetric matrix 0 1 2 / 1 0 3 / 2 3 0 in all layouts
163 const char* spec = "f: word w[3][3]: int layout f";
164 const char* inputs[] = {
165 "FULL_MATRIX 0 1 2 1 0 3 2 3 0",
166 "UPPER_ROW 1 2 3", "LOWER_COL 1 2 3",
167 "LOWER_ROW 1 2 3", "UPPER_COL 1 2 3",
168 "UPPER_DIAG_ROW 0 1 2 0 3 0", "LOWER_DIAG_COL 0 1 2 0 3 0",
169 "LOWER_DIAG_ROW 0 1 0 2 3 0", "UPPER_DIAG_COL 0 1 0 2 3 0",
170 };
171 for (const char* in : inputs) {
172 Data d = read(spec, in);
173 if (!equal(d.ints("w"), {0,1,2,1,0,3,2,3,0})) {
174 olog << "wrong matrix for " << in << "\n";
175 return false;
176 }
177 }
178 // An offset applies to the numbers read, not to the mirrored zeros
179 CHECK(equal(read("w[3][3]: int layout \"UPPER_ROW\" offset 1", "1 2 3").ints("w"), {0,2,3,2,0,4,3,4,0}));
180 return fails(spec, "DIAGONAL 1 2 3", "unknown matrix layout");
181 });
182
183 Case lists("Read::Lists", [](void) {
184 Data d = read("list a: int until 0 list b: int until eol list c: int until eol list w: word until \"END\"",
185 "1 2\n 3 0 4 5\n6 7\nx y END");
186 CHECK(equal(d.ints("a"), {1,2,3}));
187 CHECK(equal(d.ints("b"), {4,5}));
188 CHECK(equal(d.ints("c"), {6,7}));
189 CHECK(d.size("w") == 2);
190 CHECK(d.text("w", {1}) == "y");
191 return true;
192 });
193
194 Case patterns("Read::Patterns", [](void) {
195 Data d = read("line \"# size={n:int} box={w:int}x{h:int}\"\n"
196 "find \"NAME : {name:rest}\"\n"
197 "line \"p {_} {v:int} {c:num} ...\"",
198 "# size=6 box=3x2\nnoise\nNAME: a b c \n"
199 "p cnf 10 2.5 trailing words\n");
200 CHECK(d.integer("n") == 6);
201 CHECK(d.integer("w") == 3);
202 CHECK(d.integer("h") == 2);
203 CHECK(d.text("name") == "a b c");
204 CHECK(d.integer("v") == 10);
205 CHECK(d.number("c") == 2.5);
206 // A space between two words is required
207 CHECK(fails("line \"p cnf {v:int}\"", "pcnf 3", "expected a line"));
208 return true;
209 });
210
211 Case params("Read::Params", [](void) {
212 const char* spec = "param which param k = 2\n"
213 "find \"instance {$which}\" x[k]: int ignore trailing";
214 const char* text = "instance a\n1 2\ninstance b\n3 4\n";
215 Params p;
216 p.set("which=b");
217 Data d = read(spec, text, p);
218 CHECK(equal(d.ints("x"), {3,4}));
219 CHECK(d.text("which") == "b");
220 Params q;
221 q.set("which", "a");
222 q.set("k", "1");
223 CHECK(equal(read(spec, text, q).ints("x"), {1}));
224 Params r;
225 r.set("which=a,,k=1,");
226 CHECK(equal(read(spec, text, r).ints("x"), {1}));
227 CHECK(fails([](void) { Params e; e.set("which=a,k"); }, "parameter 'k' must have the form name=value"));
228 CHECK(fails([](void) { Params e; e.set("=a"); }, "parameter '=a' must have the form name=value"));
229 return fails(spec, text, "parameter 'which' must be given");
230 });
231
232 Case repeats("Read::Repeat", [](void) {
233 Data d = read("n: int\n"
234 "repeat n { index 1 k: int s[k]: int offset -1 }\n"
235 "repeat until \"999\" { a: int }\n"
236 "repeat until \">=\" \"=\" store op { c: int v: word }\n"
237 "rhs: int\n"
238 "repeat until eof { w: word }",
239 "3\n1 2 4 5\n2 0\n3 1 1\n7 8 999\n"
240 "2 x 3 y = 4\nfoo bar");
241 CHECK(equal(d.ints("k"), {2,0,1}));
242 CHECK(d.size("s") == 3);
243 CHECK(d.size("s", {1}) == 0);
244 CHECK(equal(d.ints("s"), {3,4,0}));
245 CHECK(equal(d.ints("s", {2}), {0}));
246 CHECK(equal(d.ints("a"), {7,8}));
247 CHECK(d.text("op") == "=");
248 CHECK(equal(d.ints("c"), {2,3}));
249 CHECK(d.integer("rhs") == 4);
250 CHECK(d.size("w") == 2);
251 CHECK(fails("n: int repeat n { index 1 x: int }", "2\n1 5\n3 6", "expected index 2, found 3"));
252 // Nested repeats give nested arrays
253 Data e = read("repeat 2 { repeat 2 { x: int y: int } }", "1 2 3 4 5 6 7 8");
254 CHECK(e.depth("x") == 2);
255 CHECK(equal(e.ints("x", {1}), {5,7}));
256 CHECK(equal(e.ints("y"), {2,4,6,8}));
257 return true;
258 });
259
260 Case sections("Read::Sections", [](void) {
261 const char* spec = "sections until \"EOF\" {\n"
262 " \"N : {n:int}\"\n"
263 " \"DATA\" { x[n]: int }\n"
264 " \"NAME : {name:word}\" optional\n"
265 "}\n";
266 Data d = read(spec, "NAME : a\nN: 2\nDATA\n5 6\nEOF\n");
267 CHECK(d.integer("n") == 2);
268 CHECK(equal(d.ints("x"), {5,6}));
269 CHECK(d.text("name") == "a");
270 // No terminator needed at end of input
271 CHECK(read(spec, "N : 1\nDATA\n4").ints("x").size() == 1);
272 CHECK(fails(spec, "N : 1\nXYZZY_PLUGH\n", "expected one of"));
273 CHECK(read("sections skip other { \"v: {v:int}\" }", "junk\nv: 3\nmore junk\n").integer("v") == 3);
274 // An arm that is not optional matches exactly one line
275 CHECK(fails(spec, "N : 1\nEOF\n", "test.txt:2:1: expected a line matching \"DATA\" before 'EOF'"));
276 CHECK(fails(spec, "NAME : a\n", "expected a line matching \"N : {n:int}\" before the end of the input"));
277 CHECK(fails(spec, "N : 1\nDATA\n4\nN : 2\n",
278 "test.txt:4:1: a second line matching \"N : {n:int}\" (the first is on line 1)"));
279 CHECK(fails(spec, "NAME : a\nN : 1\nDATA\n4\nNAME : b\n", "a second line matching \"NAME : {name:word}\""));
280 // A last arm ends the statement, and may be optional
281 const char* last = "sections { \"a {a:int}\" \"end\" last } y: int";
282 CHECK(read(last, "a 1\nend\n5").integer("y") == 5);
283 CHECK(fails(last, "a 1\n5", "expected one of"));
284 CHECK(fails(last, "a 1", "expected a line matching \"end\" before the end of the input"));
285 CHECK(fails(last, "end\n5",
286 "test.txt:1:1: expected a line matching \"a {a:int}\" before the line matching \"end\""));
287 const char* optional_last = "sections { \"a {a:int}\" \"end\" optional last }";
288 CHECK(read(optional_last, "a 1").integer("a") == 1);
289 CHECK(read(optional_last, "a 1\nend").integer("a") == 1);
290 return true;
291 });
292
293 Case alphabets("Read::Alphabets", [](void) {
294 Data d = read("g[2][3]: alphabet \"123ABC\" blank \".\"", "1.A\nC 2 .");
295 CHECK(equal(d.ints("g"), {1,0,4,6,2,0}));
296 Data e = read("g[2][2]: alphabet \"ab\" base 0 strip \"|-\"", "a|b\n---\nb|a");
297 CHECK(equal(e.ints("g"), {0,1,1,0}));
298 // Alphabet options do not take the statements that follow
299 CHECK(read("g[1][2]: alphabet \"ab\" ignore trailing", "ab x").size("g") == 1);
300 CHECK(read("g[1][1]: alphabet \"ab\" base: int", "b 7").integer("base") == 7);
301 CHECK(fails("g[1][2]: alphabet \"ab\"", "ax", "unexpected symbol 'x', expected one of 'ab'"));
302 CHECK(fails("g[2][2]: alphabet \"ab\"", "ab\na", "expected a symbol for row 2, column 2"));
303 CHECK(rejects("g[2]: alphabet \"ab\"", "an alphabet type needs a two-dimensional array"));
304 CHECK(rejects("g[2][2]: alphabet \"ab\" offset 1", "'offset' needs numbers"));
305 CHECK(rejects("list g: alphabet \"ab\" until eol", "a list cannot be of 'rest' or of an alphabet type"));
306 CHECK(rejects("line \"{g:alphabet \\\"ab\\\"}\"", "a capture cannot be of an alphabet type"));
307 return true;
308 });
309
310 Case ranges("Read::Ranges", [](void) {
311 Data d = read("n: 1.. a[n]: 0..<n b: ..0 c: -2..-1", "2 0 1 -5 -2");
312 CHECK(equal(d.ints("a"), {0,1}));
313 CHECK(d.integer("b") == -5);
314 CHECK(fails("n: 1.. a[n]: 0..<n", "2 0 2", "test.txt:1:5: expected an int in 0..1, found '2'"));
315 CHECK(fails("a: 0..9", "x", "expected an int in 0..9, found 'x'"));
316 CHECK(fails("a: 0..", "-1", "expected an int in 0.., found '-1'"));
317 CHECK(fails("a: ..<0", "0", "expected an int in ..-1, found '0'"));
318 // Ranges are checked before the offset, and the terminator need not be
319 // in the range
320 CHECK(equal(read("a[2]: 1..2 offset -1 list l: 0..9 until -1", "1 2 3 -1").ints("a"), {0,1}));
321 CHECK(fails("list l: 0..9 until -1", "3 10 -1", "found '10'"));
322 CHECK(fails("w[3][3]: 0..1 layout \"UPPER_ROW\"", "1 2 1", "found '2'"));
323 // Captures are checked after the line matched, so that their ranges
324 // can use the captures before them
325 Data l = read("line \"{n:int} {m:0..n}\"", "3 2");
326 CHECK(l.integer("m") == 2);
327 CHECK(fails("line \"{n:int} {m:0..n}\"", "3 4", "test.txt:1:3: expected an int in 0..3, found '4'"));
328 CHECK(fails("a: 0..\"x\"", "1", "the bounds of a range must be integers"));
329 CHECK(fails("a: 0..<-9223372036854775807-1", "1", "integer overflow"));
330 return true;
331 });
332
333 Case types("Spec::Types", [](void) {
334 Data d = read("type time = 0..gecode.int_max / 2\n"
335 "n: 1..\n"
336 "repeat n { ready: time due: time }\n"
337 "type cell = alphabet \"ab\" blank \".\"\n"
338 "g[1][2]: cell",
339 "2 1 2 3 4 a.");
340 CHECK(equal(d.ints("due"), {2,4}));
341 CHECK(equal(d.ints("g"), {1,0}));
342 CHECK(fails("n: int type small = 0..n a: small", "3 4", "expected small (an int in 0..3), found '4'"));
343 CHECK(fails("type w = word type v = w line \"{x:v} {y:0..1}\"", "a 2", "expected an int in 0..1"));
344 // The range is evaluated where the type is defined
345 CHECK(fails("n: int type t = 0..n let n2 = n repeat 2 { b: t }", "1 1 2", "expected t (an int in 0..1)"));
346 // Names can be keywords when they are declared
347 Data k = read("line: int type: 0.. list: word each: int layout: int", "1 2 a 3 4");
348 CHECK(k.integer("type") == 2);
349 CHECK(k.integer("layout") == 4);
350 // A range ends before a statement or a declaration
351 CHECK(read("a: 0..\nb[2]: int check a == 0", "0 1 2").size("b") == 2);
352 CHECK(read("a: 0.. index: int", "0 1").integer("index") == 1);
353 CHECK(rejects("a: 0..<", "'..<' needs an upper bound"));
354 CHECK(rejects("a: ..", "a range needs a lower or an upper bound"));
355 CHECK(rejects("a: foo", "unknown type 'foo'"));
356 CHECK(rejects("a: 1 + 2", "expected '..' or '..<' after the lower bound of a range"));
357 CHECK(rejects("type int = 0..", "'int' is a base type"));
358 CHECK(rejects("type t = int type t = word", "the type 't' is already defined"));
359 CHECK(rejects("type t = int t: int", "s:1: 't' names a type, so it cannot also name a value"));
360 CHECK(rejects("if 1 > 0 { type t = int } a: t", "unknown type 't'"));
361 CHECK(rejects("a: word offset 1", "'offset' needs numbers"));
362 CHECK(rejects("a[2]: int layout \"FULL_MATRIX\"", "'layout' needs a two-dimensional array of numbers"));
363 CHECK(rejects("line \"{x:0..<}\"", "s:1: '..<' needs an upper bound"));
364 CHECK(rejects("line \"{x:int int}\"", "unexpected 'int' in the capture type 'int int'"));
365 CHECK(rejects("line \"{x:}\"", "a capture needs a type after ':'"));
366 return true;
367 });
368
369 Case control("Read::Control", [](void) {
370 Data d = read("n: int\n"
371 "if n > 1 { w: word } else { let w = \"none\" }\n"
372 "let m = n * 3 + 1\n"
373 "a[2]: int\n"
374 "let s = sum(a)\n"
375 "check max(a) - min(a) == 2 \"spread\"\n"
376 "check count(a) == 2 && defined(m) && !defined(zz)\n"
377 "check 7 / 2 == 3 && 7 % 2 == 1",
378 "2 x 1 3");
379 CHECK(d.text("w") == "x");
380 CHECK(d.integer("m") == 7);
381 CHECK(d.integer("s") == 4);
382 CHECK(read("n: int if n > 1 { w: word } else { let w = \"none\" }", "1").text("w") == "none");
383 CHECK(fails("a: int check a == 2 \"must be two\"", "3", "check failed: must be two"));
384 CHECK(fails("a: int let b = a / 0", "3", "division by zero"));
385 CHECK(fails("a: int let b = c", "3", "'c' is not defined yet"));
386 return true;
387 });
388
389 Case lexical("Read::Lexical", [](void) {
390 Data d = read("comment \"c\" \"#\"\n"
391 "stop \"%\"\n"
392 "tokens \";\"\n"
393 "expect \"p\" \"cnf\"\n"
394 "repeat until eof { w: word expect \";\" }",
395 "c comment\r\n# another\r\np cnf\r\na; b ;\r\nc x\r\n%\r\n0\r\n");
396 CHECK(d.size("w") == 2);
397 CHECK(d.text("w", {1}) == "b");
398 CHECK(fails("a: int", "1 2", "unexpected input after the end"));
399 CHECK(read("a: int ignore trailing", "1 2").integer("a") == 1);
400 return true;
401 });
402
403 Case robustness("Read::Robustness", [](void) {
404 // Separators, and a string terminator for a list of numbers
405 Data d = read("separators \",\" list a: int until eol list b: int until \"EOF\"", "1,2, 3\n4 5 EOF");
406 CHECK(equal(d.ints("a"), {1,2,3}));
407 CHECK(equal(d.ints("b"), {4,5}));
408 // Names with dashes only for formats; '-' is otherwise subtraction
409 Spec f = Spec::parse("format dimacs-cnf.v2 n: int x: int let k = n-x", "s");
410 CHECK(f.name() == "dimacs-cnf.v2");
411 CHECK(f.read_text("5 2").integer("k") == 3);
412 // Overflow and non-decimal numbers are errors
413 CHECK(fails("a: int let b = a * a", "9000000000", "integer overflow"));
414 CHECK(fails("a: int b: int offset 1", "1 9223372036854775807", "integer overflow"));
415 CHECK(fails("f: float", "nan", "expected float"));
416 // Signs come first or after an exponent, in input, captures, and specs
417 Data n = read("line \"{a:float}x{b:int}-{c:num}\" f: float\n"
418 "check 1.5e+1 == 15 && 5-2 == 3",
419 "-1.5e+2x+3-2.5\n+2.5E-1");
420 CHECK(n.number("a") == -150.0);
421 CHECK(n.integer("b") == 3);
422 CHECK(n.number("c") == 2.5);
423 CHECK(n.number("f") == 0.25);
424 CHECK(fails("f: float", "1-2", "expected float"));
425 CHECK(fails("f: num", "0x10", "expected a number"));
426 CHECK(fails("n: int a[n]: int", "2147483648", "too large"));
427 // Integers in lists and arrays, which are read without making strings
428 CHECK(equal(read("list a: int until 0", "+5 -7 05 -0").ints("a"), {5,-7,5}));
429 CHECK(equal(read("tokens \";\" a[3]: int expect \";\"", "1 -2 3;").ints("a"), {1,-2,3}));
430 CHECK(fails("list a: int until 0", "9223372036854775808 0", "expected int, found '9223372036854775808'"));
431 CHECK(fails("list a: int until 0", "-9223372036854775809 0", "found '-9223372036854775809'"));
432 CHECK(fails("list a: int until 0", "5x 0", "expected int, found '5x'"));
433 CHECK(fails("list a: int until 0", "1 - 0", "expected int, found '-'"));
434 CHECK(fails("a[2]: int", "1", "expected int, found end of input"));
435 CHECK(fails([](void) { (void) Spec::parse("line \"a ... b\"", "s"); }, "'...' must end the pattern"));
436 CHECK(fails("repeat 2 { k: int if k > 0 { x: int } }", "1 5 0", "'x' is defined in only some repetitions"));
437 // A wrong count fails at the end of the input, without allocating
438 CHECK(fails("n: int a[n][1]: int", "1000000000 1 2", "found end of input"));
439 CHECK(fails("n: int g[n][1]: alphabet \"ab\"", "1000000000 ab", "expected a symbol for row 3, column 1"));
440 CHECK(fails("r: int c: int x[r][c]: int", "2000000000 0", "empty rows without reading input"));
441 CHECK(fails("r: int g[r][0]: alphabet \"ab\"", "2000000000", "empty rows without reading input"));
442 CHECK(read("r: int c: int x[r][c]: int", "3 0").size("x") == 3);
443 return true;
444 });
445
446 Case instances("Read::Instances", [](void) {
447 const char* spec = "comment \"+++\"\n"
448 "instances {\n"
449 " sections skip other {\n"
450 " \"instance {name:word}\" optional\n"
451 " \"{n:int}\" last { x[n]: int }\n"
452 " }\n"
453 "}\n";
454 const char* text = "header text\ninstance a\n2\n1 2\n+++\n"
455 "instance b\ndescription\n1\n7\n+++ end\n";
456 Params by_name, by_number, bad;
457 by_name.set("instance", "b");
458 by_number.set("instance", "1");
459 bad.set("instance", "3");
460 CHECK(equal(read(spec, text, by_name).ints("x"), {7}));
461 CHECK(equal(read(spec, text, by_number).ints("x"), {1,2}));
462 CHECK(read(spec, text, by_number).text("name") == "a");
463 CHECK(fails([&](void) { (void) read(spec, text, bad); }, "there is no instance '3' (the file has 2 instances)"));
464 CHECK(fails(spec, text, "the file has 2 instances; select one"));
465 // A single instance needs no selection, and needs no name
466 CHECK(equal(read(spec, "3\n4 5 6\n").ints("x"), {4,5,6}));
467 // The catalog lists numbers and names
468 Spec s = Spec::parse(spec, "s");
469 Data c = s.catalog_text(text);
470 CHECK(c.integer("instances") == 2);
471 CHECK(c.text("name", {1}) == "b");
472 Data c1 = s.catalog_text("3\n4 5 6\n");
473 CHECK((c1.integer("instances") == 1) && !c1.has("name"));
474 CHECK(Spec::parse("a: int", "s").catalog_text("5").integer("instances") == 1);
475 // Trailing input that holds no instance is an error
476 CHECK(fails(spec, "1\n2\njunk\n", "expected a line matching \"{n:int}\""));
477 CHECK(fails("instances { a: int }", "", "the file contains no instance"));
478 CHECK(fails([](void) {
479 (void) Spec::parse("instances { a: int } b: int", "s"); },
480 "'instances' must be the last statement"));
481 CHECK(fails([](void) {
482 (void) Spec::parse("repeat 2 { instances { a: int } }", "s"); },
483 "'instances' must be at the top level"));
484 CHECK(fails("instances { if 0 > 1 { a: int } }", "5", "an instance must read some input"));
485 return true;
486 });
487
488 Case arithmetic("Read::Arithmetic", [](void) {
489 Data d = read("a[3]: int g: float h: float\n"
490 "let s = sum(a) let lo = min(a) let hi = max(a, 7)\n"
491 "check g < 0 && -h < -3.5 \"floats compare\"",
492 "-5 2 1 -1.5 4");
493 CHECK(d.integer("s") == -2);
494 CHECK(d.integer("lo") == -5);
495 CHECK(d.integer("hi") == 7);
496 // Arithmetic is on integers
497 CHECK(fails("f: float let g = f * 2", "1.5", "'*' needs integers"));
498 CHECK(fails("f[1]: float let g = sum(f)", "1.5", "'sum' takes integers"));
499 Data m = read("a: int let p = a * 1 let q = a - a let r = 1 * a", "-9223372036854775808");
500 CHECK(m.integer("p") == m.integer("a"));
501 CHECK(m.integer("q") == 0);
502 CHECK(m.integer("r") == m.integer("a"));
503 CHECK(fails("a: int let b = 0 - a", "-9223372036854775808", "integer overflow"));
504 CHECK(fails("g[1][1]: alphabet \"ab\" base 9223372036854775807", "b", "integer overflow"));
505 return true;
506 });
507
508 Case progress("Read::Progress", [](void) {
509 // Repeats whose body reads no input
510 CHECK(fails("repeat until eof { let x = 1 }", "1", "the body of a repeat until read no input"));
511 CHECK(read("repeat until \"END\" { if 1 > 2 { w: word } }", "END").size("w") == 0);
512 CHECK(fails("repeat until \"END\" { if 1 > 2 { w: word } }", "y END", "the body of a repeat until read no input"));
513 CHECK(fails("n: int repeat n { a[0]: int }", "2000000000", "without reading input"));
514 CHECK(read("n: int repeat n { a[0]: int }", "3").size("a") == 3);
515 // The limit is for the whole run, not each statement
516 CHECK(fails("n: int repeat n { repeat n { let x = 1 } }", "3000", "without reading input"));
517 CHECK(fails("n: int repeat n { a[n][0]: int }", "3000", "without reading input"));
518 return true;
519 });
520
521 Case shapes("Read::Shapes", [](void) {
522 // Empty values keep their declared depth and type
523 Data d = read("repeat 2 { x[0][3]: float }", "");
524 CHECK(d.depth("x") == 3);
526 Data z = read("repeat 0 { x[2][3]: float w: word list l: int until 0 }", "");
527 CHECK((z.depth("x") == 3) && (z.type("x") == Gecode::Instance::ValueType::FLOAT));
528 CHECK((z.depth("w") == 1) && (z.type("w") == Gecode::Instance::ValueType::STRING));
529 CHECK((z.depth("l") == 2) && (z.size("l") == 0));
530 Data m = read("repeat 2 { k: int if k > 5 { x[2][2]: int } }", "1 2");
531 CHECK((m.depth("x") == 3) && (m.size("x") == 2) && (m.size("x", {1}) == 0));
532 CHECK(fails("repeat 2 { k: int if k > 5 { x: int } }", "1 2", "'x' is defined in no repetition"));
533 // Paths reach values at any depth
534 Data e = read("s[1][2][2]: word v[2][1][2]: int", "a b c d 1 2 3 4");
535 CHECK(e.text("s", {0,1,1}) == "d");
536 CHECK(e.integer("v", {1,0,0}) == 3);
537 CHECK(e.size("v", {1,0}) == 2);
538 CHECK(equal(e.ints("v", {1,0}), {3,4}));
539 CHECK(fails([&](void) { (void) e.text("s", {0,2,0}); }, "index out of range"));
540 // Word lists end at an integer terminator
541 CHECK(read("list w: word until 0", "a b 0").size("w") == 2);
542 return true;
543 });
544
545 Case parameters("Read::Parameters", [](void) {
546 Params p;
547 p.set("k", "1.5");
548 CHECK(read("param k check k > 1 && k < 2", "", p).number("k") == 1.5);
549 Params q;
550 q.set("kk", "7");
551 CHECK(fails([&](void) { (void) read("param k = 1", "", q); }, "the spec has no parameter 'kk'"));
552 // A given value has the type of the default
553 Params r;
554 r.set("s", "3"); r.set("i", "4");
555 Data d = read("param s = \"x\" param i = 1 check s == \"3\" && i == 4", "", r);
556 CHECK(d.text("s") == "3");
557 Params t;
558 t.set("i", "4.5");
559 CHECK(fails([&](void) { (void) read("param i = 1", "", t); }, "parameter 'i' must be an integer"));
560 return true;
561 });
562
563 Case checks("Spec::Checks", [](void) {
564 // Errors in specs are found when they are parsed
565 CHECK(fails([](void) {
566 (void) Spec::parse("n: int if n > 5 { let y = sqrt(n) }", "s");
567 }, "unknown function 'sqrt'"));
568 CHECK(fails([](void) { (void) Spec::parse("let y = count(1, 2)", "s"); }, "wrong arguments for function 'count'"));
569 CHECK(fails([](void) { (void) Spec::parse("line \"{bad-name:int}\"", "s"); }, "is not a name"));
570 CHECK(fails([](void) {
571 (void) Spec::parse("let y = " + std::string(300, '(') + "1" + std::string(300, ')'), "s");
572 }, "nested too deeply"));
573 // Long operator chains and else-if chains are deep trees as well
574 std::string sum = "let y = 1", chain = "n: int if n == 0 { }";
575 for (int i=0; i<300; i++) {
576 sum += " + 1";
577 chain += " else if n == " + std::to_string(i+1) + " { }";
578 }
579 CHECK(fails([&](void) { (void) Spec::parse(sum, "s"); }, "nested too deeply"));
580 CHECK(fails([&](void) { (void) Spec::parse(chain, "s"); }, "nested too deeply"));
581 CHECK(fails([](void) { (void) Spec::parse("let _ = 1", "s"); }, "'_' cannot be defined here"));
582 CHECK(fails([](void) { (void) Spec::parse("w: word offset 1", "s"); }, "'offset' needs numbers"));
583 return true;
584 });
585
586 Case strings("Spec::Strings", [](void) {
587 // The escapes \n, \t, \\, and \"
588 Data d = read("let s = \"a\\nb\\tc\\\\d\\\"e\"", "");
589 CHECK(d.text("s") == "a\nb\tc\\d\"e");
590 // Other escapes and a backslash before a newline are errors on their line
591 CHECK(fails([](void) { (void) Spec::parse("a: int\nlet s = \"a\\db\"", "s"); }, "s:2: unknown escape '\\d'"));
592 CHECK(fails([](void) { (void) Spec::parse("a: int\nlet s = \"a\\\nb\"\nb: int", "s"); }, "s:2: unterminated string"));
593 // Escapes do not disturb the line numbers of later errors
594 CHECK(fails([](void) {
595 (void) Spec::parse("let s = \"a\\\\\"\nlet t = \"\\\"\"\nx: int untl", "s");
596 }, "s:3: unknown statement 'untl'"));
597 return true;
598 });
599
600 Case settings("Spec::Settings", [](void) {
601 // Settings apply to the rest of the input, so they are not in blocks
602 const char* nested[] = {
603 "repeat 2 { comment \"c\" a: int }",
604 "if 1 > 0 { stop \"%\" }",
605 "n: int if n > 0 { } else if n < 0 { tokens \";\" }",
606 "instances { separators \",\" a: int }",
607 "sections { \"x\" { ignore trailing } }"
608 };
609 for (const char* s : nested)
610 CHECK(fails([&](void) { (void) Spec::parse(s, "s"); }, "must be at the top level of the spec"));
611 CHECK(fails([](void) { (void) Spec::parse("a: int\nrepeat a {\n comment \"c\"\n}", "s"); },
612 "s:3: the setting 'comment' must be at the top level"));
613 // Literal tokens are not a setting
614 CHECK(read("repeat 2 { expect \"x\" a: int }", "x 1 x 2").size("a") == 2);
615 return true;
616 });
617
619 struct HelpShown {};
620
622 template<class Opt>
623 class HelpOptions : public Opt {
624 public:
625 HelpOptions(void) : Opt("Strict parsing test") {}
626 void help(void) override {
627 Opt::help();
628 throw HelpShown();
629 }
630 };
631
633 template<class Opt>
634 bool rejects(HelpOptions<Opt>& options, int argc, char* argv[],
635 const char* arg) {
636 bool help_shown = false;
637 std::ostringstream output;
638 std::streambuf* previous = std::cerr.rdbuf(output.rdbuf());
639 try {
640 options.parse_strict(argc, argv);
641 } catch (const HelpShown&) {
642 help_shown = true;
643 } catch (...) {
644 std::cerr.rdbuf(previous);
645 throw;
646 }
647 std::cerr.rdbuf(previous);
648 std::string expected = std::string("Unrecognised argument \"") + arg + "\"";
649 return help_shown &&
650 (output.str().find(expected) != std::string::npos) &&
651 (output.str().find("Options for Strict parsing test:") != std::string::npos);
652 }
653
654 Case strict_options("Driver::Options::Strict", [](void) {
655 Gecode::Options options("Test");
656 char name[] = "test", iterations[] = "-iterations", value[] = "200";
657 char unknown[] = "--typo", help[] = "--help", positional[] = "instance.txt";
658 char* valid_argv[] = {name, iterations, value, nullptr};
659 int valid_argc = 3;
660 options.parse_strict(valid_argc, valid_argv);
661 CHECK(valid_argc == 1 && options.iterations() == 200);
662
663 // Both the original overload and explicit non-strict parsing leave
664 // arguments for callers to interpret.
665 char* remaining_argv[] = {name, unknown, positional, nullptr};
666 int remaining_argc = 3;
667 options.parse(remaining_argc, remaining_argv);
668 CHECK(remaining_argc == 3 && remaining_argv[1] == unknown);
669 options.parse_permissive(remaining_argc, remaining_argv);
670 CHECK(remaining_argc == 3 && remaining_argv[2] == positional);
671
673 char* invalid_argv[] = {name, iterations, value, unknown, help, nullptr};
674 CHECK(rejects(strict, 5, invalid_argv, "--typo"));
675 char* positional_argv[] = {name, positional, nullptr};
676 CHECK(rejects(strict, 2, positional_argv, "instance.txt"));
677 return true;
678 });
679
680 Case strict_size_options("Driver::SizeOptions::Strict", [](void) {
681 char name[] = "test", iterations[] = "-iterations", value[] = "200";
682 char size[] = "7", other[] = "8", unknown[] = "--typo", word[] = "seven";
683
684 // The size is the only argument that may remain
686 char* valid_argv[] = {name, iterations, value, size, nullptr};
687 int valid_argc = 4;
688 options.parse_strict(valid_argc, valid_argv);
689 CHECK(options.size() == 7 && options.iterations() == 200);
690 char* options_argv[] = {name, iterations, value, nullptr};
691 int options_argc = 3;
692 options.parse_strict(options_argc, options_argv);
693 CHECK(options_argc == 1 && options.size() == 7);
694
695 char* unknown_argv[] = {name, unknown, size, nullptr};
696 CHECK(rejects(options, 3, unknown_argv, "--typo"));
697 char* extra_argv[] = {name, size, other, nullptr};
698 CHECK(rejects(options, 3, extra_argv, "8"));
699 char* word_argv[] = {name, word, nullptr};
700 CHECK(rejects(options, 2, word_argv, "seven"));
701
702 // Permissive parsing still reads the size and keeps the rest
703 char* permissive_argv[] = {name, other, size, nullptr};
704 int permissive_argc = 3;
705 options.parse_permissive(permissive_argc, permissive_argv);
706 CHECK(permissive_argc == 3 && options.size() == 8);
707 return true;
708 });
709
710 Case strict_instance_options("Driver::InstanceOptions::Strict", [](void) {
711 char name[] = "test", iterations[] = "-iterations", value[] = "200";
712 char inst[] = "instance.txt", other[] = "other.txt", unknown[] = "--typo";
713
714 // The instance is the only argument that may remain
716 char* valid_argv[] = {name, iterations, value, inst, nullptr};
717 int valid_argc = 4;
718 options.parse_strict(valid_argc, valid_argv);
719 CHECK(std::strcmp(options.instance(), "instance.txt") == 0 &&
720 options.iterations() == 200);
721
722 char* unknown_argv[] = {name, unknown, inst, nullptr};
723 CHECK(rejects(options, 3, unknown_argv, "--typo"));
724 char* extra_argv[] = {name, inst, other, nullptr};
725 CHECK(rejects(options, 3, extra_argv, "other.txt"));
726
727 // Permissive parsing takes the first remaining argument as instance
728 char* permissive_argv[] = {name, other, inst, nullptr};
729 int permissive_argc = 3;
730 options.parse_permissive(permissive_argc, permissive_argv);
731 CHECK(permissive_argc == 3 &&
732 std::strcmp(options.instance(), "other.txt") == 0);
733 return true;
734 });
735
736 Case options("Driver::InstanceOptions", [](void) {
737 // Unique names in the temporary directory
738 const char* tmp = std::getenv("TMPDIR");
739 if (tmp == nullptr) tmp = std::getenv("TEMP");
740 std::string base = std::string(tmp == nullptr ? "." : tmp) +
741 "/gecode-instance-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count());
742 std::string fs = base + ".txt", os = base + ".reader";
743 const char* file = fs.c_str();
744 const char* other = os.c_str();
745 {
746 std::ofstream f(file);
747 f << "2 3 4\n";
748 std::ofstream g(other);
749 g << "a: int b: int c: int\n";
750 }
751 bool ok = true;
752 try {
753 // The script's own spec, with parameters given by repeated options
754 const char* with_params = "param k = 3 param m = 0 n: int x[n * k - m]: int";
755 Gecode::InstanceOptions o("Test", with_params);
756 char a0[] = "test", a1[] = "-param", a2[] = "k=2", a3[] = "", a4[] = "m=2";
757 std::string inst(file);
758 char* argv[] = {a0, a1, a2, a1, a4, &inst[0], a3};
759 int argc = 6;
760 o.parse(argc, argv);
761 ok = ok && o.is_file();
762 ok = ok && equal(o.data().ints("x"), {3,4});
763 // The same parameters separated by commas
764 Gecode::InstanceOptions c("Test", with_params);
765 char c2[] = "k=2,m=2";
766 char* argu[] = {a0, a1, c2, &inst[0], a3};
767 int argcu = 4;
768 c.parse(argcu, argu);
769 ok = ok && equal(c.data().ints("x"), {3,4});
770 // A spec file replaces the script's spec
771 Gecode::InstanceOptions s("Test", "n: int");
772 char b1[] = "-spec";
773 std::string spec(other);
774 char* argw[] = {a0, b1, &spec[0], &inst[0], a3};
775 int argcw = 4;
776 s.parse(argcw, argw);
777 ok = ok && (s.data().integer("c") == 4);
778 // Directories are not instance files
779 s.instance(".");
780 ok = ok && !s.is_file();
781 } catch (const Error& e) {
782 olog << e.what() << "\n";
783 ok = false;
784 }
785 std::remove(file);
786 std::remove(other);
787 return ok;
788 });
789
790 Case errors("Read::Errors", [](void) {
791 CHECK(fails("n: int repeat n { x: int }", "3\n1\n2 z\n", "test.txt:3:3: expected int, found 'z'"));
792 CHECK(fails("n: int repeat n { x: int }", "3\n1\n2\n", "while reading: repeat [3 of 3] > x"));
793 CHECK(fails("n: int repeat n { x: int }", "3\n1\n2\n", "spec: test.reader:1"));
794 CHECK(fails([](void) { (void) Spec::parse("x: int untl", "s"); }, "s:1: unknown statement 'untl'"));
795 CHECK(fails([](void) { (void) Spec::parse("repeat 2 { x: int", "s"); }, "missing '}'"));
796 CHECK(fails([](void) { (void) Spec::parse("line \"{x:bad}\"", "s"); }, "unknown type 'bad'"));
797 CHECK(fails([](void) { (void) Spec::load("/nonexistent/x.reader"); }, "cannot open file"));
798 CHECK(fails([](void) { (void) Spec::load("."); }, "is a directory"));
799 return true;
800 });
801
802 Case access("Data::Access", [](void) {
803 Data d = read("big: int w: word n: int repeat n { k: int x[k]: int }", "9999999999 hi 2 1 5 2 6 7");
804 CHECK(d.integer("big") == 9999999999LL);
805 CHECK(fails([&](void) { (void) d.ints("big"); }, "is not an array"));
806 CHECK(fails([&](void) { (void) d.integer("w"); }, "is not an integer"));
807 CHECK(fails([&](void) { (void) d.integer("nope"); }, "no value named"));
808 CHECK(fails([&](void) { (void) d.size("x", {2}); }, "index out of range"));
809 CHECK(fails([&](void) { (void) d.integer("x", {0}); }, "is not a single value"));
810 Data e = read("n: int repeat n { v: int }", "1 9999999999");
811 CHECK(fails([&](void) { (void) e.ints("v"); }, "does not fit into an int"));
812 return true;
813 });
814
815 Case output("Data::Output", [](void) {
816 Data d = read("n: int f: float w: word m[2][2]: int repeat n { k: int x[k]: int }", "2 20 a 1 2 3 4 1 5 2 6 7");
817 std::ostringstream z;
818 d.dzn(z);
819 CHECK(z.str().find("f = 20.0;") != std::string::npos);
820 CHECK(z.str().find("m = [| 1, 2\n | 3, 4 |];") != std::string::npos);
821 CHECK(z.str().find("% x: array[int] of tuple(array[int] of int)\n"
822 "x = [([5],), ([6, 7],)];") != std::string::npos);
823 CHECK(z.str().find("w = \"a\";") != std::string::npos);
824 // MiniZinc keywords are quoted, control characters escaped
825 std::ostringstream zq;
826 read("var: int w: word", "3 a\033b").dzn(zq);
827 CHECK(zq.str().find("'var' = 3;") != std::string::npos);
828 CHECK(zq.str().find("w = \"a\\x1bb\";") != std::string::npos);
829 // Empty dimensions and deeply ragged arrays
830 Data e = read("e[2][0]: int repeat 2 { k: int repeat k { list y: int until 0 } }", "1 7 0 2 8 9 0 0");
831 std::ostringstream ze;
832 e.dzn(ze);
833 CHECK(ze.str().find("e = array2d(1..2, 1..0, []);") != std::string::npos);
834 CHECK(ze.str().find("y = [([([7],)],), ([([8, 9],), ([],)],)];") != std::string::npos);
835 // MiniZinc has no constructor beyond array6d
836 std::ostringstream z7;
837 read("a[1][1][1][1][1][1][1]: int", "5").dzn(z7);
838 CHECK(z7.str().find("a = [([([([([([([5],)],)],)],)],)],)];") != std::string::npos);
839 return true;
840 });
841
842 Case labels("Read::Labels", [](void) {
843 // The layout of PSPLIB single-mode RCPSP files
844 const char* spec = "comment \"***\" \"---\"\n"
845 "find \"jobs (incl. supersource/sink ): {jobs:int}\"\n"
846 "find \"- renewable : {renewable:int} R\"\n"
847 "find \"PRECEDENCE RELATIONS:\"\n"
848 "line \"jobnr. #modes #successors successors\"\n"
849 "repeat jobs { index 1 modes: int nsucc: int successors[nsucc]: int offset -1 }\n"
850 "line \"REQUESTS/DURATIONS:\"\n"
851 "line \"jobnr. mode duration ...\"\n"
852 "repeat jobs { index 1 _: int duration: int request[renewable]: int }\n"
853 "line \"RESOURCEAVAILABILITIES:\"\n"
854 "line \"R 1 ...\"\n"
855 "capacity[renewable]: int\n";
856 Data d = read(spec,
857 "****\n"
858 "jobs (incl. supersource/sink ): 3\n"
859 "horizon : 9\n"
860 "RESOURCES\n"
861 " - renewable : 1 R\n"
862 " - nonrenewable : 0 N\n"
863 " - doubly constrained : 0 D\n"
864 "****\n"
865 "PRECEDENCE RELATIONS:\n"
866 "jobnr. #modes #successors successors\n"
867 " 1 1 1 2\n"
868 " 2 1 1 3\n"
869 " 3 1 0\n"
870 "****\n"
871 "REQUESTS/DURATIONS:\n"
872 "jobnr. mode duration R 1\n"
873 "------------------------\n"
874 " 1 1 0 0\n"
875 " 2 1 4 2\n"
876 " 3 1 0 0\n"
877 "****\n"
878 "RESOURCEAVAILABILITIES:\n"
879 " R 1\n"
880 " 3\n"
881 "****\n");
882 CHECK(equal(d.ints("successors"), {1,2}));
883 CHECK(equal(d.ints("duration"), {0,4,0}));
884 CHECK(equal(d.ints("capacity"), {3}));
885 return true;
886 });
887
888 Case expressions("Read::Expressions", [](void) {
889 // Indices start at 0, for numbers and for rows of ragged arrays
890 const char* rows = "n: int repeat n { list r: int until eol } f[2]: float w[2]: word\n";
891 const char* text = "3\n1 2\n3 3 4\n5\n0.5 2.5 a b";
892 Data d = read((std::string(rows) +
893 "let a = r[1] let b = r[1][2] + r[2][0] let g = f[1] let v = w[0]\n"
894 "let s = sum(x in r: sum(x)) let c = count(x in r: count(x) > 1)\n"
895 "let t = sum(x in r: sum(y in x: y * y)) let k = count(x in f: x > 1)\n"
896 "check all(x in r: sum(x) + count(x) - 1 <= 12) && !all(x in r: count(x) == 2)\n"
897 "check any(x in r: !distinct(x)) && !any(x in w: x == \"c\") && any(x in w: x == \"b\")\n"
898 "let d = distinct(r[0], 3) && !distinct(r[0], r[2], 2) && distinct(r[1][1]) check d\n"
899 "check all(x in r: defined(x)) && !defined(x)").c_str(), text);
900 CHECK(equal(d.ints("a"), {3,3,4}));
901 CHECK(d.integer("b") == 9);
902 CHECK(d.number("g") == 2.5);
903 CHECK(d.text("v") == "a");
904 CHECK(d.integer("s") == 18);
905 CHECK(d.integer("c") == 2);
906 CHECK(d.integer("t") == 64);
907 CHECK(d.integer("k") == 1);
908 // Empty arrays
909 Data e = read("a[0]: int let s = sum(x in a: x) let c = count(x in a: 1)\n"
910 "check all(x in a: 0) && !any(x in a: 1) && distinct(a)", "");
911 CHECK((e.integer("s") == 0) && (e.integer("c") == 0));
912 // Errors
913 std::string r(rows);
914 CHECK(fails((r + "let z = r[3]").c_str(), text, "index 3 is out of range for 'r' (size 3, indices start at 0)"));
915 CHECK(fails((r + "let z = r[0 - 1]").c_str(), text, "index -1 is out of range"));
916 CHECK(fails((r + "let z = r[1][3]").c_str(), text, "index 3 is out of range for an element of 'r' (size 3"));
917 CHECK(fails((r + "let z = n[0]").c_str(), text, "only arrays can be indexed, not 'n'"));
918 CHECK(fails((r + "let z = r[f[0]]").c_str(), text, "an index must be an integer"));
919 CHECK(fails((r + "let z = r[0][0][0]").c_str(), text, "only arrays can be indexed, not an element of 'r'"));
920 CHECK(fails((r + "let z = all(x in n: 1)").c_str(), text, "'all(x in ...)' needs an array"));
921 CHECK(fails((r + "let z = sum(x in r: x)").c_str(), text, "'sum' needs integers"));
922 CHECK(fails((r + "let z = count(x in r: 1) + x").c_str(), text, "'x' is not defined yet"));
923 CHECK(fails((r + "let z = all(x in r: q)").c_str(), text, "'q' is not defined yet"));
924 CHECK(fails((r + "let z = distinct(w)").c_str(), text, "'distinct' takes integers"));
925 CHECK(fails("a[2]: int let z = sum(x in a: x)", "9223372036854775807 1", "integer overflow in 'sum'"));
926 return true;
927 });
928
929 Case comprehensions("Spec::Comprehensions", [](void) {
930 // The bound name is defined only in the body, and must be new
931 CHECK(fails([](void) { (void) Spec::parse("n: int a[n]: int check all(n in a: n > 0)", "s"); },
932 "s:1: 'n' is bound by a comprehension but is also a name in the spec"));
933 CHECK(fails([](void) { (void) Spec::parse("a[2]: int\ncheck all(x in a: 1)\nrepeat 2 { x: int }", "s"); },
934 "s:2: 'x' is bound by a comprehension but is also a name in the spec"));
935 CHECK(fails([](void) { (void) Spec::parse("a[2][2]: int check all(x in a: all(x in x: 1))", "s"); },
936 "'x' is already bound by an enclosing comprehension"));
937 CHECK(fails([](void) { (void) Spec::parse("a[2]: int check all(_ in a: 1)", "s"); }, "'_' cannot be bound"));
938 CHECK(fails([](void) { (void) Spec::parse("a[2]: int check all(a)", "s"); },
939 "'all' needs the form all(x in a: e)"));
940 CHECK(fails([](void) { (void) Spec::parse("a[2]: int check any(x in a)", "s"); }, "expected ':'"));
941 CHECK(fails([](void) { (void) Spec::parse("a[2]: int check a[0", "s"); }, "expected ']'"));
942 CHECK(fails([](void) { (void) Spec::parse("let y = distinct()", "s"); },
943 "wrong arguments for function 'distinct'"));
944 // Comprehensions over the bound name of an enclosing one, and the same
945 // name in comprehensions that do not nest
946 Data d = read("a[2][2]: int let s = sum(x in a: sum(y in x: y)) + sum(y in a: count(y))", "1 2 3 4");
947 CHECK(d.integer("s") == 14);
948 // Long index chains are deep trees as well
949 std::string chain = "a[1]: int let y = a";
950 for (int i=0; i<300; i++)
951 chain += "[0]";
952 CHECK(fails([&](void) { (void) Spec::parse(chain, "s"); }, "nested too deeply"));
953 return true;
954 });
955
956 Case effort("Read::Effort", [](void) {
957 // Expressions visit values in proportion to the input
958 std::string text = "2000\n";
959 for (int i=0; i<2000; i++)
960 text += "1 ";
961 CHECK(read("n: int a[n]: int check all(x in a: x == 1) && sum(a) == n", text.c_str()).size("a") == 2000);
962 // Comprehensions and repeated sums over the whole array
963 CHECK(fails("n: int a[n]: int check all(x in a: sum(a) > 0)", text.c_str(),
964 "the expressions do too much work for the size of the input"));
965 // Nested comprehensions, which copy rows
966 std::string rows = "100 500\n";
967 for (int i=0; i<100*500; i++)
968 rows += "1 ";
969 CHECK(read("m: int k: int a[m][k]: int check all(r in a: all(s in r: s == 1))", rows.c_str()).size("a") == 100);
970 CHECK(fails("m: int k: int a[m][k]: int check all(r in a: all(s in a: 1))", rows.c_str(), "too much work"));
971 std::string more = text;
972 for (int i=0; i<2000; i++)
973 more += "1 ";
974 CHECK(fails("n: int a[n]: int repeat n { k: int check sum(a) > 0 }", more.c_str(), "too much work"));
975 return true;
976 });
977
978 Case skipped("Read::SkippedInstances", [](void) {
979 const char* spec = "instances {\n"
980 " sections skip other {\n"
981 " \"instance {name:word}\" optional\n"
982 " \"{n:int}\" last { check n <= 3 \"n is at most 3\" x[n][n]: int }\n"
983 " }\n"
984 "}\n";
985 const char* text = "instance a\n4\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16\ninstance b\n1\n7\n";
986 Params first, second, a, b;
987 first.set("instance", "1"); second.set("instance", "2");
988 a.set("instance", "a"); b.set("instance", "b");
989 // An invalid earlier instance does not hide a valid later one
990 CHECK(equal(read(spec, text, second).ints("x"), {7}));
991 CHECK(equal(read(spec, text, b).ints("x"), {7}));
992 // An invalid selected instance is an error
993 CHECK(fails([&](void) { (void) read(spec, text, first); }, "check failed: n is at most 3"));
994 CHECK(fails([&](void) { (void) read(spec, text, a); }, "check failed: n is at most 3"));
995 CHECK(fails(spec, "4\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16\n", "check failed: n is at most 3"));
996 // Without a selection, a later invalid instance gives the usual error
997 CHECK(fails(spec, "1\n7\n4\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16\n", "the file has 2 instances; select one"));
998 // The catalog has the message of the first failed check of each instance
999 Spec s = Spec::parse(spec, "s");
1000 Data c = s.catalog_text(text);
1001 CHECK(c.integer("instances") == 2);
1002 CHECK((c.text("failed", {0}) == "n is at most 3") && (c.text("failed", {1}) == ""));
1003 CHECK(!s.catalog_text("instance a\n1\n7\n").has("failed"));
1004 CHECK(Spec::parse("instances { n: int check n > 5 }", "s").catalog_text("7 1").text("failed", {1}) ==
1005 "check on line 1 of the spec");
1006 // An instance selected by name may fail a check before its name is known
1007 const char* late = "instances { n: int check n > 0 \"positive\" name: word }";
1008 Params y;
1009 y.set("instance", "y");
1010 CHECK(read(late, "0 x 5 y", y).integer("n") == 5);
1011 CHECK(fails([&](void) { (void) read(late, "5 x 0 y", y); }, "check failed: positive"));
1012 // Other errors in a skipped instance stop reading, also when large sizes
1013 // follow a failed check
1014 CHECK(fails([&](void) { (void) read(spec, "instance a\n2\n1 2 3 x\ninstance b\n1\n7\n", b); }, "expected int"));
1015 auto start = std::chrono::steady_clock::now();
1016 CHECK(fails([&](void) { (void) read(spec, "instance a\n1000000000\n1 2\ninstance b\n1\n7\n", b); },
1017 "array is too large"));
1018 CHECK(fails([&](void) { (void) read(spec, "instance a\n40000\n1 2\ninstance b\n1\n7\n", b); },
1019 "after an earlier error in the instance: n is at most 3"));
1020 CHECK(std::chrono::steady_clock::now() - start < std::chrono::seconds(10));
1021 // A missing or repeated sections line in a skipped instance is deferred
1022 // as a failed check is
1023 const char* repeated = "instance a\ninstance x\n1\n7\ninstance b\n1\n8\n";
1024 CHECK(equal(read(spec, repeated, b).ints("x"), {8}));
1025 CHECK(fails([&](void) { (void) read(spec, repeated, a); },
1026 "test.txt:2:1: a second line matching \"instance {name:word}\""));
1027 CHECK(s.catalog_text(repeated).text("failed", {0}) == "a second line matching \"instance {name:word}\"");
1028 const char* stop = "instances { sections { \"n {n:int}\" \"m {m:int}\" \"end\" last } }";
1029 Params two;
1030 two.set("instance", "2");
1031 CHECK(read(stop, "n 1\nend\nn 2\nm 3\nend\n", two).integer("m") == 3);
1032 CHECK(Spec::parse(stop, "s").catalog_text("n 1\nend\nn 2\nm 3\nend\n").text("failed", {0}) ==
1033 "no line matching \"m {m:int}\"");
1034 // A selection that is not a number is a name
1035 Params named;
1036 named.set("instance", "3x");
1037 CHECK(read("instances { n: int name: word }", "1 a 2 3x 3 c", named).integer("n") == 2);
1038 return true;
1039 });
1040
1041 Case power("Read::Power", [](void) {
1042 // ^ binds tighter than * and unary -, and groups to the right
1043 Data d = read("let a = 2 * 3 ^ 2 let b = 2 ^ 3 ^ 2 let c = (2 ^ 3) ^ 2 let e = -2 ^ 2 let f = 1 + 2 ^ 2 * 3\n"
1044 "let k = (-2) ^ 2 let m = -2 ^ 3 ^ 2\n"
1045 "let g = 7 ^ 0 let h = (0 - 2) ^ 63 let i = 1 ^ 9223372036854775807 let j = 3 ^ 39", "");
1046 CHECK(d.integer("a") == 18);
1047 CHECK(d.integer("b") == 512);
1048 CHECK(d.integer("c") == 64);
1049 CHECK(d.integer("e") == -4);
1050 CHECK(d.integer("k") == 4);
1051 CHECK(d.integer("m") == -512);
1052 CHECK(d.integer("f") == 13);
1053 CHECK(d.integer("g") == 1);
1054 CHECK(d.integer("h") == LLONG_MIN);
1055 CHECK(d.integer("i") == 1);
1056 CHECK(d.integer("j") == 4052555153018976267LL);
1057 CHECK(fails("let x = 3 ^ 40", "", "integer overflow in '^'"));
1058 CHECK(fails("let x = 2 ^ 63", "", "integer overflow in '^'"));
1059 CHECK(fails("let x = 2 ^ -1", "", "negative exponent in '^'"));
1060 CHECK(fails("let x = 2 ^ -1 + 3", "", "negative exponent in '^'"));
1061 CHECK(fails("let x = -2 ^ 63", "", "integer overflow in '^'"));
1062 CHECK(fails("f: float let x = f ^ 2", "1.5", "'^' needs integers"));
1063 return true;
1064 });
1065
1066 Case constants("Spec::GecodeConstants", [](void) {
1067 Data d = read("let a = gecode.int_max let b = gecode.int_min let c = gecode.int_max / 2\n"
1068 "gecode: int check gecode == 3", "3");
1069 CHECK(d.integer("a") == Gecode::Int::Limits::max);
1070 CHECK(d.integer("b") == Gecode::Int::Limits::min);
1071 CHECK(d.integer("c") == 1073741823);
1072 CHECK(fails([](void) { (void) Spec::parse("let x = 1\nlet y = gecode.foo", "s"); },
1073 "s:2: unknown Gecode constant 'gecode.foo' (known: gecode.int_max, gecode.int_min)"));
1074 // Specs cannot define such names
1075 const char* defining[] = {
1076 "gecode.x: int", "let gecode.int_max = 3", "param gecode.p", "list gecode.l: int until 0",
1077 "gecode.g[1][1]: alphabet \"a\"", "repeat until \"x\" store gecode.t { a: int }",
1078 "a[2]: int check all(gecode.v in a: 1)"
1079 };
1080 for (const char* spec : defining)
1081 if (!fails([&](void) { (void) Spec::parse(spec, "s"); }, "names starting with 'gecode.' are Gecode constants"))
1082 return false;
1083 return true;
1084 });
1085
1086 Case records("Read::Records", [](void) {
1087 // A check after a repeat holds for every record, and a failure names
1088 // the record and points at its input
1089 const char* rows = "n: int repeat n { list row: int until eol } width: int\n"
1090 "check sum(row) + count(row) - 1 <= width \"the clues do not fit\"";
1091 CHECK(read(rows, "2\n1 1\n2\n3").size("row") == 2);
1092 CHECK(fails(rows, "2\n1 1\n 2 2\n3", "test.txt:3:3: check failed for record 2 of 'row': the clues do not fit"));
1093 // Internal values do not show in the data
1094 CHECK(read(rows, "2\n1 1\n2\n3").entries() == 3);
1095 // Names of one repeat are taken from the same record
1096 const char* windows = "n: int repeat n { ready: int due: int } check ready <= due \"window\"";
1097 CHECK(read(windows, "2 3 5 0 1").size("ready") == 2);
1098 CHECK(fails(windows, "3 0 5 2 4 6 1", "check failed for record 3 of 'ready': window"));
1099 // Nested repeats: every inner record of every outer record
1100 const char* jobs = "j: int m: int repeat j { k: int repeat m { x: int } } check x < k \"x below k\"";
1101 CHECK(read(jobs, "2 2\n5 1 2\n3 1 2\n").size("x") == 2);
1102 CHECK(fails(jobs, "2 2\n5 1 2\n3 1 4\n", "test.txt:3:5: check failed for record 2 of record 2 of 'x': x below k"));
1103 // The whole array: size, the array of a comprehension, and defined
1104 Data d = read("n: int repeat n { list row: int until eol }\n"
1105 "check size(row) == 2 && count(row) == 3 && sum(r in row: sum(r)) == 21\n"
1106 "check count(r in row: count(r) == 3) == size(row) && defined(row)", "2\n1 2 3\n4 5 6\n");
1107 CHECK(d.size("row") == 2);
1108 // Record names in the body of a comprehension range over records
1109 CHECK(fails("n: int lim[2]: int repeat n { x: int } check all(l in lim: x < l) \"below\"", "2 5 3 1 4",
1110 "check failed for element 2 of 'lim' in record 2 of 'x': below"));
1111 // A name that is not defined does not range over records
1112 const char* optional =
1113 "sections { \"A\" optional { repeat 2 { x: int } } \"B\" optional } check !defined(x) || x > 0 \"positive\"";
1114 CHECK(!read(optional, "B").has("x"));
1115 CHECK(read(optional, "A\n1 2").size("x") == 2);
1116 CHECK(fails(optional, "A\n1 0", "check failed for record 2 of 'x': positive"));
1117 // Inside the repeat that defines it, a name is the current record
1118 CHECK(fails("n: int repeat n { list row: int until eol check count(row) == 2 \"two\" }", "2\n1 2\n3\n",
1119 "check failed: two"));
1120 CHECK(fails("n: int repeat n { list row: int until eol check count(row) == 2 \"two\" }", "2\n1 2\n3\n",
1121 "while reading: repeat [2 of 2]"));
1122 // Between the check and the definition, the repeats range over records
1123 CHECK(read("repeat 2 { repeat 2 { x: int } check size(x) == 2 && x > 0 }", "1 2 3 4").size("x") == 2);
1124 CHECK(fails("repeat 2 { repeat 2 { x: int } check x > 0 \"positive\" }", "1 2 3 0",
1125 "check failed for record 2 of 'x': positive"));
1126 // Only checks range over records
1127 Data l = read("n: int repeat n { x: int } let s = sum(x) let f = x[0] if count(x) == 2 { let t = 1 }", "2 3 4");
1128 CHECK(l.integer("s") == 7);
1129 CHECK(l.integer("f") == 3);
1130 CHECK(l.has("t"));
1131 // Without records, the check holds
1132 CHECK(read("n: int repeat n { x: int } check x > 0 && 1 > 2", "0").size("x") == 0);
1133 return true;
1134 });
1135
1136 Case record_names("Spec::Records", [](void) {
1137 CHECK(fails([](void) { (void) Spec::parse("n: int repeat n { a: int }\nrepeat n { b: int }\ncheck a < b", "s"); },
1138 "s:3: a check can only range over the records of one repeat, but 'a' and 'b' are defined in different "
1139 "repeats"));
1140 CHECK(fails([](void) {
1141 (void) Spec::parse("repeat 2 { repeat 2 { a: int } repeat 2 { b: int } } check a < b", "s");
1142 }, "can only range over the records of one repeat"));
1143 CHECK(fails([](void) { (void) Spec::parse("n: int repeat n { a: int } let a = 3\ncheck a < 1", "s"); },
1144 "s:2: 'a' is defined in several repeats, or inside and outside a repeat"));
1145 CHECK(fails([](void) { (void) Spec::parse("repeat 2 { a: int } repeat 2 { a: int } check a < 1", "s"); },
1146 "'a' is defined in several repeats"));
1147 // Definitions that all enclose the check, or in one repeat
1148 (void) Spec::parse("n: int repeat n { a: int check a > 0 } let a = 3", "s");
1149 (void) Spec::parse("repeat 2 { k: int if k > 0 { a: int } else { let a = 0 } } check a >= 0", "s");
1150 return true;
1151 });
1152
1153 Case record_effort("Read::RecordEffort", [](void) {
1154 // Each record that a check visits counts
1155 std::string text = "2000\n";
1156 for (int i=0; i<4000; i++)
1157 text += "1 ";
1158 CHECK(read("n: int repeat n { x: int } a[n]: int check x == 1 && a[0] == 1", text.c_str()).size("x") == 2000);
1159 CHECK(fails("n: int repeat n { x: int } a[n]: int check x <= sum(a)", text.c_str(),
1160 "the expressions do too much work for the size of the input"));
1161 return true;
1162 });
1163
1164 Case skipped_records("Read::SkippedInstanceRecords", [](void) {
1165 // A check over records in an instance before the selected one does not
1166 // stop reading
1167 const char* spec = "instances { n: int repeat n { x: int } check x > 0 \"positive\" name: word }";
1168 const char* text = "2 1 0 a\n1 5 b\n";
1169 Params a, b;
1170 a.set("instance", "a"); b.set("instance", "b");
1171 CHECK(equal(read(spec, text, b).ints("x"), {5}));
1172 CHECK(fails([&](void) { (void) read(spec, text, a); }, "test.txt:1:5: check failed for record 2 of 'x': positive"));
1173 Data c = Spec::parse(spec, "s").catalog_text(text);
1174 CHECK((c.text("failed", {0}) == "positive") && (c.text("failed", {1}) == ""));
1175 return true;
1176 });
1177
1178 Case record_lists("Read::RecordLists", [](void) {
1179 // The list of records of a repeat, and each of its records
1180 const char* nodes = "n: int repeat n as nodes { each node ready: int due: int }\n"
1181 "check node.ready <= node.due \"window\"\n"
1182 "check nodes[0].ready == 0 \"depot\"\n"
1183 "let k = size(nodes) let d = nodes[1].due let c = count(x in nodes: x.due > 4)";
1184 Data d = read(nodes, "3\n0 5\n2 4\n6 7\n");
1185 CHECK((d.integer("k") == 3) && (d.integer("d") == 4) && (d.integer("c") == 2));
1186 // The names are not in the data
1187 CHECK(!d.has("nodes") && !d.has("node") && (d.entries() == 6));
1188 CHECK(fails(nodes, "3\n0 5\n2 4\n6 1\n", "test.txt:4:1: check failed for record 3 of 'nodes': window"));
1189 CHECK(fails(nodes, "3\n1 5\n2 4\n6 7\n", "check failed: depot"));
1190 CHECK(fails("n: int repeat n as nodes { a: int } let x = nodes[3].a", "2 1 2",
1191 "index 3 is out of range for 'nodes' (size 2, indices start at 0)"));
1192 // Only the list, or only each record
1193 CHECK(read("repeat 2 as xs { a: int } let s = sum(x in xs: x.a)", "3 4").integer("s") == 7);
1194 CHECK(fails("repeat 3 { each x a: int b: int } check x.a < x.b \"less\"", "1 2 3 4 6 5",
1195 "test.txt:1:9: check failed for record 3 of 'x': less"));
1196 // Inside the repeat, each record is the current one
1197 Data in = read("repeat 2 as xs { each x a: int b: int let w = x.b - x.a check x.a <= x.b }", "1 4 2 2");
1198 CHECK(equal(in.ints("w"), {3, 0}));
1199 // Nested lists: each record of a job has a list of steps
1200 const char* jobs = "n: int m: int\n"
1201 "repeat n as jobs { each job repeat m as steps { each step machine: int duration: int } }\n"
1202 "check step.machine < m \"exists\"\n"
1203 "check distinct(job.machine) \"twice\"\n"
1204 "check size(job.steps) == m && all(s in job.steps: s.duration >= 0)\n"
1205 "let x = jobs[1].steps[0].machine let y = size(jobs[0].steps) let z = sum(j in jobs: sum(j.duration))";
1206 Data j = read(jobs, "2 2\n0 5 1 6\n1 2 0 3\n");
1207 CHECK((j.integer("x") == 1) && (j.integer("y") == 2) && (j.integer("z") == 16));
1208 CHECK(fails(jobs, "2 2\n0 5 1 6\n1 2 7 3\n", "test.txt:3:5: check failed for record 2 of 'steps' in record 2 of "
1209 "'jobs': exists"));
1210 CHECK(fails(jobs, "2 2\n0 5 1 6\n1 2 1 3\n", "test.txt:3:1: check failed for record 2 of 'jobs': twice"));
1211 // The terminating token of a repeat is kept with store
1212 Data t = read("repeat until \"end\" \"stop\" store t as xs { a: int } let k = size(xs)", "1 2 stop");
1213 CHECK((t.text("t") == "stop") && (t.integer("k") == 2));
1214 return true;
1215 });
1216
1217 Case record_list_errors("Spec::RecordLists", [](void) {
1218 CHECK(rejects("repeat 2 { a: int each x }", "s:1: 'each' must be the first statement of a repeat"));
1219 CHECK(rejects("repeat 2 { each x each y }",
1220 "'each' must be the first statement of a repeat, and comes at most once"));
1221 CHECK(rejects("each x", "'each' must be the first statement of a repeat"));
1222 CHECK(rejects("if 1 { each x }", "'each' must be the first statement of a repeat"));
1223 // The names are new
1224 CHECK(rejects("repeat 2 as xs { each xs }", "'xs' cannot name both the list and each record"));
1225 CHECK(rejects("repeat 2 as xs { a: int }\nrepeat 2 { each xs }", "s:2: 'xs' already names records"));
1226 CHECK(rejects("repeat 2 as a { a: int }", "'a' names records, so it cannot also be defined"));
1227 CHECK(rejects("repeat 2 { each x a: int } let x = 1", "'x' names records, so it cannot also be defined"));
1228 CHECK(rejects("repeat 2 as gecode.xs { a: int }", "names starting with 'gecode.' are Gecode constants"));
1229 CHECK(rejects("repeat 2 { each gecode.x }", "names starting with 'gecode.' are Gecode constants"));
1230 CHECK(rejects("repeat 2 as xs { a: int } check all(xs in xs: 1)",
1231 "'xs' is bound by a comprehension but names records"));
1232 // Where the names can be used
1233 CHECK(rejects("repeat 2 as xs { a: int let k = size(xs) }", "'xs' cannot be used inside its own repeat"));
1234 CHECK(rejects("repeat 2 { each job repeat 2 as steps { a: int } } check size(steps) == 2",
1235 "'steps' is a list in each record of the repeat around it; use 'job.steps'"));
1236 CHECK(rejects("repeat 2 { repeat 2 as steps { a: int } } check size(steps) == 2",
1237 "name each of these records with 'each'"));
1238 CHECK(rejects("repeat 2 { each x a: int } let k = x.a",
1239 "'x' is each record of a repeat, so only checks can use it"));
1240 // Fields
1241 CHECK(rejects("repeat 2 as nodes { each node ready: int } check nodes.ready > 0",
1242 "'nodes' is a list of records, so '.ready' needs one of them: use 'nodes[i].ready', or 'node.ready' "
1243 "for each record"));
1244 CHECK(rejects("repeat 2 as nodes { ready: int due: int } check nodes[0].read > 0",
1245 "the records of 'nodes' have no field 'read' (they have ready, due)"));
1246 CHECK(rejects("repeat 2 as xs { a: int } let a = 1 check xs[0].a > 0", "'a' is defined inside and outside"));
1247 CHECK(rejects("repeat 2 { each job repeat 2 { a: int let b = job.a } }",
1248 "the field 'a' cannot be used inside the repeat that reads it"));
1249 CHECK(rejects("a: int check a.b > 0", "only records have fields such as '.b'"));
1250 // Records are not values
1251 CHECK(rejects("repeat 2 as xs { a: int } let k = xs[0]", "a record of 'xs' is not a value; use one of its fields, "
1252 "as in 'xs[0].a'"));
1253 CHECK(rejects("repeat 2 as xs { a: int } let k = xs", "'xs' is a list of records, not a value"));
1254 CHECK(rejects("repeat 2 as xs { each x a: int } check x > 0", "as in 'x.a'"));
1255 CHECK(rejects("repeat 2 as xs { a: int } check xs[0][1] > 0", "a record of 'xs' cannot be indexed"));
1256 return true;
1257 });
1258
1259 Case failure_locations("Read::FailureLocations", [](void) {
1260 // A failed all names the element that fails it
1261 CHECK(fails("a[4]: int check all(x in a: x > 0) \"positive\"", "1 2 0 3",
1262 "check failed for element 3 of 'a': positive"));
1263 CHECK(fails("repeat 3 as xs { a: int } check all(x in xs: x.a > 0) \"positive\"", "1\n2\n0\n",
1264 "test.txt:3:1: check failed for record 3 of 'xs': positive"));
1265 CHECK(fails("n: int repeat n { list row: int until eol } check all(r in row: min(r) > 0) \"positive\"",
1266 "2\n1 2\n3 0\n", "test.txt:3:1: check failed for record 2 of 'row': positive"));
1267 // Nested comprehensions and records report every level
1268 const char* jobs = "repeat 2 as jobs { each job repeat 2 as steps { d: int } }\n";
1269 std::string nested = std::string(jobs) + "check all(j in jobs: all(s in j.steps: s.d > 0)) \"positive\"";
1270 CHECK(fails(nested.c_str(), "1 2\n3 0\n", "test.txt:2:3: check failed for record 2 of 'steps' in record 2 of "
1271 "'jobs': positive"));
1272 std::string lifted = std::string(jobs) + "check all(x in job.d: x > 0) \"positive\"";
1273 CHECK(fails(lifted.c_str(), "1 2\n3 0\n", "test.txt:2:3: check failed for record 2 of 'steps' in record 2 of "
1274 "'jobs': positive"));
1275 CHECK(fails("a[2][2]: int check all(r in a: all(x in r: x > 0)) \"positive\"", "1 2 3 0",
1276 "check failed for element 2 of 'r' in element 2 of 'a': positive"));
1277 // Only a failed all that fails the check is reported
1278 CHECK(fails("a[2]: int check any(x in a: x > 5) \"big\"", "1 2", "check failed: big"));
1279 CHECK(fails("a[2]: int check !all(x in a: x > 0) \"not all\"", "1 2", "check failed: not all"));
1280 CHECK(fails("a[2]: int check 1 > 2 || all(x in a: x > 1) \"m\"", "1 2", "check failed for element 1 of 'a': m"));
1281 CHECK(fails("a[2]: int check all(x in a: x > 1) == 1 \"m\"", "1 2", "check failed: m"));
1282 CHECK(fails("a[2]: int check count(x in a: all(y in a: y > x)) == 2 \"m\"", "1 2", "check failed: m"));
1283 // Indexing a single value of a record suggests naming the records
1284 CHECK(fails("n: int repeat n { ready: int } check ready[0] == 0", "2 1 2",
1285 "which is one value of each record here; to index the records, name them, as in 'repeat n as nodes { "
1286 "each node ... }', and use 'nodes[0].ready'"));
1287 CHECK(fails("n: int repeat n as nodes { ready: int } check ready[0] == 0", "2 1 2",
1288 "to index the records, use 'nodes[0].ready'"));
1289 return true;
1290 });
1291
1292#undef CHECK
1293
1294}}
1295
1296// STATISTICS: test-any
FloatNum size(void) const
Return size of float value (distance between maximum and minimum).
Definition val.hpp:78
Options for scripts with additional instance parameter
Definition driver.hh:834
bool is_file(void) const
Test whether the instance names a readable file.
Definition options.cpp:882
void parse(int &argc, char *argv[])
Parse options from arguments argv (number is argc).
Definition options.cpp:833
void instance(const char *s)
Set default instance name.
Definition options.cpp:800
Instance::Data data(void) const
Read the instance file.
Definition options.cpp:893
Named values read from an instance.
Definition instance.hh:406
IntArgs ints(const std::string &n, const IntArgs &path=IntArgs()) const
Return all integers in the array or row n at path.
Definition data.cpp:405
int size(const std::string &n, const IntArgs &path=IntArgs()) const
Return the length of the array or row n at path.
Definition data.cpp:385
void dzn(std::ostream &os) const
Print all entries as MiniZinc data.
Definition data.cpp:537
double number(const std::string &n, const IntArgs &path=IntArgs()) const
Return the number n at path (integers are converted).
Definition data.cpp:395
ValueType type(const std::string &n) const
Return the value type of entry n.
Definition data.cpp:375
std::string text(const std::string &n, const IntArgs &path=IntArgs()) const
Return the string n at path.
Definition data.cpp:400
int depth(const std::string &n) const
Return the depth of entry n (0 for scalars).
Definition data.cpp:380
bool has(const std::string &n) const
Test whether there is an entry n.
Definition data.cpp:370
long long int integer(const std::string &n, const IntArgs &path=IntArgs()) const
Return the integer n at path.
Definition data.cpp:390
Exception for errors in specs and instance files
Definition instance.hh:337
virtual const char * what(void) const noexcept override
Return the full message.
Definition data.cpp:56
Values for the param statements of a spec.
Definition instance.hh:364
void set(const std::string &name, const std::string &value)
Set parameter name to value.
Definition data.cpp:64
Reader spec for a textual instance format.
Definition instance.hh:470
Data read_text(const std::string &text, const std::string &origin="<input>", const Params &p=Params()) const
Read instance text, using origin in error messages.
Definition spec.cpp:1290
Data catalog_text(const std::string &text, const std::string &origin="<input>", const Params &p=Params()) const
List the instances in text, using origin in error messages.
Definition spec.cpp:1300
Passing integer arguments.
Definition int.hh:653
unsigned int size(void) const
Return size (cardinality) of set.
Options for scripts
Definition driver.hh:447
Base(std::string s)
Create and register a standard test with name s.
Definition test.cpp:125
const std::string & name(void) const
Return name of test.
Definition test.hpp:91
Test given by a function
Definition instance.cpp:114
std::function< bool(void)> f
The test.
Definition instance.cpp:117
Case(const std::string &n, std::function< bool(void)> f0)
Create test n running f0.
Definition instance.cpp:120
virtual bool run(void)
Run the test.
Definition instance.cpp:123
Observe help requests of options Opt without terminating the test runner.
Definition instance.cpp:623
void help(void) override
Definition instance.cpp:626
static Spec load(const std::string &path)
Load the spec in file path.
Definition spec.cpp:1275
static Spec parse(const std::string &text, const std::string &origin="<spec>")
Parse spec text, using origin in error messages.
Definition spec.cpp:1268
#define CHECK(c)
Definition instance.cpp:107
@ FLOAT
Floating point numbers.
Definition instance.hh:351
const int min
Smallest allowed integer value.
Definition int.hh:123
const int max
Largest allowed integer value.
Definition int.hh:121
Case sections("Read::Sections", [](void) { const char *spec="sections until \"EOF\" {\n" " \"N : {n:int}\"\n" " \"DATA\" { x[n]: int }\n" " \"NAME : {name:word}\" optional\n" "}\n";Data d=read(spec, "NAME : a\nN: 2\nDATA\n5 6\nEOF\n");CHECK(d.integer("n")==2);CHECK(equal(d.ints("x"), {5, 6}));CHECK(d.text("name")=="a");CHECK(read(spec, "N : 1\nDATA\n4").ints("x").size()==1);CHECK(fails(spec, "N : 1\nXYZZY_PLUGH\n", "expected one of"));CHECK(read("sections skip other { \"v: {v:int}\" }", "junk\nv: 3\nmore junk\n").integer("v")==3);CHECK(fails(spec, "N : 1\nEOF\n", "test.txt:2:1: expected a line matching \"DATA\" before 'EOF'"));CHECK(fails(spec, "NAME : a\n", "expected a line matching \"N : {n:int}\" before the end of the input"));CHECK(fails(spec, "N : 1\nDATA\n4\nN : 2\n", "test.txt:4:1: a second line matching \"N : {n:int}\" (the first is on line 1)"));CHECK(fails(spec, "NAME : a\nN : 1\nDATA\n4\nNAME : b\n", "a second line matching \"NAME : {name:word}\""));const char *last="sections { \"a {a:int}\" \"end\" last } y: int";CHECK(read(last, "a 1\nend\n5").integer("y")==5);CHECK(fails(last, "a 1\n5", "expected one of"));CHECK(fails(last, "a 1", "expected a line matching \"end\" before the end of the input"));CHECK(fails(last, "end\n5", "test.txt:1:1: expected a line matching \"a {a:int}\" before the line matching \"end\""));const char *optional_last="sections { \"a {a:int}\" \"end\" optional last }";CHECK(read(optional_last, "a 1").integer("a")==1);CHECK(read(optional_last, "a 1\nend").integer("a")==1);return true;})
Case strict_instance_options("Driver::InstanceOptions::Strict", [](void) { char name[]="test", iterations[]="-iterations", value[]="200";char inst[]="instance.txt", other[]="other.txt", unknown[]="--typo";HelpOptions< Gecode::InstanceOptions > options;char *valid_argv[]={name, iterations, value, inst, nullptr};int valid_argc=4;options.parse_strict(valid_argc, valid_argv);CHECK(std::strcmp(options.instance(), "instance.txt")==0 &&options.iterations()==200);char *unknown_argv[]={name, unknown, inst, nullptr};CHECK(rejects(options, 3, unknown_argv, "--typo"));char *extra_argv[]={name, inst, other, nullptr};CHECK(rejects(options, 3, extra_argv, "other.txt"));char *permissive_argv[]={name, other, inst, nullptr};int permissive_argc=3;options.parse_permissive(permissive_argc, permissive_argv);CHECK(permissive_argc==3 &&std::strcmp(options.instance(), "other.txt")==0);return true;})
bool fails(const std::function< void(void)> &f, const char *what)
Check that f throws an Error whose message contains what.
Definition instance.cpp:70
Case output("Data::Output", [](void) { Data d=read("n: int f: float w: word m[2][2]: int repeat n { k: int x[k]: int }", "2 20 a 1 2 3 4 1 5 2 6 7");std::ostringstream z;d.dzn(z);CHECK(z.str().find("f = 20.0;") !=std::string::npos);CHECK(z.str().find("m = [| 1, 2\n | 3, 4 |];") !=std::string::npos);CHECK(z.str().find("% x: array[int] of tuple(array[int] of int)\n" "x = [([5],), ([6, 7],)];") !=std::string::npos);CHECK(z.str().find("w = \"a\";") !=std::string::npos);std::ostringstream zq;read("var: int w: word", "3 a\033b").dzn(zq);CHECK(zq.str().find("'var' = 3;") !=std::string::npos);CHECK(zq.str().find("w = \"a\\x1bb\";") !=std::string::npos);Data e=read("e[2][0]: int repeat 2 { k: int repeat k { list y: int until 0 } }", "1 7 0 2 8 9 0 0");std::ostringstream ze;e.dzn(ze);CHECK(ze.str().find("e = array2d(1..2, 1..0, []);") !=std::string::npos);CHECK(ze.str().find("y = [([([7],)],), ([([8, 9],), ([],)],)];") !=std::string::npos);std::ostringstream z7;read("a[1][1][1][1][1][1][1]: int", "5").dzn(z7);CHECK(z7.str().find("a = [([([([([([([5],)],)],)],)],)],)];") !=std::string::npos);return true;})
Case alphabets("Read::Alphabets", [](void) { Data d=read("g[2][3]: alphabet \"123ABC\" blank \".\"", "1.A\nC 2 .");CHECK(equal(d.ints("g"), {1, 0, 4, 6, 2, 0}));Data e=read("g[2][2]: alphabet \"ab\" base 0 strip \"|-\"", "a|b\n---\nb|a");CHECK(equal(e.ints("g"), {0, 1, 1, 0}));CHECK(read("g[1][2]: alphabet \"ab\" ignore trailing", "ab x").size("g")==1);CHECK(read("g[1][1]: alphabet \"ab\" base: int", "b 7").integer("base")==7);CHECK(fails("g[1][2]: alphabet \"ab\"", "ax", "unexpected symbol 'x', expected one of 'ab'"));CHECK(fails("g[2][2]: alphabet \"ab\"", "ab\na", "expected a symbol for row 2, column 2"));CHECK(rejects("g[2]: alphabet \"ab\"", "an alphabet type needs a two-dimensional array"));CHECK(rejects("g[2][2]: alphabet \"ab\" offset 1", "'offset' needs numbers"));CHECK(rejects("list g: alphabet \"ab\" until eol", "a list cannot be of 'rest' or of an alphabet type"));CHECK(rejects("line \"{g:alphabet \\\"ab\\\"}\"", "a capture cannot be of an alphabet type"));return true;})
Case options("Driver::InstanceOptions", [](void) { const char *tmp=std::getenv("TMPDIR");if(tmp==nullptr) tmp=std::getenv("TEMP");std::string base=std::string(tmp==nullptr ? "." :tmp)+"/gecode-instance-test-"+std::to_string(std::chrono::steady_clock::now().time_since_epoch().count());std::string fs=base+".txt", os=base+".reader";const char *file=fs.c_str();const char *other=os.c_str();{ std::ofstream f(file);f<< "2 3 4\n";std::ofstream g(other);g<< "a: int b: int c: int\n";} bool ok=true;try { const char *with_params="param k = 3 param m = 0 n: int x[n * k - m]: int";Gecode::InstanceOptions o("Test", with_params);char a0[]="test", a1[]="-param", a2[]="k=2", a3[]="", a4[]="m=2";std::string inst(file);char *argv[]={a0, a1, a2, a1, a4, &inst[0], a3};int argc=6;o.parse(argc, argv);ok=ok &&o.is_file();ok=ok &&equal(o.data().ints("x"), {3, 4});Gecode::InstanceOptions c("Test", with_params);char c2[]="k=2,m=2";char *argu[]={a0, a1, c2, &inst[0], a3};int argcu=4;c.parse(argcu, argu);ok=ok &&equal(c.data().ints("x"), {3, 4});Gecode::InstanceOptions s("Test", "n: int");char b1[]="-spec";std::string spec(other);char *argw[]={a0, b1, &spec[0], &inst[0], a3};int argcw=4;s.parse(argcw, argw);ok=ok &&(s.data().integer("c")==4);s.instance(".");ok=ok &&!s.is_file();} catch(const Error &e) { olog<< e.what()<< "\n";ok=false;} std::remove(file);std::remove(other);return ok;})
Case progress("Read::Progress", [](void) { CHECK(fails("repeat until eof { let x = 1 }", "1", "the body of a repeat until read no input"));CHECK(read("repeat until \"END\" { if 1 > 2 { w: word } }", "END").size("w")==0);CHECK(fails("repeat until \"END\" { if 1 > 2 { w: word } }", "y END", "the body of a repeat until read no input"));CHECK(fails("n: int repeat n { a[0]: int }", "2000000000", "without reading input"));CHECK(read("n: int repeat n { a[0]: int }", "3").size("a")==3);CHECK(fails("n: int repeat n { repeat n { let x = 1 } }", "3000", "without reading input"));CHECK(fails("n: int repeat n { a[n][0]: int }", "3000", "without reading input"));return true;})
Case record_effort("Read::RecordEffort", [](void) { std::string text="2000\n";for(int i=0;i< 4000;i++) text+="1 ";CHECK(read("n: int repeat n { x: int } a[n]: int check x == 1 && a[0] == 1", text.c_str()).size("x")==2000);CHECK(fails("n: int repeat n { x: int } a[n]: int check x <= sum(a)", text.c_str(), "the expressions do too much work for the size of the input"));return true;})
Case access("Data::Access", [](void) { Data d=read("big: int w: word n: int repeat n { k: int x[k]: int }", "9999999999 hi 2 1 5 2 6 7");CHECK(d.integer("big")==9999999999LL);CHECK(fails([&](void) {(void) d.ints("big");}, "is not an array"));CHECK(fails([&](void) {(void) d.integer("w");}, "is not an integer"));CHECK(fails([&](void) {(void) d.integer("nope");}, "no value named"));CHECK(fails([&](void) {(void) d.size("x", {2});}, "index out of range"));CHECK(fails([&](void) {(void) d.integer("x", {0});}, "is not a single value"));Data e=read("n: int repeat n { v: int }", "1 9999999999");CHECK(fails([&](void) {(void) e.ints("v");}, "does not fit into an int"));return true;})
Case lists("Read::Lists", [](void) { Data d=read("list a: int until 0 list b: int until eol list c: int until eol list w: word until \"END\"", "1 2\n 3 0 4 5\n6 7\nx y END");CHECK(equal(d.ints("a"), {1, 2, 3}));CHECK(equal(d.ints("b"), {4, 5}));CHECK(equal(d.ints("c"), {6, 7}));CHECK(d.size("w")==2);CHECK(d.text("w", {1})=="y");return true;})
Case checks("Spec::Checks", [](void) { CHECK(fails([](void) {(void) Spec::parse("n: int if n > 5 { let y = sqrt(n) }", "s");}, "unknown function 'sqrt'"));CHECK(fails([](void) {(void) Spec::parse("let y = count(1, 2)", "s");}, "wrong arguments for function 'count'"));CHECK(fails([](void) {(void) Spec::parse("line \"{bad-name:int}\"", "s");}, "is not a name"));CHECK(fails([](void) {(void) Spec::parse("let y = "+std::string(300, '(')+"1"+std::string(300, ')'), "s");}, "nested too deeply"));std::string sum="let y = 1", chain="n: int if n == 0 { }";for(int i=0;i< 300;i++) { sum+=" + 1";chain+=" else if n == "+std::to_string(i+1)+" { }";} CHECK(fails([&](void) {(void) Spec::parse(sum, "s");}, "nested too deeply"));CHECK(fails([&](void) {(void) Spec::parse(chain, "s");}, "nested too deeply"));CHECK(fails([](void) {(void) Spec::parse("let _ = 1", "s");}, "'_' cannot be defined here"));CHECK(fails([](void) {(void) Spec::parse("w: word offset 1", "s");}, "'offset' needs numbers"));return true;})
Case constants("Spec::GecodeConstants", [](void) { Data d=read("let a = gecode.int_max let b = gecode.int_min let c = gecode.int_max / 2\n" "gecode: int check gecode == 3", "3");CHECK(d.integer("a")==Gecode::Int::Limits::max);CHECK(d.integer("b")==Gecode::Int::Limits::min);CHECK(d.integer("c")==1073741823);CHECK(fails([](void) {(void) Spec::parse("let x = 1\nlet y = gecode.foo", "s");}, "s:2: unknown Gecode constant 'gecode.foo' (known: gecode.int_max, gecode.int_min)"));const char *defining[]={ "gecode.x: int", "let gecode.int_max = 3", "param gecode.p", "list gecode.l: int until 0", "gecode.g[1][1]: alphabet \"a\"", "repeat until \"x\" store gecode.t { a: int }", "a[2]: int check all(gecode.v in a: 1)" };for(const char *spec :defining) if(!fails([&](void) {(void) Spec::parse(spec, "s");}, "names starting with 'gecode.' are Gecode constants")) return false;return true;})
Case skipped("Read::SkippedInstances", [](void) { const char *spec="instances {\n" " sections skip other {\n" " \"instance {name:word}\" optional\n" " \"{n:int}\" last { check n <= 3 \"n is at most 3\" x[n][n]: int }\n" " }\n" "}\n";const char *text="instance a\n4\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16\ninstance b\n1\n7\n";Params first, second, a, b;first.set("instance", "1");second.set("instance", "2");a.set("instance", "a");b.set("instance", "b");CHECK(equal(read(spec, text, second).ints("x"), {7}));CHECK(equal(read(spec, text, b).ints("x"), {7}));CHECK(fails([&](void) {(void) read(spec, text, first);}, "check failed: n is at most 3"));CHECK(fails([&](void) {(void) read(spec, text, a);}, "check failed: n is at most 3"));CHECK(fails(spec, "4\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16\n", "check failed: n is at most 3"));CHECK(fails(spec, "1\n7\n4\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16\n", "the file has 2 instances; select one"));Spec s=Spec::parse(spec, "s");Data c=s.catalog_text(text);CHECK(c.integer("instances")==2);CHECK((c.text("failed", {0})=="n is at most 3") &&(c.text("failed", {1})==""));CHECK(!s.catalog_text("instance a\n1\n7\n").has("failed"));CHECK(Spec::parse("instances { n: int check n > 5 }", "s").catalog_text("7 1").text("failed", {1})=="check on line 1 of the spec");const char *late="instances { n: int check n > 0 \"positive\" name: word }";Params y;y.set("instance", "y");CHECK(read(late, "0 x 5 y", y).integer("n")==5);CHECK(fails([&](void) {(void) read(late, "5 x 0 y", y);}, "check failed: positive"));CHECK(fails([&](void) {(void) read(spec, "instance a\n2\n1 2 3 x\ninstance b\n1\n7\n", b);}, "expected int"));auto start=std::chrono::steady_clock::now();CHECK(fails([&](void) {(void) read(spec, "instance a\n1000000000\n1 2\ninstance b\n1\n7\n", b);}, "array is too large"));CHECK(fails([&](void) {(void) read(spec, "instance a\n40000\n1 2\ninstance b\n1\n7\n", b);}, "after an earlier error in the instance: n is at most 3"));CHECK(std::chrono::steady_clock::now() - start< std::chrono::seconds(10));const char *repeated="instance a\ninstance x\n1\n7\ninstance b\n1\n8\n";CHECK(equal(read(spec, repeated, b).ints("x"), {8}));CHECK(fails([&](void) {(void) read(spec, repeated, a);}, "test.txt:2:1: a second line matching \"instance {name:word}\""));CHECK(s.catalog_text(repeated).text("failed", {0})=="a second line matching \"instance {name:word}\"");const char *stop="instances { sections { \"n {n:int}\" \"m {m:int}\" \"end\" last } }";Params two;two.set("instance", "2");CHECK(read(stop, "n 1\nend\nn 2\nm 3\nend\n", two).integer("m")==3);CHECK(Spec::parse(stop, "s").catalog_text("n 1\nend\nn 2\nm 3\nend\n").text("failed", {0})=="no line matching \"m {m:int}\"");Params named;named.set("instance", "3x");CHECK(read("instances { n: int name: word }", "1 a 2 3x 3 c", named).integer("n")==2);return true;})
Case layouts("Read::Layouts", [](void) { const char *spec="f: word w[3][3]: int layout f";const char *inputs[]={ "FULL_MATRIX 0 1 2 1 0 3 2 3 0", "UPPER_ROW 1 2 3", "LOWER_COL 1 2 3", "LOWER_ROW 1 2 3", "UPPER_COL 1 2 3", "UPPER_DIAG_ROW 0 1 2 0 3 0", "LOWER_DIAG_COL 0 1 2 0 3 0", "LOWER_DIAG_ROW 0 1 0 2 3 0", "UPPER_DIAG_COL 0 1 0 2 3 0", };for(const char *in :inputs) { Data d=read(spec, in);if(!equal(d.ints("w"), {0, 1, 2, 1, 0, 3, 2, 3, 0})) { olog<< "wrong matrix for "<< in<< "\n";return false;} } CHECK(equal(read("w[3][3]: int layout \"UPPER_ROW\" offset 1", "1 2 3").ints("w"), {0, 2, 3, 2, 0, 4, 3, 4, 0}));return fails(spec, "DIAGONAL 1 2 3", "unknown matrix layout");})
Case effort("Read::Effort", [](void) { std::string text="2000\n";for(int i=0;i< 2000;i++) text+="1 ";CHECK(read("n: int a[n]: int check all(x in a: x == 1) && sum(a) == n", text.c_str()).size("a")==2000);CHECK(fails("n: int a[n]: int check all(x in a: sum(a) > 0)", text.c_str(), "the expressions do too much work for the size of the input"));std::string rows="100 500\n";for(int i=0;i< 100 *500;i++) rows+="1 ";CHECK(read("m: int k: int a[m][k]: int check all(r in a: all(s in r: s == 1))", rows.c_str()).size("a")==100);CHECK(fails("m: int k: int a[m][k]: int check all(r in a: all(s in a: 1))", rows.c_str(), "too much work"));std::string more=text;for(int i=0;i< 2000;i++) more+="1 ";CHECK(fails("n: int a[n]: int repeat n { k: int check sum(a) > 0 }", more.c_str(), "too much work"));return true;})
Case strict_size_options("Driver::SizeOptions::Strict", [](void) { char name[]="test", iterations[]="-iterations", value[]="200";char size[]="7", other[]="8", unknown[]="--typo", word[]="seven";HelpOptions< Gecode::SizeOptions > options;char *valid_argv[]={name, iterations, value, size, nullptr};int valid_argc=4;options.parse_strict(valid_argc, valid_argv);CHECK(options.size()==7 &&options.iterations()==200);char *options_argv[]={name, iterations, value, nullptr};int options_argc=3;options.parse_strict(options_argc, options_argv);CHECK(options_argc==1 &&options.size()==7);char *unknown_argv[]={name, unknown, size, nullptr};CHECK(rejects(options, 3, unknown_argv, "--typo"));char *extra_argv[]={name, size, other, nullptr};CHECK(rejects(options, 3, extra_argv, "8"));char *word_argv[]={name, word, nullptr};CHECK(rejects(options, 2, word_argv, "seven"));char *permissive_argv[]={name, other, size, nullptr};int permissive_argc=3;options.parse_permissive(permissive_argc, permissive_argv);CHECK(permissive_argc==3 &&options.size()==8);return true;})
Case types("Spec::Types", [](void) { Data d=read("type time = 0..gecode.int_max / 2\n" "n: 1..\n" "repeat n { ready: time due: time }\n" "type cell = alphabet \"ab\" blank \".\"\n" "g[1][2]: cell", "2 1 2 3 4 a.");CHECK(equal(d.ints("due"), {2, 4}));CHECK(equal(d.ints("g"), {1, 0}));CHECK(fails("n: int type small = 0..n a: small", "3 4", "expected small (an int in 0..3), found '4'"));CHECK(fails("type w = word type v = w line \"{x:v} {y:0..1}\"", "a 2", "expected an int in 0..1"));CHECK(fails("n: int type t = 0..n let n2 = n repeat 2 { b: t }", "1 1 2", "expected t (an int in 0..1)"));Data k=read("line: int type: 0.. list: word each: int layout: int", "1 2 a 3 4");CHECK(k.integer("type")==2);CHECK(k.integer("layout")==4);CHECK(read("a: 0..\nb[2]: int check a == 0", "0 1 2").size("b")==2);CHECK(read("a: 0.. index: int", "0 1").integer("index")==1);CHECK(rejects("a: 0..<", "'..<' needs an upper bound"));CHECK(rejects("a: ..", "a range needs a lower or an upper bound"));CHECK(rejects("a: foo", "unknown type 'foo'"));CHECK(rejects("a: 1 + 2", "expected '..' or '..<' after the lower bound of a range"));CHECK(rejects("type int = 0..", "'int' is a base type"));CHECK(rejects("type t = int type t = word", "the type 't' is already defined"));CHECK(rejects("type t = int t: int", "s:1: 't' names a type, so it cannot also name a value"));CHECK(rejects("if 1 > 0 { type t = int } a: t", "unknown type 't'"));CHECK(rejects("a: word offset 1", "'offset' needs numbers"));CHECK(rejects("a[2]: int layout \"FULL_MATRIX\"", "'layout' needs a two-dimensional array of numbers"));CHECK(rejects("line \"{x:0..<}\"", "s:1: '..<' needs an upper bound"));CHECK(rejects("line \"{x:int int}\"", "unexpected 'int' in the capture type 'int int'"));CHECK(rejects("line \"{x:}\"", "a capture needs a type after ':'"));return true;})
Case control("Read::Control", [](void) { Data d=read("n: int\n" "if n > 1 { w: word } else { let w = \"none\" }\n" "let m = n * 3 + 1\n" "a[2]: int\n" "let s = sum(a)\n" "check max(a) - min(a) == 2 \"spread\"\n" "check count(a) == 2 && defined(m) && !defined(zz)\n" "check 7 / 2 == 3 && 7 % 2 == 1", "2 x 1 3");CHECK(d.text("w")=="x");CHECK(d.integer("m")==7);CHECK(d.integer("s")==4);CHECK(read("n: int if n > 1 { w: word } else { let w = \"none\" }", "1").text("w")=="none");CHECK(fails("a: int check a == 2 \"must be two\"", "3", "check failed: must be two"));CHECK(fails("a: int let b = a / 0", "3", "division by zero"));CHECK(fails("a: int let b = c", "3", "'c' is not defined yet"));return true;})
Case skipped_records("Read::SkippedInstanceRecords", [](void) { const char *spec="instances { n: int repeat n { x: int } check x > 0 \"positive\" name: word }";const char *text="2 1 0 a\n1 5 b\n";Params a, b;a.set("instance", "a");b.set("instance", "b");CHECK(equal(read(spec, text, b).ints("x"), {5}));CHECK(fails([&](void) {(void) read(spec, text, a);}, "test.txt:1:5: check failed for record 2 of 'x': positive"));Data c=Spec::parse(spec, "s").catalog_text(text);CHECK((c.text("failed", {0})=="positive") &&(c.text("failed", {1})==""));return true;})
Case record_list_errors("Spec::RecordLists", [](void) { CHECK(rejects("repeat 2 { a: int each x }", "s:1: 'each' must be the first statement of a repeat"));CHECK(rejects("repeat 2 { each x each y }", "'each' must be the first statement of a repeat, and comes at most once"));CHECK(rejects("each x", "'each' must be the first statement of a repeat"));CHECK(rejects("if 1 { each x }", "'each' must be the first statement of a repeat"));CHECK(rejects("repeat 2 as xs { each xs }", "'xs' cannot name both the list and each record"));CHECK(rejects("repeat 2 as xs { a: int }\nrepeat 2 { each xs }", "s:2: 'xs' already names records"));CHECK(rejects("repeat 2 as a { a: int }", "'a' names records, so it cannot also be defined"));CHECK(rejects("repeat 2 { each x a: int } let x = 1", "'x' names records, so it cannot also be defined"));CHECK(rejects("repeat 2 as gecode.xs { a: int }", "names starting with 'gecode.' are Gecode constants"));CHECK(rejects("repeat 2 { each gecode.x }", "names starting with 'gecode.' are Gecode constants"));CHECK(rejects("repeat 2 as xs { a: int } check all(xs in xs: 1)", "'xs' is bound by a comprehension but names records"));CHECK(rejects("repeat 2 as xs { a: int let k = size(xs) }", "'xs' cannot be used inside its own repeat"));CHECK(rejects("repeat 2 { each job repeat 2 as steps { a: int } } check size(steps) == 2", "'steps' is a list in each record of the repeat around it; use 'job.steps'"));CHECK(rejects("repeat 2 { repeat 2 as steps { a: int } } check size(steps) == 2", "name each of these records with 'each'"));CHECK(rejects("repeat 2 { each x a: int } let k = x.a", "'x' is each record of a repeat, so only checks can use it"));CHECK(rejects("repeat 2 as nodes { each node ready: int } check nodes.ready > 0", "'nodes' is a list of records, so '.ready' needs one of them: use 'nodes[i].ready', or 'node.ready' " "for each record"));CHECK(rejects("repeat 2 as nodes { ready: int due: int } check nodes[0].read > 0", "the records of 'nodes' have no field 'read' (they have ready, due)"));CHECK(rejects("repeat 2 as xs { a: int } let a = 1 check xs[0].a > 0", "'a' is defined inside and outside"));CHECK(rejects("repeat 2 { each job repeat 2 { a: int let b = job.a } }", "the field 'a' cannot be used inside the repeat that reads it"));CHECK(rejects("a: int check a.b > 0", "only records have fields such as '.b'"));CHECK(rejects("repeat 2 as xs { a: int } let k = xs[0]", "a record of 'xs' is not a value; use one of its fields, " "as in 'xs[0].a'"));CHECK(rejects("repeat 2 as xs { a: int } let k = xs", "'xs' is a list of records, not a value"));CHECK(rejects("repeat 2 as xs { each x a: int } check x > 0", "as in 'x.a'"));CHECK(rejects("repeat 2 as xs { a: int } check xs[0][1] > 0", "a record of 'xs' cannot be indexed"));return true;})
Case arithmetic("Read::Arithmetic", [](void) { Data d=read("a[3]: int g: float h: float\n" "let s = sum(a) let lo = min(a) let hi = max(a, 7)\n" "check g < 0 && -h < -3.5 \"floats compare\"", "-5 2 1 -1.5 4");CHECK(d.integer("s")==-2);CHECK(d.integer("lo")==-5);CHECK(d.integer("hi")==7);CHECK(fails("f: float let g = f * 2", "1.5", "'*' needs integers"));CHECK(fails("f[1]: float let g = sum(f)", "1.5", "'sum' takes integers"));Data m=read("a: int let p = a * 1 let q = a - a let r = 1 * a", "-9223372036854775808");CHECK(m.integer("p")==m.integer("a"));CHECK(m.integer("q")==0);CHECK(m.integer("r")==m.integer("a"));CHECK(fails("a: int let b = 0 - a", "-9223372036854775808", "integer overflow"));CHECK(fails("g[1][1]: alphabet \"ab\" base 9223372036854775807", "b", "integer overflow"));return true;})
bool equal(const IntArgs &a, std::initializer_list< int > v)
Compare integer array a with the values v.
Definition instance.cpp:97
Case instances("Read::Instances", [](void) { const char *spec="comment \"+++\"\n" "instances {\n" " sections skip other {\n" " \"instance {name:word}\" optional\n" " \"{n:int}\" last { x[n]: int }\n" " }\n" "}\n";const char *text="header text\ninstance a\n2\n1 2\n+++\n" "instance b\ndescription\n1\n7\n+++ end\n";Params by_name, by_number, bad;by_name.set("instance", "b");by_number.set("instance", "1");bad.set("instance", "3");CHECK(equal(read(spec, text, by_name).ints("x"), {7}));CHECK(equal(read(spec, text, by_number).ints("x"), {1, 2}));CHECK(read(spec, text, by_number).text("name")=="a");CHECK(fails([&](void) {(void) read(spec, text, bad);}, "there is no instance '3' (the file has 2 instances)"));CHECK(fails(spec, text, "the file has 2 instances; select one"));CHECK(equal(read(spec, "3\n4 5 6\n").ints("x"), {4, 5, 6}));Spec s=Spec::parse(spec, "s");Data c=s.catalog_text(text);CHECK(c.integer("instances")==2);CHECK(c.text("name", {1})=="b");Data c1=s.catalog_text("3\n4 5 6\n");CHECK((c1.integer("instances")==1) &&!c1.has("name"));CHECK(Spec::parse("a: int", "s").catalog_text("5").integer("instances")==1);CHECK(fails(spec, "1\n2\njunk\n", "expected a line matching \"{n:int}\""));CHECK(fails("instances { a: int }", "", "the file contains no instance"));CHECK(fails([](void) {(void) Spec::parse("instances { a: int } b: int", "s");}, "'instances' must be the last statement"));CHECK(fails([](void) {(void) Spec::parse("repeat 2 { instances { a: int } }", "s");}, "'instances' must be at the top level"));CHECK(fails("instances { if 0 > 1 { a: int } }", "5", "an instance must read some input"));return true;})
Case record_lists("Read::RecordLists", [](void) { const char *nodes="n: int repeat n as nodes { each node ready: int due: int }\n" "check node.ready <= node.due \"window\"\n" "check nodes[0].ready == 0 \"depot\"\n" "let k = size(nodes) let d = nodes[1].due let c = count(x in nodes: x.due > 4)";Data d=read(nodes, "3\n0 5\n2 4\n6 7\n");CHECK((d.integer("k")==3) &&(d.integer("d")==4) &&(d.integer("c")==2));CHECK(!d.has("nodes") &&!d.has("node") &&(d.entries()==6));CHECK(fails(nodes, "3\n0 5\n2 4\n6 1\n", "test.txt:4:1: check failed for record 3 of 'nodes': window"));CHECK(fails(nodes, "3\n1 5\n2 4\n6 7\n", "check failed: depot"));CHECK(fails("n: int repeat n as nodes { a: int } let x = nodes[3].a", "2 1 2", "index 3 is out of range for 'nodes' (size 2, indices start at 0)"));CHECK(read("repeat 2 as xs { a: int } let s = sum(x in xs: x.a)", "3 4").integer("s")==7);CHECK(fails("repeat 3 { each x a: int b: int } check x.a < x.b \"less\"", "1 2 3 4 6 5", "test.txt:1:9: check failed for record 3 of 'x': less"));Data in=read("repeat 2 as xs { each x a: int b: int let w = x.b - x.a check x.a <= x.b }", "1 4 2 2");CHECK(equal(in.ints("w"), {3, 0}));const char *jobs="n: int m: int\n" "repeat n as jobs { each job repeat m as steps { each step machine: int duration: int } }\n" "check step.machine < m \"exists\"\n" "check distinct(job.machine) \"twice\"\n" "check size(job.steps) == m && all(s in job.steps: s.duration >= 0)\n" "let x = jobs[1].steps[0].machine let y = size(jobs[0].steps) let z = sum(j in jobs: sum(j.duration))";Data j=read(jobs, "2 2\n0 5 1 6\n1 2 0 3\n");CHECK((j.integer("x")==1) &&(j.integer("y")==2) &&(j.integer("z")==16));CHECK(fails(jobs, "2 2\n0 5 1 6\n1 2 7 3\n", "test.txt:3:5: check failed for record 2 of 'steps' in record 2 of " "'jobs': exists"));CHECK(fails(jobs, "2 2\n0 5 1 6\n1 2 1 3\n", "test.txt:3:1: check failed for record 2 of 'jobs': twice"));Data t=read("repeat until \"end\" \"stop\" store t as xs { a: int } let k = size(xs)", "1 2 stop");CHECK((t.text("t")=="stop") &&(t.integer("k")==2));return true;})
Data read(const char *spec, const char *text, const Params &p=Params())
Read text with the spec spec.
Definition instance.cpp:64
Case comprehensions("Spec::Comprehensions", [](void) { CHECK(fails([](void) {(void) Spec::parse("n: int a[n]: int check all(n in a: n > 0)", "s");}, "s:1: 'n' is bound by a comprehension but is also a name in the spec"));CHECK(fails([](void) {(void) Spec::parse("a[2]: int\ncheck all(x in a: 1)\nrepeat 2 { x: int }", "s");}, "s:2: 'x' is bound by a comprehension but is also a name in the spec"));CHECK(fails([](void) {(void) Spec::parse("a[2][2]: int check all(x in a: all(x in x: 1))", "s");}, "'x' is already bound by an enclosing comprehension"));CHECK(fails([](void) {(void) Spec::parse("a[2]: int check all(_ in a: 1)", "s");}, "'_' cannot be bound"));CHECK(fails([](void) {(void) Spec::parse("a[2]: int check all(a)", "s");}, "'all' needs the form all(x in a: e)"));CHECK(fails([](void) {(void) Spec::parse("a[2]: int check any(x in a)", "s");}, "expected ':'"));CHECK(fails([](void) {(void) Spec::parse("a[2]: int check a[0", "s");}, "expected ']'"));CHECK(fails([](void) {(void) Spec::parse("let y = distinct()", "s");}, "wrong arguments for function 'distinct'"));Data d=read("a[2][2]: int let s = sum(x in a: sum(y in x: y)) + sum(y in a: count(y))", "1 2 3 4");CHECK(d.integer("s")==14);std::string chain="a[1]: int let y = a";for(int i=0;i< 300;i++) chain+="[0]";CHECK(fails([&](void) {(void) Spec::parse(chain, "s");}, "nested too deeply"));return true;})
Case params("Read::Params", [](void) { const char *spec="param which param k = 2\n" "find \"instance {$which}\" x[k]: int ignore trailing";const char *text="instance a\n1 2\ninstance b\n3 4\n";Params p;p.set("which=b");Data d=read(spec, text, p);CHECK(equal(d.ints("x"), {3, 4}));CHECK(d.text("which")=="b");Params q;q.set("which", "a");q.set("k", "1");CHECK(equal(read(spec, text, q).ints("x"), {1}));Params r;r.set("which=a,,k=1,");CHECK(equal(read(spec, text, r).ints("x"), {1}));CHECK(fails([](void) { Params e;e.set("which=a,k");}, "parameter 'k' must have the form name=value"));CHECK(fails([](void) { Params e;e.set("=a");}, "parameter '=a' must have the form name=value"));return fails(spec, text, "parameter 'which' must be given");})
Case repeats("Read::Repeat", [](void) { Data d=read("n: int\n" "repeat n { index 1 k: int s[k]: int offset -1 }\n" "repeat until \"999\" { a: int }\n" "repeat until \">=\" \"=\" store op { c: int v: word }\n" "rhs: int\n" "repeat until eof { w: word }", "3\n1 2 4 5\n2 0\n3 1 1\n7 8 999\n" "2 x 3 y = 4\nfoo bar");CHECK(equal(d.ints("k"), {2, 0, 1}));CHECK(d.size("s")==3);CHECK(d.size("s", {1})==0);CHECK(equal(d.ints("s"), {3, 4, 0}));CHECK(equal(d.ints("s", {2}), {0}));CHECK(equal(d.ints("a"), {7, 8}));CHECK(d.text("op")=="=");CHECK(equal(d.ints("c"), {2, 3}));CHECK(d.integer("rhs")==4);CHECK(d.size("w")==2);CHECK(fails("n: int repeat n { index 1 x: int }", "2\n1 5\n3 6", "expected index 2, found 3"));Data e=read("repeat 2 { repeat 2 { x: int y: int } }", "1 2 3 4 5 6 7 8");CHECK(e.depth("x")==2);CHECK(equal(e.ints("x", {1}), {5, 7}));CHECK(equal(e.ints("y"), {2, 4, 6, 8}));return true;})
Case scalars("Read::Scalars", [](void) { Data d=read("a: int b: float c: num e: num w: word r: rest", " -7 2.5\n 3 4.5e1 hello the rest \n");CHECK(d.integer("a")==-7);CHECK(d.number("b")==2.5);CHECK(d.integer("c")==3);CHECK(d.type("e")==Gecode::Instance::ValueType::FLOAT);CHECK(d.number("e")==45.0);CHECK(d.text("w")=="hello");CHECK(d.text("r")=="the rest");CHECK(d.entries()==6);CHECK(d.name(0)=="a");return true;})
Case robustness("Read::Robustness", [](void) { Data d=read("separators \",\" list a: int until eol list b: int until \"EOF\"", "1,2, 3\n4 5 EOF");CHECK(equal(d.ints("a"), {1, 2, 3}));CHECK(equal(d.ints("b"), {4, 5}));Spec f=Spec::parse("format dimacs-cnf.v2 n: int x: int let k = n-x", "s");CHECK(f.name()=="dimacs-cnf.v2");CHECK(f.read_text("5 2").integer("k")==3);CHECK(fails("a: int let b = a * a", "9000000000", "integer overflow"));CHECK(fails("a: int b: int offset 1", "1 9223372036854775807", "integer overflow"));CHECK(fails("f: float", "nan", "expected float"));Data n=read("line \"{a:float}x{b:int}-{c:num}\" f: float\n" "check 1.5e+1 == 15 && 5-2 == 3", "-1.5e+2x+3-2.5\n+2.5E-1");CHECK(n.number("a")==-150.0);CHECK(n.integer("b")==3);CHECK(n.number("c")==2.5);CHECK(n.number("f")==0.25);CHECK(fails("f: float", "1-2", "expected float"));CHECK(fails("f: num", "0x10", "expected a number"));CHECK(fails("n: int a[n]: int", "2147483648", "too large"));CHECK(equal(read("list a: int until 0", "+5 -7 05 -0").ints("a"), {5,-7, 5}));CHECK(equal(read("tokens \";\" a[3]: int expect \";\"", "1 -2 3;").ints("a"), {1,-2, 3}));CHECK(fails("list a: int until 0", "9223372036854775808 0", "expected int, found '9223372036854775808'"));CHECK(fails("list a: int until 0", "-9223372036854775809 0", "found '-9223372036854775809'"));CHECK(fails("list a: int until 0", "5x 0", "expected int, found '5x'"));CHECK(fails("list a: int until 0", "1 - 0", "expected int, found '-'"));CHECK(fails("a[2]: int", "1", "expected int, found end of input"));CHECK(fails([](void) {(void) Spec::parse("line \"a ... b\"", "s");}, "'...' must end the pattern"));CHECK(fails("repeat 2 { k: int if k > 0 { x: int } }", "1 5 0", "'x' is defined in only some repetitions"));CHECK(fails("n: int a[n][1]: int", "1000000000 1 2", "found end of input"));CHECK(fails("n: int g[n][1]: alphabet \"ab\"", "1000000000 ab", "expected a symbol for row 3, column 1"));CHECK(fails("r: int c: int x[r][c]: int", "2000000000 0", "empty rows without reading input"));CHECK(fails("r: int g[r][0]: alphabet \"ab\"", "2000000000", "empty rows without reading input"));CHECK(read("r: int c: int x[r][c]: int", "3 0").size("x")==3);return true;})
Case lexical("Read::Lexical", [](void) { Data d=read("comment \"c\" \"#\"\n" "stop \"%\"\n" "tokens \";\"\n" "expect \"p\" \"cnf\"\n" "repeat until eof { w: word expect \";\" }", "c comment\r\n# another\r\np cnf\r\na; b ;\r\nc x\r\n%\r\n0\r\n");CHECK(d.size("w")==2);CHECK(d.text("w", {1})=="b");CHECK(fails("a: int", "1 2", "unexpected input after the end"));CHECK(read("a: int ignore trailing", "1 2").integer("a")==1);return true;})
Case strings("Spec::Strings", [](void) { Data d=read("let s = \"a\\nb\\tc\\\\d\\\"e\"", "");CHECK(d.text("s")=="a\nb\tc\\d\"e");CHECK(fails([](void) {(void) Spec::parse("a: int\nlet s = \"a\\db\"", "s");}, "s:2: unknown escape '\\d'"));CHECK(fails([](void) {(void) Spec::parse("a: int\nlet s = \"a\\\nb\"\nb: int", "s");}, "s:2: unterminated string"));CHECK(fails([](void) {(void) Spec::parse("let s = \"a\\\\\"\nlet t = \"\\\"\"\nx: int untl", "s");}, "s:3: unknown statement 'untl'"));return true;})
Case labels("Read::Labels", [](void) { const char *spec="comment \"***\" \"---\"\n" "find \"jobs (incl. supersource/sink ): {jobs:int}\"\n" "find \"- renewable : {renewable:int} R\"\n" "find \"PRECEDENCE RELATIONS:\"\n" "line \"jobnr. #modes #successors successors\"\n" "repeat jobs { index 1 modes: int nsucc: int successors[nsucc]: int offset -1 }\n" "line \"REQUESTS/DURATIONS:\"\n" "line \"jobnr. mode duration ...\"\n" "repeat jobs { index 1 _: int duration: int request[renewable]: int }\n" "line \"RESOURCEAVAILABILITIES:\"\n" "line \"R 1 ...\"\n" "capacity[renewable]: int\n";Data d=read(spec, "****\n" "jobs (incl. supersource/sink ): 3\n" "horizon : 9\n" "RESOURCES\n" " - renewable : 1 R\n" " - nonrenewable : 0 N\n" " - doubly constrained : 0 D\n" "****\n" "PRECEDENCE RELATIONS:\n" "jobnr. #modes #successors successors\n" " 1 1 1 2\n" " 2 1 1 3\n" " 3 1 0\n" "****\n" "REQUESTS/DURATIONS:\n" "jobnr. mode duration R 1\n" "------------------------\n" " 1 1 0 0\n" " 2 1 4 2\n" " 3 1 0 0\n" "****\n" "RESOURCEAVAILABILITIES:\n" " R 1\n" " 3\n" "****\n");CHECK(equal(d.ints("successors"), {1, 2}));CHECK(equal(d.ints("duration"), {0, 4, 0}));CHECK(equal(d.ints("capacity"), {3}));return true;})
Case patterns("Read::Patterns", [](void) { Data d=read("line \"# size={n:int} box={w:int}x{h:int}\"\n" "find \"NAME : {name:rest}\"\n" "line \"p {_} {v:int} {c:num} ...\"", "# size=6 box=3x2\nnoise\nNAME: a b c \n" "p cnf 10 2.5 trailing words\n");CHECK(d.integer("n")==6);CHECK(d.integer("w")==3);CHECK(d.integer("h")==2);CHECK(d.text("name")=="a b c");CHECK(d.integer("v")==10);CHECK(d.number("c")==2.5);CHECK(fails("line \"p cnf {v:int}\"", "pcnf 3", "expected a line"));return true;})
Case power("Read::Power", [](void) { Data d=read("let a = 2 * 3 ^ 2 let b = 2 ^ 3 ^ 2 let c = (2 ^ 3) ^ 2 let e = -2 ^ 2 let f = 1 + 2 ^ 2 * 3\n" "let k = (-2) ^ 2 let m = -2 ^ 3 ^ 2\n" "let g = 7 ^ 0 let h = (0 - 2) ^ 63 let i = 1 ^ 9223372036854775807 let j = 3 ^ 39", "");CHECK(d.integer("a")==18);CHECK(d.integer("b")==512);CHECK(d.integer("c")==64);CHECK(d.integer("e")==-4);CHECK(d.integer("k")==4);CHECK(d.integer("m")==-512);CHECK(d.integer("f")==13);CHECK(d.integer("g")==1);CHECK(d.integer("h")==LLONG_MIN);CHECK(d.integer("i")==1);CHECK(d.integer("j")==4052555153018976267LL);CHECK(fails("let x = 3 ^ 40", "", "integer overflow in '^'"));CHECK(fails("let x = 2 ^ 63", "", "integer overflow in '^'"));CHECK(fails("let x = 2 ^ -1", "", "negative exponent in '^'"));CHECK(fails("let x = 2 ^ -1 + 3", "", "negative exponent in '^'"));CHECK(fails("let x = -2 ^ 63", "", "integer overflow in '^'"));CHECK(fails("f: float let x = f ^ 2", "1.5", "'^' needs integers"));return true;})
Case record_names("Spec::Records", [](void) { CHECK(fails([](void) {(void) Spec::parse("n: int repeat n { a: int }\nrepeat n { b: int }\ncheck a < b", "s");}, "s:3: a check can only range over the records of one repeat, but 'a' and 'b' are defined in different " "repeats"));CHECK(fails([](void) {(void) Spec::parse("repeat 2 { repeat 2 { a: int } repeat 2 { b: int } } check a < b", "s");}, "can only range over the records of one repeat"));CHECK(fails([](void) {(void) Spec::parse("n: int repeat n { a: int } let a = 3\ncheck a < 1", "s");}, "s:2: 'a' is defined in several repeats, or inside and outside a repeat"));CHECK(fails([](void) {(void) Spec::parse("repeat 2 { a: int } repeat 2 { a: int } check a < 1", "s");}, "'a' is defined in several repeats"));(void) Spec::parse("n: int repeat n { a: int check a > 0 } let a = 3", "s");(void) Spec::parse("repeat 2 { k: int if k > 0 { a: int } else { let a = 0 } } check a >= 0", "s");return true;})
Case expressions("Read::Expressions", [](void) { const char *rows="n: int repeat n { list r: int until eol } f[2]: float w[2]: word\n";const char *text="3\n1 2\n3 3 4\n5\n0.5 2.5 a b";Data d=read((std::string(rows)+"let a = r[1] let b = r[1][2] + r[2][0] let g = f[1] let v = w[0]\n" "let s = sum(x in r: sum(x)) let c = count(x in r: count(x) > 1)\n" "let t = sum(x in r: sum(y in x: y * y)) let k = count(x in f: x > 1)\n" "check all(x in r: sum(x) + count(x) - 1 <= 12) && !all(x in r: count(x) == 2)\n" "check any(x in r: !distinct(x)) && !any(x in w: x == \"c\") && any(x in w: x == \"b\")\n" "let d = distinct(r[0], 3) && !distinct(r[0], r[2], 2) && distinct(r[1][1]) check d\n" "check all(x in r: defined(x)) && !defined(x)").c_str(), text);CHECK(equal(d.ints("a"), {3, 3, 4}));CHECK(d.integer("b")==9);CHECK(d.number("g")==2.5);CHECK(d.text("v")=="a");CHECK(d.integer("s")==18);CHECK(d.integer("c")==2);CHECK(d.integer("t")==64);CHECK(d.integer("k")==1);Data e=read("a[0]: int let s = sum(x in a: x) let c = count(x in a: 1)\n" "check all(x in a: 0) && !any(x in a: 1) && distinct(a)", "");CHECK((e.integer("s")==0) &&(e.integer("c")==0));std::string r(rows);CHECK(fails((r+"let z = r[3]").c_str(), text, "index 3 is out of range for 'r' (size 3, indices start at 0)"));CHECK(fails((r+"let z = r[0 - 1]").c_str(), text, "index -1 is out of range"));CHECK(fails((r+"let z = r[1][3]").c_str(), text, "index 3 is out of range for an element of 'r' (size 3"));CHECK(fails((r+"let z = n[0]").c_str(), text, "only arrays can be indexed, not 'n'"));CHECK(fails((r+"let z = r[f[0]]").c_str(), text, "an index must be an integer"));CHECK(fails((r+"let z = r[0][0][0]").c_str(), text, "only arrays can be indexed, not an element of 'r'"));CHECK(fails((r+"let z = all(x in n: 1)").c_str(), text, "'all(x in ...)' needs an array"));CHECK(fails((r+"let z = sum(x in r: x)").c_str(), text, "'sum' needs integers"));CHECK(fails((r+"let z = count(x in r: 1) + x").c_str(), text, "'x' is not defined yet"));CHECK(fails((r+"let z = all(x in r: q)").c_str(), text, "'q' is not defined yet"));CHECK(fails((r+"let z = distinct(w)").c_str(), text, "'distinct' takes integers"));CHECK(fails("a[2]: int let z = sum(x in a: x)", "9223372036854775807 1", "integer overflow in 'sum'"));return true;})
Case strict_options("Driver::Options::Strict", [](void) { Gecode::Options options("Test");char name[]="test", iterations[]="-iterations", value[]="200";char unknown[]="--typo", help[]="--help", positional[]="instance.txt";char *valid_argv[]={name, iterations, value, nullptr};int valid_argc=3;options.parse_strict(valid_argc, valid_argv);CHECK(valid_argc==1 &&options.iterations()==200);char *remaining_argv[]={name, unknown, positional, nullptr};int remaining_argc=3;options.parse(remaining_argc, remaining_argv);CHECK(remaining_argc==3 &&remaining_argv[1]==unknown);options.parse_permissive(remaining_argc, remaining_argv);CHECK(remaining_argc==3 &&remaining_argv[2]==positional);HelpOptions< Gecode::Options > strict;char *invalid_argv[]={name, iterations, value, unknown, help, nullptr};CHECK(rejects(strict, 5, invalid_argv, "--typo"));char *positional_argv[]={name, positional, nullptr};CHECK(rejects(strict, 2, positional_argv, "instance.txt"));return true;})
Case records("Read::Records", [](void) { const char *rows="n: int repeat n { list row: int until eol } width: int\n" "check sum(row) + count(row) - 1 <= width \"the clues do not fit\"";CHECK(read(rows, "2\n1 1\n2\n3").size("row")==2);CHECK(fails(rows, "2\n1 1\n 2 2\n3", "test.txt:3:3: check failed for record 2 of 'row': the clues do not fit"));CHECK(read(rows, "2\n1 1\n2\n3").entries()==3);const char *windows="n: int repeat n { ready: int due: int } check ready <= due \"window\"";CHECK(read(windows, "2 3 5 0 1").size("ready")==2);CHECK(fails(windows, "3 0 5 2 4 6 1", "check failed for record 3 of 'ready': window"));const char *jobs="j: int m: int repeat j { k: int repeat m { x: int } } check x < k \"x below k\"";CHECK(read(jobs, "2 2\n5 1 2\n3 1 2\n").size("x")==2);CHECK(fails(jobs, "2 2\n5 1 2\n3 1 4\n", "test.txt:3:5: check failed for record 2 of record 2 of 'x': x below k"));Data d=read("n: int repeat n { list row: int until eol }\n" "check size(row) == 2 && count(row) == 3 && sum(r in row: sum(r)) == 21\n" "check count(r in row: count(r) == 3) == size(row) && defined(row)", "2\n1 2 3\n4 5 6\n");CHECK(d.size("row")==2);CHECK(fails("n: int lim[2]: int repeat n { x: int } check all(l in lim: x < l) \"below\"", "2 5 3 1 4", "check failed for element 2 of 'lim' in record 2 of 'x': below"));const char *optional="sections { \"A\" optional { repeat 2 { x: int } } \"B\" optional } check !defined(x) || x > 0 \"positive\"";CHECK(!read(optional, "B").has("x"));CHECK(read(optional, "A\n1 2").size("x")==2);CHECK(fails(optional, "A\n1 0", "check failed for record 2 of 'x': positive"));CHECK(fails("n: int repeat n { list row: int until eol check count(row) == 2 \"two\" }", "2\n1 2\n3\n", "check failed: two"));CHECK(fails("n: int repeat n { list row: int until eol check count(row) == 2 \"two\" }", "2\n1 2\n3\n", "while reading: repeat [2 of 2]"));CHECK(read("repeat 2 { repeat 2 { x: int } check size(x) == 2 && x > 0 }", "1 2 3 4").size("x")==2);CHECK(fails("repeat 2 { repeat 2 { x: int } check x > 0 \"positive\" }", "1 2 3 0", "check failed for record 2 of 'x': positive"));Data l=read("n: int repeat n { x: int } let s = sum(x) let f = x[0] if count(x) == 2 { let t = 1 }", "2 3 4");CHECK(l.integer("s")==7);CHECK(l.integer("f")==3);CHECK(l.has("t"));CHECK(read("n: int repeat n { x: int } check x > 0 && 1 > 2", "0").size("x")==0);return true;})
Case failure_locations("Read::FailureLocations", [](void) { CHECK(fails("a[4]: int check all(x in a: x > 0) \"positive\"", "1 2 0 3", "check failed for element 3 of 'a': positive"));CHECK(fails("repeat 3 as xs { a: int } check all(x in xs: x.a > 0) \"positive\"", "1\n2\n0\n", "test.txt:3:1: check failed for record 3 of 'xs': positive"));CHECK(fails("n: int repeat n { list row: int until eol } check all(r in row: min(r) > 0) \"positive\"", "2\n1 2\n3 0\n", "test.txt:3:1: check failed for record 2 of 'row': positive"));const char *jobs="repeat 2 as jobs { each job repeat 2 as steps { d: int } }\n";std::string nested=std::string(jobs)+"check all(j in jobs: all(s in j.steps: s.d > 0)) \"positive\"";CHECK(fails(nested.c_str(), "1 2\n3 0\n", "test.txt:2:3: check failed for record 2 of 'steps' in record 2 of " "'jobs': positive"));std::string lifted=std::string(jobs)+"check all(x in job.d: x > 0) \"positive\"";CHECK(fails(lifted.c_str(), "1 2\n3 0\n", "test.txt:2:3: check failed for record 2 of 'steps' in record 2 of " "'jobs': positive"));CHECK(fails("a[2][2]: int check all(r in a: all(x in r: x > 0)) \"positive\"", "1 2 3 0", "check failed for element 2 of 'r' in element 2 of 'a': positive"));CHECK(fails("a[2]: int check any(x in a: x > 5) \"big\"", "1 2", "check failed: big"));CHECK(fails("a[2]: int check !all(x in a: x > 0) \"not all\"", "1 2", "check failed: not all"));CHECK(fails("a[2]: int check 1 > 2 || all(x in a: x > 1) \"m\"", "1 2", "check failed for element 1 of 'a': m"));CHECK(fails("a[2]: int check all(x in a: x > 1) == 1 \"m\"", "1 2", "check failed: m"));CHECK(fails("a[2]: int check count(x in a: all(y in a: y > x)) == 2 \"m\"", "1 2", "check failed: m"));CHECK(fails("n: int repeat n { ready: int } check ready[0] == 0", "2 1 2", "which is one value of each record here; to index the records, name them, as in 'repeat n as nodes { " "each node ... }', and use 'nodes[0].ready'"));CHECK(fails("n: int repeat n as nodes { ready: int } check ready[0] == 0", "2 1 2", "to index the records, use 'nodes[0].ready'"));return true;})
Case arrays("Read::Arrays", [](void) { Data d=read("n: int m: int a[n][m]: int _: int f[2]: float offset 1", "2 3\n1 2\n3 4 5 6\n99 1.5 2");CHECK(d.depth("a")==2);CHECK(d.size("a")==2);CHECK(d.size("a", {1})==3);CHECK(equal(d.ints("a"), {1, 2, 3, 4, 5, 6}));CHECK(equal(d.ints("a", {1}), {4, 5, 6}));CHECK(d.integer("a", {1, 2})==6);CHECK(!d.has("_"));CHECK(d.numbers("f")[0]==2.5);CHECK(d.numbers("f")[1]==3.0);return true;})
Case settings("Spec::Settings", [](void) { const char *nested[]={ "repeat 2 { comment \"c\" a: int }", "if 1 > 0 { stop \"%\" }", "n: int if n > 0 { } else if n < 0 { tokens \";\" }", "instances { separators \",\" a: int }", "sections { \"x\" { ignore trailing } }" };for(const char *s :nested) CHECK(fails([&](void) {(void) Spec::parse(s, "s");}, "must be at the top level of the spec"));CHECK(fails([](void) {(void) Spec::parse("a: int\nrepeat a {\n comment \"c\"\n}", "s");}, "s:3: the setting 'comment' must be at the top level"));CHECK(read("repeat 2 { expect \"x\" a: int }", "x 1 x 2").size("a")==2);return true;})
bool rejects(const char *spec, const char *what)
Check that parsing spec fails with what.
Definition instance.cpp:91
Case shapes("Read::Shapes", [](void) { Data d=read("repeat 2 { x[0][3]: float }", "");CHECK(d.depth("x")==3);CHECK(d.type("x")==Gecode::Instance::ValueType::FLOAT);Data z=read("repeat 0 { x[2][3]: float w: word list l: int until 0 }", "");CHECK((z.depth("x")==3) &&(z.type("x")==Gecode::Instance::ValueType::FLOAT));CHECK((z.depth("w")==1) &&(z.type("w")==Gecode::Instance::ValueType::STRING));CHECK((z.depth("l")==2) &&(z.size("l")==0));Data m=read("repeat 2 { k: int if k > 5 { x[2][2]: int } }", "1 2");CHECK((m.depth("x")==3) &&(m.size("x")==2) &&(m.size("x", {1})==0));CHECK(fails("repeat 2 { k: int if k > 5 { x: int } }", "1 2", "'x' is defined in no repetition"));Data e=read("s[1][2][2]: word v[2][1][2]: int", "a b c d 1 2 3 4");CHECK(e.text("s", {0, 1, 1})=="d");CHECK(e.integer("v", {1, 0, 0})==3);CHECK(e.size("v", {1, 0})==2);CHECK(equal(e.ints("v", {1, 0}), {3, 4}));CHECK(fails([&](void) {(void) e.text("s", {0, 2, 0});}, "index out of range"));CHECK(read("list w: word until 0", "a b 0").size("w")==2);return true;})
Case ranges("Read::Ranges", [](void) { Data d=read("n: 1.. a[n]: 0..<n b: ..0 c: -2..-1", "2 0 1 -5 -2");CHECK(equal(d.ints("a"), {0, 1}));CHECK(d.integer("b")==-5);CHECK(fails("n: 1.. a[n]: 0..<n", "2 0 2", "test.txt:1:5: expected an int in 0..1, found '2'"));CHECK(fails("a: 0..9", "x", "expected an int in 0..9, found 'x'"));CHECK(fails("a: 0..", "-1", "expected an int in 0.., found '-1'"));CHECK(fails("a: ..<0", "0", "expected an int in ..-1, found '0'"));CHECK(equal(read("a[2]: 1..2 offset -1 list l: 0..9 until -1", "1 2 3 -1").ints("a"), {0, 1}));CHECK(fails("list l: 0..9 until -1", "3 10 -1", "found '10'"));CHECK(fails("w[3][3]: 0..1 layout \"UPPER_ROW\"", "1 2 1", "found '2'"));Data l=read("line \"{n:int} {m:0..n}\"", "3 2");CHECK(l.integer("m")==2);CHECK(fails("line \"{n:int} {m:0..n}\"", "3 4", "test.txt:1:3: expected an int in 0..3, found '4'"));CHECK(fails("a: 0..\"x\"", "1", "the bounds of a range must be integers"));CHECK(fails("a: 0..<-9223372036854775807-1", "1", "integer overflow"));return true;})
Case errors("Read::Errors", [](void) { CHECK(fails("n: int repeat n { x: int }", "3\n1\n2 z\n", "test.txt:3:3: expected int, found 'z'"));CHECK(fails("n: int repeat n { x: int }", "3\n1\n2\n", "while reading: repeat [3 of 3] > x"));CHECK(fails("n: int repeat n { x: int }", "3\n1\n2\n", "spec: test.reader:1"));CHECK(fails([](void) {(void) Spec::parse("x: int untl", "s");}, "s:1: unknown statement 'untl'"));CHECK(fails([](void) {(void) Spec::parse("repeat 2 { x: int", "s");}, "missing '}'"));CHECK(fails([](void) {(void) Spec::parse("line \"{x:bad}\"", "s");}, "unknown type 'bad'"));CHECK(fails([](void) {(void) Spec::load("/nonexistent/x.reader");}, "cannot open file"));CHECK(fails([](void) {(void) Spec::load(".");}, "is a directory"));return true;})
Case parameters("Read::Parameters", [](void) { Params p;p.set("k", "1.5");CHECK(read("param k check k > 1 && k < 2", "", p).number("k")==1.5);Params q;q.set("kk", "7");CHECK(fails([&](void) {(void) read("param k = 1", "", q);}, "the spec has no parameter 'kk'"));Params r;r.set("s", "3");r.set("i", "4");Data d=read("param s = \"x\" param i = 1 check s == \"3\" && i == 4", "", r);CHECK(d.text("s")=="3");Params t;t.set("i", "4.5");CHECK(fails([&](void) {(void) read("param i = 1", "", t);}, "parameter 'i' must be an integer"));return true;})
General test support.
Definition afc.cpp:41
std::ostringstream olog
Stream used for logging.
Definition test.cpp:54
Region r
Definition region.cpp:65
Signals that help was shown.
Definition instance.cpp:619