GCC Code Coverage Report
Directory: . Exec Total Coverage
File: src/main/interactive_shell.cpp Lines: 59 87 67.8 %
Date: 2021-08-20 Branches: 99 279 35.5 %

Line Exec Source
1
/******************************************************************************
2
 * Top contributors (to current version):
3
 *   Morgan Deters, Christopher L. Conway, Andrew V. Jones
4
 *
5
 * This file is part of the cvc5 project.
6
 *
7
 * Copyright (c) 2009-2021 by the authors listed in the file AUTHORS
8
 * in the top-level source directory and their institutional affiliations.
9
 * All rights reserved.  See the file COPYING in the top-level source
10
 * directory for licensing information.
11
 * ****************************************************************************
12
 *
13
 * Interactive shell for cvc5.
14
 *
15
 * This file is the implementation for the cvc5 interactive shell.
16
 * The shell supports the editline library.
17
 */
18
#include "main/interactive_shell.h"
19
20
#include <cstring>
21
#include <unistd.h>
22
23
#include <algorithm>
24
#include <cstdlib>
25
#include <iostream>
26
#include <set>
27
#include <string>
28
#include <utility>
29
#include <vector>
30
31
// This must go before HAVE_LIBEDITLINE.
32
#include "base/cvc5config.h"
33
34
#if HAVE_LIBEDITLINE
35
#include <editline/readline.h>
36
#  if HAVE_EXT_STDIO_FILEBUF_H
37
#    include <ext/stdio_filebuf.h>
38
#  endif /* HAVE_EXT_STDIO_FILEBUF_H */
39
#endif   /* HAVE_LIBEDITLINE */
40
41
#include "api/cpp/cvc5.h"
42
#include "base/check.h"
43
#include "base/output.h"
44
#include "expr/symbol_manager.h"
45
#include "options/base_options.h"
46
#include "options/language.h"
47
#include "options/main_options.h"
48
#include "options/options.h"
49
#include "options/parser_options.h"
50
#include "parser/input.h"
51
#include "parser/parser.h"
52
#include "parser/parser_builder.h"
53
#include "smt/command.h"
54
#include "theory/logic_info.h"
55
56
using namespace std;
57
58
namespace cvc5 {
59
60
using namespace parser;
61
using namespace language;
62
63
9779
const string InteractiveShell::INPUT_FILENAME = "<shell>";
64
65
#if HAVE_LIBEDITLINE
66
67
#if HAVE_EXT_STDIO_FILEBUF_H
68
using __gnu_cxx::stdio_filebuf;
69
#endif /* HAVE_EXT_STDIO_FILEBUF_H */
70
71
char** commandCompletion(const char* text, int start, int end);
72
char* commandGenerator(const char* text, int state);
73
74
static const std::string cvc_commands[] = {
75
#include "main/cvc_tokens.h"
76
};/* cvc_commands */
77
78
static const std::string smt2_commands[] = {
79
#include "main/smt2_tokens.h"
80
};/* smt2_commands */
81
82
static const std::string tptp_commands[] = {
83
#include "main/tptp_tokens.h"
84
};/* tptp_commands */
85
86
static const std::string* commandsBegin;
87
static const std::string* commandsEnd;
88
89
static set<string> s_declarations;
90
91
#endif /* HAVE_LIBEDITLINE */
92
93
12
InteractiveShell::InteractiveShell(api::Solver* solver, SymbolManager* sm)
94
12
    : d_options(solver->getOptions()),
95
12
      d_in(*d_options.base.in),
96
12
      d_out(*d_options.base.out),
97
36
      d_quit(false)
98
{
99
24
  ParserBuilder parserBuilder(solver, sm, d_options);
100
  /* Create parser with bogus input. */
101
12
  d_parser = parserBuilder.build();
102
12
  if (d_options.parser.forceLogicStringWasSetByUser)
103
  {
104
    LogicInfo tmp(d_options.parser.forceLogicString);
105
    d_parser->forceLogic(tmp.getLogicString());
106
  }
107
108
#if HAVE_LIBEDITLINE
109
  if (&d_in == &std::cin && isatty(fileno(stdin)))
110
  {
111
    ::rl_readline_name = const_cast<char*>("cvc5");
112
#if EDITLINE_COMPENTRY_FUNC_RETURNS_CHARP
113
    ::rl_completion_entry_function = commandGenerator;
114
#else /* EDITLINE_COMPENTRY_FUNC_RETURNS_CHARP */
115
    ::rl_completion_entry_function = (int (*)(const char*, int)) commandGenerator;
116
#endif /* EDITLINE_COMPENTRY_FUNC_RETURNS_CHARP */
117
    ::using_history();
118
119
    OutputLanguage lang =
120
        toOutputLanguage(d_options.base.inputLanguage);
121
    switch(lang) {
122
      case output::LANG_CVC:
123
        d_historyFilename = string(getenv("HOME")) + "/.cvc5_history";
124
        commandsBegin = cvc_commands;
125
        commandsEnd =
126
            cvc_commands + sizeof(cvc_commands) / sizeof(*cvc_commands);
127
        break;
128
      case output::LANG_TPTP:
129
        d_historyFilename = string(getenv("HOME")) + "/.cvc5_history_tptp";
130
        commandsBegin = tptp_commands;
131
        commandsEnd =
132
            tptp_commands + sizeof(tptp_commands) / sizeof(*tptp_commands);
133
        break;
134
      default:
135
        if (language::isOutputLang_smt2(lang))
136
        {
137
          d_historyFilename = string(getenv("HOME")) + "/.cvc5_history_smtlib2";
138
          commandsBegin = smt2_commands;
139
          commandsEnd =
140
              smt2_commands + sizeof(smt2_commands) / sizeof(*smt2_commands);
141
        }
142
        else
143
        {
144
          std::stringstream ss;
145
          ss << "internal error: unhandled language " << lang;
146
          throw Exception(ss.str());
147
        }
148
    }
149
    d_usingEditline = true;
150
    int err = ::read_history(d_historyFilename.c_str());
151
    ::stifle_history(s_historyLimit);
152
    if(Notice.isOn()) {
153
      if(err == 0) {
154
        Notice() << "Read " << ::history_length << " lines of history from "
155
                 << d_historyFilename << std::endl;
156
      } else {
157
        Notice() << "Could not read history from " << d_historyFilename
158
                 << ": " << strerror(err) << std::endl;
159
      }
160
    }
161
  }
162
  else
163
  {
164
    d_usingEditline = false;
165
  }
166
#else  /* HAVE_LIBEDITLINE */
167
12
  d_usingEditline = false;
168
#endif /* HAVE_LIBEDITLINE */
169
12
}/* InteractiveShell::InteractiveShell() */
170
171
24
InteractiveShell::~InteractiveShell() {
172
#if HAVE_LIBEDITLINE
173
  int err = ::write_history(d_historyFilename.c_str());
174
  if(err == 0) {
175
    Notice() << "Wrote " << ::history_length << " lines of history to "
176
             << d_historyFilename << std::endl;
177
  } else {
178
    Notice() << "Could not write history to " << d_historyFilename
179
             << ": " << strerror(err) << std::endl;
180
  }
181
#endif /* HAVE_LIBEDITLINE */
182
12
  delete d_parser;
183
12
}
184
185
28
Command* InteractiveShell::readCommand()
186
{
187
28
  char* lineBuf = NULL;
188
56
  string line = "";
189
190
28
restart:
191
192
  /* Don't do anything if the input is closed or if we've seen a
193
   * QuitCommand. */
194
28
  if(d_in.eof() || d_quit) {
195
    d_out << endl;
196
    return NULL;
197
  }
198
199
  /* If something's wrong with the input, there's nothing we can do. */
200
28
  if( !d_in.good() ) {
201
    throw ParserException("Interactive input broken.");
202
  }
203
204
  /* Prompt the user for input. */
205
28
  if (d_usingEditline)
206
  {
207
#if HAVE_LIBEDITLINE
208
    lineBuf = ::readline(line == "" ? "cvc5> " : "... > ");
209
    if(lineBuf != NULL && lineBuf[0] != '\0') {
210
      ::add_history(lineBuf);
211
    }
212
    line += lineBuf == NULL ? "" : lineBuf;
213
    free(lineBuf);
214
#endif /* HAVE_LIBEDITLINE */
215
  }
216
  else
217
  {
218
28
    if (line == "")
219
    {
220
28
      d_out << "cvc5> " << flush;
221
    }
222
    else
223
    {
224
      d_out << "... > " << flush;
225
    }
226
227
    /* Read a line */
228
56
    stringbuf sb;
229
28
    d_in.get(sb);
230
28
    line += sb.str();
231
  }
232
233
28
  string input = "";
234
  while(true) {
235
56
    Debug("interactive") << "Input now '" << input << line << "'" << endl
236
28
                         << flush;
237
238
28
    Assert(!(d_in.fail() && !d_in.eof()) || line.empty());
239
240
    /* Check for failure. */
241
28
    if(d_in.fail() && !d_in.eof()) {
242
      /* This should only happen if the input line was empty. */
243
6
      Assert(line.empty());
244
6
      d_in.clear();
245
    }
246
247
    /* Strip trailing whitespace. */
248
28
    int n = line.length() - 1;
249
28
    while( !line.empty() && isspace(line[n]) ) {
250
      line.erase(n,1);
251
      n--;
252
    }
253
254
    /* If we hit EOF, we're done. */
255
84
    if ((!d_usingEditline && d_in.eof())
256
44
        || (d_usingEditline && lineBuf == NULL))
257
    {
258
12
      input += line;
259
260
12
      if(input.empty()) {
261
        /* Nothing left to parse. */
262
12
        d_out << endl;
263
12
        return NULL;
264
      }
265
266
      /* Some input left to parse, but nothing left to read.
267
         Jump out of input loop. */
268
      d_out << endl;
269
      input = line = "";
270
      d_in.clear();
271
      goto restart;
272
    }
273
274
16
    if (!d_usingEditline)
275
    {
276
      /* Extract the newline delimiter from the stream too */
277
16
      int c CVC5_UNUSED = d_in.get();
278
16
      Assert(c == '\n');
279
32
      Debug("interactive") << "Next char is '" << (char)c << "'" << endl
280
16
                           << flush;
281
    }
282
283
16
    input += line;
284
285
    /* If the last char was a backslash, continue on the next line. */
286
16
    n = input.length() - 1;
287
16
    if( !line.empty() && input[n] == '\\' ) {
288
      input[n] = '\n';
289
      if (d_usingEditline)
290
      {
291
#if HAVE_LIBEDITLINE
292
        lineBuf = ::readline("... > ");
293
        if(lineBuf != NULL && lineBuf[0] != '\0') {
294
          ::add_history(lineBuf);
295
        }
296
        line = lineBuf == NULL ? "" : lineBuf;
297
        free(lineBuf);
298
#endif /* HAVE_LIBEDITLINE */
299
      }
300
      else
301
      {
302
        d_out << "... > " << flush;
303
304
        /* Read a line */
305
        stringbuf sb;
306
        d_in.get(sb);
307
        line = sb.str();
308
      }
309
    } else {
310
      /* No continuation, we're done. */
311
16
      Debug("interactive") << "Leaving input loop." << endl << flush;
312
16
      break;
313
    }
314
  }
315
316
32
  d_parser->setInput(Input::newStringInput(
317
16
      d_options.base.inputLanguage, input, INPUT_FILENAME));
318
319
  /* There may be more than one command in the input. Build up a
320
     sequence. */
321
16
  CommandSequence *cmd_seq = new CommandSequence();
322
  Command *cmd;
323
324
  try
325
  {
326
40
    while ((cmd = d_parser->nextCommand()))
327
    {
328
12
      cmd_seq->addCommand(cmd);
329
12
      if (dynamic_cast<QuitCommand*>(cmd) != NULL)
330
      {
331
        d_quit = true;
332
        break;
333
      }
334
      else
335
      {
336
#if HAVE_LIBEDITLINE
337
        if (dynamic_cast<DeclareFunctionCommand*>(cmd) != NULL)
338
        {
339
          s_declarations.insert(
340
              dynamic_cast<DeclareFunctionCommand*>(cmd)->getSymbol());
341
        }
342
        else if (dynamic_cast<DefineFunctionCommand*>(cmd) != NULL)
343
        {
344
          s_declarations.insert(
345
              dynamic_cast<DefineFunctionCommand*>(cmd)->getSymbol());
346
        }
347
        else if (dynamic_cast<DeclareSortCommand*>(cmd) != NULL)
348
        {
349
          s_declarations.insert(
350
              dynamic_cast<DeclareSortCommand*>(cmd)->getSymbol());
351
        }
352
        else if (dynamic_cast<DefineSortCommand*>(cmd) != NULL)
353
        {
354
          s_declarations.insert(
355
              dynamic_cast<DefineSortCommand*>(cmd)->getSymbol());
356
        }
357
#endif /* HAVE_LIBEDITLINE */
358
      }
359
    }
360
  }
361
  catch (ParserEndOfFileException& pe)
362
  {
363
    line += "\n";
364
    goto restart;
365
  }
366
  catch (ParserException& pe)
367
  {
368
    if (language::isOutputLang_smt2(d_options.base.outputLanguage))
369
    {
370
      d_out << "(error \"" << pe << "\")" << endl;
371
    }
372
    else
373
    {
374
      d_out << pe << endl;
375
    }
376
    // We can't really clear out the sequence and abort the current line,
377
    // because the parse error might be for the second command on the
378
    // line.  The first ones haven't yet been executed by the SmtEngine,
379
    // but the parser state has already made the variables and the mappings
380
    // in the symbol table.  So unfortunately, either we exit cvc5 entirely,
381
    // or we commit to the current line up to the command with the parse
382
    // error.
383
    //
384
    // FIXME: does that mean e.g. that a pushed LET scope might not yet have
385
    // been popped?!
386
    //
387
    // delete cmd_seq;
388
    // cmd_seq = new CommandSequence();
389
  }
390
391
16
  return cmd_seq;
392
}/* InteractiveShell::readCommand() */
393
394
#if HAVE_LIBEDITLINE
395
396
char** commandCompletion(const char* text, int start, int end) {
397
  Debug("rl") << "text: " << text << endl;
398
  Debug("rl") << "start: " << start << " end: " << end << endl;
399
  return rl_completion_matches(text, commandGenerator);
400
}
401
402
// Our peculiar versions of "less than" for strings
403
struct StringPrefix1Less {
404
  bool operator()(const std::string& s1, const std::string& s2) {
405
    size_t l1 = s1.length(), l2 = s2.length();
406
    size_t l = l1 <= l2 ? l1 : l2;
407
    return s1.compare(0, l1, s2, 0, l) < 0;
408
  }
409
};/* struct StringPrefix1Less */
410
struct StringPrefix2Less {
411
  bool operator()(const std::string& s1, const std::string& s2) {
412
    size_t l1 = s1.length(), l2 = s2.length();
413
    size_t l = l1 <= l2 ? l1 : l2;
414
    return s1.compare(0, l, s2, 0, l2) < 0;
415
  }
416
};/* struct StringPrefix2Less */
417
418
char* commandGenerator(const char* text, int state) {
419
  static thread_local const std::string* rlCommand;
420
  static thread_local set<string>::const_iterator* rlDeclaration;
421
422
  const std::string* i = lower_bound(commandsBegin, commandsEnd, text, StringPrefix2Less());
423
  const std::string* j = upper_bound(commandsBegin, commandsEnd, text, StringPrefix1Less());
424
425
  set<string>::const_iterator ii = lower_bound(s_declarations.begin(), s_declarations.end(), text, StringPrefix2Less());
426
  set<string>::const_iterator jj = upper_bound(s_declarations.begin(), s_declarations.end(), text, StringPrefix1Less());
427
428
  if(rlDeclaration == NULL) {
429
    rlDeclaration = new set<string>::const_iterator();
430
  }
431
432
  if(state == 0) {
433
    rlCommand = i;
434
    *rlDeclaration = ii;
435
  }
436
437
  if(rlCommand != j) {
438
    return strdup((*rlCommand++).c_str());
439
  }
440
441
  return *rlDeclaration == jj ? NULL : strdup((*(*rlDeclaration)++).c_str());
442
}
443
444
#endif /* HAVE_LIBEDITLINE */
445
446
29337
}  // namespace cvc5