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