home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyth_os2.zip / python-1.0.2 / Python / pythonrun.c < prev    next >
C/C++ Source or Header  |  1994-05-04  |  12KB  |  606 lines

  1. /***********************************************************
  2. Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
  3. Amsterdam, The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its 
  8. documentation for any purpose and without fee is hereby granted, 
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in 
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI not be used in advertising or publicity pertaining to
  13. distribution of the software without specific, written prior permission.
  14.  
  15. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  16. THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  17. FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  18. FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  19. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  20. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  21. OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  22.  
  23. ******************************************************************/
  24.  
  25. /* Python interpreter top-level routines, including init/exit */
  26.  
  27. #include "allobjects.h"
  28.  
  29. #include "grammar.h"
  30. #include "node.h"
  31. #include "parsetok.h"
  32. #include "graminit.h"
  33. #include "errcode.h"
  34. #include "sysmodule.h"
  35. #include "compile.h"
  36. #include "eval.h"
  37. #include "ceval.h"
  38. #include "pythonrun.h"
  39. #include "import.h"
  40.  
  41. #ifdef HAVE_SIGNAL_H
  42. #include <signal.h>
  43. #endif
  44.  
  45. extern char *getpythonpath();
  46.  
  47. extern grammar gram; /* From graminit.c */
  48.  
  49. /* Forward */
  50. static object *run_err_node PROTO((node *n, char *filename,
  51.                    object *globals, object *locals));
  52. static object *run_node PROTO((node *n, char *filename,
  53.                    object *globals, object *locals));
  54. static void err_input PROTO((perrdetail *));
  55. static void initsigs PROTO((void));
  56.  
  57. int debugging; /* Needed by parser.c */
  58. int verbose; /* Needed by import.c */
  59.  
  60. /* Initialize all */
  61.  
  62. void
  63. initall()
  64. {
  65.     static int inited;
  66.     
  67.     if (inited)
  68.         return;
  69.     inited = 1;
  70.     
  71.     initimport();
  72.     
  73.     /* Modules '__builtin__' and 'sys' are initialized here,
  74.        they are needed by random bits of the interpreter.
  75.        All other modules are optional and are initialized
  76.        when they are first imported. */
  77.     
  78.     initbuiltin(); /* Also initializes builtin exceptions */
  79.     initsys();
  80.  
  81.     setpythonpath(getpythonpath());
  82.  
  83.     initsigs(); /* Signal handling stuff, including initintr() */
  84. }
  85.  
  86. /* Parse input from a file and execute it */
  87.  
  88. int
  89. run(fp, filename)
  90.     FILE *fp;
  91.     char *filename;
  92. {
  93.     if (filename == NULL)
  94.         filename = "???";
  95.     if (isatty((int)fileno(fp)))
  96.         return run_tty_loop(fp, filename);
  97.     else
  98.         return run_script(fp, filename);
  99. }
  100.  
  101. int
  102. run_tty_loop(fp, filename)
  103.     FILE *fp;
  104.     char *filename;
  105. {
  106.     object *v;
  107.     int ret;
  108.     v = sysget("ps1");
  109.     if (v == NULL) {
  110.         sysset("ps1", v = newstringobject(">>> "));
  111.         XDECREF(v);
  112.     }
  113.     v = sysget("ps2");
  114.     if (v == NULL) {
  115.         sysset("ps2", v = newstringobject("... "));
  116.         XDECREF(v);
  117.     }
  118.     for (;;) {
  119.         ret = run_tty_1(fp, filename);
  120. #ifdef REF_DEBUG
  121.         fprintf(stderr, "[%ld refs]\n", ref_total);
  122. #endif
  123.         if (ret == E_EOF)
  124.             return 0;
  125.         /*
  126.         if (ret == E_NOMEM)
  127.             return -1;
  128.         */
  129.     }
  130. }
  131.  
  132. int
  133. run_tty_1(fp, filename)
  134.     FILE *fp;
  135.     char *filename;
  136. {
  137.     object *m, *d, *v, *w;
  138.     node *n;
  139.     perrdetail err;
  140.     char *ps1, *ps2;
  141.     v = sysget("ps1");
  142.     w = sysget("ps2");
  143.     if (v != NULL && is_stringobject(v)) {
  144.         INCREF(v);
  145.         ps1 = getstringvalue(v);
  146.     }
  147.     else {
  148.         v = NULL;
  149.         ps1 = "";
  150.     }
  151.     if (w != NULL && is_stringobject(w)) {
  152.         INCREF(w);
  153.         ps2 = getstringvalue(w);
  154.     }
  155.     else {
  156.         w = NULL;
  157.         ps2 = "";
  158.     }
  159.     BGN_SAVE
  160.     n = parsefile(fp, filename, &gram, single_input, ps1, ps2, &err);
  161.     END_SAVE
  162.     XDECREF(v);
  163.     XDECREF(w);
  164.     if (n == NULL) {
  165.         if (err.error == E_EOF) {
  166.             if (err.text)
  167.                 free(err.text);
  168.             return E_EOF;
  169.         }
  170.         err_input(&err);
  171.         print_error();
  172.         return err.error;
  173.     }
  174.     m = add_module("__main__");
  175.     if (m == NULL)
  176.         return -1;
  177.     d = getmoduledict(m);
  178.     v = run_node(n, filename, d, d);
  179.     flushline();
  180.     if (v == NULL) {
  181.         print_error();
  182.         return -1;
  183.     }
  184.     DECREF(v);
  185.     return 0;
  186. }
  187.  
  188. int
  189. run_script(fp, filename)
  190.     FILE *fp;
  191.     char *filename;
  192. {
  193.     object *m, *d, *v;
  194.     m = add_module("__main__");
  195.     if (m == NULL)
  196.         return -1;
  197.     d = getmoduledict(m);
  198.     v = run_file(fp, filename, file_input, d, d);
  199.     flushline();
  200.     if (v == NULL) {
  201.         print_error();
  202.         return -1;
  203.     }
  204.     DECREF(v);
  205.     return 0;
  206. }
  207.  
  208. int
  209. run_command(command)
  210.     char *command;
  211. {
  212.     object *m, *d, *v;
  213.     m = add_module("__main__");
  214.     if (m == NULL)
  215.         return -1;
  216.     d = getmoduledict(m);
  217.     v = run_string(command, file_input, d, d);
  218.     flushline();
  219.     if (v == NULL) {
  220.         print_error();
  221.         return -1;
  222.     }
  223.     DECREF(v);
  224.     return 0;
  225. }
  226.  
  227. void
  228. print_error()
  229. {
  230.     object *exception, *v, *f;
  231.     err_get(&exception, &v);
  232.     if (exception == NULL) {
  233.         fprintf(stderr, "print_error called but no exception\n");
  234.         abort();
  235.     }
  236.     if (exception == SystemExit) {
  237.         if (v == NULL || v == None)
  238.             goaway(0);
  239.         if (is_intobject(v))
  240.             goaway((int)getintvalue(v));
  241.         else {
  242.             /* OK to use real stderr here */
  243.             printobject(v, stderr, PRINT_RAW);
  244.             fprintf(stderr, "\n");
  245.             goaway(1);
  246.         }
  247.     }
  248.     sysset("last_type", exception);
  249.     sysset("last_value", v);
  250.     f = sysget("stderr");
  251.     if (f == NULL)
  252.         fprintf(stderr, "lost sys.stderr\n");
  253.     else {
  254.         printtraceback(f);
  255.         if (exception == SyntaxError) {
  256.             object *message;
  257.             char *filename, *text;
  258.             int lineno, offset;
  259.             if (!getargs(v, "(O(ziiz))", &message,
  260.                      &filename, &lineno, &offset, &text))
  261.                 err_clear();
  262.             else {
  263.                 char buf[10];
  264.                 writestring("  File \"", f);
  265.                 if (filename == NULL)
  266.                     writestring("<string>", f);
  267.                 else
  268.                     writestring(filename, f);
  269.                 writestring("\", line ", f);
  270.                 sprintf(buf, "%d", lineno);
  271.                 writestring(buf, f);
  272.                 writestring("\n", f);
  273.                 if (text != NULL) {
  274.                     while (*text == ' ' || *text == '\t') {
  275.                         text++;
  276.                         offset--;
  277.                     }
  278.                     writestring("    ", f);
  279.                     writestring(text, f);
  280.                     if (*text == '\0' ||
  281.                         text[strlen(text)-1] != '\n')
  282.                         writestring("\n", f);
  283.                     writestring("    ", f);
  284.                     offset--;
  285.                     while (offset > 0) {
  286.                         writestring(" ", f);
  287.                         offset--;
  288.                     }
  289.                     writestring("^\n", f);
  290.                 }
  291.                 v = message;
  292.             }
  293.         }
  294.         if (writeobject(exception, f, PRINT_RAW) != 0)
  295.             err_clear();
  296.         if (v != NULL && v != None) {
  297.             writestring(": ", f);
  298.             if (writeobject(v, f, PRINT_RAW) != 0)
  299.                 err_clear();
  300.         }
  301.         writestring("\n", f);
  302.     }
  303.     XDECREF(exception);
  304.     XDECREF(v);
  305. }
  306.  
  307. object *
  308. run_string(str, start, globals, locals)
  309.     char *str;
  310.     int start;
  311.     object *globals, *locals;
  312. {
  313.     return run_err_node(parse_string(str, start),
  314.                 "<string>", globals, locals);
  315. }
  316.  
  317. object *
  318. run_file(fp, filename, start, globals, locals)
  319.     FILE *fp;
  320.     char *filename;
  321.     int start;
  322.     object *globals, *locals;
  323. {
  324.     return run_err_node(parse_file(fp, filename, start),
  325.                 filename, globals, locals);
  326. }
  327.  
  328. static object *
  329. run_err_node(n, filename, globals, locals)
  330.     node *n;
  331.     char *filename;
  332.     object *globals, *locals;
  333. {
  334.     if (n == NULL)
  335.         return  NULL;
  336.     return run_node(n, filename, globals, locals);
  337. }
  338.  
  339. static object *
  340. run_node(n, filename, globals, locals)
  341.     node *n;
  342.     char *filename;
  343.     object *globals, *locals;
  344. {
  345.     codeobject *co;
  346.     object *v;
  347.     co = compile(n, filename);
  348.     freetree(n);
  349.     if (co == NULL)
  350.         return NULL;
  351.     v = eval_code(co, globals, locals, (object *)NULL, (object *)NULL);
  352.     DECREF(co);
  353.     return v;
  354. }
  355.  
  356. object *
  357. compile_string(str, filename, start)
  358.     char *str;
  359.     char *filename;
  360.     int start;
  361. {
  362.     node *n;
  363.     int err;
  364.     codeobject *co;
  365.     n = parse_string(str, start);
  366.     if (n == NULL)
  367.         return NULL;
  368.     co = compile(n, filename);
  369.     freetree(n);
  370.     return (object *)co;
  371. }
  372.  
  373. /* Simplified interface to parsefile -- return node or set exception */
  374.  
  375. node *
  376. parse_file(fp, filename, start)
  377.     FILE *fp;
  378.     char *filename;
  379.     int start;
  380. {
  381.     node *n;
  382.     perrdetail err;
  383.     BGN_SAVE
  384.     n = parsefile(fp, filename, &gram, start,
  385.                 (char *)0, (char *)0, &err);
  386.     END_SAVE
  387.     if (n == NULL)
  388.         err_input(&err);
  389.     return n;
  390. }
  391.  
  392. /* Simplified interface to parsestring -- return node or set exception */
  393.  
  394. node *
  395. parse_string(str, start)
  396.     char *str;
  397.     int start;
  398. {
  399.     node *n;
  400.     perrdetail err;
  401.     n = parsestring(str, &gram, start, &err);
  402.     if (n == NULL)
  403.         err_input(&err);
  404.     return n;
  405. }
  406.  
  407. /* Set the error appropriate to the given input error code (see errcode.h) */
  408.  
  409. static void
  410. err_input(err)
  411.     perrdetail *err;
  412. {
  413.     object *v, *w;
  414.     char *msg = NULL;
  415.     v = mkvalue("(ziiz)", err->filename,
  416.                 err->lineno, err->offset, err->text);
  417.     if (err->text != NULL) {
  418.         free(err->text);
  419.         err->text = NULL;
  420.     }
  421.     switch (err->error) {
  422.     case E_SYNTAX:
  423.         msg = "invalid syntax";
  424.         break;
  425.     case E_TOKEN:
  426.         msg = "invalid token";
  427.  
  428.         break;
  429.     case E_INTR:
  430.         err_set(KeyboardInterrupt);
  431.         return;
  432.     case E_NOMEM:
  433.         err_nomem();
  434.         return;
  435.     case E_EOF:
  436.         msg = "unexpected EOF while parsing";
  437.         break;
  438.     default:
  439.         fprintf(stderr, "error=%d\n", err->error);
  440.         msg = "unknown parsing error";
  441.         break;
  442.     }
  443.     w = mkvalue("(sO)", msg, v);
  444.     XDECREF(v);
  445.     err_setval(SyntaxError, w);
  446.     XDECREF(w);
  447. }
  448.  
  449. /* Print fatal error message and abort */
  450.  
  451. void
  452. fatal(msg)
  453.     char *msg;
  454. {
  455.     fprintf(stderr, "Fatal error: %s\n", msg);
  456.     abort();
  457. }
  458.  
  459. /* Clean up and exit */
  460.  
  461. #ifdef WITH_THREAD
  462. #include "thread.h"
  463. int threads_started = 0; /* Set by threadmodule.c and maybe others */
  464. #endif
  465.  
  466. void
  467. cleanup()
  468. {
  469.     object *exitfunc = sysget("exitfunc");
  470.  
  471.     if (exitfunc) {
  472.         object *arg;
  473.         object *res;
  474.         sysset("exitfunc", (object *)NULL);
  475.         arg = newtupleobject(0);
  476.         if (arg == NULL)
  477.             res = NULL;
  478.         else {
  479.             res = call_object(exitfunc, arg);
  480.             DECREF(arg);
  481.         }
  482.         if (res == NULL) {
  483.             fprintf(stderr, "Error in sys.exitfunc:\n");
  484.             print_error();
  485.         }
  486.     }
  487.  
  488.     flushline();
  489. }
  490.  
  491. #ifdef COUNT_ALLOCS
  492. extern void dump_counts PROTO((void));
  493. #endif
  494.  
  495. void
  496. goaway(sts)
  497.     int sts;
  498. {
  499.     cleanup();
  500.  
  501. #ifdef COUNT_ALLOCS
  502.     dump_counts();
  503. #endif
  504.  
  505. #ifdef WITH_THREAD
  506.  
  507.     /* Other threads may still be active, so skip most of the
  508.        cleanup actions usually done (these are mostly for
  509.        debugging anyway). */
  510.     
  511.     (void) save_thread();
  512. #ifndef NO_EXIT_PROG
  513.     if (threads_started)
  514.         _exit_prog(sts);
  515.     else
  516.         exit_prog(sts);
  517. #else /* !NO_EXIT_PROG */
  518.     if (threads_started)
  519.         _exit(sts);
  520.     else
  521.         exit(sts);
  522. #endif /* !NO_EXIT_PROG */
  523.     
  524. #else /* WITH_THREAD */
  525.     
  526.     doneimport();
  527.     
  528.     err_clear();
  529.  
  530. #ifdef REF_DEBUG
  531.     fprintf(stderr, "[%ld refs]\n", ref_total);
  532. #endif
  533.  
  534. #ifdef TRACE_REFS
  535.     if (askyesno("Print left references?")) {
  536.         printrefs(stderr);
  537.     }
  538. #endif /* TRACE_REFS */
  539.  
  540.     exit(sts);
  541. #endif /* WITH_THREAD */
  542.     /*NOTREACHED*/
  543. }
  544.  
  545. #ifdef HAVE_SIGNAL_H
  546. static RETSIGTYPE
  547. sighandler(sig)
  548.     int sig;
  549. {
  550.     signal(sig, SIG_DFL); /* Don't catch recursive signals */
  551.     cleanup(); /* Do essential clean-up */
  552. #ifdef HAVE_GETPID
  553.     kill(getpid(), sig); /* Pretend the signal killed us */
  554. #else
  555.     exit(1);
  556. #endif
  557.     /*NOTREACHED*/
  558. }
  559. #endif
  560.  
  561. static void
  562. initsigs()
  563. {
  564.     initintr();
  565. #ifdef HAVE_SIGNAL_H
  566. #ifdef SIGHUP
  567.     if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
  568.         signal(SIGHUP, sighandler);
  569. #endif              
  570. #ifdef SIGTERM
  571.     if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
  572.         signal(SIGTERM, sighandler);
  573. #endif
  574. #endif /* HAVE_SIGNAL_H */
  575. }
  576.  
  577. #ifdef TRACE_REFS
  578. /* Ask a yes/no question */
  579.  
  580. int
  581. askyesno(prompt)
  582.     char *prompt;
  583. {
  584.     char buf[256];
  585.     
  586.     printf("%s [ny] ", prompt);
  587.     if (fgets(buf, sizeof buf, stdin) == NULL)
  588.         return 0;
  589.     return buf[0] == 'y' || buf[0] == 'Y';
  590. }
  591. #endif
  592.  
  593. #ifdef applec /* MPW (also usable for Think C 3.0) */
  594.  
  595. /* Check for file descriptor connected to interactive device.
  596.    Pretend that stdin is always interactive, other files never. */
  597.  
  598. int
  599. isatty(fd)
  600.     int fd;
  601. {
  602.     return fd == fileno(stdin);
  603. }
  604.  
  605. #endif
  606.