ltlcross.cc 37.4 KB
Newer Older
1
// -*- coding: utf-8 -*-
2
3
// Copyright (C) 2012, 2013 Laboratoire de Recherche et Développement
// de l'Epita (LRDE).
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//
// This file is part of Spot, a model checking library.
//
// Spot is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// Spot is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
// License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.


#include "common_sys.hh"

#include <string>
#include <iostream>
#include <sstream>
26
#include <fstream>
27
28
29
#include <cstdlib>
#include <cstdio>
#include <argp.h>
30
31
32
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
33
#include "error.h"
34
#include "gethrxtime.h"
35
#include "argmatch.h"
36
37
38
39
40

#include "common_setup.hh"
#include "common_cout.hh"
#include "common_finput.hh"
#include "neverparse/public.hh"
41
#include "dstarparse/public.hh"
42
43
44
45
#include "ltlast/unop.hh"
#include "ltlvisit/tostring.hh"
#include "ltlvisit/apcollect.hh"
#include "ltlvisit/lbt.hh"
46
#include "ltlvisit/relabel.hh"
47
#include "tgbaalgos/lbtt.hh"
48
49
50
51
52
#include "tgba/tgbaproduct.hh"
#include "tgbaalgos/gtec/gtec.hh"
#include "tgbaalgos/randomgraph.hh"
#include "tgbaalgos/scc.hh"
#include "tgbaalgos/dotty.hh"
53
#include "tgbaalgos/isweakscc.hh"
54
55
#include "tgbaalgos/reducerun.hh"
#include "tgbaalgos/word.hh"
56
#include "tgbaalgos/dbacomp.hh"
57
#include "misc/formater.hh"
58
59
#include "tgbaalgos/stats.hh"
#include "tgbaalgos/isdet.hh"
60
#include "misc/escape.hh"
61
#include "misc/hash.hh"
62
#include "misc/random.hh"
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
63
#include "misc/tmpfile.hh"
64

65
66
67
68
69
70
71
72
// Disable handling of timeout on systems that miss kill() or alarm().
// For instance MinGW.
#if HAVE_KILL && HAVE_ALARM
# define ENABLE_TIMEOUT 1
#else
# define ENABLE_TIMEOUT 0
#endif

73
74
const char argp_program_doc[] ="\
Call several LTL/PSL translators and cross-compare their output to detect \
75
bugs, or to gather statistics.  The list of formulas to use should be \
76
supplied on standard input, or using the -f or -F options.\v\
77
78
79
80
Exit status:\n\
  0  everything went fine (timeouts are OK too)\n\
  1  some translator failed to output something we understand, or failed\n\
     sanity checks (statistics were output nonetheless)\n\
81
  2  ltlcross aborted on error\n\
82
";
83
84
85
86


#define OPT_STATES 1
#define OPT_DENSITY 2
87
88
#define OPT_JSON 3
#define OPT_CSV 4
89
#define OPT_DUPS 5
90
#define OPT_NOCHECKS 6
91
#define OPT_STOP_ERR 7
92
#define OPT_SEED 8
93
#define OPT_PRODUCTS 9
94
#define OPT_COLOR 10
95
#define OPT_NOCOMP 11
96
97
98
99

static const argp_option options[] =
  {
    /**************************************************/
100
    { 0, 0, 0, 0, "Specifying translators to call:", 2 },
101
    { "translator", 't', "COMMANDFMT", 0,
102
      "register one translator to call", 0 },
103
    { "timeout", 'T', "NUMBER", 0, "kill translators after NUMBER seconds", 0 },
104
105
106
107
    /**************************************************/
    { 0, 0, 0, 0,
      "COMMANDFMT should specify input and output arguments using the "
      "following character sequences:", 3 },
108
109
110
111
112
    { "%f,%s,%l,%w", 0, 0, OPTION_DOC | OPTION_NO_USAGE,
      "the formula as a (quoted) string in Spot, Spin, LBT, or Wring's syntax",
      0 },
    { "%F,%S,%L,%W", 0, 0, OPTION_DOC | OPTION_NO_USAGE,
      "the formula as a file in Spot, Spin, LBT, or Wring's syntax", 0 },
113
114
115
    { "%N,%T,%D", 0, 0, OPTION_DOC | OPTION_NO_USAGE,
      "the output automaton as a Never claim, in LBTT's or in LTL2DSTAR's "
      "format", 0 },
116
117
118
119
    { 0, 0, 0, 0,
      "If either %l, %L, or %T are used, any input formula that does "
      "not use LBT-style atomic propositions (i.e. p0, p1, ...) will be "
      "relabeled automatically.", 0 },
120
    /**************************************************/
121
    { 0, 0, 0, 0, "ltlcross behavior:", 4 },
122
123
124
125
126
    { "allow-dups", OPT_DUPS, 0, 0,
      "translate duplicate formulas in input", 0 },
    { "no-checks", OPT_NOCHECKS, 0, 0,
      "do not perform any sanity checks (negated formulas "
      "will not be translated)", 0 },
127
128
    { "no-complement", OPT_NOCOMP, 0, 0,
      "do not complement deterministic automata to perform extra checks", 0 },
129
130
131
    { "stop-on-error", OPT_STOP_ERR, 0, 0,
      "stop on first execution error or failure to pass"
      " sanity checks (timeouts are OK)", 0 },
132
133
    /**************************************************/
    { 0, 0, 0, 0, "State-space generation:", 5 },
134
135
136
137
138
    { "states", OPT_STATES, "INT", 0,
      "number of the states in the state-spaces (200 by default)", 0 },
    { "density", OPT_DENSITY, "FLOAT", 0,
      "probability, between 0.0 and 1.0, to add a transition between "
      "two states (0.1 by default)", 0 },
139
140
    { "seed", OPT_SEED, "INT", 0,
      "seed for the random number generator (0 by default)", 0 },
141
142
143
    { "products", OPT_PRODUCTS, "INT", 0,
      "number of product to perform (1 by default), statistics will be "
      "averaged", 0 },
144
    /**************************************************/
145
    { 0, 0, 0, 0, "Statistics output:", 6 },
146
147
148
149
150
    { "json", OPT_JSON, "FILENAME", OPTION_ARG_OPTIONAL,
      "output statistics as JSON in FILENAME or on standard output", 0 },
    { "csv", OPT_CSV, "FILENAME", OPTION_ARG_OPTIONAL,
      "output statistics as CSV in FILENAME or on standard output", 0 },
    /**************************************************/
151
    { 0, 0, 0, 0, "Miscellaneous options:", -1 },
152
153
154
155
    { "color", OPT_COLOR, "WHEN", OPTION_ARG_OPTIONAL,
      "colorize output; WHEN can be 'never', 'always' (the default if "
      "--color is used without argument), or "
      "'auto' (the default if --color is not used)", 0 },
156
157
158
159
160
161
    { 0, 0, 0, 0, 0, 0 }
  };

const struct argp_child children[] =
  {
    { &finput_argp, 0, 0, 1 },
162
    { &misc_argp, 0, 0, -1 },
163
164
165
    { 0, 0, 0, 0 }
  };

166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185

enum color_type { color_never, color_always, color_if_tty };

static char const *const color_args[] =
{
  "always", "yes", "force",
  "never", "no", "none",
  "auto", "tty", "if-tty", 0
};
static color_type const color_types[] =
{
  color_always, color_always, color_always,
  color_never, color_never, color_never,
  color_if_tty, color_if_tty, color_if_tty
};
ARGMATCH_VERIFY(color_args, color_types);

color_type color_opt = color_if_tty;
const char* bright_red = "\033[01;31m";
const char* bright_white = "\033[01;37m";
186
const char* bright_yellow = "\033[01;33m";
187
188
const char* reset_color = "\033[m";

189
190
unsigned states = 200;
float density = 0.1;
191
unsigned timeout = 0;
192
193
194
const char* json_output = 0;
const char* csv_output = 0;
bool want_stats = false;
195
bool allow_dups = false;
196
bool no_checks = false;
197
bool no_complement = false;
198
bool stop_on_error = false;
199
int seed = 0;
200
unsigned products = 1;
201

202
std::vector<char*> translators;
203
204
205
206
207
208
bool global_error_flag = false;

static std::ostream&
global_error()
{
  global_error_flag = true;
209
210
  if (color_opt)
    std::cerr << bright_red;
211
212
  return std::cerr;
}
213

214
215
216
217
218
219
220
221
222
static std::ostream&
example()
{
  if (color_opt)
    std::cerr << bright_yellow;
  return std::cerr;
}


223
224
225
226
227
228
229
230
static void
end_error()
{
  if (color_opt)
    std::cerr << reset_color;
}


231
232
struct statistics
{
233
234
  statistics()
    : ok(false),
235
236
237
238
239
240
241
242
243
244
245
246
247
248
      states(0),
      transitions(0),
      acc(0),
      scc(0),
      nonacc_scc(0),
      terminal_scc(0),
      weak_scc(0),
      strong_scc(0),
      nondetstates(0),
      nondeterministic(false),
      terminal_aut(false),
      weak_aut(false),
      strong_aut(false),
      time(0),
249
250
251
252
253
254
      product_states(0),
      product_transitions(0),
      product_scc(0)
  {
  }

255
256
257
258
259
260
  bool ok;
  unsigned states;
  unsigned edges;
  unsigned transitions;
  unsigned acc;
  unsigned scc;
261
262
263
264
  unsigned nonacc_scc;
  unsigned terminal_scc;
  unsigned weak_scc;
  unsigned strong_scc;
265
266
  unsigned nondetstates;
  bool nondeterministic;
267
268
269
  bool terminal_aut;
  bool weak_aut;
  bool strong_aut;
270
  double time;
271
272
273
  double product_states;
  double product_transitions;
  double product_scc;
274
275
276
277

  static void
  fields(std::ostream& os)
  {
278
279
280
281
282
    os << (" \"states\","
	   " \"edges\","
	   " \"transitions\","
	   " \"acc\","
	   " \"scc\","
283
284
285
286
287
288
289
290
291
	   " \"nonacc_scc\","
	   " \"terminal_scc\","
	   " \"weak_scc\","
	   " \"strong_scc\","
	   " \"nondet_states\","
	   " \"nondet_aut\","
	   " \"terminal_aut\","
	   " \"weak_aut\","
	   " \"strong_aut\","
292
293
294
295
	   " \"time\","
	   " \"product_states\","
	   " \"product_transitions\","
	   " \"product_scc\"");
296
297
298
299
300
301
302
303
304
305
  }

  void
  to_csv(std::ostream& os)
  {
    os << states << ", "
       << edges << ", "
       << transitions << ", "
       << acc << ", "
       << scc << ", "
306
307
308
309
       << nonacc_scc << ", "
       << terminal_scc << ", "
       << weak_scc << ", "
       << strong_scc << ", "
310
311
       << nondetstates << ", "
       << nondeterministic << ", "
312
313
314
       << terminal_aut << ", "
       << weak_aut << ", "
       << strong_aut << ", "
315
       << time << ", "
316
317
318
319
320
321
322
323
324
325
326
       << product_states << ", "
       << product_transitions << ", "
       << product_scc;
  }
};

typedef std::vector<statistics> statistics_formula;
typedef std::vector<statistics_formula> statistics_vector;
statistics_vector vstats;
std::vector<std::string> formulas;

327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
static int
to_int(const char* s)
{
  char* endptr;
  int res = strtol(s, &endptr, 10);
  if (*endptr)
    error(2, 0, "failed to parse '%s' as an integer.", s);
  return res;
}

static int
to_pos_int(const char* s)
{
  int res = to_int(s);
  if (res < 0)
    error(2, 0, "%d is not positive", res);
  return res;
}

static float
to_float(const char* s)
{
  char* endptr;
  // Do not use strtof(), it does not exist on Solaris 9.
  float res = strtod(s, &endptr);
  if (*endptr)
    error(2, 0, "failed to parse '%s' as a float.", s);
  return res;
}

static float
to_probability(const char* s)
{
  float res = to_float(s);
  if (res < 0.0 || res > 1.0)
    error(2, 0, "%f is not between 0 and 1.", res);
  return res;
}


static int
parse_opt(int key, char* arg, struct argp_state*)
{
  // This switch is alphabetically-ordered.
  switch (key)
    {
    case 't':
    case ARGP_KEY_ARG:
      translators.push_back(arg);
      break;
377
378
    case 'T':
      timeout = to_pos_int(arg);
379
380
381
382
#if !ENABLE_TIMEOUT
      std::cerr << "warning: setting a timeout is not supported "
		<< "on your platform" << std::endl;
#endif
383
      break;
384
385
386
387
388
389
390
391
    case OPT_COLOR:
      {
	if (arg)
	  color_opt = XARGMATCH("--color", arg, color_args, color_types);
	else
	  color_opt = color_always;
	break;
      }
392
393
394
395
    case OPT_CSV:
      want_stats = true;
      csv_output = arg ? arg : "-";
      break;
396
397
398
    case OPT_DENSITY:
      density = to_probability(arg);
      break;
399
400
401
    case OPT_DUPS:
      allow_dups = true;
      break;
402
403
404
405
    case OPT_JSON:
      want_stats = true;
      json_output = arg ? arg : "-";
      break;
406
407
408
    case OPT_PRODUCTS:
      products = to_pos_int(arg);
      break;
409
410
    case OPT_NOCHECKS:
      no_checks = true;
411
412
413
414
      no_complement = true;
      break;
    case OPT_NOCOMP:
      no_complement = true;
415
      break;
416
417
418
    case OPT_SEED:
      seed = to_pos_int(arg);
      break;
419
420
421
    case OPT_STATES:
      states = to_pos_int(arg);
      break;
422
423
424
    case OPT_STOP_ERR:
      stop_on_error = true;
      break;
425
426
427
428
429
430
    default:
      return ARGP_ERR_UNKNOWN;
    }
  return 0;
}

431
static volatile bool timed_out = false;
432
unsigned timeout_count = 0;
433

434
435
#if ENABLE_TIMEOUT
static volatile int alarm_on = 0;
436
437
438
439
440
441
442
443
444
445
446
447
448
449
static int child_pid = -1;

static void
sig_handler(int sig)
{
  if (child_pid == 0)
    error(2, 0, "child received signal %d before starting", sig);

  if (sig == SIGALRM && alarm_on)
    {
      timed_out = true;
      if (--alarm_on)
	{
	  // Send SIGTERM to children.
450
	  kill(-child_pid, SIGTERM);
451
452
453
454
455
456
457
	  // Try again later if it didn't work.  (alarm() will be reset
	  // if it did work and the call to wait() returns)
	  alarm(2);
	}
      else
	{
	  // After a few gentle tries, really kill that child.
458
	  kill(-child_pid, SIGKILL);
459
460
461
462
463
	}
    }
  else
    {
      // forward signal
464
      kill(-child_pid, sig);
465
      // cleanup files
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
466
      spot::cleanup_tmpfiles();
467
468
      // and die verbosely
      error(2, 0, "received signal %d", sig);
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
    }
}

static void
setup_sig_handler()
{
  struct sigaction sa;
  sa.sa_handler = sig_handler;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = SA_RESTART; // So that wait() doesn't get aborted by SIGALRM.
  sigaction(SIGALRM, &sa, 0);
  // Catch termination signals, so we can kill the subprocess.
  sigaction(SIGHUP, &sa, 0);
  sigaction(SIGINT, &sa, 0);
  sigaction(SIGQUIT, &sa, 0);
  sigaction(SIGTERM, &sa, 0);
}

static int
exec_with_timeout(const char* cmd)
{
  int status;

  timed_out = false;

  child_pid = fork();
  if (child_pid == -1)
    error(2, errno, "failed to fork()");

  if (child_pid == 0)
    {
      setpgid(0, 0);
      execlp("sh", "sh", "-c", cmd, (char*)0);
      error(2, errno, "failed to run 'sh'");
503
504
      // never reached
      return -1;
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
    }
  else
    {
      alarm(timeout);
      // Upon SIGALRM, the child will receive up to 3
      // signals: SIGTERM, SIGTERM, SIGKILL.
      alarm_on = 3;
      int w = waitpid(child_pid, &status, 0);
      alarm_on = 0;

      if (w == -1)
	error(2, errno, "error during wait()");

      alarm(0);
    }
  return status;
}
522
523
524
525
#else // !ENABLE_TIMEOUT
#define exec_with_timeout(cmd) system(cmd)
#define setup_sig_handler() while (0);
#endif // !ENABLE_TIMEOUT
526

527
namespace
528
{
529
530
531
  struct quoted_string: public spot::printable_value<std::string>
  {
    using spot::printable_value<std::string>::operator=;
532

533
534
535
536
537
538
539
540
    void
    print(std::ostream& os, const char* pos) const
    {
      os << '\'';
      this->spot::printable_value<std::string>::print(os, pos);
      os << '\'';
    }
  };
541

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
542
543
  struct printable_result_filename:
    public spot::printable_value<spot::temporary_file*>
544
545
  {
    unsigned translator_num;
546
    enum output_format { None, Spin, Lbtt, Dstar };
547
    mutable output_format format;
548

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
549
550
551
552
553
554
555
556
557
558
    printable_result_filename()
    {
      val_ = 0;
    }

    ~printable_result_filename()
    {
      delete val_;
    }

559
560
561
562
563
    void reset(unsigned n)
    {
      translator_num = n;
      format = None;
    }
564

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
565
566
567
568
569
570
    void cleanup()
    {
      delete val_;
      val_ = 0;
    }

571
572
573
    void
    print(std::ostream& os, const char* pos) const
    {
574
      output_format old_format = format;
575
576
      if (*pos == 'N')
	format = Spin;
577
      else if (*pos == 'T')
578
	format = Lbtt;
579
580
581
582
583
      else if (*pos == 'D')
	format = Dstar;
      else
	assert(!"BUG");

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
584
      if (val_)
585
586
587
588
589
590
591
592
593
594
595
596
597
598
	{
	  // It's OK to use a specified multiple time, but it's not OK
	  // to mix the formats.
	  if (format != old_format)
	    error(2, 0, "you may not mix %%D, %%N, and %%T specifiers: %s",
		  translators[translator_num]);
	}
      else
	{
	  char prefix[30];
	  snprintf(prefix, sizeof prefix, "lcr-o%u-", translator_num);
	  const_cast<printable_result_filename*>(this)->val_
	    = spot::create_tmpfile(prefix);
	}
599
600
601
      os << '\'' << val_ << '\'';
    }
  };
602

603
604
605
  class translator_runner: protected spot::formater
  {
  private:
606
    spot::bdd_dict& dict;
607
608
609
610
    // Round-specific variables
    quoted_string string_ltl_spot;
    quoted_string string_ltl_spin;
    quoted_string string_ltl_lbt;
611
    quoted_string string_ltl_wring;
612
613
614
    quoted_string filename_ltl_spot;
    quoted_string filename_ltl_spin;
    quoted_string filename_ltl_lbt;
615
    quoted_string filename_ltl_wring;
616
617
618
    // Run-specific variables
    printable_result_filename output;
  public:
619
620
    using spot::formater::has;

621
622
    translator_runner(spot::bdd_dict& dict)
      : dict(dict)
623
624
625
626
    {
      declare('f', &string_ltl_spot);
      declare('s', &string_ltl_spin);
      declare('l', &string_ltl_lbt);
627
      declare('w', &string_ltl_wring);
628
629
630
      declare('F', &filename_ltl_spot);
      declare('S', &filename_ltl_spin);
      declare('L', &filename_ltl_lbt);
631
      declare('W', &filename_ltl_wring);
632
      declare('D', &output);
633
634
635
      declare('N', &output);
      declare('T', &output);

636
      std::vector<bool> has(256);
637
638
639
      size_t s = translators.size();
      assert(s);
      for (size_t n = 0; n < s; ++n)
640
641
642
643
644
645
646
647
648
649
	{
	  // Check that each translator uses at least one input and
	  // one output.
	  has.clear();
	  scan(translators[n], has);
	  if (!(has['f'] || has['s'] || has['l'] || has['w']
		|| has['F'] || has['S'] || has['L'] || has['W']))
	    error(2, 0, "no input %%-sequence in '%s'.\n       Use "
		  "one of %%f,%%s,%%l,%%w,%%F,%%S,%%L,%%W to indicate how "
		  "to pass the formula.", translators[n]);
650
651
652
	  if (!(has['D'] || has['N'] || has['T']))
	    error(2, 0, "no output %%-sequence in '%s'.\n      Use one of "
		  "%%D,%%N,%%T to indicate where the automaton is saved.",
653
654
655
656
657
		  translators[n]);

	  // Remember the %-sequences used by all translators.
	  prime(translators[n]);
	}
658

659
660
661
662
    }

    void
    string_to_tmp(std::string& str, unsigned n, std::string& tmpname)
663
    {
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
664
665
666
667
668
      char prefix[30];
      snprintf(prefix, sizeof prefix, "lcr-i%u-", n);
      spot::open_temporary_file* tmpfile = spot::create_open_tmpfile(prefix);
      tmpname = tmpfile->name();
      int fd = tmpfile->fd();
669
670
671
672
      ssize_t s = str.size();
      if (write(fd, str.c_str(), s) != s
	  || write(fd, "\n", 1) != 1)
	error(2, errno, "failed to write into %s", tmpname.c_str());
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
673
      tmpfile->close();
674
675
    }

676
677
    const std::string&
    formula() const
678
679
680
681
682
683
    {
      // Pick the most readable format we have...
      if (!string_ltl_spot.val().empty())
	return string_ltl_spot;
      if (!string_ltl_spin.val().empty())
	return string_ltl_spin;
684
685
      if (!string_ltl_wring.val().empty())
	return string_ltl_wring;
686
687
      if (!string_ltl_lbt.val().empty())
	return string_ltl_lbt;
688
      assert(!"None of the translators need the input formula?");
689
690
691
      return string_ltl_spot;
    }

692
693
    void
    round_formula(const spot::ltl::formula* f, unsigned serial)
694
695
696
697
698
699
700
    {
      if (has('f') || has('F'))
	string_ltl_spot = spot::ltl::to_string(f, true);
      if (has('s') || has('S'))
	string_ltl_spin = spot::ltl::to_spin_string(f, true);
      if (has('l') || has('L'))
	string_ltl_lbt = spot::ltl::to_lbt_string(f);
701
702
      if (has('w') || has('W'))
	string_ltl_wring = spot::ltl::to_wring_string(f);
703
704
705
706
707
708
      if (has('F'))
	string_to_tmp(string_ltl_spot, serial, filename_ltl_spot);
      if (has('S'))
	string_to_tmp(string_ltl_spin, serial, filename_ltl_spin);
      if (has('L'))
	string_to_tmp(string_ltl_lbt, serial, filename_ltl_lbt);
709
710
      if (has('W'))
	string_to_tmp(string_ltl_wring, serial, filename_ltl_wring);
711
712
    }

713
714
    const spot::tgba*
    translate(unsigned int translator_num, char l, statistics_formula* fstats)
715
716
717
718
719
    {
      output.reset(translator_num);

      std::ostringstream command;
      format(command, translators[translator_num]);
720

721
      assert(output.format != printable_result_filename::None);
722

723
724
725
      std::string cmd = command.str();
      std::cerr << "Running [" << l << translator_num << "]: "
		<< cmd << std::endl;
726
      xtime_t before = gethrxtime();
727
      int es = exec_with_timeout(cmd.c_str());
728
      xtime_t after = gethrxtime();
729
730

      const spot::tgba* res = 0;
731
732
      if (timed_out)
	{
733
734
	  // This is not considered to be a global error.
	  std::cerr << "warning: timeout during execution of command\n";
735
	  ++timeout_count;
736
737
738
	}
      else if (WIFSIGNALED(es))
	{
739
740
	  global_error() << "error: execution terminated by signal "
			 << WTERMSIG(es) << ".\n";
741
	  end_error();
742
743
	}
      else if (WIFEXITED(es) && WEXITSTATUS(es) != 0)
744
	{
745
746
	  global_error() << "error: execution returned exit code "
			 << WEXITSTATUS(es) << ".\n";
747
	  end_error();
748
749
750
751
752
753
	}
      else
	{
	  switch (output.format)
	    {
	    case printable_result_filename::Spin:
754
	      {
755
		spot::neverclaim_parse_error_list pel;
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
756
757
		std::string filename = output.val()->name();
		res = spot::neverclaim_parse(filename, pel, &dict);
758
759
		if (!pel.empty())
		  {
760
761
		    std::ostream& err = global_error();
		    err << "error: failed to parse the produced neverclaim.\n";
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
762
		    spot::format_neverclaim_parse_errors(err, filename, pel);
763
		    end_error();
764
765
766
767
		    delete res;
		    res = 0;
		  }
		break;
768
	      }
769
	    case printable_result_filename::Lbtt:
770
	      {
771
		std::string error;
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
772
		std::ifstream f(output.val()->name());
773
774
		if (!f)
		  {
775
776
		    global_error() << "Cannot open " << output.val()
				   << std::endl;
777
		    end_error();
778
779
780
		  }
		else
		  {
781
		    res = spot::lbtt_parse(f, error, &dict);
782
		    if (!res)
783
784
785
786
787
788
		      {
			global_error() << ("error: failed to parse output in "
					   "LBTT format: ")
				       << error << std::endl;
			end_error();
		      }
789
790
		  }
		break;
791
	      }
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
	    case printable_result_filename::Dstar:
	      {
		spot::dstar_parse_error_list pel;
		std::string filename = output.val()->name();
		spot::dstar_aut* aut;
		aut = spot::dstar_parse(filename, pel, &dict);
		if (!pel.empty())
		  {
		    std::ostream& err = global_error();
		    err << "error: failed to parse the produced DSTAR"
		      " output.\n";
		    spot::format_dstar_parse_errors(err, filename, pel);
		    end_error();
		    delete aut;
		    res = 0;
		  }
		else
809
810
811
812
		  {
		    res = dstar_to_tgba(aut);
		    delete aut;
		  }
813
814
		break;
	      }
815
816
817
	    case printable_result_filename::None:
	      assert(!"unreachable code");
	    }
818
	}
819
      // Compute statistics.
820
      if (res && want_stats)
821
822
823
824
825
826
827
828
829
830
	{
	  statistics* st = &(*fstats)[translator_num];
	  st->ok = true;
	  spot::tgba_sub_statistics s = sub_stats_reachable(res);
	  st->states = s.states;
	  st->edges = s.transitions;
	  st->transitions = s.sub_transitions;
	  st->acc = res->number_of_acceptance_conditions();
	  spot::scc_map m(res);
	  m.build_map();
831
	  unsigned c = m.scc_count();
832
833
834
	  st->scc = m.scc_count();
	  st->nondetstates = spot::count_nondet_states(res);
	  st->nondeterministic = st->nondetstates != 0;
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
	  for (unsigned n = 0; n < c; ++n)
	    {
	      if (!m.accepting(n))
		++st->nonacc_scc;
	      else if (is_terminal_scc(m, n))
		++st->terminal_scc;
	      else if (is_weak_scc(m, n))
		++st->weak_scc;
	      else
		++st->strong_scc;
	    }
	  if (st->strong_scc)
	    st->strong_aut = true;
	  else if (st->weak_scc)
	    st->weak_aut = true;
	  else
	    st->terminal_aut = true;
852
853
          double prec = XTIME_PRECISION;
	  st->time = (after - before) / prec;
854
	}
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
855
      output.cleanup();
856
      return res;
857
    }
858
  };
859

860
861
  static void
  check_empty_prod(const spot::tgba* aut_i, const spot::tgba* aut_j,
862
		   size_t i, size_t j, bool icomp, bool jcomp)
863
  {
864
865
    spot::tgba_product* prod = new spot::tgba_product(aut_i, aut_j);
    spot::emptiness_check* ec = spot::couvreur99(prod);
866
    spot::emptiness_check_result* res = ec->check();
867
868
869

    if (res)
      {
870
871
872
873
874
875
876
877
878
879
880
	std::ostream& err = global_error();
	err << "error: ";
	if (icomp)
	  err << "Comp(N" << i << ")";
	else
	  err << "P" << i;
	if (jcomp)
	  err << "*Comp(P" << j << ")";
	else
	  err << "*N" << j;
	err << " is nonempty";
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899

	spot::tgba_run* run = res->accepting_run();
	if (run)
	  {
	    const spot::tgba_run* runmin = reduce_run(prod, run);
	    delete run;
	    std::cerr << "; both automata accept the infinite word\n"
		      << "       ";
	    spot::tgba_word w(runmin);
	    w.simplify();
	    w.print(example(), prod->get_dict()) << "\n";
	    delete runmin;
	  }
	else
	  {
	    std::cerr << "\n";
	  }
	end_error();
      }
900
901
    delete res;
    delete ec;
902
    delete prod;
903
904
905
  }

  static void
906
  cross_check(const std::vector<spot::scc_map*>& maps, char l, unsigned p)
907
908
  {
    size_t m = maps.size();
909

910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
    std::vector<bool> res(m);
    unsigned verified = 0;
    unsigned violated = 0;
    for (size_t i = 0; i < m; ++i)
      if (spot::scc_map* m = maps[i])
	{
	  // r == true iff the automaton i is accepting.
	  bool r = false;
	  unsigned c = m->scc_count();
	  for (unsigned j = 0; (j < c) && !r; ++j)
	    r |= m->accepting(j);
	  res[i] = r;
	  if (r)
	    ++verified;
	  else
	    ++violated;
	}
    if (verified != 0 && violated != 0)
928
      {
929
930
	std::ostream& err = global_error();
	err << "error: {";
931
932
933
934
935
936
937
	bool first = true;
	for (size_t i = 0; i < m; ++i)
	  if (maps[i] && res[i])
	    {
	      if (first)
		first = false;
	      else
938
939
		err << ",";
	      err << l << i;
940
	    }
941
	err << "} disagree with {";
942
943
944
945
946
947
948
	first = true;
	for (size_t i = 0; i < m; ++i)
	  if (maps[i] && !res[i])
	    {
	      if (first)
		first = false;
	      else
949
950
		err << ",";
	      err << l << i;
951
	    }
952
953
	err << "} when evaluating ";
	if (products > 1)
954
	  err << "state-space #" << p << "/" << products << "\n";
955
	else
956
	  err << "the state-space\n";
957
	end_error();
958
      }
959
  }
960

961
  typedef std::set<spot::state*, spot::state_ptr_less_than> state_set;
962

963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
  // Collect all the states of SSPACE that appear in the accepting SCCs
  // of PROD.
  static void
  states_in_acc(const spot::scc_map* m, const spot::tgba* sspace,
		state_set& s)
  {
    const spot::tgba* aut = m->get_aut();
    unsigned c = m->scc_count();
    for (unsigned n = 0; n < c; ++n)
      if (m->accepting(n))
	{
	  const std::list<const spot::state*>& l = m->states_of(n);
	  for (std::list<const spot::state*>::const_iterator i = l.begin();
	       i != l.end(); ++i)
	    {
	      spot::state* x = aut->project_state(*i, sspace);
	      if (!s.insert(x).second)
		x->destroy();
	    }
	}
  }
984

985
986
987
988
989
990
991
992
993
994
995
  static bool
  consistency_check(const spot::scc_map* pos, const spot::scc_map* neg,
		    const spot::tgba* sspace)
  {
    // the states of SSPACE should appear in the accepting SCC of at
    // least one of POS or NEG.  Maybe both.
    state_set s;
    states_in_acc(pos, sspace, s);
    states_in_acc(neg, sspace, s);
    bool res = s.size() == states;
    state_set::iterator it;
996
    for (it = s.begin(); it != s.end(); ++it)
997
998
999
      (*it)->destroy();
    return res;
  }
1000

1001
1002
1003
1004
1005
  typedef
  Sgi::hash_set<const spot::ltl::formula*,
		const spot::ptr_hash<const spot::ltl::formula> > fset_t;


1006
1007
  class processor: public job_processor
  {
1008
    spot::bdd_dict dict;
1009
    translator_runner runner;
1010
    fset_t unique_set;
1011
  public:
1012
1013
1014
1015
1016
    processor()
      : runner(dict)
    {
    }

1017
1018
1019
1020
1021
1022
1023
    ~processor()
    {
      fset_t::iterator i = unique_set.begin();
      while (i != unique_set.end())
	(*i++)->destroy();
    }

1024
1025
1026
1027
1028
1029
    int
    process_formula(const spot::ltl::formula* f,
		    const char* filename = 0, int linenum = 0)
    {
      (void) filename;
      (void) linenum;
1030
      static unsigned round = 0;
1031

1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
      // If we need LBT atomic proposition in any of the input or
      // output, relabel the formula.
      if (!f->has_lbt_atomic_props() &&
	  (runner.has('l') || runner.has('L') || runner.has('T')))
	{
	  const spot::ltl::formula* g = spot::ltl::relabel(f, spot::ltl::Pnn);
	  f->destroy();
	  f = g;
	}

1042
1043
      // ---------- Positive Formula ----------

1044
      runner.round_formula(f, round);
1045

1046
1047
1048
      // Call formula() before printing anything else, in case it
      // complains.
      std::string fstr = runner.formula();
1049
1050
1051
1052
1053
1054
      if (filename)
	std::cerr << filename << ":";
      if (linenum)
	std::cerr << linenum << ":";
      if (filename || linenum)
	std::cerr << " ";
1055
1056
      if (color_opt)
	std::cerr << bright_white;
1057
      std::cerr << fstr << "\n";
1058
1059
      if (color_opt)
	std::cerr << reset_color;
1060

1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
      // Make sure we do not translate the same formula twice.
      if (!allow_dups)
	{
	  if (unique_set.insert(f).second)
	    {
	      f->clone();
	    }
	  else
	    {
	      std::cerr
		<< ("warning: This formula or its negation has already"
		    " been checked.\n         Use --allow-dups if it "
		    "should not be ignored.\n")
		<< std::endl;
	      f->destroy();
	      return 0;
	    }
	}

1080
1081
      // These store the result of the translation of the positive and
      // negative formulas.
1082
1083
1084
      size_t m = translators.size();
      std::vector<const spot::tgba*> pos(m);
      std::vector<const spot::tgba*> neg(m);
1085
1086
1087
1088
1089
      // These store the complement of the above results, when we can
      // compute it easily.
      std::vector<const spot::tgba*> comp_pos(m);
      std::vector<const spot::tgba*> comp_neg(m);

1090
1091

      unsigned n = vstats.size();
1092
      vstats.resize(n + (no_checks ? 1 : 2));
1093
      statistics_formula* pstats = &vstats[n];
1094
      statistics_formula* nstats = 0;
1095
      pstats->resize(m);
1096
1097
      formulas.push_back(fstr);

1098
      for (size_t n = 0; n < m; ++n)
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
	{
	  pos[n] = runner.translate(n, 'P', pstats);
	  // If the automaton is deterministic, compute its complement
	  // as well.  Note that if we have computed statistics
	  // already, there is no need to call is_deterministic()
	  // again.
	  if (!no_complement && pos[n]
	      && ((want_stats && !(*pstats)[n].nondeterministic)
		  || (!want_stats && is_deterministic(pos[n]))))
	    comp_pos[n] = dba_complement(pos[n]);
	}
1110
1111

      // ---------- Negative Formula ----------
1112

1113
1114
1115
      // The negative formula is only needed when checks are
      // activated.
      if (!no_checks)
1116
	{
1117
1118
	  nstats = &vstats[n + 1];
	  nstats->resize(m);
1119

1120
1121
	  const spot::ltl::formula* nf =
	    spot::ltl::unop::instance(spot::ltl::unop::Not, f->clone());
1122

1123
1124
1125
1126
1127
1128
1129
1130
1131
	  if (!allow_dups)
	    {
	      bool res = unique_set.insert(nf->clone()).second;
	      // It is not possible to discover that nf has already been
	      // translated, otherwise that would mean that f had been
	      // translated too and we would have caught it before.
	      assert(res);
	      (void) res;
	    }
1132

1133
1134
	  runner.round_formula(nf, round);
	  formulas.push_back(runner.formula());
1135

1136
	  for (size_t n = 0; n < m; ++n)
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
	    {
	      neg[n] = runner.translate(n, 'N', nstats);
	      // If the automaton is deterministic, compute its
	      // complement as well.  Note that if we have computed
	      // statistics already, there is no need to call
	      // is_deterministic() again.
	      if (!no_complement && neg[n]
		  && ((want_stats && !(*nstats)[n].nondeterministic)
		      || (!want_stats && is_deterministic(neg[n]))))
		comp_neg[n] = dba_complement(neg[n]);
	    }
1148
1149
	  nf->destroy();
	}
1150

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1151
      spot::cleanup_tmpfiles();
1152
      ++round;
1153

1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
      if (!no_checks)
	{
	  std::cerr << "Performing sanity checks and gathering statistics..."
		    << std::endl;

	  // intersection test
	  for (size_t i = 0; i < m; ++i)
	    if (pos[i])
	      for (size_t j = 0; j < m; ++j)
		if (neg[j])
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
		  {
		    check_empty_prod(pos[i], neg[j], i, j, false, false);

		    // Deal with the extra complemented automata if we
		    // have some.

		    // If comp_pos[j] and comp_neg[j] exist for the
		    // same j, it means pos[j] and neg[j] were both
		    // deterministic.  In that case, we will want to
		    // make sure that comp_pos[j]*comp_neg[j] is empty
		    // to assert the complementary of pos[j] and
		    // neg[j].  However using comp_pos[j] and
		    // comp_neg[j] against other translator will not
		    // give us any more insight than pos[j] and
		    // neg[j].  So we only do intersection checks with
		    // a complement automata when one of the two
		    // translation was not deterministic.

		    if (i != j && comp_pos[j] && !comp_neg[j])
		      check_empty_prod(pos[i], comp_pos[j], i, j, false, true);
		    if (i != j && comp_neg[i] && !comp_neg[i])
		      check_empty_prod(comp_neg[i], neg[j], i, j, true, false);
		    if (comp_pos[i] && comp_neg[j] &&
			(i == j || (!comp_neg[i] && !comp_pos[j])))
		      check_empty_prod(comp_pos[i], comp_neg[j],
				       i, j, true, true);
		  }
1191
1192
1193
1194
1195
	}
      else
	{
	  std::cerr << "Gathering statistics..." << std::endl;
	}
1196

1197
      spot::ltl::atomic_prop_set* ap = spot::ltl::atomic_prop_collect(f);
1198
      f->destroy();
1199

1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
      for (unsigned p = 0; p < products; ++p)
	{
	  // build a random state-space.
	  spot::srand(seed);
	  spot::tgba* statespace = spot::random_graph(states, density,
						      ap, &dict);

	  // Products of the state space with the positive automata.
	  std::vector<spot::tgba*> pos_prod(m);
	  // Products of the state space with the negative automata.
	  std::vector<spot::tgba*> neg_prod(m);
	  // Associated SCC maps.
	  std::vector<spot::scc_map*> pos_map(m);
	  std::vector<spot::scc_map*> neg_map(m);
	  for (size_t i = 0; i < m; ++i)
	    if (pos[i])
1216
	      {
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
		spot::tgba* p = new spot::tgba_product(pos[i], statespace);
		pos_prod[i] = p;
		spot::scc_map* sm = new spot::scc_map(p);
		sm->build_map();
		pos_map[i] = sm;

		// Statistics
		if (want_stats)
		  {
		    (*pstats)[i].product_scc += sm->scc_count();
		    spot::tgba_statistics s = spot::stats_reachable(p);
		    (*pstats)[i].product_states += s.states;
		    (*pstats)[i].product_transitions += s.transitions;
		  }
1231
	      }
1232

1233
1234
1235
1236

	  if (!no_checks)
	    for (size_t i = 0; i < m; ++i)
	      if (neg[i])
1237
		{
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
		  spot::tgba* p = new spot::tgba_product(neg[i], statespace);
		  neg_prod[i] = p;
		  spot::scc_map* sm = new spot::scc_map(p);
		  sm->build_map();
		  neg_map[i] = sm;

		  // Statistics
		  if (want_stats)
		    {
		      (*nstats)[i].product_scc += sm->scc_count();
		      spot::tgba_statistics s = spot::stats_reachable(p);
		      (*nstats)[i].product_states += s.states;
		      (*nstats)[i].product_transitions += s.transitions;
		    }
1252
		}
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264

	  if (!no_checks)
	    {
	      // cross-comparison test
	      cross_check(pos_map, 'P', p);
	      cross_check(neg_map, 'N', p);

	      // consistency check
	      for (size_t i = 0; i < m; ++i)
		if (pos_map[i] && neg_map[i] &&
		    !(consistency_check(pos_map[i], neg_map[i], statespace)))
		  {
1265
1266
1267
		    std::ostream& err = global_error();
		    err << "error: inconsistency between P" << i
			<< " and N" << i;
1268
		    if (products > 1)
1269
1270
		      err << " for state-space #" << p
			  << "/" << products << "\n";
1271
		    else
1272
1273
		      err << "\n";
		    end_error();
1274
		  }
1275
	    }
1276

1277
	  // Cleanup.