File: interpreter.cc

package info (click to toggle)
octave 6.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 124,192 kB
  • sloc: cpp: 322,665; ansic: 68,088; fortran: 20,980; objc: 8,121; sh: 7,719; yacc: 4,266; lex: 4,123; perl: 1,530; java: 1,366; awk: 1,257; makefile: 424; xml: 147
file content (1969 lines) | stat: -rw-r--r-- 57,526 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
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
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 1993-2021 The Octave Project Developers
//
// See the file COPYRIGHT.md in the top-level directory of this
// distribution or <https://octave.org/copyright/>.
//
// This file is part of Octave.
//
// Octave 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.
//
// Octave 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 Octave; see the file COPYING.  If not, see
// <https://www.gnu.org/licenses/>.
//
////////////////////////////////////////////////////////////////////////

#if defined (HAVE_CONFIG_H)
#  include "config.h"
#endif

#include <cstdio>

#include <set>
#include <string>
#include <iostream>

#include "cmd-edit.h"
#include "cmd-hist.h"
#include "file-ops.h"
#include "file-stat.h"
#include "file-ops.h"
#include "fpucw-wrappers.h"
#include "lo-blas-proto.h"
#include "lo-error.h"
#include "oct-env.h"
#include "str-vec.h"
#include "signal-wrappers.h"
#include "unistd-wrappers.h"

#include "builtin-defun-decls.h"
#include "defaults.h"
#include "Cell.h"
#include "defun.h"
#include "display.h"
#include "error.h"
#include "event-manager.h"
#include "file-io.h"
#include "graphics.h"
#include "help.h"
#include "input.h"
#include "interpreter-private.h"
#include "interpreter.h"
#include "load-path.h"
#include "load-save.h"
#include "octave.h"
#include "oct-hist.h"
#include "oct-map.h"
#include "oct-mutex.h"
#include "ovl.h"
#include "ov.h"
#include "ov-classdef.h"
#include "parse.h"
#include "pt-classdef.h"
#include "pt-eval.h"
#include "pt-jump.h"
#include "pt-stmt.h"
#include "settings.h"
#include "sighandlers.h"
#include "sysdep.h"
#include "unwind-prot.h"
#include "utils.h"
#include "variables.h"
#include "version.h"

// TRUE means the quit() call is allowed.
bool quit_allowed = true;

// TRUE means we are ready to interpret commands, but not everything
// is ready for interactive use.
bool octave_interpreter_ready = false;

// TRUE means we've processed all the init code and we are good to go.
bool octave_initialized = false;

DEFUN (__version_info__, args, ,
       doc: /* -*- texinfo -*-
@deftypefn {} {retval =} __version_info__ (@var{name}, @var{version}, @var{release}, @var{date})
Undocumented internal function.
@end deftypefn */)
{
  static octave_map vinfo;

  int nargin = args.length ();

  if (nargin != 0 && nargin != 4)
    print_usage ();

  octave_value retval;

  if (nargin == 0)
    retval = vinfo;
  else if (nargin == 4)
    {
      if (vinfo.nfields () == 0)
        {
          vinfo.assign ("Name", args(0));
          vinfo.assign ("Version", args(1));
          vinfo.assign ("Release", args(2));
          vinfo.assign ("Date", args(3));
        }
      else
        {
          octave_idx_type n = vinfo.numel () + 1;

          vinfo.resize (dim_vector (n, 1));

          octave_value idx (n);

          vinfo.assign (idx, "Name", Cell (octave_value (args(0))));
          vinfo.assign (idx, "Version", Cell (octave_value (args(1))));
          vinfo.assign (idx, "Release", Cell (octave_value (args(2))));
          vinfo.assign (idx, "Date", Cell (octave_value (args(3))));
        }
    }

  return retval;
}

DEFMETHOD (quit, interp, args, ,
           doc: /* -*- texinfo -*-
@deftypefn  {} {} quit
@deftypefnx {} {} quit cancel
@deftypefnx {} {} quit force
@deftypefnx {} {} quit ("cancel")
@deftypefnx {} {} quit ("force")
@deftypefnx {} {} quit (@var{status})
@deftypefnx {} {} quit (@var{status}, "force")
Quit the current Octave session.

The @code{exit} function is an alias for @code{quit}.

If the optional integer value @var{status} is supplied, pass that value to
the operating system as Octave's exit status.  The default value is zero.

When exiting, Octave will attempt to run the m-file @file{finish.m} if it
exists.  User commands to save the workspace or clean up temporary files
may be placed in that file.  Alternatively, another m-file may be scheduled
to run using @code{atexit}.  If an error occurs while executing the
@file{finish.m} file, Octave does not exit and control is returned to
the command prompt.

If the optional argument @qcode{"cancel"} is provided, Octave does not
exit and control is returned to the command prompt.  This feature allows
the @code{finish.m} file to cancel the quit process.

If the user preference to request confirmation before exiting, Octave
will display a dialog and give the user an option to cancel the exit
process.

If the optional argument @qcode{"force"} is provided, no confirmation is
requested, and the execution of the @file{finish.m} file is skipped.
@seealso{atexit}
@end deftypefn */)
{
  int numel = args.length ();

  if (numel > 2)
    print_usage ();

  int exit_status = 0;

  bool force = false;
  bool cancel = false;

  if (numel == 2)
    {
      exit_status = args(0).xnint_value ("quit: STATUS must be an integer");
      std::string frc
        = args(1).xstring_value ("quit: second argument must be a string");

      if (frc == "force")
        force = true;
      else
        error (R"(quit: second argument must be string "force")");
    }
  else if (numel == 1)
    {
      if (args(0).is_string ())
        {
          const char *msg
            = R"(quit: option must be string "cancel" or "force")";

          std::string opt = args(0).xstring_value (msg);

          if (opt == "cancel")
            cancel = true;
          else if (opt == "force")
            force = true;
          else
            error ("%s", msg);
        }
      else
        exit_status = args(0).xnint_value ("quit: STATUS must be an integer");
    }

  if (cancel)
    {
      // No effect if "quit cancel" appears outside of finish script.

      if (interp.executing_finish_script ())
        interp.cancel_quit (true);

      return ovl ();
    }

  interp.quit (exit_status, force);

  return ovl ();
}

DEFALIAS (exit, quit);

DEFMETHOD (atexit, interp, args, nargout,
           doc: /* -*- texinfo -*-
@deftypefn  {} {} atexit (@var{fcn})
@deftypefnx {} {} atexit (@var{fcn}, @var{flag})
Register a function to be called when Octave exits.

For example,

@example
@group
function last_words ()
  disp ("Bye bye");
endfunction
atexit ("last_words");
@end group
@end example

@noindent
will print the message @qcode{"Bye bye"} when Octave exits.

The additional argument @var{flag} will register or unregister @var{fcn}
from the list of functions to be called when Octave exits.  If @var{flag} is
true, the function is registered, and if @var{flag} is false, it is
unregistered.  For example, after registering the function @code{last_words}
above,

@example
atexit ("last_words", false);
@end example

@noindent
will remove the function from the list and Octave will not call
@code{last_words} when it exits.

Note that @code{atexit} only removes the first occurrence of a function
from the list, so if a function was placed in the list multiple times with
@code{atexit}, it must also be removed from the list multiple times.
@seealso{quit}
@end deftypefn */)
{
  int nargin = args.length ();

  if (nargin < 1 || nargin > 2)
    print_usage ();

  std::string arg = args(0).xstring_value ("atexit: FCN argument must be a string");

  bool add_mode = (nargin == 2)
    ? args(1).xbool_value ("atexit: FLAG argument must be a logical value")
    : true;

  octave_value_list retval;

  if (add_mode)
    interp.add_atexit_fcn (arg);
  else
    {
      bool found = interp.remove_atexit_fcn (arg);

      if (nargout > 0)
        retval = ovl (found);
    }

  return retval;
}

namespace octave
{
  temporary_file_list::~temporary_file_list (void)
  {
    cleanup ();
  }

  void temporary_file_list::insert (const std::string& file)
  {
    m_files.insert (file);
  }

  void temporary_file_list::cleanup (void)
  {
    while (! m_files.empty ())
      {
        auto it = m_files.begin ();

        octave_unlink_wrapper (it->c_str ());

        m_files.erase (it);
      }
  }

  // The time we last time we changed directories.
  sys::time Vlast_chdir_time = 0.0;

  // Execute commands from a file and catch potential exceptions in a consistent
  // way.  This function should be called anywhere we might parse and execute
  // commands from a file before we have entered the main loop in
  // toplev.cc.

  static int safe_source_file (const std::string& file_name,
                               const std::string& context = "",
                               bool verbose = false,
                               bool require_file = true)
  {
    interpreter& interp = __get_interpreter__ ("safe_source_file");

    try
      {
        source_file (file_name, context, verbose, require_file);
      }
    catch (const interrupt_exception&)
      {
        interp.recover_from_exception ();

        return 1;
      }
    catch (const execution_exception& e)
      {
        interp.handle_exception (e);

        return 1;
      }

    return 0;
  }

  static void initialize_version_info (void)
  {
    octave_value_list args;

    args(3) = OCTAVE_RELEASE_DATE;
    args(2) = config::release ();
    args(1) = OCTAVE_VERSION;
    args(0) = "GNU Octave";

    F__version_info__ (args, 0);
  }

  static void xerbla_abort (void)
  {
    error ("Fortran procedure terminated by call to XERBLA");
  }

  static void initialize_xerbla_error_handler (void)
  {
    // The idea here is to force xerbla to be referenced so that we will
    // link to our own version instead of the one provided by the BLAS
    // library.  But numeric_limits<double>::NaN () should never be -1, so
    // we should never actually call xerbla.  FIXME (again!): If this
    // becomes a constant expression the test might be optimized away and
    // then the reference to the function might also disappear.

    if (numeric_limits<double>::NaN () == -1)
      F77_FUNC (xerbla, XERBLA) ("octave", 13 F77_CHAR_ARG_LEN (6));

    typedef void (*xerbla_handler_ptr) (void);

    typedef void (*octave_set_xerbla_handler_ptr) (xerbla_handler_ptr);

    dynamic_library libs ("");

    if (libs)
      {
        octave_set_xerbla_handler_ptr octave_set_xerbla_handler
          = reinterpret_cast<octave_set_xerbla_handler_ptr>
              (libs.search ("octave_set_xerbla_handler"));

        if (octave_set_xerbla_handler)
          octave_set_xerbla_handler (xerbla_abort);
      }
  }

  OCTAVE_NORETURN static void
  lo_error_handler (const char *fmt, ...)
  {
    va_list args;
    va_start (args, fmt);
    verror_with_cfn (fmt, args);
    va_end (args);

    throw execution_exception ();
  }

  OCTAVE_NORETURN static void
  lo_error_with_id_handler (const char *id, const char *fmt, ...)
  {
    va_list args;
    va_start (args, fmt);
    verror_with_id_cfn (id, fmt, args);
    va_end (args);

    throw execution_exception ();
  }

  static void initialize_error_handlers (void)
  {
    set_liboctave_error_handler (lo_error_handler);
    set_liboctave_error_with_id_handler (lo_error_with_id_handler);
    set_liboctave_warning_handler (warning);
    set_liboctave_warning_with_id_handler (warning_with_id);
  }

  // Create an interpreter object and perform initialization up to the
  // point of setting reading command history and setting the load
  // path.

  interpreter::interpreter (application *app_context)
    : m_app_context (app_context),
      m_tmp_files (),
      m_atexit_fcns (),
      m_display_info (),
      m_environment (),
      m_settings (),
      m_error_system (*this),
      m_help_system (*this),
      m_input_system (*this),
      m_output_system (*this),
      m_history_system (*this),
      m_dynamic_loader (*this),
      m_load_path (*this),
      m_load_save_system (*this),
      m_type_info (),
      m_symbol_table (*this),
      m_evaluator (*this),
      m_stream_list (*this),
      m_child_list (),
      m_url_handle_manager (),
      m_cdef_manager (*this),
      m_gtk_manager (),
      m_event_manager (*this),
      m_gh_manager (nullptr),
      m_interactive (false),
      m_read_site_files (true),
      m_read_init_files (m_app_context != nullptr),
      m_verbose (false),
      m_inhibit_startup_message (false),
      m_load_path_initialized (false),
      m_history_initialized (false),
      m_in_top_level_repl (false),
      m_cancel_quit (false),
      m_executing_finish_script (false),
      m_executing_atexit (false),
      m_initialized (false)
  {
    // FIXME: When thread_local storage is used by default, this message
    // should change to say something like
    //
    //   only one Octave interpreter may be active in any given thread

    if (instance)
      throw std::runtime_error
        ("only one Octave interpreter may be active");

    instance = this;

    // Matlab uses "C" locale for LC_NUMERIC class regardless of local setting
    setlocale (LC_ALL, "");
    setlocale (LC_NUMERIC, "C");
    setlocale (LC_TIME, "C");
    sys::env::putenv ("LC_NUMERIC", "C");
    sys::env::putenv ("LC_TIME", "C");

    // Initialize the default floating point unit control state.
    octave_set_default_fpucw ();

    thread::init ();

    octave_ieee_init ();

    initialize_xerbla_error_handler ();

    initialize_error_handlers ();

    if (m_app_context)
      {
        install_signal_handlers ();
        octave_unblock_signal_by_name ("SIGTSTP");
      }
    else
      quit_allowed = false;

    if (! m_app_context)
      m_display_info.initialize ();

    bool line_editing = false;
    bool traditional = false;

    if (m_app_context)
      {
        // Embedded interpreters don't execute command line options.
        const cmdline_options& options = m_app_context->options ();

        // Make all command-line arguments available to startup files,
        // including PKG_ADD files.

        string_vector args = options.all_args ();

        m_app_context->intern_argv (args);
        intern_nargin (args.numel () - 1);

        bool is_octave_program = m_app_context->is_octave_program ();

        std::list<std::string> command_line_path = options.command_line_path ();

        for (const auto& pth : command_line_path)
          m_load_path.set_command_line_path (pth);

        std::string exec_path = options.exec_path ();
        if (! exec_path.empty ())
          m_environment.exec_path (exec_path);

        std::string image_path = options.image_path ();
        if (! image_path.empty ())
          m_environment.image_path (image_path);

        if (! options.no_window_system ())
          m_display_info.initialize ();

        // Is input coming from a terminal?  If so, we are probably
        // interactive.

        // If stdin is not a tty, then we are reading commands from a
        // pipe or a redirected file.
        bool stdin_is_tty = octave_isatty_wrapper (fileno (stdin));

        m_interactive = (! is_octave_program && stdin_is_tty
                         && octave_isatty_wrapper (fileno (stdout)));

        // Check if the user forced an interactive session.
        if (options.forced_interactive ())
          m_interactive = true;

        line_editing = options.line_editing ();
        if ((! m_interactive || options.forced_interactive ())
            && ! options.forced_line_editing ())
          line_editing = false;

        traditional = options.traditional ();

        // FIXME: if possible, perform the following actions directly
        // instead of using the interpreter-level functions.

        if (options.echo_commands ())
          m_evaluator.echo
            (tree_evaluator::ECHO_SCRIPTS | tree_evaluator::ECHO_FUNCTIONS
             | tree_evaluator::ECHO_ALL);

        std::string docstrings_file = options.docstrings_file ();
        if (! docstrings_file.empty ())
          Fbuilt_in_docstrings_file (*this, octave_value (docstrings_file));

        std::string doc_cache_file = options.doc_cache_file ();
        if (! doc_cache_file.empty ())
          Fdoc_cache_file (*this, octave_value (doc_cache_file));

        std::string info_file = options.info_file ();
        if (! info_file.empty ())
          Finfo_file (*this, octave_value (info_file));

        std::string info_program = options.info_program ();
        if (! info_program.empty ())
          Finfo_program (*this, octave_value (info_program));

        if (options.debug_jit ())
          Fdebug_jit (octave_value (true));

        if (options.jit_compiler ())
          Fjit_enable (octave_value (true));

        std::string texi_macros_file = options.texi_macros_file ();
        if (! texi_macros_file.empty ())
          Ftexi_macros_file (*this, octave_value (texi_macros_file));
      }

    // FIXME: we defer creation of the gh_manager object because it
    // creates a root_figure object that requires the display_info
    // object, but that is currently only accessible through the global
    // interpreter object and that is not available until after the
    // interpreter::instance pointer is set (above).  It would be better
    // if m_gh_manager could be an object value instead of a pointer and
    // created as part of the interpreter initialization.  To do that,
    // we should either make the display_info object independent of the
    // interpreter object (does it really need to cache any
    // information?) or defer creation of the root_figure object until
    // it is actually needed.
    m_gh_manager = new gh_manager (*this);

    m_input_system.initialize (line_editing);

    // These can come after command line args since none of them set any
    // defaults that might be changed by command line options.

    initialize_version_info ();

    // This should be done before initializing the load path because
    // some PKG_ADD files might need --traditional behavior.

    if (traditional)
      maximum_braindamage ();

    octave_interpreter_ready = true;
  }

  OCTAVE_THREAD_LOCAL interpreter *interpreter::instance = nullptr;

  interpreter::~interpreter (void)
  {
    delete m_gh_manager;
  }

  void interpreter::intern_nargin (octave_idx_type nargs)
  {
    m_evaluator.set_auto_fcn_var (stack_frame::NARGIN, nargs);
  }

  // Read the history file unless a command-line option inhibits that.

  void interpreter::initialize_history (bool read_history_file)
  {
    if (! m_history_initialized)
      {
        // Allow command-line option to override.

        if (m_app_context)
          {
            const cmdline_options& options = m_app_context->options ();

            read_history_file = options.read_history_file ();

            if (! read_history_file)
              command_history::ignore_entries ();
          }

        m_history_system.initialize (read_history_file);

        if (! m_app_context)
          command_history::ignore_entries ();

        m_history_initialized = true;
      }
  }

  // Set the initial path to the system default unless command-line
  // option says to leave it empty.

  void interpreter::initialize_load_path (bool set_initial_path)
  {
    if (! m_load_path_initialized)
      {
        // Allow command-line option to override.

        if (m_app_context)
          {
            const cmdline_options& options = m_app_context->options ();

            set_initial_path = options.set_initial_path ();
          }

        // Temporarily set the execute_pkg_add function to one that
        // catches exceptions.  This is better than wrapping
        // load_path::initialize in a try-catch block because it will
        // not stop executing PKG_ADD files at the first exception.
        // It's also better than changing the default execute_pkg_add
        // function to use safe_source file because that will normally
        // be evaluated from the normal interpreter loop where exceptions
        // are already handled.

        unwind_protect frame;

        frame.add_method (m_load_path, &load_path::set_add_hook,
                          m_load_path.get_add_hook ());

        m_load_path.set_add_hook ([this] (const std::string& dir)
                                  { this->execute_pkg_add (dir); });

        m_load_path.initialize (set_initial_path);

        m_load_path_initialized = true;
      }
  }

  // This may be called separately from execute

  void interpreter::initialize (void)
  {
    if (m_initialized)
      return;

    display_startup_message ();

    // Wait to read the history file until the interpreter reads input
    // files and begins evaluating commands.

    initialize_history ();

    // Initializing the load path may execute PKG_ADD files, so can't be
    // done until the interpreter is ready to execute commands.

    // Deferring it to the execute step also allows the path to be
    // initialized between creating and execute the interpreter, for
    // example, to set a custom path for an embedded interpreter.

    initialize_load_path ();

    octave_save_signal_mask ();

    can_interrupt = true;

    octave_signal_hook = respond_to_pending_signals;
    octave_interrupt_hook = nullptr;

    catch_interrupts ();

    // FIXME: could we eliminate this variable or make it not be global?
    // Global used to communicate with signal handler.
    octave_initialized = true;

    m_initialized = true;
  }

  // FIXME: this function is intended to be executed only once.  Should
  // we enforce that restriction?

  int interpreter::execute (void)
  {
    int exit_status = 0;

    try
      {
        initialize ();

        execute_startup_files ();

        if (m_app_context)
          {
            const cmdline_options& options = m_app_context->options ();

            if (m_app_context->have_eval_option_code ())
              {
                int status = execute_eval_option_code ();

                if (status )
                  exit_status = status;

                if (! options.persist ())
                  return exit_status;
              }

            // If there is an extra argument, see if it names a file to
            // read.  Additional arguments are taken as command line options
            // for the script.

            if (m_app_context->have_script_file ())
              {
                int status = execute_command_line_file ();

                if (status)
                  exit_status = status;

                if (! options.persist ())
                  return exit_status;
              }

            if (options.forced_interactive ())
              command_editor::blink_matching_paren (false);

            exit_status = main_loop ();
          }
      }
    catch (const exit_exception& ex)
      {
        return ex.exit_status ();
      }

    return exit_status;
  }

  // Call a function with exceptions handled to avoid problems with
  // errors while shutting down.

#define OCTAVE_IGNORE_EXCEPTION(E)                                      \
  catch (E)                                                             \
    {                                                                   \
      recover_from_exception ();                                        \
                                                                        \
      std::cerr << "error: ignoring " #E " while preparing to exit"     \
                << std::endl;                                           \
    }

#define OCTAVE_SAFE_CALL(F, ARGS)                                       \
  do                                                                    \
    {                                                                   \
      try                                                               \
        {                                                               \
          unwind_protect frame;                                         \
                                                                        \
          frame.add_method (m_error_system,                             \
                            &error_system::set_debug_on_error,          \
                            m_error_system.debug_on_error ());          \
          frame.add_method (m_error_system,                             \
                            &error_system::set_debug_on_warning,        \
                            m_error_system.debug_on_warning ());        \
                                                                        \
          m_error_system.debug_on_error (false);                        \
          m_error_system.debug_on_warning (false);                      \
                                                                        \
          F ARGS;                                                       \
        }                                                               \
      OCTAVE_IGNORE_EXCEPTION (const exit_exception&)                   \
      OCTAVE_IGNORE_EXCEPTION (const interrupt_exception&)              \
      OCTAVE_IGNORE_EXCEPTION (const execution_exception&)              \
      OCTAVE_IGNORE_EXCEPTION (const std::bad_alloc&)                   \
    }                                                                   \
  while (0)

  void interpreter::shutdown (void)
  {
    OCTAVE_SAFE_CALL (feval, ("close", ovl ("all"), 0));

    // If we are attached to a GUI, process pending events and
    // disable the link.

    OCTAVE_SAFE_CALL (m_event_manager.process_events, (true));
    OCTAVE_SAFE_CALL (m_event_manager.disable, ());

    OCTAVE_SAFE_CALL (m_input_system.clear_input_event_hooks, ());

    // Any atexit functions added after this function call won't be
    // executed.  Each atexit function is executed with
    // OCTAVE_SAFE_CALL, so we don't need that here.

    execute_atexit_fcns ();

    // Clear all functions and variables.

    // Note that we don't force symbols to be cleared, so we will
    // respect mlock at this point.  Later, we'll force all variables
    // and functions to be cleared.

    OCTAVE_SAFE_CALL (clear_all, ());

    // We may still have some figures.  Close them.

    OCTAVE_SAFE_CALL (feval, ("close", ovl ("all"), 0));

    // What is supposed to happen if a figure has a closerequestfcn or
    // deletefcn callback registered that creates other figures or
    // variables?  What if those variables are classdef objects with
    // destructors that can create figures?  The possibilities are
    // endless.  At some point, we have to give up and force execution
    // to end.

    // Note that we again don't force symbols to be cleared, so we
    // continue to respect mlock here.  Later, we'll force all variables
    // and functions to be cleared.

    OCTAVE_SAFE_CALL (clear_all, ());

    // Do this explicitly so that destructors for mex file objects
    // are called, so that functions registered with mexAtExit are
    // called.

    OCTAVE_SAFE_CALL (m_symbol_table.clear_mex_functions, ());

    OCTAVE_SAFE_CALL (command_editor::restore_terminal_state, ());

    OCTAVE_SAFE_CALL (m_history_system.write_timestamp, ());

    if (! command_history::ignoring_entries ())
      OCTAVE_SAFE_CALL (command_history::clean_up_and_save, ());

    OCTAVE_SAFE_CALL (m_gtk_manager.unload_all_toolkits, ());

    // Now that the graphics toolkits have been unloaded, force all
    // symbols to be cleared.

    OCTAVE_SAFE_CALL (clear_all, (true));

    // FIXME:  May still need something like this to ensure that
    // destructors for class objects will run properly.  Should that be
    // done earlier?  Before or after atexit functions are executed?
    // What will happen if the destructor for an obect attempts to
    // display a figure?

    OCTAVE_SAFE_CALL (m_symbol_table.cleanup, ());

    OCTAVE_SAFE_CALL (sysdep_cleanup, ());

    OCTAVE_SAFE_CALL (flush_stdout, ());

    // Don't call singleton_cleanup_list::cleanup until we have the
    // problems with registering/unregistering types worked out.  For
    // example, uncomment the following line, then use the make_int
    // function from the examples directory to create an integer
    // object and then exit Octave.  Octave should crash with a
    // segfault when cleaning up the typinfo singleton.  We need some
    // way to force new octave_value_X types that are created in
    // .oct files to be unregistered when the .oct file shared library
    // is unloaded.
    //
    // OCTAVE_SAFE_CALL (singleton_cleanup_list::cleanup, ());
  }

  void interpreter::execute_atexit_fcns (void)
  {
    // Prevent atexit functions from adding new functions to the list.
    m_executing_atexit = true;

    while (! m_atexit_fcns.empty ())
      {
        std::string fcn = m_atexit_fcns.front ();

        m_atexit_fcns.pop_front ();

        OCTAVE_SAFE_CALL (feval, (fcn, octave_value_list (), 0));

        OCTAVE_SAFE_CALL (flush_stdout, ());
      }
  }

  void interpreter::display_startup_message (void) const
  {
    bool inhibit_startup_message = false;

    if (m_app_context)
      {
        const cmdline_options& options = m_app_context->options ();

        inhibit_startup_message = options.inhibit_startup_message ();
      }

    if (m_interactive && ! inhibit_startup_message)
      std::cout << octave_startup_message () << "\n" << std::endl;
  }

  // Initialize by reading startup files.  Return non-zero if an exception
  // occurs when reading any of them, but don't exit early because of an
  // exception.

  int interpreter::execute_startup_files (void)
  {
    bool read_site_files = m_read_site_files;
    bool read_init_files = m_read_init_files;
    bool verbose = m_verbose;
    bool inhibit_startup_message = m_inhibit_startup_message;

    if (m_app_context)
      {
        const cmdline_options& options = m_app_context->options ();

        read_site_files = options.read_site_files ();
        read_init_files = options.read_init_files ();
        verbose = options.verbose_flag ();
        inhibit_startup_message = options.inhibit_startup_message ();
      }

    verbose = (verbose && ! inhibit_startup_message);

    bool require_file = false;

    std::string context;

    int exit_status = 0;

    if (read_site_files)
      {
        // Execute commands from the site-wide configuration file.
        // First from the file $(prefix)/lib/octave/site/m/octaverc
        // (if it exists), then from the file
        // $(prefix)/share/octave/$(version)/m/octaverc (if it exists).

        int status = safe_source_file (config::local_site_defaults_file (),
                                       context, verbose, require_file);

        if (status)
          exit_status = status;

        status = safe_source_file (config::site_defaults_file (),
                                   context, verbose, require_file);

        if (status)
          exit_status = status;
      }

    if (read_init_files)
      {
        // Try to execute commands from the Matlab compatible startup.m file
        // if it exists anywhere in the load path when starting Octave.
        std::string ff_startup_m = file_in_path ("startup.m", "");

        if (! ff_startup_m.empty ())
          {
            int parse_status = 0;

            try
              {
                eval_string (std::string ("startup"), false, parse_status, 0);
              }
            catch (const interrupt_exception&)
              {
                recover_from_exception ();
              }
            catch (const execution_exception& e)
              {
                handle_exception (e);
              }
          }

        // Try to execute commands from $CONFIG/octave/octaverc, where
        // $CONFIG is the platform-dependent location for user local
        // configuration files.

        std::string user_config_dir = sys::env::get_user_config_directory ();

        std::string cfg_dir = user_config_dir + sys::file_ops::dir_sep_str ()
                              + "octave";

        std::string cfg_rc = sys::env::make_absolute ("octaverc", cfg_dir);

        if (! cfg_rc.empty ())
          {
            int status = safe_source_file (cfg_rc, context, verbose,
                                           require_file);

            if (status)
              exit_status = status;
          }

        // Try to execute commands from $HOME/$OCTAVE_INITFILE and
        // $OCTAVE_INITFILE.  If $OCTAVE_INITFILE is not set,
        // .octaverc is assumed.

        bool home_rc_already_executed = false;

        std::string initfile = sys::env::getenv ("OCTAVE_INITFILE");

        if (initfile.empty ())
          initfile = ".octaverc";

        std::string home_dir = sys::env::get_home_directory ();

        std::string home_rc = sys::env::make_absolute (initfile, home_dir);

        std::string local_rc;

        if (! home_rc.empty ())
          {
            int status = safe_source_file (home_rc, context, verbose,
                                           require_file);

            if (status)
              exit_status = status;

            // Names alone are not enough.

            sys::file_stat fs_home_rc (home_rc);

            if (fs_home_rc)
              {
                // We want to check for curr_dir after executing home_rc
                // because doing that may change the working directory.

                local_rc = sys::env::make_absolute (initfile);

                home_rc_already_executed = same_file (home_rc, local_rc);
              }
          }

        if (! home_rc_already_executed)
          {
            if (local_rc.empty ())
              local_rc = sys::env::make_absolute (initfile);

            int status = safe_source_file (local_rc, context, verbose,
                                           require_file);

            if (status)
              exit_status = status;
          }
      }

    if (m_interactive && verbose)
      std::cout << std::endl;

    return exit_status;
  }

  // Execute any code specified with --eval 'CODE'

  int interpreter::execute_eval_option_code (void)
  {
    if (! m_app_context)
      return 0;

    const cmdline_options& options = m_app_context->options ();

    std::string code_to_eval = options.code_to_eval ();

    unwind_protect_var<bool> upv (m_interactive, false);

    int parse_status = 0;

    try
      {
        eval_string (code_to_eval, false, parse_status, 0);
      }
    catch (const interrupt_exception&)
      {
        recover_from_exception ();

        return 1;
      }
    catch (const execution_exception& e)
      {
        handle_exception (e);

        return 1;
      }

    return parse_status;
  }

  int interpreter::execute_command_line_file (void)
  {
    if (! m_app_context)
      return 0;

    const cmdline_options& options = m_app_context->options ();

    unwind_protect frame;

    frame.add_method (this, &interpreter::interactive, m_interactive);

    string_vector args = options.all_args ();

    frame.add_method (m_app_context, &application::intern_argv, args);

    frame.add_method (this, &interpreter::intern_nargin, args.numel () - 1);

    frame.add_method (m_app_context,
                      &application::program_invocation_name,
                      application::program_invocation_name ());

    frame.add_method (m_app_context,
                      &application::program_name,
                      application::program_name ());

    m_interactive = false;

    // If we are running an executable script (#! /bin/octave) then
    // we should only see the args passed to the script.

    string_vector script_args = options.remaining_args ();

    m_app_context->intern_argv (script_args);
    intern_nargin (script_args.numel () - 1);

    std::string fname = script_args[0];

    m_app_context->set_program_names (fname);

    std::string context;
    bool verbose = false;
    bool require_file = true;

    return safe_source_file (fname, context, verbose, require_file);
  }

  int interpreter::main_loop (void)
  {
    // The big loop.  Read, Eval, Print, Loop.  Normally user
    // interaction at the command line in a terminal session, but we may
    // also end up here when reading from a pipe or when stdin is
    // connected to a file by the magic of input redirection.

    int exit_status = 0;

    // FIXME: should this choice be a command-line option?  Note that we
    // intend that the push parser interface only be used for
    // interactive sessions.

#if defined (OCTAVE_ENABLE_COMMAND_LINE_PUSH_PARSER)
    static bool use_command_line_push_parser = true;
#else
    static bool use_command_line_push_parser = false;
#endif

    // The following logic is written as it is to allow easy transition
    // to setting USE_COMMAND_LINE_PUSH_PARSER at run time and to
    // simplify the logic of the main loop below by using the same
    // base_parser::run interface for both push and pull parsers.

    std::shared_ptr<base_parser> repl_parser;

    if (m_interactive)
      {
        if (use_command_line_push_parser)
          {
            push_parser *pp = new push_parser (*this, new input_reader (*this));
            repl_parser = std::shared_ptr<base_parser> (pp);
          }
        else
          {
            parser *pp = new parser (new lexer (*this));
            repl_parser = std::shared_ptr<base_parser> (pp);
          }
      }
    else
      {
        parser *pp = new parser (new lexer (stdin, *this));
        repl_parser = std::shared_ptr<base_parser> (pp);
      }

    do
      {
        try
          {
            unwind_protect_var<bool> upv (m_in_top_level_repl, true);

            repl_parser->reset ();

            if (m_evaluator.at_top_level ())
              {
                m_evaluator.dbstep_flag (0);
                m_evaluator.reset_debug_state ();
              }

            exit_status = repl_parser->run ();

            if (exit_status == 0)
              {
                std::shared_ptr<tree_statement_list>
                  stmt_list = repl_parser->statement_list ();

                if (stmt_list)
                  {
                    command_editor::increment_current_command_number ();

                    m_evaluator.eval (stmt_list, m_interactive);
                  }
                else if (repl_parser->at_end_of_input ())
                  {
                    exit_status = EOF;
                    break;
                  }
              }
          }
        catch (const interrupt_exception&)
          {
            recover_from_exception ();

            // Required newline when the user does Ctrl+C at the prompt.
            if (m_interactive)
              octave_stdout << "\n";
          }
        catch (const index_exception& e)
          {
            recover_from_exception ();

            std::cerr << "error: unhandled index exception: "
                      << e.message () << " -- trying to return to prompt"
                      << std::endl;
          }
        catch (const execution_exception& ee)
          {
            m_error_system.save_exception (ee);
            m_error_system.display_exception (ee, std::cerr);

            if (m_interactive)
              recover_from_exception ();
            else
              {
                // We should exit with a nonzero status.
                exit_status = 1;
                break;
              }
          }
        catch (const std::bad_alloc&)
          {
            recover_from_exception ();

            std::cerr << "error: out of memory -- trying to return to prompt"
                      << std::endl;
          }
      }
    while (exit_status == 0);

    if (exit_status == EOF)
      {
        if (m_interactive)
          octave_stdout << "\n";

        exit_status = 0;
      }

    return exit_status;
  }

  tree_evaluator& interpreter::get_evaluator (void)
  {
    return m_evaluator;
  }

  stream_list& interpreter::get_stream_list (void)
  {
    return m_stream_list;
  }

  url_handle_manager& interpreter::get_url_handle_manager (void)
  {
    return m_url_handle_manager;
  }

  symbol_scope
  interpreter::get_top_scope (void) const
  {
    return m_evaluator.get_top_scope ();
  }

  symbol_scope
  interpreter::get_current_scope (void) const
  {
    return m_evaluator.get_current_scope ();
  }

  symbol_scope
  interpreter::require_current_scope (const std::string& who) const
  {
    symbol_scope scope = get_current_scope ();

    if (! scope)
      error ("%s: symbol table scope missing", who.c_str ());

    return scope;
  }

  profiler& interpreter::get_profiler (void)
  {
    return m_evaluator.get_profiler ();
  }

  int interpreter::chdir (const std::string& dir)
  {
    std::string xdir = sys::file_ops::tilde_expand (dir);

    int cd_ok = sys::env::chdir (xdir);

    if (! cd_ok)
      error ("%s: %s", dir.c_str (), std::strerror (errno));

    Vlast_chdir_time.stamp ();

    // FIXME: should these actions be handled as a list of functions
    // to call so users can add their own chdir handlers?

    m_load_path.update ();

    m_event_manager.directory_changed (sys::env::get_current_directory ());

    return cd_ok;
  }

  void interpreter::mlock (bool skip_first) const
  {
    m_evaluator.mlock (skip_first);
  }

  void interpreter::munlock (bool skip_first) const
  {
    m_evaluator.munlock (skip_first);
  }

  bool interpreter::mislocked (bool skip_first) const
  {
    return m_evaluator.mislocked (skip_first);
  }

  void interpreter::munlock (const char *nm)
  {
    if (! nm)
      error ("munlock: invalid value for NAME");

    munlock (std::string (nm));
  }

  void interpreter::munlock (const std::string& nm)
  {
    octave_value val = m_symbol_table.find_function (nm);

    if (val.is_defined ())
      {
        octave_function *fcn = val.function_value ();

        if (fcn)
          fcn->unlock ();
      }
  }

  bool interpreter::mislocked (const char *nm)
  {
    if (! nm)
      error ("mislocked: invalid value for NAME");

    return mislocked (std::string (nm));
  }

  bool interpreter::mislocked (const std::string& nm)
  {
    bool retval = false;

    octave_value val = m_symbol_table.find_function (nm);

    if (val.is_defined ())
      {
        octave_function *fcn = val.function_value ();

        if (fcn)
          retval = fcn->islocked ();
      }

    return retval;
  }

  std::string interpreter::mfilename (const std::string& opt) const
  {
    return m_evaluator.mfilename (opt);
  }

  octave_value_list interpreter::eval_string (const std::string& eval_str,
                                              bool silent, int& parse_status,
                                              int nargout)
  {
    return m_evaluator.eval_string (eval_str, silent, parse_status, nargout);
  }

  octave_value interpreter::eval_string (const std::string& eval_str,
                                         bool silent, int& parse_status)
  {
    return m_evaluator.eval_string (eval_str, silent, parse_status);
  }

  octave_value_list interpreter::eval_string (const octave_value& arg,
                                              bool silent, int& parse_status,
                                              int nargout)
  {
    return m_evaluator.eval_string (arg, silent, parse_status, nargout);
  }

  octave_value_list interpreter::eval (const std::string& try_code,
                                       int nargout)
  {
    return m_evaluator.eval (try_code, nargout);
  }

  octave_value_list interpreter::eval (const std::string& try_code,
                                       const std::string& catch_code,
                                       int nargout)
  {
    return m_evaluator.eval (try_code, catch_code, nargout);
  }

  octave_value_list interpreter::evalin (const std::string& context,
                                         const std::string& try_code,
                                         int nargout)
  {
    return m_evaluator.evalin (context, try_code, nargout);
  }

  octave_value_list interpreter::evalin (const std::string& context,
                                         const std::string& try_code,
                                         const std::string& catch_code,
                                         int nargout)
  {
    return m_evaluator.evalin (context, try_code, catch_code, nargout);
  }

  //! Evaluate an Octave function (built-in or interpreted) and return
  //! the list of result values.
  //!
  //! @param name The name of the function to call.
  //! @param args The arguments to the function.
  //! @param nargout The number of output arguments expected.
  //! @return A list of output values.  The length of the list is not
  //!         necessarily the same as @c nargout.

  octave_value_list interpreter::feval (const char *name,
                                        const octave_value_list& args,
                                        int nargout)
  {
    return feval (std::string (name), args, nargout);
  }

  octave_value_list interpreter::feval (const std::string& name,
                                        const octave_value_list& args,
                                        int nargout)
  {
    octave_value fcn = m_symbol_table.find_function (name, args);

    if (fcn.is_undefined ())
      error ("feval: function '%s' not found", name.c_str ());

    octave_function *of = fcn.function_value ();

    return of->call (m_evaluator, nargout, args);
  }

  octave_value_list interpreter::feval (octave_function *fcn,
                                        const octave_value_list& args,
                                        int nargout)
  {
    if (fcn)
      return fcn->call (m_evaluator, nargout, args);

    return octave_value_list ();
  }

  octave_value_list interpreter::feval (const octave_value& val,
                                        const octave_value_list& args,
                                        int nargout)
  {
    // FIXME: do we really want to silently return an empty ovl if
    // the function object is undefined?  It's essentially what the
    // version above that accepts a pointer to an octave_function
    // object does and some code was apparently written to rely on it
    // (for example, __ode15__).

    if (val.is_undefined ())
      return ovl ();

    if (val.is_function ())
      {
        return feval (val.function_value (), args, nargout);
      }
    else if (val.is_function_handle () || val.is_inline_function ())
      {
        // This covers function handles, inline functions, and anonymous
        //  functions.

        std::list<octave_value_list> arg_list;
        arg_list.push_back (args);

        // FIXME: could we make octave_value::subsref a const method?
        // It would be difficult because there are instances of
        // incrementing the reference count inside subsref methods,
        // which means they can't be const with the current way of
        // handling reference counting.

        octave_value xval = val;
        return xval.subsref ("(", arg_list, nargout);
      }
    else if (val.is_string ())
      {
        return feval (val.string_value (), args, nargout);
      }
    else
      error ("feval: first argument must be a string, inline function, or a function handle");

    return ovl ();
  }

  //! Evaluate an Octave function (built-in or interpreted) and return
  //! the list of result values.
  //!
  //! @param args The first element of @c args is the function to call.
  //!             It may be the name of the function as a string, a function
  //!             handle, or an inline function.  The remaining arguments are
  //!             passed to the function.
  //! @param nargout The number of output arguments expected.
  //! @return A list of output values.  The length of the list is not
  //!         necessarily the same as @c nargout.

  octave_value_list interpreter::feval (const octave_value_list& args,
                                        int nargout)
  {
    if (args.length () == 0)
      error ("feval: first argument must be a string, inline function, or a function handle");

    octave_value f_arg = args(0);

    octave_value_list tmp_args = args.slice (1, args.length () - 1, true);

    return feval (f_arg, tmp_args, nargout);
  }

  octave_value interpreter::make_function_handle (const std::string& name)
  {
    return m_evaluator.make_fcn_handle (name);
  }

  void interpreter::install_variable (const std::string& name,
                                      const octave_value& value, bool global)
  {
    m_evaluator.install_variable (name, value, global);
  }

  octave_value interpreter::global_varval (const std::string& name) const
  {
    return m_evaluator.global_varval (name);
  }

  void interpreter::global_assign (const std::string& name,
                                   const octave_value& val)
  {
    m_evaluator.global_assign (name, val);
  }

  octave_value interpreter::top_level_varval (const std::string& name) const
  {
    return m_evaluator.top_level_varval (name);
  }

  void interpreter::top_level_assign (const std::string& name,
                                      const octave_value& val)
  {
    m_evaluator.top_level_assign (name, val);
  }

  bool interpreter::is_variable (const std::string& name) const
  {
    return m_evaluator.is_variable (name);
  }

  bool interpreter::is_local_variable (const std::string& name) const
  {
    return m_evaluator.is_local_variable (name);
  }

  octave_value interpreter::varval (const std::string& name) const
  {
    return m_evaluator.varval (name);
  }

  void interpreter::assign (const std::string& name,
                            const octave_value& val)
  {
    m_evaluator.assign (name, val);
  }

  void interpreter::assignin (const std::string& context,
                              const std::string& name,
                              const octave_value& val)
  {
    m_evaluator.assignin (context, name, val);
  }

  void interpreter::source_file (const std::string& file_name,
                                 const std::string& context, bool verbose,
                                 bool require_file)
  {
    m_evaluator.source_file (file_name, context, verbose, require_file);
  }

  bool interpreter::at_top_level (void) const
  {
    return m_evaluator.at_top_level ();
  }

  bool interpreter::isglobal (const std::string& name) const
  {
    return m_evaluator.is_global (name);
  }

  octave_value interpreter::find (const std::string& name)
  {
    return m_evaluator.find (name);
  }

  void interpreter::clear_all (bool force)
  {
    m_evaluator.clear_all (force);
  }

  void interpreter::clear_objects (void)
  {
    m_evaluator.clear_objects ();
  }

  void interpreter::clear_variable (const std::string& name)
  {
    m_evaluator.clear_variable (name);
  }

  void interpreter::clear_variable_pattern (const std::string& pattern)
  {
    m_evaluator.clear_variable_pattern (pattern);
  }

  void interpreter::clear_variable_regexp (const std::string& pattern)
  {
    m_evaluator.clear_variable_regexp (pattern);
  }

  void interpreter::clear_variables (void)
  {
    m_evaluator.clear_variables ();
  }

  void interpreter::clear_global_variable (const std::string& name)
  {
    m_evaluator.clear_global_variable (name);
  }

  void interpreter::clear_global_variable_pattern (const std::string& pattern)
  {
    m_evaluator.clear_global_variable_pattern (pattern);
  }

  void interpreter::clear_global_variable_regexp (const std::string& pattern)
  {
    m_evaluator.clear_global_variable_regexp (pattern);
  }

  void interpreter::clear_global_variables (void)
  {
    m_evaluator.clear_global_variables ();
  }

  void interpreter::clear_functions (bool force)
  {
    m_symbol_table.clear_functions (force);
  }

  void interpreter::clear_function (const std::string& name)
  {
    m_symbol_table.clear_function (name);
  }

  void interpreter::clear_symbol (const std::string& name)
  {
    m_evaluator.clear_symbol (name);
  }

  void interpreter::clear_function_pattern (const std::string& pat)
  {
    m_symbol_table.clear_function_pattern (pat);
  }

  void interpreter::clear_function_regexp (const std::string& pat)
  {
    m_symbol_table.clear_function_regexp (pat);
  }

  void interpreter::clear_symbol_pattern (const std::string& pat)
  {
    return m_evaluator.clear_symbol_pattern (pat);
  }

  void interpreter::clear_symbol_regexp (const std::string& pat)
  {
    return m_evaluator.clear_symbol_regexp (pat);
  }

  std::list<std::string> interpreter::global_variable_names (void)
  {
    return m_evaluator.global_variable_names ();
  }

  std::list<std::string> interpreter::top_level_variable_names (void)
  {
    return m_evaluator.top_level_variable_names ();
  }

  std::list<std::string> interpreter::variable_names (void)
  {
    return m_evaluator.variable_names ();
  }

  std::list<std::string> interpreter::user_function_names (void)
  {
    return m_symbol_table.user_function_names ();
  }

  std::list<std::string> interpreter::autoloaded_functions (void) const
  {
    return m_evaluator.autoloaded_functions ();
  }

  void interpreter::handle_exception (const execution_exception& e)
  {
    m_error_system.save_exception (e);

    // FIXME: use a separate stream instead of std::cerr directly so that
    // error messages can be redirected more easily?  Pass the message
    // to an event manager function?
    m_error_system.display_exception (e, std::cerr);

    recover_from_exception ();
  }

  void interpreter::recover_from_exception (void)
  {
    can_interrupt = true;
    octave_interrupt_state = 0;
    octave_signal_caught = 0;
    octave_restore_signal_mask ();
    catch_interrupts ();
  }

  void interpreter::mark_for_deletion (const std::string& file)
  {
    m_tmp_files.insert (file);
  }

  void interpreter::cleanup_tmp_files (void)
  {
    m_tmp_files.cleanup ();
  }

  void interpreter::quit (int exit_status, bool force, bool confirm)
  {
    if (! force)
      {
        try
          {
            bool cancel = false;

            if (symbol_exist ("finish.m", "file"))
              {
                unwind_protect_var<bool> upv1 (m_executing_finish_script, true);
                unwind_protect_var<bool> upv2 (m_cancel_quit);

                evalin ("base", "finish", 0);

                cancel = m_cancel_quit;
              }

            if (cancel)
              return;

            // Check for confirmation.

            if (confirm && ! m_event_manager.confirm_shutdown ())
              return;
          }
        catch (const execution_exception&)
          {
            // Catch execution_exceptions so we don't throw an
            // exit_exception if there is an in finish.m.  But throw it
            // again so that will be handled as any other
            // execution_exception by the evaluator.  This way, errors
            // will be ignored properly and we won't exit if quit is
            // called recursively from finish.m.

            throw;
          }
      }

    throw exit_exception (exit_status);
  }

  void interpreter::add_atexit_fcn (const std::string& fname)
  {
    if (m_executing_atexit)
      return;

    m_atexit_fcns.push_front (fname);
  }

  bool interpreter::remove_atexit_fcn (const std::string& fname)
  {
    bool found = false;

    for (auto it = m_atexit_fcns.begin ();
         it != m_atexit_fcns.end (); it++)
      {
        if (*it == fname)
          {
            m_atexit_fcns.erase (it);
            found = true;
            break;
          }
      }

    return found;
  }

  void interpreter::add_atexit_function (const std::string& fname)
  {
    interpreter& interp
      = __get_interpreter__ ("interpreter::add_atexit_function");

    interp.add_atexit_fcn (fname);
  }

  bool interpreter::remove_atexit_function (const std::string& fname)
  {
    interpreter& interp
      = __get_interpreter__ ("interpreter::remove_atexit_function");

    return interp.remove_atexit_fcn (fname);
  }

  // What internal options get configured by --traditional.

  void interpreter::maximum_braindamage (void)
  {
    m_input_system.PS1 (">> ");
    m_input_system.PS2 ("");

    m_evaluator.PS4 ("");

    m_load_save_system.crash_dumps_octave_core (false);
    m_load_save_system.save_default_options ("-mat-binary");

    m_history_system.timestamp_format_string ("%%-- %D %I:%M %p --%%");

    m_error_system.beep_on_error (true);
    Fconfirm_recursive_rmdir (octave_value (false));

    Fdisable_diagonal_matrix (octave_value (true));
    Fdisable_permutation_matrix (octave_value (true));
    Fdisable_range (octave_value (true));
    Ffixed_point_format (octave_value (true));
    Fprint_empty_dimensions (octave_value (false));
    Fstruct_levels_to_print (octave_value (0));

    disable_warning ("Octave:abbreviated-property-match");
    disable_warning ("Octave:colon-nonscalar-argument");
    disable_warning ("Octave:data-file-in-path");
    disable_warning ("Octave:function-name-clash");
    disable_warning ("Octave:possible-matlab-short-circuit-operator");
  }

  void interpreter::execute_pkg_add (const std::string& dir)
  {
    try
      {
        m_load_path.execute_pkg_add (dir);
      }
    catch (const interrupt_exception&)
      {
        recover_from_exception ();
      }
    catch (const execution_exception& e)
      {
        handle_exception (e);
      }
  }
}