GCC Code Coverage Report
Directory: . Exec Total Coverage
File: src/main/interactive_shell.cpp Lines: 57 85 67.1 %
Date: 2021-09-07 Branches: 103 291 35.4 %

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