GNU Octave  4.4.1
A high-level interpreted language, primarily intended for numerical computations, mostly compatible with Matlab
interpreter.cc
Go to the documentation of this file.
1 /*
2 
3 Copyright (C) 1993-2018 John W. Eaton
4 
5 This file is part of Octave.
6 
7 Octave is free software: you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11 
12 Octave is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16 
17 You should have received a copy of the GNU General Public License
18 along with Octave; see the file COPYING. If not, see
19 <https://www.gnu.org/licenses/>.
20 
21 */
22 
23 #if defined (HAVE_CONFIG_H)
24 # include "config.h"
25 #endif
26 
27 #include <string>
28 #include <iostream>
29 
30 #include "cmd-edit.h"
31 #include "cmd-hist.h"
32 #include "file-ops.h"
33 #include "file-stat.h"
34 #include "fpucw-wrappers.h"
35 #include "lo-blas-proto.h"
36 #include "lo-error.h"
37 #include "oct-env.h"
38 #include "str-vec.h"
39 #include "signal-wrappers.h"
40 #include "unistd-wrappers.h"
41 
42 #include "builtin-defun-decls.h"
43 #include "defaults.h"
44 #include "Cell.h"
45 #include "call-stack.h"
46 #include "defun.h"
47 #include "display.h"
48 #include "error.h"
49 #include "file-io.h"
50 #include "graphics.h"
51 #include "help.h"
52 #include "interpreter-private.h"
53 #include "interpreter.h"
54 #include "load-path.h"
55 #include "load-save.h"
56 #include "octave-link.h"
57 #include "octave.h"
58 #include "oct-hist.h"
59 #include "oct-map.h"
60 #include "oct-mutex.h"
61 #include "ovl.h"
62 #include "ov.h"
63 #include "ov-classdef.h"
64 #include "parse.h"
65 #include "pt-eval.h"
66 #include "pt-jump.h"
67 #include "pt-mat.h"
68 #include "pt-stmt.h"
69 #include "sighandlers.h"
70 #include "sysdep.h"
71 #include "unwind-prot.h"
72 #include "utils.h"
73 #include "variables.h"
74 #include "version.h"
75 
76 // TRUE means the quit() call is allowed.
77 bool quit_allowed = true;
78 
79 // TRUE means we are ready to interpret commands, but not everything
80 // is ready for interactive use.
82 
83 // TRUE means we've processed all the init code and we are good to go.
84 bool octave_initialized = false;
85 
86 DEFUN (__version_info__, args, ,
87  doc: /* -*- texinfo -*-
88 @deftypefn {} {retval =} __version_info__ (@var{name}, @var{version}, @var{release}, @var{date})
89 Undocumented internal function.
90 @end deftypefn */)
91 {
92  static octave_map vinfo;
93 
94  int nargin = args.length ();
95 
96  if (nargin != 0 && nargin != 4)
97  print_usage ();
98 
100 
101  if (nargin == 0)
102  retval = vinfo;
103  else if (nargin == 4)
104  {
105  if (vinfo.nfields () == 0)
106  {
107  vinfo.assign ("Name", args(0));
108  vinfo.assign ("Version", args(1));
109  vinfo.assign ("Release", args(2));
110  vinfo.assign ("Date", args(3));
111  }
112  else
113  {
114  octave_idx_type n = vinfo.numel () + 1;
115 
116  vinfo.resize (dim_vector (n, 1));
117 
118  octave_value idx (n);
119 
120  vinfo.assign (idx, "Name", Cell (octave_value (args(0))));
121  vinfo.assign (idx, "Version", Cell (octave_value (args(1))));
122  vinfo.assign (idx, "Release", Cell (octave_value (args(2))));
123  vinfo.assign (idx, "Date", Cell (octave_value (args(3))));
124  }
125  }
126 
127  return retval;
128 }
129 
130 DEFUN (quit, args, ,
131  doc: /* -*- texinfo -*-
132 @deftypefn {} {} exit
133 @deftypefnx {} {} exit (@var{status})
134 @deftypefnx {} {} quit
135 @deftypefnx {} {} quit (@var{status})
136 Exit the current Octave session.
137 
138 If the optional integer value @var{status} is supplied, pass that value to
139 the operating system as Octave's exit status. The default value is zero.
140 
141 When exiting, Octave will attempt to run the m-file @file{finish.m} if it
142 exists. User commands to save the workspace or clean up temporary files
143 may be placed in that file. Alternatively, another m-file may be scheduled
144 to run using @code{atexit}.
145 @seealso{atexit}
146 @end deftypefn */)
147 {
148  // Confirm OK to shutdown. Note: A dynamic function installation similar
149  // to overriding polymorphism for which the GUI can install its own "quit"
150  // yet call this base "quit" could be nice. No link would be needed here.
152  return ovl ();
153 
154  if (! quit_allowed)
155  error ("quit: not supported in embedded mode");
156 
157  int exit_status = 0;
158 
159  if (args.length () > 0)
160  exit_status = args(0).nint_value ();
161 
162  // Instead of simply calling exit, we thrown an exception so that no
163  // matter where the call to quit occurs, we will run the
164  // unwind_protect stack, clear the OCTAVE_LOCAL_BUFFER allocations,
165  // etc. before exiting.
166 
167  throw octave::exit_exception (exit_status);
168 
169  return ovl ();
170 }
171 
172 DEFALIAS (exit, quit);
173 
174 DEFUN (atexit, args, nargout,
175  doc: /* -*- texinfo -*-
176 @deftypefn {} {} atexit (@var{fcn})
177 @deftypefnx {} {} atexit (@var{fcn}, @var{flag})
178 Register a function to be called when Octave exits.
179 
180 For example,
181 
182 @example
183 @group
184 function last_words ()
185  disp ("Bye bye");
186 endfunction
187 atexit ("last_words");
188 @end group
189 @end example
190 
191 @noindent
192 will print the message @qcode{"Bye bye"} when Octave exits.
193 
194 The additional argument @var{flag} will register or unregister @var{fcn}
195 from the list of functions to be called when Octave exits. If @var{flag} is
196 true, the function is registered, and if @var{flag} is false, it is
197 unregistered. For example, after registering the function @code{last_words}
198 above,
199 
200 @example
201 atexit ("last_words", false);
202 @end example
203 
204 @noindent
205 will remove the function from the list and Octave will not call
206 @code{last_words} when it exits.
207 
208 Note that @code{atexit} only removes the first occurrence of a function
209 from the list, so if a function was placed in the list multiple times with
210 @code{atexit}, it must also be removed from the list multiple times.
211 @seealso{quit}
212 @end deftypefn */)
213 {
214  int nargin = args.length ();
215 
217  print_usage ();
218 
219  std::string arg = args(0).xstring_value ("atexit: FCN argument must be a string");
220 
221  bool add_mode = (nargin == 2)
222  ? args(1).xbool_value ("atexit: FLAG argument must be a logical value")
223  : true;
224 
226 
227  if (add_mode)
229  else
230  {
232 
233  if (nargout > 0)
234  retval = ovl (found);
235  }
236 
237  return retval;
238 }
239 
240 namespace octave
241 {
242  // Execute commands from a file and catch potential exceptions in a consistent
243  // way. This function should be called anywhere we might parse and execute
244  // commands from a file before we have entered the main loop in
245  // toplev.cc.
246 
247  static int safe_source_file (const std::string& file_name,
248  const std::string& context = "",
249  bool verbose = false,
250  bool require_file = true,
251  const std::string& warn_for = "")
252  {
253  try
254  {
255  source_file (file_name, context, verbose, require_file, warn_for);
256  }
257  catch (const interrupt_exception&)
258  {
260 
261  return 1;
262  }
263  catch (const execution_exception& e)
264  {
265  std::string stack_trace = e.info ();
266 
267  if (! stack_trace.empty ())
268  std::cerr << stack_trace;
269 
271 
272  return 1;
273  }
274 
275  return 0;
276  }
277 
278  static void execute_pkg_add (const std::string& dir)
279  {
280  std::string file_name = sys::file_ops::concat (dir, "PKG_ADD");
281 
282  load_path& lp = __get_load_path__ ("execute_pkg_add");
283 
284  try
285  {
286  lp.execute_pkg_add (dir);
287  }
288  catch (const interrupt_exception&)
289  {
291  }
292  catch (const execution_exception&)
293  {
295  }
296  }
297 
298  static void initialize_version_info (void)
299  {
300  octave_value_list args;
301 
302  args(3) = OCTAVE_RELEASE_DATE;
303  args(2) = config::release ();
304  args(1) = OCTAVE_VERSION;
305  args(0) = "GNU Octave";
306 
307  F__version_info__ (args, 0);
308  }
309 
310  static void xerbla_abort (void)
311  {
312  error ("Fortran procedure terminated by call to XERBLA");
313  }
314 
315  static void initialize_xerbla_error_handler (void)
316  {
317  // The idea here is to force xerbla to be referenced so that we will
318  // link to our own version instead of the one provided by the BLAS
319  // library. But numeric_limits<double>::NaN () should never be -1, so
320  // we should never actually call xerbla. FIXME (again!): If this
321  // becomes a constant expression the test might be optimized away and
322  // then the reference to the function might also disappear.
323 
324  if (numeric_limits<double>::NaN () == -1)
325  F77_FUNC (xerbla, XERBLA) ("octave", 13 F77_CHAR_ARG_LEN (6));
326 
327  typedef void (*xerbla_handler_ptr) (void);
328 
329  typedef void (*octave_set_xerbla_handler_ptr) (xerbla_handler_ptr);
330 
331  dynamic_library libs ("");
332 
333  if (libs)
334  {
335  octave_set_xerbla_handler_ptr octave_set_xerbla_handler
336  = reinterpret_cast<octave_set_xerbla_handler_ptr>
337  (libs.search ("octave_set_xerbla_handler"));
338 
340  octave_set_xerbla_handler (xerbla_abort);
341  }
342  }
343 
344  OCTAVE_NORETURN static void
345  lo_error_handler (const char *fmt, ...)
346  {
347  va_list args;
348  va_start (args, fmt);
349  verror_with_cfn (fmt, args);
350  va_end (args);
351 
353  }
354 
355  OCTAVE_NORETURN static void
356  lo_error_with_id_handler (const char *id, const char *fmt, ...)
357  {
358  va_list args;
359  va_start (args, fmt);
360  verror_with_id_cfn (id, fmt, args);
361  va_end (args);
362 
364  }
365 
366  static void initialize_error_handlers (void)
367  {
368  set_liboctave_error_handler (lo_error_handler);
369  set_liboctave_error_with_id_handler (lo_error_with_id_handler);
372  }
373 
374  // Create an interpreter object and perform initialization up to the
375  // point of setting reading command history and setting the load
376  // path.
377 
379  : m_app_context (app_context),
380  m_environment (),
381  m_help_system (*this),
382  m_dynamic_loader (*this),
383  m_load_path (),
384  m_type_info (),
385  m_symbol_table (),
386  m_evaluator (*this),
387  m_bp_table (),
388  m_stream_list (*this),
389  m_child_list (),
390  m_url_handle_manager (),
391  m_cdef_manager (*this),
392  m_gtk_manager (),
393  m_interactive (false),
394  m_read_site_files (true),
395  m_read_init_files (m_app_context != nullptr),
396  m_verbose (false),
397  m_inhibit_startup_message (false),
398  m_load_path_initialized (false),
399  m_history_initialized (false),
400  m_initialized (false)
401  {
402  // FIXME: When thread_local storage is used by default, this message
403  // should change to say something like
404  //
405  // only one Octave interpreter may be active in any given thread
406 
407  if (instance)
408  throw std::runtime_error
409  ("only one Octave interpreter may be active");
410 
411  instance = this;
412 
413  // Matlab uses "C" locale for LC_NUMERIC class regardless of local setting
414  setlocale (LC_NUMERIC, "C");
415  setlocale (LC_TIME, "C");
416  sys::env::putenv ("LC_NUMERIC", "C");
417  sys::env::putenv ("LC_TIME", "C");
418 
419  // Initialize the default floating point unit control state.
421 
422  thread::init ();
423 
425 
426  // Initialize default warning state before --traditional option
427  // that may reset them.
428 
430 
431  octave_ieee_init ();
432 
434 
435  initialize_xerbla_error_handler ();
436 
437  initialize_error_handlers ();
438 
439  if (m_app_context)
441  else
442  quit_allowed = false;
443 
444  bool line_editing = false;
445  bool traditional = false;
446 
447  if (m_app_context)
448  {
449  // Embedded interpeters don't execute command line options.
450  const cmdline_options& options = m_app_context->options ();
451 
452  // Make all command-line arguments available to startup files,
453  // including PKG_ADD files.
454 
455  string_vector args = options.all_args ();
456 
457  m_app_context->intern_argv (args);
458  intern_nargin (args.numel () - 1);
459 
460  bool is_octave_program = m_app_context->is_octave_program ();
461 
462  std::list<std::string> command_line_path = options.command_line_path ();
463 
464  for (const auto& pth : command_line_path)
465  m_load_path.set_command_line_path (pth);
466 
467  std::string exec_path = options.exec_path ();
468  if (! exec_path.empty ())
469  m_environment.exec_path (exec_path);
470 
471  std::string image_path = options.image_path ();
472  if (! image_path.empty ())
473  m_environment.image_path (image_path);
474 
475  if (options.no_window_system ())
476  display_info::no_window_system ();
477 
478  // Is input coming from a terminal? If so, we are probably
479  // interactive.
480 
481  // If stdin is not a tty, then we are reading commands from a
482  // pipe or a redirected file.
483  bool stdin_is_tty = octave_isatty_wrapper (fileno (stdin));
484 
485  m_interactive = (! is_octave_program && stdin_is_tty
486  && octave_isatty_wrapper (fileno (stdout)));
487 
488  // Check if the user forced an interactive session.
489  if (options.forced_interactive ())
490  m_interactive = true;
491 
492  line_editing = options.line_editing ();
493  if ((! m_interactive || options.forced_interactive ())
494  && ! options.forced_line_editing ())
495  line_editing = false;
496 
497  traditional = options.traditional ();
498 
499  // FIXME: if possible, perform the following actions directly
500  // instead of using the interpreter-level functions.
501 
502  if (options.echo_commands ())
503  m_evaluator.echo
504  (tree_evaluator::ECHO_SCRIPTS | tree_evaluator::ECHO_FUNCTIONS
505  | tree_evaluator::ECHO_ALL);
506 
507  std::string docstrings_file = options.docstrings_file ();
508  if (! docstrings_file.empty ())
509  Fbuilt_in_docstrings_file (*this, octave_value (docstrings_file));
510 
511  std::string doc_cache_file = options.doc_cache_file ();
512  if (! doc_cache_file.empty ())
513  Fdoc_cache_file (*this, octave_value (doc_cache_file));
514 
515  std::string info_file = options.info_file ();
516  if (! info_file.empty ())
517  Finfo_file (*this, octave_value (info_file));
518 
519  std::string info_program = options.info_program ();
520  if (! info_program.empty ())
521  Finfo_program (*this, octave_value (info_program));
522 
523  if (options.debug_jit ())
524  Fdebug_jit (octave_value (true));
525 
526  if (options.jit_compiler ())
527  Fjit_enable (octave_value (true));
528 
529  std::string texi_macros_file = options.texi_macros_file ();
530  if (! texi_macros_file.empty ())
531  Ftexi_macros_file (*this, octave_value (texi_macros_file));
532  }
533 
534  // Force default line editor if we don't want readline editing.
535  if (line_editing)
537  else
538  command_editor::force_default_editor ();
539 
540  // These can come after command line args since none of them set any
541  // defaults that might be changed by command line options.
542 
543  initialize_version_info ();
544 
545  // This should be done before initializing the load path because
546  // some PKG_ADD files might need --traditional behavior.
547 
548  if (traditional)
549  maximum_braindamage ();
550 
552  }
553 
554  OCTAVE_THREAD_LOCAL interpreter *interpreter::instance = nullptr;
555 
556  interpreter::~interpreter (void)
557  {
558  cleanup ();
559  }
560 
561  void interpreter::intern_nargin (octave_idx_type nargs)
562  {
563  // FIXME: should this explicitly be top_scope?
564  symbol_scope scope = m_symbol_table.current_scope ();
565 
566  if (scope)
567  {
568  scope.assign (".nargin.", nargs);
569  scope.mark_hidden (".nargin.");
570  }
571  }
572 
573  // Read the history file unless a command-line option inhibits that.
574 
575  void interpreter::initialize_history (bool read_history_file)
576  {
577  if (! m_history_initialized)
578  {
579  // Allow command-line option to override.
580 
581  if (m_app_context)
582  {
583  const cmdline_options& options = m_app_context->options ();
584 
585  read_history_file = options.read_history_file ();
586 
587  if (! read_history_file)
588  command_history::ignore_entries ();
589  }
590 
591  ::initialize_history (read_history_file);
592 
593  if (! m_app_context)
594  command_history::ignore_entries ();
595 
596  m_history_initialized = true;
597  }
598  }
599 
600  // Set the initial path to the system default unless command-line
601  // option says to leave it empty.
602 
603  void interpreter::initialize_load_path (bool set_initial_path)
604  {
605  if (! m_load_path_initialized)
606  {
607  // Allow command-line option to override.
608 
609  if (m_app_context)
610  {
611  const cmdline_options& options = m_app_context->options ();
612 
613  set_initial_path = options.set_initial_path ();
614  }
615 
616  // Temporarily set the execute_pkg_add function to one that
617  // catches exceptions. This is better than wrapping
618  // load_path::initialize in a try-catch block because it will
619  // not stop executing PKG_ADD files at the first exception.
620  // It's also better than changing the default execute_pkg_add
621  // function to use safe_source file because that will normally
622  // be evaluated from the normal intepreter loop where exceptions
623  // are already handled.
624 
625  unwind_protect frame;
626 
627  frame.add_method (m_load_path, &load_path::set_add_hook,
628  m_load_path.get_add_hook ());
629 
630  m_load_path.set_add_hook (execute_pkg_add);
631 
632  m_load_path.initialize (set_initial_path);
633 
634  m_load_path_initialized = true;
635  }
636  }
637 
638  // This may be called separately from execute
639 
640  void interpreter::initialize (void)
641  {
642  if (m_initialized)
643  return;
644 
645  display_startup_message ();
646 
647  // Wait to read the history file until the interpreter reads input
648  // files and begins evaluating commands.
649 
651 
652  // Initializing the load path may execute PKG_ADD files, so can't be
653  // done until the interpreter is ready to execute commands.
654 
655  // Deferring it to the execute step also allows the path to be
656  // initialized between creating and execute the interpreter, for
657  // example, to set a custom path for an embedded interpreter.
658 
659  initialize_load_path ();
660 
661  m_initialized = true;
662  }
663 
664  // FIXME: this function is intended to be executed only once. Should
665  // we enforce that restriction?
666 
667  int interpreter::execute (void)
668  {
669  try
670  {
671  initialize ();
672 
673  // We ignore errors in startup files.
674 
675  execute_startup_files ();
676 
677  int exit_status = 0;
678 
679  if (m_app_context)
680  {
681  const cmdline_options& options = m_app_context->options ();
682 
683  if (m_app_context->have_eval_option_code ())
684  {
685  int status = execute_eval_option_code ();
686 
687  if (status )
688  exit_status = status;
689 
690  if (! options.persist ())
691  return exit_status;
692  }
693 
694  // If there is an extra argument, see if it names a file to
695  // read. Additional arguments are taken as command line options
696  // for the script.
697 
698  if (m_app_context->have_script_file ())
699  {
700  int status = execute_command_line_file ();
701 
702  if (status)
703  exit_status = status;
704 
705  if (! options.persist ())
706  return exit_status;
707  }
708 
709  if (options.forced_interactive ())
710  command_editor::blink_matching_paren (false);
711  }
712 
713  // Avoid counting commands executed from startup or script files.
714 
715  command_editor::reset_current_command_number (1);
716 
717  return main_loop ();
718  }
719  catch (const exit_exception& ex)
720  {
721  return ex.exit_status ();
722  }
723  }
724 
725  void interpreter::display_startup_message (void) const
726  {
727  bool inhibit_startup_message = false;
728 
729  if (m_app_context)
730  {
731  const cmdline_options& options = m_app_context->options ();
732 
733  inhibit_startup_message = options.inhibit_startup_message ();
734  }
735 
736  if (m_interactive && ! inhibit_startup_message)
737  std::cout << octave_startup_message () << "\n" << std::endl;
738  }
739 
740  // Initialize by reading startup files. Return non-zero if an exception
741  // occurs when reading any of them, but don't exit early because of an
742  // exception.
743 
744  int interpreter::execute_startup_files (void) const
745  {
746  bool read_site_files = m_read_site_files;
747  bool read_init_files = m_read_init_files;
748  bool verbose = m_verbose;
749  bool inhibit_startup_message = m_inhibit_startup_message;
750 
751  if (m_app_context)
752  {
753  const cmdline_options& options = m_app_context->options ();
754 
755  read_site_files = options.read_site_files ();
756  read_init_files = options.read_init_files ();
757  verbose = options.verbose_flag ();
758  inhibit_startup_message = options.inhibit_startup_message ();
759  }
760 
761  verbose = (verbose && ! inhibit_startup_message);
762 
763  bool require_file = false;
764 
766 
767  int exit_status = 0;
768 
769  if (read_site_files)
770  {
771  // Execute commands from the site-wide configuration file.
772  // First from the file $(prefix)/lib/octave/site/m/octaverc
773  // (if it exists), then from the file
774  // $(prefix)/share/octave/$(version)/m/octaverc (if it exists).
775 
776  int status = safe_source_file (config::local_site_defaults_file (),
777  context, verbose, require_file);
778 
779  if (status)
780  exit_status = status;
781 
782  status = safe_source_file (config::site_defaults_file (),
783  context, verbose, require_file);
784 
785  if (status)
786  exit_status = status;
787  }
788 
789  if (read_init_files)
790  {
791  // Try to execute commands from $HOME/$OCTAVE_INITFILE and
792  // $OCTAVE_INITFILE. If $OCTAVE_INITFILE is not set,
793  // .octaverc is assumed.
794 
795  bool home_rc_already_executed = false;
796 
797  std::string initfile = sys::env::getenv ("OCTAVE_INITFILE");
798 
799  if (initfile.empty ())
800  initfile = ".octaverc";
801 
802  std::string home_dir = sys::env::get_home_directory ();
803 
804  std::string home_rc = sys::env::make_absolute (initfile, home_dir);
805 
806  std::string local_rc;
807 
808  if (! home_rc.empty ())
809  {
810  int status = safe_source_file (home_rc, context, verbose,
811  require_file);
812 
813  if (status)
814  exit_status = status;
815 
816  // Names alone are not enough.
817 
818  sys::file_stat fs_home_rc (home_rc);
819 
820  if (fs_home_rc)
821  {
822  // We want to check for curr_dir after executing home_rc
823  // because doing that may change the working directory.
824 
825  local_rc = sys::env::make_absolute (initfile);
826 
827  home_rc_already_executed = same_file (home_rc, local_rc);
828  }
829  }
830 
831  if (! home_rc_already_executed)
832  {
833  if (local_rc.empty ())
834  local_rc = sys::env::make_absolute (initfile);
835 
836  int status = safe_source_file (local_rc, context, verbose,
837  require_file);
838 
839  if (status)
840  exit_status = status;
841  }
842  }
843 
844  if (m_interactive && verbose)
845  std::cout << std::endl;
846 
847  return exit_status;
848  }
849 
850  // Execute any code specified with --eval 'CODE'
851 
852  int interpreter::execute_eval_option_code (void)
853  {
854  const cmdline_options& options = m_app_context->options ();
855 
856  std::string code_to_eval = options.code_to_eval ();
857 
858  unwind_protect frame;
859 
861 
862  can_interrupt = true;
863 
865  octave_interrupt_hook = nullptr;
866  octave_bad_alloc_hook = nullptr;
867 
868  catch_interrupts ();
869 
870  octave_initialized = true;
871 
872  frame.add_method (this, &interpreter::interactive, m_interactive);
873 
874  m_interactive = false;
875 
876  int parse_status = 0;
877 
878  try
879  {
880  eval_string (code_to_eval, false, parse_status, 0);
881  }
882  catch (const interrupt_exception&)
883  {
884  recover_from_exception ();
885 
886  return 1;
887  }
888  catch (const execution_exception&)
889  {
890  recover_from_exception ();
891 
892  return 1;
893  }
894 
895  return parse_status;
896  }
897 
898  int interpreter::execute_command_line_file (void)
899  {
900  const cmdline_options& options = m_app_context->options ();
901 
902  unwind_protect frame;
903 
905 
906  can_interrupt = true;
907 
909  octave_interrupt_hook = nullptr;
910  octave_bad_alloc_hook = nullptr;
911 
912  catch_interrupts ();
913 
914  octave_initialized = true;
915 
916  frame.add_method (this, &interpreter::interactive, m_interactive);
917 
918  string_vector args = options.all_args ();
919 
920  frame.add_method (m_app_context, &application::intern_argv, args);
921 
922  frame.add_method (this, &interpreter::intern_nargin, args.numel () - 1);
923 
924  frame.add_method (m_app_context,
925  &application::program_invocation_name,
926  application::program_invocation_name ());
927 
928  frame.add_method (m_app_context,
929  &application::program_name,
930  application::program_name ());
931 
932  m_interactive = false;
933 
934  // If we are running an executable script (#! /bin/octave) then
935  // we should only see the args passed to the script.
936 
937  string_vector script_args = options.remaining_args ();
938 
939  m_app_context->intern_argv (script_args);
940  intern_nargin (script_args.numel () - 1);
941 
942  std::string fname = script_args[0];
943 
944  m_app_context->set_program_names (fname);
945 
947  bool verbose = false;
948  bool require_file = true;
949 
950  return safe_source_file (fname, context, verbose, require_file, "octave");
951  }
952 
953  int interpreter::main_loop (void)
954  {
955  if (! m_app_context)
956  return 0;
957 
959 
960  can_interrupt = true;
961 
963  octave_interrupt_hook = nullptr;
964  octave_bad_alloc_hook = nullptr;
965 
966  catch_interrupts ();
967 
968  octave_initialized = true;
969 
970  // The big loop.
971 
972  lexer *lxr = (application::interactive () ? new lexer ()
973  : new lexer (stdin));
974 
975  parser parser (*lxr);
976 
977  int retval = 0;
978  do
979  {
980  try
981  {
983 
984  parser.reset ();
985 
986  if (m_symbol_table.at_top_level ())
987  tree_evaluator::reset_debug_state ();
988 
989  retval = parser.run ();
990 
991  if (retval == 0)
992  {
993  if (parser.m_stmt_list)
994  {
995  parser.m_stmt_list->accept (m_evaluator);
996 
997  octave_quit ();
998 
999  if (! application::interactive ())
1000  {
1001  bool quit = (tree_return_command::returning
1002  || tree_break_command::breaking);
1003 
1004  if (tree_return_command::returning)
1005  tree_return_command::returning = 0;
1006 
1007  if (tree_break_command::breaking)
1008  tree_break_command::breaking--;
1009 
1010  if (quit)
1011  break;
1012  }
1013 
1016  else
1017  command_editor::increment_current_command_number ();
1018  }
1019  else if (parser.m_lexer.m_end_of_input)
1020  {
1021  retval = EOF;
1022  break;
1023  }
1024  }
1025  }
1026  catch (const interrupt_exception&)
1027  {
1028  recover_from_exception ();
1029 
1030  // Required newline when the user does Ctrl+C at the prompt.
1031  if (application::interactive ())
1032  octave_stdout << "\n";
1033  }
1034  catch (const index_exception& e)
1035  {
1036  recover_from_exception ();
1037 
1038  std::cerr << "error: unhandled index exception: "
1039  << e.message () << " -- trying to return to prompt"
1040  << std::endl;
1041  }
1042  catch (const execution_exception& e)
1043  {
1044  std::string stack_trace = e.info ();
1045 
1046  if (! stack_trace.empty ())
1047  std::cerr << stack_trace;
1048 
1049  if (application::interactive ())
1050  recover_from_exception ();
1051  else
1052  {
1053  // We should exit with a nonzero status.
1054  retval = 1;
1055  break;
1056  }
1057  }
1058  catch (const std::bad_alloc&)
1059  {
1060  recover_from_exception ();
1061 
1062  std::cerr << "error: out of memory -- trying to return to prompt"
1063  << std::endl;
1064  }
1065 
1066 #if defined (DBSTOP_NANINF)
1067  if (Vdebug_on_naninf)
1068  {
1069  if (setjump (naninf_jump) != 0)
1070  debug_or_throw_exception (true); // true = stack trace
1071  }
1072 #endif
1073  }
1074  while (retval == 0);
1075 
1076  if (retval == EOF)
1077  {
1078  if (application::interactive ())
1079  octave_stdout << "\n";
1080 
1081  retval = 0;
1082  }
1083 
1084  return retval;
1085  }
1086 
1087  // Call a function with exceptions handled to avoid problems with
1088  // errors while shutting down.
1089 
1090 #define OCTAVE_IGNORE_EXCEPTION(E) \
1091  catch (E) \
1092  { \
1093  recover_from_exception (); \
1094  \
1095  std::cerr << "error: ignoring " #E " while preparing to exit" \
1096  << std::endl; \
1097  }
1098 
1099 #define OCTAVE_SAFE_CALL(F, ARGS) \
1100  do \
1101  { \
1102  try \
1103  { \
1104  unwind_protect frame; \
1105  \
1106  frame.protect_var (Vdebug_on_error); \
1107  frame.protect_var (Vdebug_on_warning); \
1108  \
1109  Vdebug_on_error = false; \
1110  Vdebug_on_warning = false; \
1111  \
1112  F ARGS; \
1113  } \
1114  OCTAVE_IGNORE_EXCEPTION (const exit_exception&) \
1115  OCTAVE_IGNORE_EXCEPTION (const interrupt_exception&) \
1116  OCTAVE_IGNORE_EXCEPTION (const execution_exception&) \
1117  OCTAVE_IGNORE_EXCEPTION (const std::bad_alloc&) \
1118  } \
1119  while (0)
1120 
1121  void interpreter::cleanup (void)
1122  {
1123  // If we are attached to a GUI, process pending events and
1124  // disconnect the link.
1125 
1128 
1130 
1131  while (! atexit_functions.empty ())
1132  {
1133  std::string fcn = atexit_functions.front ();
1134 
1135  atexit_functions.pop_front ();
1136 
1138 
1140 
1142  }
1143 
1144  // Do this explicitly so that destructors for mex file objects
1145  // are called, so that functions registered with mexAtExit are
1146  // called.
1147  OCTAVE_SAFE_CALL (m_symbol_table.clear_mex_functions, ());
1148 
1149  OCTAVE_SAFE_CALL (command_editor::restore_terminal_state, ());
1150 
1152 
1153  if (! command_history::ignoring_entries ())
1154  OCTAVE_SAFE_CALL (command_history::clean_up_and_save, ());
1155 
1157 
1158  m_gtk_manager.unload_all_toolkits ();
1159 
1161 
1162  // FIXME: May still need something like this to ensure that
1163  // destructors for class objects will run properly. Should that be
1164  // done earlier? Before or after atexit functions are executed?
1165  m_symbol_table.cleanup ();
1166 
1168 
1170 
1172 
1173  // Don't call singleton_cleanup_list::cleanup until we have the
1174  // problems with registering/unregistering types worked out. For
1175  // example, uncomment the following line, then use the make_int
1176  // function from the examples directory to create an integer
1177  // object and then exit Octave. Octave should crash with a
1178  // segfault when cleaning up the typinfo singleton. We need some
1179  // way to force new octave_value_X types that are created in
1180  // .oct files to be unregistered when the .oct file shared library
1181  // is unloaded.
1182  //
1183  // OCTAVE_SAFE_CALL (singleton_cleanup_list::cleanup, ());
1184  }
1185 
1186  tree_evaluator& interpreter::get_evaluator (void)
1187  {
1188  return m_evaluator;
1189  }
1190 
1191  stream_list& interpreter::get_stream_list (void)
1192  {
1193  return m_stream_list;
1194  }
1195 
1196  url_handle_manager& interpreter::get_url_handle_manager (void)
1197  {
1198  return m_url_handle_manager;
1199  }
1200 
1201  symbol_scope
1202  interpreter::get_current_scope (void)
1203  {
1204  return m_symbol_table.current_scope ();
1205  }
1206 
1207  symbol_scope
1208  interpreter::require_current_scope (const std::string& who)
1209  {
1210  symbol_scope scope = get_current_scope ();
1211 
1212  if (! scope)
1213  error ("%s: symbol table scope missing", who.c_str ());
1214 
1215  return scope;
1216  }
1217 
1218  call_stack& interpreter::get_call_stack (void)
1219  {
1220  return m_evaluator.get_call_stack ();
1221  }
1222 
1223  profiler& interpreter::get_profiler (void)
1224  {
1225  return m_evaluator.get_profiler ();
1226  }
1227 
1228  void interpreter::mlock (void)
1229  {
1230  call_stack& cs = get_call_stack ();
1231 
1232  octave_function *fcn = cs.current ();
1233 
1234  if (! fcn)
1235  error ("mlock: invalid use outside a function");
1236 
1237  fcn->lock ();
1238  }
1239 
1240  void interpreter::munlock (const std::string& nm)
1241  {
1242  octave_value val = m_symbol_table.find_function (nm);
1243 
1244  if (val.is_defined ())
1245  {
1246  octave_function *fcn = val.function_value ();
1247 
1248  if (fcn)
1249  fcn->unlock ();
1250  }
1251  }
1252 
1253  bool interpreter::mislocked (const std::string& nm)
1254  {
1255  bool retval = false;
1256 
1257  octave_value val = m_symbol_table.find_function (nm);
1258 
1259  if (val.is_defined ())
1260  {
1261  octave_function *fcn = val.function_value ();
1262 
1263  if (fcn)
1264  retval = fcn->islocked ();
1265  }
1266 
1267  return retval;
1268  }
1269 
1270  void interpreter::recover_from_exception (void)
1271  {
1272  can_interrupt = true;
1277  catch_interrupts ();
1278  }
1279 
1280  // Functions to call when the interpreter exits.
1281 
1282  std::list<std::string> interpreter::atexit_functions;
1283 
1284  void interpreter::add_atexit_function (const std::string& fname)
1285  {
1286  atexit_functions.push_front (fname);
1287  }
1288 
1289  bool interpreter::remove_atexit_function (const std::string& fname)
1290  {
1291  bool found = false;
1292 
1293  for (auto it = atexit_functions.begin ();
1294  it != atexit_functions.end (); it++)
1295  {
1296  if (*it == fname)
1297  {
1298  atexit_functions.erase (it);
1299  found = true;
1300  break;
1301  }
1302  }
1303 
1304  return found;
1305  }
1306 
1307  // What internal options get configured by --traditional.
1308 
1309  void interpreter::maximum_braindamage (void)
1310  {
1311  FPS1 (octave_value (">> "));
1312  FPS2 (octave_value (""));
1313 
1314  m_evaluator.PS4 ("");
1315 
1316  Fbeep_on_error (octave_value (true));
1317  Fconfirm_recursive_rmdir (octave_value (false));
1318  Fcrash_dumps_octave_core (octave_value (false));
1319  Fdisable_diagonal_matrix (octave_value (true));
1320  Fdisable_permutation_matrix (octave_value (true));
1321  Fdisable_range (octave_value (true));
1322  Ffixed_point_format (octave_value (true));
1323  Fhistory_timestamp_format_string (octave_value ("%%-- %D %I:%M %p --%%"));
1324  Fprint_empty_dimensions (octave_value (false));
1325  Fsave_default_options (octave_value ("-mat-binary"));
1326  Fstruct_levels_to_print (octave_value (0));
1327 
1328  disable_warning ("Octave:abbreviated-property-match");
1329  disable_warning ("Octave:data-file-in-path");
1330  disable_warning ("Octave:function-name-clash");
1331  disable_warning ("Octave:possible-matlab-short-circuit-operator");
1332  }
1333 }
static void close_all_figures(void)
Definition: graphics.in.h:6263
OCTINTERP_API octave_value_list feval(const std::string &name, const octave_value_list &args=octave_value_list(), int nargout=0)
void warning_with_id(const char *id, const char *fmt,...)
Definition: error.cc:816
volatile sig_atomic_t octave_signal_caught
Definition: cquit.c:49
bool octave_initialized
Definition: interpreter.cc:84
Definition: Cell.h:37
is already an absolute the name is checked against the file system instead of Octave s loadpath In this if otherwise an empty string is returned If the first argument is a cell array of search each directory of the loadpath for element of the cell array and return the first that matches If the second optional argument return a cell array containing the list of all files that have the same name in the path If no files are found
Definition: utils.cc:305
bool same_file(const std::string &f, const std::string &g)
Definition: utils.cc:130
fname
Definition: load-save.cc:767
std::string octave_startup_message(bool html)
Definition: version.cc:120
void octave_set_default_fpucw(void)
void lock(void)
Definition: ov-fcn.h:148
void assign(const std::string &k, const Cell &val)
Definition: oct-map.h:351
static void recover_from_exception(void)
void octave_prepare_hdf5(void)
Definition: load-save.cc:1255
OCTINTERP_API void initialize_default_warning_state(void)
void octave_set_xerbla_handler(xerbla_handler_fptr fcn)
Definition: xerbla.c:48
OCTINTERP_API void print_usage(void)
Definition: defun.cc:54
identity matrix If supplied two scalar respectively For allows like xample val
Definition: data.cc:4986
std::string xstring_value(const char *fmt,...) const
interrupt_handler catch_interrupts(void)
Definition: sighandlers.cc:323
bool islocked(void) const
Definition: ov-fcn.h:160
#define OCTAVE_SAFE_CALL(F, ARGS)
void octave_restore_signal_mask(void)
static string_vector make_absolute(const string_vector &sv)
Definition: utils.cc:272
void flush_stdout(void)
Definition: pager.cc:464
#define DEFUN(name, args_name, nargout_name, doc)
Macro to define a builtin function.
Definition: defun.h:53
void error(const char *fmt,...)
Definition: error.cc:578
static llvm::LLVMContext & context
Definition: jit-typeinfo.cc:79
void sysdep_cleanup(void)
Definition: sysdep.cc:337
i e
Definition: data.cc:2591
void respond_to_pending_signals(void)
Definition: sighandlers.cc:106
bool can_interrupt
Definition: sighandlers.cc:68
octave_value arg
Definition: pr-output.cc:3244
octave_function * fcn
Definition: ov-class.cc:1754
void octave_ieee_init(void)
Definition: lo-ieee.cc:131
#define OCTAVE_VERSION
Definition: main.in.cc:48
void initialize_history(bool read_history_file)
Definition: oct-hist.cc:532
void cleanup_tmp_files(void)
Definition: file-io.cc:96
OCTINTERP_API void source_file(const std::string &file_name, const std::string &context="", bool verbose=false, bool require_file=true, const std::string &warn_for="")
void set_liboctave_warning_with_id_handler(liboctave_warning_with_id_handler f)
Definition: lo-error.c:92
static void initialize(void)
std::string local_site_defaults_file(void)
Definition: defaults.cc:314
octave::call_stack & cs
Definition: ov-class.cc:1752
#define DEFALIAS(alias, name)
Macro to define an alias for another existing function name.
Definition: defun.h:211
bool verbose
Definition: load-save.cc:667
void set_liboctave_error_with_id_handler(OCTAVE_NORETURN liboctave_error_with_id_handler f)
Definition: lo-error.c:73
std::string concat(const std::string &dir, const std::string &file)
Definition: file-ops.cc:344
void verror_with_cfn(const char *fmt, va_list args)
Definition: error.cc:602
void verror_with_id_cfn(const char *id, const char *fmt, va_list args)
Definition: error.cc:632
OCTAVE_EXPORT octave_value_list isdir nd deftypefn *std::string nm
Definition: utils.cc:975
OCTINTERP_API void disable_warning(const std::string &id)
int octave_isatty_wrapper(int fd)
OCTAVE_EXPORT octave_value_list return the number of command line arguments passed to Octave If called with the optional argument the function xample nargout(@histc)
Definition: ov-usr-fcn.cc:997
void octave_throw_execution_exception(void)
Definition: quit.cc:67
OCTINTERP_API octave_value_list eval_string(const std::string &, bool silent, int &parse_status, int nargout)
#define OCTAVE_RELEASE_DATE
Definition: version.in.h:47
void initialize_command_input(void)
Definition: input.cc:580
void octave_history_write_timestamp(void)
Definition: oct-hist.cc:543
OCTINTERP_API bool mislocked(const std::string &)
sig_atomic_t octave_exception_state
Definition: cquit.c:34
is false
Definition: cellfun.cc:400
void set_liboctave_warning_handler(liboctave_warning_handler f)
Definition: lo-error.c:83
octave_value retval
Definition: data.cc:6246
void octave_save_signal_mask(void)
void(* octave_signal_hook)(void)
Definition: quit.cc:34
void reset_error_handler(void)
Definition: error.cc:125
sig_atomic_t octave_interrupt_state
Definition: cquit.c:32
returns the type of the matrix and caches it for future use Called with more than one the function will not attempt to guess the type if it is still unknown This is useful for debugging purposes The possible matrix types depend on whether the matrix is full or and can be one of the following able sis tem and mark type as unknown tem as the structure of the matrix explicitly gives this(Sparse matrices only) tem code
Definition: matrix_type.cc:120
OCTINTERP_API void munlock(const std::string &)
std::string release(void)
Definition: defaults.cc:266
load_path & __get_load_path__(const std::string &who)
octave_idx_type numel(void) const
Definition: oct-map.h:375
F77_RET_T F77_FUNC(xerbla, XERBLA)
Definition: xerbla.c:57
bool octave_interpreter_ready
Definition: interpreter.cc:81
void unlock(void)
Definition: ov-fcn.h:154
OCTAVE_EXPORT octave_value_list F__version_info__(const octave_value_list &args, int)
Definition: interpreter.cc:90
octave_function * current(void) const
Definition: call-stack.h:97
octave_idx_type nfields(void) const
Definition: oct-map.h:330
void warning(const char *fmt,...)
Definition: error.cc:801
void set_liboctave_error_handler(OCTAVE_NORETURN liboctave_error_handler f)
Definition: lo-error.c:64
octave::unwind_protect frame
Definition: graphics.cc:12190
#define octave_stdout
Definition: pager.h:174
OCTAVE_EXPORT octave_value_list isa nd deftypefn *return ovl(args(0).isinteger())
void remove_input_event_hook_functions(void)
Definition: input.cc:115
OCTAVE_EXPORT octave_value_list or N dimensional array whose elements are all equal to the IEEE symbol NaN(Not a Number). NaN is the result of operations which do not produce a well defined 0 result. Common operations which produce a NaN are arithmetic with infinity ex($\infty - \infty$)
static void add_atexit_function(const std::string &fname)
void octave_finalize_hdf5(void)
Definition: load-save.cc:1263
OCTAVE_EXPORT octave_value_list only variables visible in the local scope are displayed The following are valid options
Definition: variables.cc:1862
void add_method(T *obj, void(T::*method)(void))
args.length() nargin
Definition: file-io.cc:589
std::string site_defaults_file(void)
Definition: defaults.cc:315
interpreter(application *app_context=nullptr)
static bool remove_atexit_function(const std::string &fname)
void resize(const dim_vector &dv, bool fill=false)
Definition: oct-map.cc:577
octave_idx_type numel(void) const
Number of elements in the array.
Definition: Array.h:366
octave_idx_type length(void) const
Definition: oct-map.h:376
void(* octave_interrupt_hook)(void)
Definition: quit.cc:35
void(* octave_bad_alloc_hook)(void)
Definition: quit.cc:36
Vector representing the dimensions (size) of an Array.
Definition: dim-vector.h:87
bool octave_completion_matches_called
Definition: input.cc:90
bool quit_allowed
Definition: interpreter.cc:77
If this string is the system will ring the terminal sometimes it is useful to be able to print the original representation of the string
Definition: utils.cc:888
void set_default_prompts(void)
Definition: input.cc:121
void install_signal_handlers(void)
Definition: sighandlers.cc:362
OCTINTERP_API void mlock(void)