Generated on for Gecode by doxygen 1.17.0
spec.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
35
36#include <sys/stat.h>
37
38#include <cctype>
39#include <cerrno>
40#include <cstdlib>
41#include <cstring>
42#include <fstream>
43#include <locale>
44#include <sstream>
45
46namespace Gecode { namespace Instance {
47
48 std::string
49 read_file(const std::string& path) {
50 struct stat st;
51 if ((stat(path.c_str(), &st) == 0) && ((st.st_mode & S_IFMT) == S_IFDIR))
52 throw Error(path + ": is a directory");
53 std::ifstream f(path.c_str(), std::ios::binary);
54 if (!f)
55 throw Error(path + ": cannot open file");
56 std::ostringstream ss;
57 ss << f.rdbuf();
58 return ss.str();
59 }
60
61 bool
62 parse_int(const std::string& t, long long int& v) {
63 if (t.empty() || is_space(t[0]))
64 return false;
65 errno = 0;
66 char* end = nullptr;
67 v = std::strtoll(t.c_str(), &end, 10);
68 return (errno == 0) && (end == t.c_str() + t.size());
69 }
70
71 bool
72 parse_float(const std::string& t, double& v) {
73 // Only decimal notation: no hexadecimal, infinity, or NaN
74 if (t.empty() || (number_end(t, 0, true, true) != t.size()))
75 return false;
76 // Out-of-range values fail
77 std::istringstream in(t);
78 in.imbue(std::locale::classic());
79 in >> v;
80 return !in.fail() && (in.peek() == EOF);
81 }
82
83 void
84 fail_at(const std::string& origin, int line, const std::string& m) {
85 throw Error(origin + ":" + std::to_string(line) + ": " + m);
86 }
87
88 namespace {
89
91 class Token {
92 public:
94 enum class Kind { IDENT, INT, FLOAT, STRING, PUNCT, END } kind;
96 std::string text;
98 long long int i;
100 double f;
102 int line;
104 bool glued;
106 Token(void)
107 : kind(Kind::END), i(0), f(0.0), line(0), glued(false) {}
108 };
109
116 char
117 unescape(char e, const std::string& origin, int line) {
118 switch (e) {
119 case 'n': return '\n';
120 case 't': return '\t';
121 case '\\': case '"': return e;
122 case '\n': fail_at(origin, line, "unterminated string");
123 default:
124 fail_at(origin, line, std::string("unknown escape '\\") + e + "' in string (use \\n, \\t, \\\\, or \\\")");
125 }
126 }
127
129 size_t
130 name_end(const std::string& src, size_t p) {
131 while ((p < src.size()) && is_alnum(src[p]))
132 p++;
133 return p;
134 }
135
137 const std::string gecode_prefix = "gecode.";
138
141 bool
142 at_gecode_name(const std::string& src, size_t p, size_t q) {
143 return (src.compare(p, q-p, "gecode") == 0) && (q+1 < src.size()) && (src[q] == '.') && is_alnum(src[q+1]);
144 }
145
147 bool
148 is_gecode_name(const std::string& n) {
149 return n.compare(0, gecode_prefix.size(), gecode_prefix) == 0;
150 }
151
153 void
154 lex(const std::string& src, const std::string& origin, Seq<Token>& toks, int line = 1) {
155 size_t p = 0;
156 bool space = true;
157 while (p < src.size()) {
158 char c = src[p];
159 if (c == '\n') { line++; p++; space = true; continue; }
160 if (is_space(c)) { p++; space = true; continue; }
161 if (c == '#') {
162 while ((p < src.size()) && (src[p] != '\n')) p++;
163 space = true;
164 continue;
165 }
166 Token t;
167 t.line = line;
168 t.glued = !space;
169 space = false;
170 if (c == '"') {
171 p++;
172 // A string ends on its line: a newline, even after a backslash,
173 // leaves it unterminated
174 while ((p < src.size()) && (src[p] != '"')) {
175 if (src[p] == '\n')
176 fail_at(origin, line, "unterminated string");
177 if (src[p] == '\\') {
178 if (p+1 >= src.size())
179 break;
180 t.text += unescape(src[p+1], origin, line);
181 p += 2;
182 } else {
183 t.text += src[p++];
184 }
185 }
186 if (p >= src.size())
187 fail_at(origin, line, "unterminated string");
188 p++;
189 t.kind = Token::Kind::STRING;
190 } else if (is_digit(c)) {
191 // A minus sign before a number is an operator, and a range such
192 // as 0..9 is two numbers
193 size_t q = number_end(src, p, false, true);
194 for (size_t k=p; k+1<q; k++)
195 if (src.compare(k, 2, "..") == 0) {
196 q = k;
197 break;
198 }
199 t.text = src.substr(p, q-p);
200 p = q;
201 bool flt = (t.text.find_first_not_of("0123456789") != std::string::npos);
202 t.kind = flt ? Token::Kind::FLOAT : Token::Kind::INT;
203 if (flt ? !parse_float(t.text, t.f) : !parse_int(t.text, t.i))
204 fail_at(origin, line, "bad number " + t.text);
205 } else if (is_alnum(c)) {
206 size_t q = name_end(src, p);
207 // Gecode constants such as gecode.int_max are single names
208 if (at_gecode_name(src, p, q))
209 q = name_end(src, q+1);
210 t.text = src.substr(p, q-p);
211 p = q;
212 t.kind = Token::Kind::IDENT;
213 } else {
214 // The longest operator that comes next
215 static const char* ops[] = {"..<", "..", "==", "!=", "<=", ">=", "&&", "||"};
216 t.kind = Token::Kind::PUNCT;
217 t.text = std::string(1, c);
218 for (const char* o : ops)
219 if ((t.text.size() == 1) && (src.compare(p, std::strlen(o), o) == 0))
220 t.text = o;
221 if ((t.text.size() == 1) && (std::strchr("{}[]()=<>+-*/%^!,.:", c) == nullptr))
222 fail_at(origin, line, std::string("unexpected character '") + c + "'");
223 p += t.text.size();
224 }
225 toks.push(t);
226 }
227 Token e;
228 e.line = line;
229 toks.push(e);
230 }
231
233 bool read_type(const std::string& t, ReadType& r) {
234 if (t == "int") r = ReadType::INT;
235 else if (t == "float") r = ReadType::FLOAT;
236 else if (t == "num") r = ReadType::NUM;
237 else if (t == "word") r = ReadType::WORD;
238 else if (t == "rest") r = ReadType::REST;
239 else return false;
240 return true;
241 }
242
245 bool is_name(const std::string& s) {
246 if (s.empty() || is_digit(s[0]))
247 return false;
248 for (char c : s)
249 if (!is_alnum(c))
250 return false;
251 return true;
252 }
253
255 void
256 flush(Pattern& pat, std::string& lit) {
257 if (!lit.empty()) {
258 Pattern::Item it(Pattern::Item::Kind::LIT);
259 it.text = lit;
260 pat.items.push(std::move(it));
261 lit.clear();
262 }
263 }
264
266 bool
267 ends_word(const Pattern::Item& it) {
268 typedef Pattern::Item::Kind Kind;
269 return (it.kind == Kind::CAP) || (it.kind == Kind::VAR) ||
270 ((it.kind == Kind::LIT) && is_alnum(it.text[it.text.size()-1]));
271 }
272
274 bool
275 starts_word(const Pattern::Item& it) {
276 typedef Pattern::Item::Kind Kind;
277 return (it.kind == Kind::CAP) || (it.kind == Kind::VAR) || ((it.kind == Kind::LIT) && is_alnum(it.text[0]));
278 }
279
282 Pattern
283 compile(const std::string& src, Seq<std::string>& types) {
284 typedef Pattern::Item Item;
285 Pattern pat;
286 pat.source = src;
287 size_t p = 0;
288 std::string lit;
289 while (p < src.size()) {
290 char c = src[p];
291 if (is_blank(c)) {
292 flush(pat, lit);
293 while ((p < src.size()) && is_blank(src[p])) p++;
294 pat.items.push(Item(Item::Kind::SPACE));
295 } else if (c == '{') {
296 flush(pat, lit);
297 size_t q = src.find('}', p);
298 if (q == std::string::npos)
299 throw Error("unterminated capture in pattern \"" + src + "\"");
300 std::string cap = src.substr(p+1, q-p-1);
301 p = q+1;
302 if (!cap.empty() && (cap[0] == '$')) {
303 Item it(Item::Kind::VAR);
304 it.text = cap.substr(1);
305 if (!is_name(it.text))
306 throw Error("missing or bad name in pattern \"" + src + "\"");
307 pat.items.push(std::move(it));
308 continue;
309 }
310 Item it(Item::Kind::CAP);
311 size_t colon = cap.find(':');
312 it.text = cap.substr(0, colon);
313 if (!is_name(it.text) && !it.text.empty() && (it.text != "_"))
314 throw Error("capture name '" + it.text + "' in pattern \"" + src + "\" is not a name");
315 types.push((colon == std::string::npos) ? "word" : cap.substr(colon+1));
316 pat.items.push(std::move(it));
317 } else if (src.compare(p, 3, "...") == 0) {
318 flush(pat, lit);
319 if (src.find_first_not_of(" \t", p+3) != std::string::npos)
320 throw Error("'...' must end the pattern \"" + src + "\"");
321 pat.items.push(Item(Item::Kind::ANY));
322 p += 3;
323 } else {
324 lit += c;
325 p++;
326 }
327 }
328 flush(pat, lit);
329 // A space is required between two items that would otherwise run
330 // together, such as "p cnf" or "{a:int} {b:int}".
331 for (int k=1; k+1<pat.items.size(); k++)
332 if (pat.items[k].kind == Item::Kind::SPACE)
333 pat.items[k].required = ends_word(pat.items[k-1]) && starts_word(pat.items[k+1]);
334 return pat;
335 }
336
338 class BoundName {
339 public:
341 std::string name;
343 int line;
344 };
345
347 class TypeName {
348 public:
350 std::string name;
352 const Stmt* def;
353 };
354
356 class Parser {
357 public:
359 Parser(const std::string& src, const std::string& o)
360 : origin(o), p(0), depth(0), nesting(0), repeats(0), repeat_start(false), each_ok(false) {
361 lex(src, origin, toks);
362 }
364 void parse(SpecImpl& s) {
365 while (peek().kind != Token::Kind::END) {
366 if (keyword("format")) {
367 next();
368 if ((peek().kind != Token::Kind::IDENT) && (peek().kind != Token::Kind::STRING))
369 fail("expected a format name, found " + describe(peek()));
370 s.name = next().text;
371 // Names such as dimacs-cnf: words joined by '-' or '.'
372 while (at_name_joiner()) {
373 s.name += next().text;
374 s.name += next().text;
375 }
376 } else {
377 if (!s.body.empty() && (s.body.back()->kind == Stmt::Kind::INSTANCES))
378 fail("'instances' must be the last statement of the spec");
379 s.body.push(statement());
380 }
381 }
382 // A bound name that is also a spec name would hide it
383 Seq<Decl> names;
384 declared(s.body, names);
385 for (const BoundName& b : bound_all)
386 for (const Decl& d : names)
387 if (d.name == b.name)
388 fail_at(origin, b.line, "'" + b.name + "' is bound by a comprehension but is also a name in the spec");
389 for (const TypeName& t : types_all)
390 for (const Decl& d : names)
391 if (d.name == t.name)
392 fail_at(origin, t.def->line, "'" + t.name + "' names a type, so it cannot also name a value");
393 resolve(s.body, origin);
394 }
395 private:
397 std::string origin;
399 Seq<Token> toks;
401 int p;
403 int depth;
405 int nesting;
407 int repeats;
409 bool repeat_start;
411 bool each_ok;
413 Seq<std::string> bound;
415 Seq<BoundName> bound_all;
417 Seq<TypeName> types;
419 Seq<TypeName> types_all;
421 static const int max_nesting = 256;
422
423 const Token& peek(void) const {
424 return toks[p];
425 }
426 const Token& next(void) {
427 const Token& t = toks[p];
428 if (p+1 < toks.size()) p++;
429 return t;
430 }
431 [[noreturn]] void fail(const std::string& m) const {
432 fail_at(origin, peek().line, m);
433 }
434 static std::string describe(const Token& t) {
435 if (t.kind == Token::Kind::END) return "end of spec";
436 if (t.kind == Token::Kind::STRING) return "\"" + t.text + "\"";
437 return "'" + t.text + "'";
438 }
439 bool keyword(const char* k) const {
440 return (peek().kind == Token::Kind::IDENT) && (peek().text == k);
441 }
442 bool punct(const char* k) const {
443 return (peek().kind == Token::Kind::PUNCT) && (peek().text == k);
444 }
447 bool at_name_joiner(void) const {
448 if (!(punct("-") || punct(".")) || !peek().glued || (p+1 >= toks.size()))
449 return false;
450 const Token& t = toks[p+1];
451 return t.glued && ((t.kind == Token::Kind::IDENT) || (t.kind == Token::Kind::INT));
452 }
453 void expect_punct(const char* k) {
454 if (!punct(k))
455 fail(std::string("expected '") + k + "', found " + describe(peek()));
456 next();
457 }
458 void expect_keyword(const char* k) {
459 if (!keyword(k))
460 fail(std::string("expected '") + k + "', found " + describe(peek()));
461 next();
462 }
463 std::string ident(const char* what) {
464 if (peek().kind != Token::Kind::IDENT)
465 fail(std::string("expected ") + what + ", found " + describe(peek()));
466 return next().text;
467 }
469 std::string new_name(const char* what) {
470 std::string n = ident(what);
471 if (is_gecode_name(n))
472 fail("'" + n + "' cannot be defined: names starting with '" + gecode_prefix + "' are Gecode constants");
473 return n;
474 }
475 std::string string(const char* what) {
476 if (peek().kind != Token::Kind::STRING)
477 fail(std::string("expected ") + what + " (a string), found " + describe(peek()));
478 return next().text;
479 }
480 Pattern pattern(void) {
481 int line = peek().line;
482 std::string s = string("a line pattern");
483 Pattern pat;
484 Seq<std::string> texts;
485 try {
486 pat = compile(s, texts);
487 } catch (const Error& e) {
488 fail_at(origin, line, e.what());
489 }
490 int k = 0;
491 for (Pattern::Item& it : pat.items)
492 if (it.kind == Pattern::Item::Kind::CAP) {
493 it.type = capture_type(texts[k++], line);
494 if (it.type.read == ReadType::SYMBOL)
495 fail_at(origin, line, "a capture cannot be of an alphabet type");
496 }
497 return pat;
498 }
500 Type capture_type(const std::string& text, int line) {
501 // Parse the text in place of the tokens of the spec
502 Seq<Token> sub;
503 lex(text, origin, sub, line);
504 if (sub.size() == 1)
505 fail_at(origin, line, "a capture needs a type after ':'");
506 std::swap(toks, sub);
507 int at = p;
508 p = 0;
509 Type t = type();
510 if (peek().kind != Token::Kind::END)
511 fail("unexpected " + describe(peek()) + " in the capture type '" + text + "'");
512 std::swap(toks, sub);
513 p = at;
514 return t;
515 }
517 void enter(int& n, const char* what) {
518 if (++n > max_nesting)
519 fail(std::string(what) + " are nested too deeply");
520 }
521 Block block(void) {
522 expect_punct("{");
523 enter(depth, "blocks");
524 // The types defined in the block are only visible inside it
525 int scope = types.size();
526 Block b;
527 while (!punct("}")) {
528 if (peek().kind == Token::Kind::END)
529 fail("missing '}'");
530 b.push(statement());
531 }
532 next();
533 while (types.size() > scope)
534 types.pop();
535 depth--;
536 return b;
537 }
538 std::unique_ptr<Expr> integer(long long int v) {
539 std::unique_ptr<Expr> e(new Expr(Expr::Kind::INT));
540 e->i = v;
541 return e;
542 }
543
545 bool accept(const char* k) {
546 if (!keyword(k))
547 return false;
548 next();
549 return true;
550 }
551
552 /*
553 * Statements: one function per keyword, called after the keyword
554 * with a new statement of the keyword's kind
555 */
556
558 typedef void (Parser::*Parse)(Stmt& s, const std::string& kw);
559
561 class Keyword {
562 public:
564 const char* keyword;
566 Stmt::Kind kind;
568 Parse parse;
571 bool setting;
572 };
573
575 static const Keyword* statement_keyword(const std::string& k) {
576 static const Keyword statements[] = {
577 {"comment", Stmt::Kind::COMMENT, &Parser::words, true},
578 {"stop", Stmt::Kind::STOP, &Parser::words, true},
579 {"expect", Stmt::Kind::EXPECT, &Parser::words, false},
580 {"tokens", Stmt::Kind::TOKENS, &Parser::chars, true},
581 {"separators", Stmt::Kind::SEPARATORS, &Parser::chars, true},
582 {"ignore", Stmt::Kind::TRAILING, &Parser::trailing, true},
583 {"param", Stmt::Kind::PARAM, &Parser::param, false},
584 {"list", Stmt::Kind::LIST, &Parser::list, false},
585 {"line", Stmt::Kind::LINE, &Parser::line_pattern, false},
586 {"find", Stmt::Kind::FIND, &Parser::line_pattern, false},
587 {"skip", Stmt::Kind::SKIP, &Parser::skip, false},
588 {"index", Stmt::Kind::INDEX, &Parser::index, false},
589 {"repeat", Stmt::Kind::REPEAT, &Parser::repeat, false},
590 {"each", Stmt::Kind::EACH, &Parser::each, false},
591 {"instances", Stmt::Kind::INSTANCES, &Parser::instances, false},
592 {"sections", Stmt::Kind::SECTIONS, &Parser::sections, false},
593 {"if", Stmt::Kind::IF, &Parser::conditional, false},
594 {"let", Stmt::Kind::LET, &Parser::let, false},
595 {"check", Stmt::Kind::CHECK, &Parser::check, false},
596 {"type", Stmt::Kind::TYPE, &Parser::type_def, false}
597 };
598 for (const Keyword& e : statements)
599 if (k == e.keyword)
600 return &e;
601 return nullptr;
602 }
603
610 bool at_declaration(int k) const {
611 if (toks[k].kind != Token::Kind::IDENT)
612 return false;
613 k++;
614 while ((toks[k].kind == Token::Kind::PUNCT) && (toks[k].text == "[")) {
615 int open = 0;
616 do {
617 if (toks[k].kind == Token::Kind::END)
618 return false;
619 if (toks[k].kind == Token::Kind::PUNCT)
620 open += (toks[k].text == "[") ? 1 : ((toks[k].text == "]") ? -1 : 0);
621 k++;
622 } while (open > 0);
623 }
624 return (toks[k].kind == Token::Kind::PUNCT) && (toks[k].text == ":");
625 }
626
627 std::unique_ptr<Stmt> statement(void) {
628 const Token& t = peek();
629 each_ok = repeat_start;
630 repeat_start = false;
631 if (t.kind != Token::Kind::IDENT)
632 fail("expected a statement, found " + describe(t));
633 if (at_declaration(p)) {
634 std::unique_ptr<Stmt> s(new Stmt(Stmt::Kind::READ, t.line));
635 declaration(*s);
636 return s;
637 }
638 const Keyword* e = statement_keyword(t.text);
639 if (e == nullptr)
640 fail("unknown statement '" + t.text + "'");
641 if (e->setting && (depth > 0))
642 fail("the setting '" + t.text + "' must be at the top level of the spec");
643 std::unique_ptr<Stmt> s(new Stmt(e->kind, t.line));
644 std::string kw = next().text;
645 (this->*e->parse)(*s, kw);
646 return s;
647 }
648
650 void words(Stmt& s, const std::string&) {
651 s.words.push(string(s.kind == Stmt::Kind::EXPECT ? "a literal token" : "a line prefix"));
652 while (peek().kind == Token::Kind::STRING)
653 s.words.push(next().text);
654 }
656 void chars(Stmt& s, const std::string&) {
657 s.chars = string(s.kind == Stmt::Kind::TOKENS ? "single-character tokens" : "separator characters");
658 }
660 void trailing(Stmt&, const std::string&) {
661 expect_keyword("trailing");
662 }
664 std::string defined(const char* what) {
665 std::string n = new_name(what);
666 if (n == "_")
667 fail("'_' cannot be defined here");
668 return n;
669 }
671 void param(Stmt& s, const std::string&) {
672 s.name = defined("a parameter name");
673 if (punct("=")) {
674 next();
675 s.expr = expr();
676 }
677 }
684 bool option(const char* k) {
685 return !at_declaration(p) && accept(k);
686 }
688 static bool ends_range(const std::string& k) {
689 return (statement_keyword(k) != nullptr) || (k == "layout") || (k == "offset") || (k == "until");
690 }
692 bool at_upper_bound(void) const {
693 const Token& t = peek();
694 switch (t.kind) {
695 case Token::Kind::IDENT:
696 return !ends_range(t.text) && !at_declaration(p);
697 case Token::Kind::PUNCT:
698 return punct("(") || punct("-") || punct("!");
699 case Token::Kind::END:
700 return false;
701 default:
702 return true;
703 }
704 }
706 const Stmt* named_type(const std::string& n) const {
707 for (int k=types.size(); k--; )
708 if (types[k].name == n)
709 return types[k].def;
710 return nullptr;
711 }
713 static bool is_base_type(const std::string& n) {
714 ReadType r;
715 return read_type(n, r) || (n == "alphabet");
716 }
724 Type type(void) {
725 Type t;
726 if (peek().kind == Token::Kind::IDENT) {
727 const std::string& n = peek().text;
728 if (read_type(n, t.read)) {
729 next();
730 return t;
731 }
732 if (n == "alphabet") {
733 next();
734 alphabet(t);
735 return t;
736 }
737 if (const Stmt* d = named_type(n)) {
738 next();
739 Type u = d->type.use(d);
740 u.name = d->name;
741 return u;
742 }
743 }
744 if (!punct("..") && !punct("..<")) {
745 std::unique_ptr<Expr> lo = expr();
746 if (!punct("..") && !punct("..<")) {
747 if (lo->kind == Expr::Kind::NAME)
748 fail("unknown type '" + lo->s + "'");
749 fail("expected '..' or '..<' after the lower bound of a range, found " + describe(peek()));
750 }
751 t.lo = std::move(lo);
752 }
753 t.exclusive = punct("..<");
754 next();
755 if (at_upper_bound())
756 t.hi = expr();
757 if (t.exclusive && !t.hi)
758 fail("'..<' needs an upper bound");
759 if (!t.lo && !t.hi)
760 fail("a range needs a lower or an upper bound");
761 return t;
762 }
764 void alphabet(Type& t) {
765 t.read = ReadType::SYMBOL;
766 t.alphabet = string("an alphabet");
767 for (;;) {
768 if (option("blank")) {
769 t.blank = string("blank symbols");
770 } else if (option("strip")) {
771 t.strip = string("symbols to strip");
772 } else if (option("base")) {
773 bool neg = punct("-");
774 if (neg)
775 next();
776 if (peek().kind != Token::Kind::INT)
777 fail("expected an integer, found " + describe(peek()));
778 t.base = neg ? -next().i : next().i;
779 } else {
780 break;
781 }
782 }
783 }
785 static bool numeric(const Type& t) {
786 return (t.read == ReadType::INT) || (t.read == ReadType::FLOAT) || (t.read == ReadType::NUM);
787 }
789 void offset(Stmt& s) {
790 if (!option("offset"))
791 return;
792 if (!numeric(s.type))
793 fail("'offset' needs numbers");
794 s.offset = expr();
795 }
797 void declaration(Stmt& s) {
798 s.name = new_name("a name");
799 while (punct("[")) {
800 next();
801 s.dims.push(expr());
802 expect_punct("]");
803 }
804 expect_punct(":");
805 s.type = type();
806 if ((s.type.read == ReadType::REST) && !s.dims.empty())
807 fail("'rest' values cannot be arrays");
808 if ((s.type.read == ReadType::SYMBOL) && (s.dims.size() != 2))
809 fail("an alphabet type needs a two-dimensional array");
810 if (option("layout")) {
811 if ((s.dims.size() != 2) || !numeric(s.type))
812 fail("'layout' needs a two-dimensional array of numbers");
813 s.expr = expr();
814 }
815 offset(s);
816 }
818 void list(Stmt& s, const std::string&) {
819 s.name = new_name("a name");
820 expect_punct(":");
821 s.type = type();
822 if ((s.type.read == ReadType::REST) || (s.type.read == ReadType::SYMBOL))
823 fail("a list cannot be of 'rest' or of an alphabet type");
824 expect_keyword("until");
825 if (accept("eol"))
826 s.until_eol = true;
827 else
828 s.sentinel = expr();
829 offset(s);
830 }
832 void type_def(Stmt& s, const std::string&) {
833 s.name = defined("a type name");
834 if (is_base_type(s.name))
835 fail("'" + s.name + "' is a base type");
836 if (named_type(s.name) != nullptr)
837 fail("the type '" + s.name + "' is already defined");
838 expect_punct("=");
839 s.type = type();
840 TypeName t;
841 t.name = s.name;
842 t.def = &s;
843 types.push(t);
844 types_all.push(t);
845 }
847 void line_pattern(Stmt& s, const std::string&) {
848 s.pattern = pattern();
849 }
851 void skip(Stmt& s, const std::string&) {
852 if (accept("line")) {
853 s.expr = integer(1);
854 } else {
855 s.expr = expr();
856 expect_keyword("lines");
857 }
858 }
860 void index(Stmt& s, const std::string&) {
861 s.expr = expr();
862 }
864 void until(Stmt& s) {
865 s.has_until = true;
866 s.words.push(string("a terminating token"));
867 while (peek().kind == Token::Kind::STRING)
868 s.words.push(next().text);
869 if (accept("store"))
870 s.store = new_name("a name");
871 }
873 void repeat(Stmt& s, const std::string&) {
874 s.id = repeats++;
875 if (accept("until")) {
876 if (accept("eof"))
877 s.until_eof = true;
878 else
879 until(s);
880 } else {
881 s.expr = expr();
882 }
883 if (accept("as"))
884 s.list = new_name("a name for the records");
885 repeat_start = true;
886 s.body = block();
887 repeat_start = false;
888 if (!s.body.empty() && (s.body[0]->kind == Stmt::Kind::EACH))
889 s.each = s.body[0]->name;
890 }
892 void each(Stmt& s, const std::string&) {
893 if (!each_ok)
894 fail("'each' must be the first statement of a repeat, and comes at most once");
895 s.name = new_name("a name for each record");
896 }
898 void instances(Stmt& s, const std::string&) {
899 if (depth > 0)
900 fail("'instances' must be at the top level of the spec");
901 s.body = block();
902 }
904 void sections(Stmt& s, const std::string&) {
905 for (;;) {
906 if (accept("until")) {
907 until(s);
908 } else if (accept("skip")) {
909 expect_keyword("other");
910 s.skip_other = true;
911 } else {
912 break;
913 }
914 }
915 expect_punct("{");
916 while (!punct("}")) {
917 if (peek().kind == Token::Kind::END)
918 fail("missing '}'");
919 Arm a;
920 a.pattern = pattern();
921 a.optional = accept("optional");
922 a.last = accept("last");
923 if (punct("{"))
924 a.body = block();
925 s.arms.push(std::move(a));
926 }
927 next();
928 }
930 void conditional(Stmt& s, const std::string&) {
931 s.expr = expr();
932 s.body = block();
933 if (accept("else")) {
934 if (keyword("if")) {
935 // A chain of else if nests like blocks
936 enter(depth, "blocks");
937 s.orelse.push(statement());
938 depth--;
939 } else {
940 s.orelse = block();
941 }
942 }
943 }
945 void let(Stmt& s, const std::string&) {
946 s.name = defined("a name");
947 expect_punct("=");
948 s.expr = expr();
949 }
951 void check(Stmt& s, const std::string&) {
952 s.expr = expr();
953 if (peek().kind == Token::Kind::STRING)
954 s.message = next().text;
955 }
956 /*
957 * Expressions, by precedence climbing
958 */
959 std::unique_ptr<Expr> expr(void) {
960 return binary(0);
961 }
964 static int binary_op(const Token& t, Expr::Op& op) {
965 static const struct {
966 const char* text; Expr::Op op; int precedence;
967 } ops[] = {
968 {"||", Expr::Op::OR, 1}, {"&&", Expr::Op::AND, 2},
969 {"==", Expr::Op::EQ, 3}, {"!=", Expr::Op::NE, 3},
970 {"<", Expr::Op::LT, 4}, {">", Expr::Op::GT, 4},
971 {"<=", Expr::Op::LE, 4}, {">=", Expr::Op::GE, 4},
972 {"+", Expr::Op::ADD, 5}, {"-", Expr::Op::SUB, 5},
973 {"*", Expr::Op::MUL, 6}, {"/", Expr::Op::DIV, 6}, {"%", Expr::Op::MOD, 6}
974 };
975 if (t.kind == Token::Kind::PUNCT)
976 for (const auto& o : ops)
977 if (t.text == o.text) {
978 op = o.op;
979 return o.precedence;
980 }
981 return -1;
982 }
984 std::unique_ptr<Expr> binary(int min) {
985 std::unique_ptr<Expr> lhs = unary();
986 // Each operator adds a level above lhs
987 int levels = 0;
988 for (;;) {
989 Expr::Op op;
990 int prec = binary_op(peek(), op);
991 if ((prec < 0) || (prec < min))
992 break;
993 enter(nesting, "expressions");
994 levels++;
995 std::unique_ptr<Expr> e(new Expr(Expr::Kind::BINARY));
996 e->op = op;
997 e->s = next().text;
998 e->args.push(std::move(lhs));
999 e->args.push(binary(prec+1));
1000 lhs = std::move(e);
1001 }
1002 nesting -= levels;
1003 return lhs;
1004 }
1005 std::unique_ptr<Expr> unary(void) {
1006 enter(nesting, "expressions");
1007 std::unique_ptr<Expr> e;
1008 if (punct("-") || punct("!")) {
1009 e.reset(new Expr(Expr::Kind::UNARY));
1010 e->op = punct("-") ? Expr::Op::NEG : Expr::Op::NOT;
1011 e->s = next().text;
1012 e->args.push(unary());
1013 } else {
1014 e = power();
1015 }
1016 nesting--;
1017 return e;
1018 }
1021 std::unique_ptr<Expr> power(void) {
1022 std::unique_ptr<Expr> e = postfix();
1023 if (!punct("^"))
1024 return e;
1025 std::unique_ptr<Expr> x(new Expr(Expr::Kind::BINARY));
1026 x->op = Expr::Op::POW;
1027 x->s = next().text;
1028 x->args.push(std::move(e));
1029 x->args.push(unary());
1030 return x;
1031 }
1033 std::unique_ptr<Expr> postfix(void) {
1034 std::unique_ptr<Expr> e = primary();
1035 // Each index or field adds a level above e
1036 int levels = 0;
1037 while (punct("[") || punct(".")) {
1038 bool field = punct(".");
1039 next();
1040 enter(nesting, "expressions");
1041 levels++;
1042 std::unique_ptr<Expr> x(new Expr(field ? Expr::Kind::FIELD : Expr::Kind::INDEX));
1043 x->args.push(std::move(e));
1044 if (field) {
1045 x->s = ident("a field name");
1046 } else {
1047 x->args.push(expr());
1048 expect_punct("]");
1049 }
1050 e = std::move(x);
1051 }
1052 nesting -= levels;
1053 return e;
1054 }
1055
1058 void check_call(const Expr& e, int line) {
1059 const std::string& f = e.s;
1060 int n = e.args.size();
1061 bool ok;
1062 if (f == "defined")
1063 ok = (n == 1) && (e.args[0]->kind == Expr::Kind::NAME);
1064 else if ((f == "count") || (f == "size"))
1065 ok = (n == 1);
1066 else if ((f == "min") || (f == "max") || (f == "sum") || (f == "distinct"))
1067 ok = (n >= 1);
1068 else if ((f == "all") || (f == "any"))
1069 fail_at(origin, line, "'" + f + "' needs the form " + f + "(x in a: e)");
1070 else
1071 fail_at(origin, line, "unknown function '" + f + "'");
1072 if (!ok)
1073 fail_at(origin, line, "wrong arguments for function '" + f + "'");
1074 }
1076 long long int gecode_constant(const std::string& n, int line) {
1077 static const struct {
1078 const char* name; long long int value;
1079 } constants[] = {
1080 {"gecode.int_max", Gecode::Int::Limits::max},
1081 {"gecode.int_min", Gecode::Int::Limits::min}
1082 };
1083 std::string known;
1084 for (const auto& c : constants) {
1085 if (n == c.name)
1086 return c.value;
1087 known += (known.empty() ? "" : ", ") + std::string(c.name);
1088 }
1089 fail_at(origin, line, "unknown Gecode constant '" + n + "' (known: " + known + ")");
1090 }
1092 bool at_comprehension(const std::string& f) const {
1093 if ((f != "all") && (f != "any") && (f != "sum") && (f != "count"))
1094 return false;
1095 if ((peek().kind != Token::Kind::IDENT) || (p+1 >= toks.size()))
1096 return false;
1097 const Token& t = toks[p+1];
1098 return (t.kind == Token::Kind::IDENT) && (t.text == "in");
1099 }
1101 std::unique_ptr<Expr> comprehension(const std::string& f) {
1102 std::unique_ptr<Expr> e(new Expr(Expr::Kind::COMPREHENSION));
1103 e->s = f;
1104 BoundName b;
1105 b.line = peek().line;
1106 b.name = new_name("a name");
1107 if (b.name == "_")
1108 fail("'_' cannot be bound");
1109 for (const std::string& o : bound)
1110 if (o == b.name)
1111 fail("'" + b.name + "' is already bound by an enclosing comprehension");
1112 e->var = b.name;
1113 expect_keyword("in");
1114 // The name is bound in the body only
1115 e->args.push(expr());
1116 expect_punct(":");
1117 bound.push(b.name);
1118 e->args.push(expr());
1119 bound.pop();
1120 expect_punct(")");
1121 bound_all.push(b);
1122 return e;
1123 }
1124 std::unique_ptr<Expr> primary(void) {
1125 const Token& t = peek();
1126 if (t.kind == Token::Kind::INT)
1127 return integer(next().i);
1128 if (t.kind == Token::Kind::FLOAT) {
1129 std::unique_ptr<Expr> e(new Expr(Expr::Kind::FLOAT));
1130 e->f = next().f;
1131 return e;
1132 }
1133 if (t.kind == Token::Kind::STRING) {
1134 std::unique_ptr<Expr> e(new Expr(Expr::Kind::STR));
1135 e->s = next().text;
1136 return e;
1137 }
1138 if (punct("(")) {
1139 next();
1140 std::unique_ptr<Expr> e = expr();
1141 expect_punct(")");
1142 return e;
1143 }
1144 if ((t.kind == Token::Kind::IDENT) && is_gecode_name(t.text)) {
1145 int line = t.line;
1146 return integer(gecode_constant(next().text, line));
1147 }
1148 if (t.kind == Token::Kind::IDENT) {
1149 int line = t.line;
1150 std::string n = next().text;
1151 if (punct("(")) {
1152 next();
1153 if (at_comprehension(n))
1154 return comprehension(n);
1155 std::unique_ptr<Expr> e(new Expr(Expr::Kind::CALL));
1156 e->s = n;
1157 if (!punct(")")) {
1158 e->args.push(expr());
1159 while (punct(",")) {
1160 next();
1161 e->args.push(expr());
1162 }
1163 }
1164 expect_punct(")");
1165 check_call(*e, line);
1166 return e;
1167 }
1168 std::unique_ptr<Expr> e(new Expr(Expr::Kind::NAME));
1169 e->s = n;
1170 return e;
1171 }
1172 fail("expected an expression, found " + describe(t));
1173 }
1174 };
1175
1177 ValueType value_type(ReadType t) {
1178 switch (t) {
1179 case ReadType::FLOAT: return ValueType::FLOAT;
1180 case ReadType::WORD: case ReadType::REST: return ValueType::STRING;
1181 default: return ValueType::INT;
1182 }
1183 }
1184
1186 void declare(Seq<Decl>& out, const std::string& n, ValueType t, int d) {
1187 if (n.empty() || (n == "_"))
1188 return;
1189 for (const Decl& o : out)
1190 if (o.name == n)
1191 return;
1192 Decl x;
1193 x.name = n; x.type = t; x.depth = d;
1194 out.push(x);
1195 }
1196
1198 void declare(Seq<Decl>& out, const Pattern& p) {
1199 for (const Pattern::Item& it : p.items)
1200 if (it.kind == Pattern::Item::Kind::CAP)
1201 declare(out, it.text, value_type(it.type.read), 0);
1202 }
1203
1204 }
1205
1206 void
1207 declared(const Block& b, Seq<Decl>& out) {
1208 for (const std::unique_ptr<Stmt>& s : b) {
1209 switch (s->kind) {
1210 case Stmt::Kind::READ:
1211 declare(out, s->name, value_type(s->type.read), s->dims.size());
1212 break;
1213 case Stmt::Kind::LIST:
1214 declare(out, s->name, value_type(s->type.read), 1);
1215 break;
1217 // Usually a single value; the type is only known when running
1218 declare(out, s->name, ValueType::INT, 0);
1219 break;
1221 declare(out, s->pattern);
1222 break;
1223 case Stmt::Kind::REPEAT: {
1224 // Values of a nested repeat are one level deeper
1225 declare(out, s->store, ValueType::STRING, 0);
1226 declare(out, record_starts(s->id), ValueType::INT, 1);
1227 Seq<Decl> inner;
1228 declared(s->body, inner);
1229 for (const Decl& d : inner)
1230 declare(out, d.name, d.type, d.depth+1);
1231 break;
1232 }
1234 declare(out, s->store, ValueType::STRING, 0);
1235 for (const Arm& a : s->arms) {
1236 declare(out, a.pattern);
1237 declared(a.body, out);
1238 }
1239 break;
1240 case Stmt::Kind::IF:
1241 declared(s->body, out);
1242 declared(s->orelse, out);
1243 break;
1245 declared(s->body, out);
1246 break;
1247 default:
1248 break;
1249 }
1250 }
1251 }
1252
1253 SpecImpl::SpecImpl(const std::string& t, const std::string& o)
1254 : origin(o) {
1255 Parser p(t, o);
1256 p.parse(*this);
1257 }
1258
1259 /*
1260 * Specs
1261 *
1262 */
1263
1265 : impl(std::make_shared<SpecImpl>("", "<empty>")) {}
1266
1267 Spec
1268 Spec::parse(const std::string& text, const std::string& origin) {
1269 Spec s;
1270 s.impl = std::make_shared<SpecImpl>(text, origin);
1271 return s;
1272 }
1273
1274 Spec
1275 Spec::load(const std::string& path) {
1276 return parse(read_file(path), path);
1277 }
1278
1279 std::string
1280 Spec::name(void) const {
1281 return impl->name;
1282 }
1283
1284 Data
1285 Spec::read(const std::string& path, const Params& p) const {
1286 return impl->read(read_file(path), path, p, false);
1287 }
1288
1289 Data
1290 Spec::read_text(const std::string& text, const std::string& origin, const Params& p) const {
1291 return impl->read(text, origin, p, false);
1292 }
1293
1294 Data
1295 Spec::catalog(const std::string& path, const Params& p) const {
1296 return impl->read(read_file(path), path, p, true);
1297 }
1298
1299 Data
1300 Spec::catalog_text(const std::string& text, const std::string& origin, const Params& p) const {
1301 return impl->read(text, origin, p, true);
1302 }
1303
1304}}
1305
1306// STATISTICS: instance-any
Arm of a sections statement.
Definition impl.hpp:606
Named values read from an instance.
Definition instance.hh:406
A name that a block may define, with the type and depth of its values.
Definition impl.hpp:683
Exception for errors in specs and instance files
Definition instance.hh:337
Values for the param statements of a spec.
Definition instance.hh:364
Growable array on the Gecode heap.
Definition impl.hpp:118
int size(void) const
Return number of elements.
Definition impl.hpp:168
Implementation of Spec.
Definition impl.hpp:709
SpecImpl(const std::string &text, const std::string &origin)
Parse text from origin.
Definition spec.cpp:1253
std::string origin
Where the spec comes from.
Definition impl.hpp:712
Reader spec for a textual instance format.
Definition instance.hh:470
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
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 read(const std::string &path, const Params &p=Params()) const
Read instance file path.
Definition spec.cpp:1285
std::string name(void) const
Return the format name declared by the spec (may be empty).
Definition spec.cpp:1280
Data catalog(const std::string &path, const Params &p=Params()) const
List the instances in file path.
Definition spec.cpp:1295
Spec(void)
The empty spec (reads only empty input).
Definition spec.cpp:1264
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
static std::string str(bool b)
Map bool to string.
Definition int.hpp:278
GECODE_FLATZINC_EXPORT FlatZincSpace * parse(const std::string &fileName, Printer &p, std::ostream &err=std::cerr, FlatZincSpace *fzs=nullptr, Rnd &rnd=defrnd)
Parse FlatZinc file fileName into fzs and return it.
bool neg(const View &x)
Test whether x is negative.
Definition mult.hpp:47
void check(const FloatVal &n, const char *l)
Check whether float n is a valid number, otherwise throw out of limits exception with information l.
Definition limits.hpp:44
Reading instance files described by reader specs.
void resolve(Block &b, const std::string &origin)
Resolve the names in the expressions of b, the body of a spec from origin.
Definition resolve.cpp:619
ValueType
Type of the values in a data entry.
Definition instance.hh:349
bool is_digit(char c)
Test whether c is a digit.
Definition impl.hpp:56
std::string record_starts(int id)
Return the name of the record starts of the repeat numbered id.
Definition impl.hpp:511
bool parse_float(const std::string &t, double &v)
Parse decimal float t into v, and return whether it is one.
Definition spec.cpp:72
bool sub(long long int x, long long int y, long long int &r)
Store x - y in r unless it overflows.
Definition eval.cpp:62
std::string read_file(const std::string &path)
Read file path into a string.
Definition spec.cpp:49
void declared(const Block &b, Seq< Decl > &out)
Add the names that block b may define to out.
Definition spec.cpp:1207
bool is_space(char c)
Test whether c is white space.
Definition impl.hpp:68
ReadType
What a declaration or a capture reads.
Definition impl.hpp:520
bool is_alnum(char c)
Test whether c can occur in a name.
Definition impl.hpp:64
bool parse_int(const std::string &t, long long int &v)
Parse decimal integer t into v, and return whether it is one.
Definition spec.cpp:62
size_t number_end(const std::string &s, size_t p, bool sign, bool real)
Return where the number starting at position p of s ends.
Definition impl.hpp:90
void fail_at(const std::string &origin, int line, const std::string &m)
Throw an error with message m for line line of the spec from origin.
Definition spec.cpp:84
bool is_blank(char c)
Test whether c is white space within a line.
Definition impl.hpp:72
Seq< std::unique_ptr< Stmt > > Block
Sequence of statements.
Definition impl.hpp:603
const int min
Smallest allowed integer value.
Definition int.hh:123
const int max
Largest allowed integer value.
Definition int.hh:121
Gecode toplevel namespace
void lex(Home home, const IntVarArgs &x, IntRelType r, const IntVarArgs &y, IntPropLevel ipl=IPL_DEF)
Post lexical order between x and y.
Definition aliases.hpp:132
IntVar expr(Home home, const LinIntExpr &e, const IntPropLevels &ipls=IntPropLevels::def)
Post linear expression and return its value.
Definition int-expr.cpp:988
void path(Home home, const IntVarArgs &x, IntVar s, IntVar e, IntPropLevel ipl=IPL_DEF)
Post propagator such that x forms a Hamiltonian path.
Definition circuit.cpp:169
void unary(Home home, const IntVarArgs &s, const IntArgs &p, IntPropLevel ipl=IPL_DEF)
Post propagators for scheduling tasks on unary resources.
Definition unary.cpp:44
Gecode::FloatVal b(9, 12)
Gecode::FloatVal a(-8, 5)
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 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 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 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 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 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;})
Gecode::IntSet d(v, 7)
const int r[4][2]
Definition dom.cpp:152
Constraint precedence("Precede", Constraint::Kind::PRECEDE, 3)