home *** CD-ROM | disk | FTP | other *** search
/ linuxmafia.com 2016 / linuxmafia.com.tar / linuxmafia.com / pub / palmos / pippy-0.6beta-src.tar.gz / pippy-0.6beta-src.tar / pippy-0.6beta-src / src / Python / pythonrun.c < prev    next >
C/C++ Source or Header  |  2000-12-21  |  28KB  |  1,226 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. 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 or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Python interpreter top-level routines, including init/exit */
  33.  
  34. #include "Python.h"
  35.  
  36. #include "grammar.h"
  37. #include "node.h"
  38. #include "parsetok.h"
  39. #include "errcode.h"
  40. #include "compile.h"
  41. #include "eval.h"
  42. #include "marshal.h"
  43.  
  44. #ifdef HAVE_UNISTD_H
  45. #include <unistd.h>
  46. #endif
  47.  
  48. #ifdef HAVE_SIGNAL_H
  49. #include <signal.h>
  50. #endif
  51.  
  52. #ifdef MS_WIN32
  53. #undef BYTE
  54. #include "windows.h"
  55. #endif
  56.  
  57. #include "PalmOS.h"
  58.  
  59. extern char *Py_GetPath();
  60.  
  61. #ifndef WITHOUT_COMPILER
  62. extern grammar _PyParser_Grammar; /* From graminit.c */
  63. #endif /* WITHOUT_COMPILER */
  64.  
  65. /* Forward */
  66. static void initmain Py_PROTO((void)) SEG_PYTHONRUN_C;
  67. static void initsite Py_PROTO((void)) SEG_PYTHONRUN_C;
  68. static PyObject *run_err_node Py_PROTO((node *n, char *filename,
  69.                    PyObject *globals, PyObject *locals)) SEG_PYTHONRUN_C;
  70. static PyObject *run_node Py_PROTO((node *n, char *filename,
  71.                    PyObject *globals, PyObject *locals)) SEG_PYTHONRUN_C;
  72. static PyObject *run_pyc_file Py_PROTO((FILE *fp, char *filename,
  73.                    PyObject *globals, PyObject *locals)) SEG_PYTHONRUN_C;
  74. static void err_input Py_PROTO((perrdetail *)) SEG_PYTHONRUN_C;
  75. static void initsigs Py_PROTO((void)) SEG_PYTHONRUN_C;
  76. static void call_sys_exitfunc Py_PROTO((void)) SEG_PYTHONRUN_C;
  77. static void call_ll_exitfuncs Py_PROTO((void)) SEG_PYTHONRUN_C;
  78.  
  79. #ifdef Py_TRACE_REFS
  80. int _Py_AskYesNo(char *prompt);
  81. #endif
  82.  
  83. int Py_DebugFlag; /* Needed by parser.c */
  84. int Py_VerboseFlag; /* Needed by import.c */
  85. int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
  86. int Py_NoSiteFlag; /* Suppress 'import site' */
  87. int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c */
  88. int Py_FrozenFlag; /* Needed by getpath.c */
  89.  
  90. static int initialized = 0;
  91.  
  92.  
  93. /* API to access the initialized flag -- useful for eroteric use */
  94.  
  95. int
  96. Py_IsInitialized()
  97. {
  98.     return initialized;
  99. }
  100.  
  101. /* Global initializations.  Can be undone by Py_Finalize().  Don't
  102.    call this twice without an intervening Py_Finalize() call.  When
  103.    initializations fail, a fatal error is issued and the function does
  104.    not return.  On return, the first thread and interpreter state have
  105.    been created.
  106.  
  107.    Locking: you must hold the interpreter lock while calling this.
  108.    (If the lock has not yet been initialized, that's equivalent to
  109.    having the lock, but you cannot use multiple threads.)
  110.  
  111. */
  112.  
  113. void
  114. Py_Initialize()
  115. {
  116.     PyInterpreterState *interp;
  117.     PyThreadState *tstate;
  118.     PyObject *bimod, *sysmod;
  119.     char *p;
  120. void _gdb_hook(void);
  121.  
  122.     DMESSAGE("starting Py_Initialize");
  123.  
  124.     if (initialized)
  125.         return;
  126.     initialized = 1;
  127.     
  128.     DMESSAGE("before getenvs");
  129.     if ((p = getenv("PYTHONDEBUG")) && *p != '\0')
  130.         Py_DebugFlag = 1;
  131.     if ((p = getenv("PYTHONVERBOSE")) && *p != '\0')
  132.         Py_VerboseFlag = 1;
  133.     if ((p = getenv("PYTHONOPTIMIZE")) && *p != '\0')
  134.         Py_OptimizeFlag = 1;
  135.  
  136.     DMESSAGE("before PyInterpreterState_New");
  137.     interp = PyInterpreterState_New();
  138.     if (interp == NULL)
  139.         Py_FatalError("Py_Initialize: can't make first interpreter");
  140.  
  141.     DMESSAGE("before PyThreadState_New");
  142.     tstate = PyThreadState_New(interp);
  143.     if (tstate == NULL)
  144.         Py_FatalError("Py_Initialize: can't make first thread");
  145.     DMESSAGE("before PythreadState_Swap");
  146.     (void) PyThreadState_Swap(tstate);
  147.  
  148.     DMESSAGE("before PyDict_New");
  149.     interp->modules = PyDict_New();
  150.     if (interp->modules == NULL)
  151.         Py_FatalError("Py_Initialize: can't make modules dictionary");
  152.  
  153.     DMESSAGE("before _PyBuiltin_Init_1()");
  154.     bimod = _PyBuiltin_Init_1();
  155.     if (bimod == NULL)
  156.         Py_FatalError("Py_Initialize: can't initialize __builtin__");
  157.     DMESSAGE("before PyModule_GetDict");
  158.     interp->builtins = PyModule_GetDict(bimod);
  159.     Py_INCREF(interp->builtins);
  160.  
  161.     DMESSAGE("before _PySys_Init");
  162.     sysmod = _PySys_Init();
  163.     if (sysmod == NULL)
  164.         Py_FatalError("Py_Initialize: can't initialize sys");
  165.     DMESSAGE("before PyModule_GetDict(sysmod)");
  166.     interp->sysdict = PyModule_GetDict(sysmod);
  167.     Py_INCREF(interp->sysdict);
  168.     DMESSAGE("before _PyImport_FixupExtension");
  169.     _PyImport_FixupExtension("sys", "sys");
  170.     DMESSAGE("before PySys_SetPath");
  171.     PySys_SetPath(Py_GetPath());
  172.     DMESSAGE("before PyDict_SetItemString");
  173.     PyDict_SetItemString(interp->sysdict, "modules",
  174.                  interp->modules);
  175.  
  176.     DMESSAGE("before _PyImport_Init");
  177.     _PyImport_Init();
  178.  
  179.     /* phase 2 of builtins */
  180.     DMESSAGE("before _PyBuiltin_Init_2");
  181.     _PyBuiltin_Init_2(interp->builtins);
  182.     DMESSAGE("before _PyImport_FixupExtension [2]");
  183.     _PyImport_FixupExtension("__builtin__", "__builtin__");
  184.  
  185.     DMESSAGE("before initsigs");
  186.     initsigs();  /* Signal handling stuff, including initintr() */
  187.  
  188.     DMESSAGE("before initmain");
  189.     initmain(); /* Module __main__ */
  190.     if (!Py_NoSiteFlag)
  191.         initsite(); /* Module site */
  192. }
  193.  
  194. #ifdef COUNT_ALLOCS
  195. extern void dump_counts Py_PROTO((void));
  196. #endif
  197.  
  198. /* Undo the effect of Py_Initialize().
  199.  
  200.    Beware: if multiple interpreter and/or thread states exist, these
  201.    are not wiped out; only the current thread and interpreter state
  202.    are deleted.  But since everything else is deleted, those other
  203.    interpreter and thread states should no longer be used.
  204.  
  205.    (XXX We should do better, e.g. wipe out all interpreters and
  206.    threads.)
  207.  
  208.    Locking: as above.
  209.  
  210. */
  211.  
  212. void
  213. Py_Finalize()
  214. {
  215.     PyInterpreterState *interp;
  216.     PyThreadState *tstate;
  217.  
  218.     DMESSAGE("finalizing");
  219.     if (!initialized)
  220.         return;
  221.     initialized = 0;
  222.  
  223.     DMESSAGE("checking for exitfunc");
  224.     call_sys_exitfunc();
  225.  
  226.     /* Get current thread state and interpreter pointer */
  227.     DMESSAGE("getting threadstate");
  228.     tstate = PyThreadState_Get();
  229.     interp = tstate->interp;
  230.  
  231.     /* Disable signal handling */
  232.     DMESSAGE("interrupts");
  233.     PyOS_FiniInterrupts();
  234.  
  235.     /* Destroy PyExc_MemoryErrorInst */
  236.     DMESSAGE("Fini_1");
  237.     _PyBuiltin_Fini_1();
  238.  
  239.     /* Destroy all modules */
  240.     DMESSAGE("Cleanup");    
  241.     PyImport_Cleanup();
  242.  
  243.     /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
  244.     DMESSAGE("Fini");
  245.     _PyImport_Fini();
  246.  
  247.     /* Debugging stuff */
  248. #ifdef COUNT_ALLOCS
  249.     dump_counts();
  250. #endif
  251.  
  252. #ifdef Py_REF_DEBUG
  253.     fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
  254. #endif
  255.  
  256. #ifdef Py_TRACE_REFS
  257.     if (_Py_AskYesNo("Print left references?")) {
  258.         _Py_PrintReferences(stderr);
  259.     }
  260. #endif /* Py_TRACE_REFS */
  261.  
  262.     /* Delete current thread */
  263.     PyInterpreterState_Clear(interp);
  264.     PyThreadState_Swap(NULL);
  265.     PyInterpreterState_Delete(interp);
  266.  
  267.     /* Now we decref the exception classes.  After this point nothing
  268.        can raise an exception.  That's okay, because each Fini() method
  269.        below has been checked to make sure no exceptions are ever
  270.        raised.
  271.     */
  272.     _PyBuiltin_Fini_2();
  273.     PyMethod_Fini();
  274.     PyFrame_Fini();
  275.     PyCFunction_Fini();
  276.     PyTuple_Fini();
  277.     PyString_Fini();
  278.     PyInt_Fini();
  279. #ifndef WITHOUT_FLOAT
  280.     PyFloat_Fini();
  281. #endif /* WITHOUT_FLOAT */
  282.  
  283.     /* XXX Still allocated:
  284.        - various static ad-hoc pointers to interned strings
  285.        - int and float free list blocks
  286.        - whatever various modules and libraries allocate
  287.     */
  288.  
  289. #ifndef WITHOUT_COMPILER
  290.     PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
  291. #endif /* WITHOUT_COMPILER */
  292.  
  293.     call_ll_exitfuncs();
  294.  
  295. #ifdef Py_TRACE_REFS
  296.     _Py_ResetReferences();
  297. #endif /* Py_TRACE_REFS */
  298. }
  299.  
  300. /* Create and initialize a new interpreter and thread, and return the
  301.    new thread.  This requires that Py_Initialize() has been called
  302.    first.
  303.  
  304.    Unsuccessful initialization yields a NULL pointer.  Note that *no*
  305.    exception information is available even in this case -- the
  306.    exception information is held in the thread, and there is no
  307.    thread.
  308.  
  309.    Locking: as above.
  310.  
  311. */
  312.  
  313. PyThreadState *
  314. Py_NewInterpreter()
  315. {
  316.     PyInterpreterState *interp;
  317.     PyThreadState *tstate, *save_tstate;
  318.     PyObject *bimod, *sysmod;
  319.  
  320.     if (!initialized)
  321.         Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
  322.  
  323.     interp = PyInterpreterState_New();
  324.     if (interp == NULL)
  325.         return NULL;
  326.  
  327.     tstate = PyThreadState_New(interp);
  328.     if (tstate == NULL) {
  329.         PyInterpreterState_Delete(interp);
  330.         return NULL;
  331.     }
  332.  
  333.     save_tstate = PyThreadState_Swap(tstate);
  334.  
  335.     /* XXX The following is lax in error checking */
  336.  
  337.     interp->modules = PyDict_New();
  338.  
  339.     bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
  340.     if (bimod != NULL) {
  341.         interp->builtins = PyModule_GetDict(bimod);
  342.         Py_INCREF(interp->builtins);
  343.     }
  344.     sysmod = _PyImport_FindExtension("sys", "sys");
  345.     if (bimod != NULL && sysmod != NULL) {
  346.         interp->sysdict = PyModule_GetDict(sysmod);
  347.         Py_INCREF(interp->sysdict);
  348.         PySys_SetPath(Py_GetPath());
  349.         PyDict_SetItemString(interp->sysdict, "modules",
  350.                      interp->modules);
  351.         initmain();
  352.         if (!Py_NoSiteFlag)
  353.             initsite();
  354.     }
  355.  
  356.     if (!PyErr_Occurred())
  357.         return tstate;
  358.  
  359.     /* Oops, it didn't work.  Undo it all. */
  360.  
  361.     PyErr_Print();
  362.     PyThreadState_Clear(tstate);
  363.     PyThreadState_Swap(save_tstate);
  364.     PyThreadState_Delete(tstate);
  365.     PyInterpreterState_Delete(interp);
  366.  
  367.     return NULL;
  368. }
  369.  
  370. /* Delete an interpreter and its last thread.  This requires that the
  371.    given thread state is current, that the thread has no remaining
  372.    frames, and that it is its interpreter's only remaining thread.
  373.    It is a fatal error to violate these constraints.
  374.  
  375.    (Py_Finalize() doesn't have these constraints -- it zaps
  376.    everything, regardless.)
  377.  
  378.    Locking: as above.
  379.  
  380. */
  381.  
  382. void
  383. Py_EndInterpreter(tstate)
  384.     PyThreadState *tstate;
  385. {
  386.     PyInterpreterState *interp = tstate->interp;
  387.  
  388.     if (tstate != PyThreadState_Get())
  389.         Py_FatalError("Py_EndInterpreter: thread is not current");
  390.     if (tstate->frame != NULL)
  391.         Py_FatalError("Py_EndInterpreter: thread still has a frame");
  392.     if (tstate != interp->tstate_head || tstate->next != NULL)
  393.         Py_FatalError("Py_EndInterpreter: not the last thread");
  394.  
  395.     PyImport_Cleanup();
  396.     PyInterpreterState_Clear(interp);
  397.     PyThreadState_Swap(NULL);
  398.     PyInterpreterState_Delete(interp);
  399. }
  400.  
  401. static char *progname = "python";
  402.  
  403. void
  404. Py_SetProgramName(pn)
  405.     char *pn;
  406. {
  407.     if (pn && *pn)
  408.         progname = pn;
  409. }
  410.  
  411. char *
  412. Py_GetProgramName()
  413. {
  414.     return progname;
  415. }
  416.  
  417. static char *default_home = NULL;
  418.  
  419. void
  420. Py_SetPythonHome(home)
  421.     char *home;
  422. {
  423.     default_home = home;
  424. }
  425.  
  426. char *
  427. Py_GetPythonHome()
  428. {
  429.     char *home = default_home;
  430.     if (home == NULL)
  431.         home = getenv("PYTHONHOME");
  432.     return home;
  433. }
  434.  
  435. /* Create __main__ module */
  436.  
  437. static void
  438. initmain()
  439. {
  440.     PyObject *m, *d;
  441.     m = PyImport_AddModule("__main__");
  442.     if (m == NULL)
  443.         Py_FatalError("can't create __main__ module");
  444.     d = PyModule_GetDict(m);
  445.     if (PyDict_GetItemString(d, "__builtins__") == NULL) {
  446.         PyObject *bimod = PyImport_ImportModule("__builtin__");
  447.         if (bimod == NULL ||
  448.             PyDict_SetItemString(d, "__builtins__", bimod) != 0)
  449.             Py_FatalError("can't add __builtins__ to __main__");
  450.         Py_DECREF(bimod);
  451.     }
  452. }
  453.  
  454. /* Import the site module (not into __main__ though) */
  455.  
  456. static void
  457. initsite()
  458. {
  459.     PyObject *m, *f;
  460.     m = PyImport_ImportModule("site");
  461.     if (m == NULL) {
  462.         f = PySys_GetObject("stderr");
  463.         if (Py_VerboseFlag) {
  464.             PyFile_WriteString(
  465.                 "'import site' failed; traceback:\n", f);
  466.             PyErr_Print();
  467.         }
  468.         else {
  469.             PyFile_WriteString(
  470.               "'import site' failed; use -v for traceback\n", f);
  471.             PyErr_Clear();
  472.         }
  473.     }
  474.     else {
  475.         Py_DECREF(m);
  476.     }
  477. }
  478.  
  479. /* Parse input from a file and execute it */
  480. #ifndef WITHOUT_COMPILER
  481. int
  482. PyRun_AnyFile(fp, filename)
  483.     FILE *fp;
  484.     char *filename;
  485. {
  486.     if (filename == NULL)
  487.         filename = "???";
  488.     if (Py_FdIsInteractive(fp, filename))
  489.         return PyRun_InteractiveLoop(fp, filename);
  490.     else
  491.         return PyRun_SimpleFile(fp, filename);
  492. }
  493.  
  494. int
  495. PyRun_InteractiveLoop(fp, filename)
  496.     FILE *fp;
  497.     char *filename;
  498. {
  499.     PyObject *v;
  500.     int ret;
  501.     v = PySys_GetObject("ps1");
  502.     if (v == NULL) {
  503.         PySys_SetObject("ps1", v = PyString_FromString(">>> "));
  504.         Py_XDECREF(v);
  505.     }
  506.     v = PySys_GetObject("ps2");
  507.     if (v == NULL) {
  508.         PySys_SetObject("ps2", v = PyString_FromString("... "));
  509.         Py_XDECREF(v);
  510.     }
  511.     for (;;) {
  512.         ret = PyRun_InteractiveOne(fp, filename);
  513. #ifdef Py_REF_DEBUG
  514.         fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
  515. #endif
  516.         if (ret == E_EOF)
  517.             return 0;
  518.         /*
  519.         if (ret == E_NOMEM)
  520.             return -1;
  521.         */
  522.     }
  523. }
  524.  
  525. int
  526. PyRun_InteractiveOne(fp, filename)
  527.     FILE *fp;
  528.     char *filename;
  529. {
  530.     PyObject *m, *d, *v, *w;
  531.     node *n;
  532.     perrdetail err;
  533.     char *ps1 = "", *ps2 = "";
  534.     v = PySys_GetObject("ps1");
  535.     if (v != NULL) {
  536.         v = PyObject_Str(v);
  537.         if (v == NULL)
  538.             PyErr_Clear();
  539.         else if (PyString_Check(v))
  540.             ps1 = PyString_AsString(v);
  541.     }
  542.     w = PySys_GetObject("ps2");
  543.     if (w != NULL) {
  544.         w = PyObject_Str(w);
  545.         if (w == NULL)
  546.             PyErr_Clear();
  547.         else if (PyString_Check(w))
  548.             ps2 = PyString_AsString(w);
  549.     }
  550.     n = PyParser_ParseFile(fp, filename, &_PyParser_Grammar,
  551.                    Py_single_input, ps1, ps2, &err);
  552.     Py_XDECREF(v);
  553.     Py_XDECREF(w);
  554.     if (n == NULL) {
  555.         if (err.error == E_EOF) {
  556.             if (err.text)
  557.                 free(err.text);
  558.             return E_EOF;
  559.         }
  560.         err_input(&err);
  561.         PyErr_Print();
  562.         return err.error;
  563.     }
  564.     m = PyImport_AddModule("__main__");
  565.     if (m == NULL)
  566.         return -1;
  567.     d = PyModule_GetDict(m);
  568.     v = run_node(n, filename, d, d);
  569.     if (v == NULL) {
  570.         PyErr_Print();
  571.         return -1;
  572.     }
  573.     Py_DECREF(v);
  574.     if (Py_FlushLine())
  575.         PyErr_Clear();
  576.     return 0;
  577. }
  578. #endif /* WITHOUT_COMPILER */
  579.  
  580. int
  581. PyRun_SimpleFile(fp, filename)
  582.     FILE *fp;
  583.     char *filename;
  584. {
  585.     PyObject *m, *d, *v;
  586.     char *ext;
  587.  
  588.     m = PyImport_AddModule("__main__");
  589.     if (m == NULL)
  590.         return -1;
  591.     d = PyModule_GetDict(m);
  592.     ext = filename + strlen(filename) - 4;
  593.     if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0
  594. #ifdef macintosh
  595.     /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
  596.         || getfiletype(filename) == 'PYC '
  597.         || getfiletype(filename) == 'APPL'
  598. #endif /* macintosh */
  599.         ) {
  600.         /* Try to run a pyc file. First, re-open in binary */
  601.         /* Don't close, done in main: fclose(fp); */
  602.         if( (fp = fopen(filename, "rb")) == NULL ) {
  603.             fprintf(stderr, "python: Can't reopen .pyc file\n");
  604.             return -1;
  605.         }
  606.         /* Turn on optimization if a .pyo file is given */
  607.         if (strcmp(ext, ".pyo") == 0)
  608.             Py_OptimizeFlag = 1;
  609.         v = run_pyc_file(fp, filename, d, d);
  610.     } else {
  611. #ifndef WITHOUT_COMPILER
  612.         v = PyRun_File(fp, filename, Py_file_input, d, d);
  613. #else /* !WITHOUT_COMPILER */
  614.         PyErr_SetString(PyExc_MissingFeatureError,
  615.                 "Compiling is not allowed");
  616.         v = NULL;
  617. #endif /* !WITHOUT_COMPILER */
  618.     }
  619.     if (v == NULL) {
  620.         PyErr_Print();
  621.         return -1;
  622.     }
  623.     Py_DECREF(v);
  624.     if (Py_FlushLine())
  625.         PyErr_Clear();
  626.     return 0;
  627. }
  628.  
  629. #ifndef WITHOUT_COMPILER
  630. int
  631. PyRun_SimpleString(command)
  632.     char *command;
  633. {
  634.     PyObject *m, *d, *v;
  635.     m = PyImport_AddModule("__main__");
  636.     if (m == NULL)
  637.         return -1;
  638.     d = PyModule_GetDict(m);
  639.     v = PyRun_String(command, Py_file_input, d, d);
  640.     if (v == NULL) {
  641.         PyErr_Print();
  642.         return -1;
  643.     }
  644.     Py_DECREF(v);
  645.     if (Py_FlushLine())
  646.         PyErr_Clear();
  647.     return 0;
  648. }
  649.  
  650. #endif /* WITHOUT_COMPILER */
  651.  
  652. static int
  653. parse_syntax_error(err, message, filename, lineno, offset, text)
  654.      PyObject* err;
  655.      PyObject** message;
  656.      char** filename;
  657.      int* lineno;
  658.      int* offset;
  659.      char** text;
  660. {
  661.     long hold;
  662.     PyObject *v;
  663.  
  664.     /* old style errors */
  665.     if (PyTuple_Check(err))
  666.         return PyArg_Parse(err, "(O(ziiz))", message, filename,
  667.                    lineno, offset, text);
  668.  
  669.     /* new style errors.  `err' is an instance */
  670.  
  671.     if (! (v = PyObject_GetAttrString(err, "msg")))
  672.         goto finally;
  673.     *message = v;
  674.  
  675.     if (!(v = PyObject_GetAttrString(err, "filename")))
  676.         goto finally;
  677.     if (v == Py_None)
  678.         *filename = NULL;
  679.     else if (! (*filename = PyString_AsString(v)))
  680.         goto finally;
  681.  
  682.     Py_DECREF(v);
  683.     if (!(v = PyObject_GetAttrString(err, "lineno")))
  684.         goto finally;
  685.     hold = PyInt_AsLong(v);
  686.     Py_DECREF(v);
  687.     v = NULL;
  688.     if (hold < 0 && PyErr_Occurred())
  689.         goto finally;
  690.     *lineno = (int)hold;
  691.  
  692.     if (!(v = PyObject_GetAttrString(err, "offset")))
  693.         goto finally;
  694.     hold = PyInt_AsLong(v);
  695.     Py_DECREF(v);
  696.     v = NULL;
  697.     if (hold < 0 && PyErr_Occurred())
  698.         goto finally;
  699.     *offset = (int)hold;
  700.  
  701.     if (!(v = PyObject_GetAttrString(err, "text")))
  702.         goto finally;
  703.     if (v == Py_None)
  704.         *text = NULL;
  705.     else if (! (*text = PyString_AsString(v)))
  706.         goto finally;
  707.     Py_DECREF(v);
  708.     return 1;
  709.  
  710. finally:
  711.     Py_XDECREF(v);
  712.     return 0;
  713. }
  714.  
  715. void
  716. PyErr_Print()
  717. {
  718.     PyErr_PrintEx(1);
  719. }
  720.  
  721. void
  722. PyErr_PrintEx(set_sys_last_vars)
  723.     int set_sys_last_vars;
  724. {
  725.     int err = 0;
  726.     PyObject *exception, *v, *tb, *f;
  727.     PyErr_Fetch(&exception, &v, &tb);
  728.     PyErr_NormalizeException(&exception, &v, &tb);
  729.  
  730.     if (exception == NULL)
  731.         return;
  732.  
  733.     if (PyErr_GivenExceptionMatches(exception, PyExc_SystemExit)) {
  734.         if (Py_FlushLine())
  735.             PyErr_Clear();
  736.         fflush(stdout);
  737.         if (v == NULL || v == Py_None)
  738.             Py_Exit(0);
  739.         if (PyInstance_Check(v)) {
  740.             /* we expect the error code to be store in the
  741.                `code' attribute
  742.             */
  743.             PyObject *code = PyObject_GetAttrString(v, "code");
  744.             if (code) {
  745.                 Py_DECREF(v);
  746.                 v = code;
  747.                 if (v == Py_None)
  748.                     Py_Exit(0);
  749.             }
  750.             /* if we failed to dig out the "code" attribute,
  751.                then just let the else clause below print the
  752.                error
  753.             */
  754.         }
  755.         if (PyInt_Check(v))
  756.             Py_Exit((int)PyInt_AsLong(v));
  757.         else {
  758.             /* OK to use real stderr here */
  759.             PyObject_Print(v, stderr, Py_PRINT_RAW);
  760.             fprintf(stderr, "\n");
  761.             Py_Exit(1);
  762.         }
  763.     }
  764.     if (set_sys_last_vars) {
  765.         PySys_SetObject("last_type", exception);
  766.         PySys_SetObject("last_value", v);
  767.         PySys_SetObject("last_traceback", tb);
  768.     }
  769.     f = PySys_GetObject("stderr");
  770.     if (f == NULL)
  771.         fprintf(stderr, "lost sys.stderr\n");
  772.     else {
  773.         if (Py_FlushLine())
  774.             PyErr_Clear();
  775.         fflush(stdout);
  776.         DMESSAGE("Starting traceback");
  777.         err = PyTraceBack_Print(tb, f);
  778.         DMESSAGE("Done traceback");
  779.         if (err == 0 &&
  780.             PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError))
  781.         {
  782.             PyObject *message;
  783.             char *filename, *text;
  784.             int lineno, offset;
  785.             if (!parse_syntax_error(v, &message, &filename,
  786.                         &lineno, &offset, &text))
  787.                 PyErr_Clear();
  788.             else {
  789.                 char buf[10];
  790.                 PyFile_WriteString("  File \"", f);
  791.                 if (filename == NULL)
  792.                     PyFile_WriteString("<string>", f);
  793.                 else
  794.                     PyFile_WriteString(filename, f);
  795.                 PyFile_WriteString("\", line ", f);
  796.                 sprintf(buf, "%d", lineno);
  797.                 PyFile_WriteString(buf, f);
  798.                 PyFile_WriteString("\n", f);
  799.                 if (text != NULL) {
  800.                     char *nl;
  801.                     if (offset > 0 &&
  802.                         offset == (int)strlen(text))
  803.                         offset--;
  804.                     for (;;) {
  805.                         nl = strchr(text, '\n');
  806.                         if (nl == NULL ||
  807.                             nl-text >= offset)
  808.                             break;
  809.                         offset -= (nl+1-text);
  810.                         text = nl+1;
  811.                     }
  812.                     while (*text == ' ' || *text == '\t') {
  813.                         text++;
  814.                         offset--;
  815.                     }
  816.                     PyFile_WriteString("    ", f);
  817.                     PyFile_WriteString(text, f);
  818.                     if (*text == '\0' ||
  819.                         text[strlen(text)-1] != '\n')
  820.                         PyFile_WriteString("\n", f);
  821.                     PyFile_WriteString("    ", f);
  822.                     offset--;
  823.                     while (offset > 0) {
  824.                         PyFile_WriteString(" ", f);
  825.                         offset--;
  826.                     }
  827.                     PyFile_WriteString("^\n", f);
  828.                 }
  829.                 Py_INCREF(message);
  830.                 Py_DECREF(v);
  831.                 v = message;
  832.                 /* Can't be bothered to check all those
  833.                    PyFile_WriteString() calls */
  834.                 if (PyErr_Occurred())
  835.                     err = -1;
  836.             }
  837.         }
  838.         if (err) {
  839.             /* Don't do anything else */
  840.             printf("error occurred during traceback\n");
  841.         }
  842.         else if (PyClass_Check(exception)) {
  843.             PyClassObject* exc = (PyClassObject*)exception;
  844.             PyObject* className = exc->cl_name;
  845.             PyObject* moduleName =
  846.                   PyDict_GetItemString(exc->cl_dict, "__module__");
  847.  
  848.             if (moduleName == NULL)
  849.                 err = PyFile_WriteString("<unknown>", f);
  850.             else {
  851.                 char* modstr = PyString_AsString(moduleName);
  852.                 if (modstr && strcmp(modstr, "exceptions")) 
  853.                 {
  854.                     err = PyFile_WriteString(modstr, f);
  855.                     err += PyFile_WriteString(".", f);
  856.                 }
  857.             }
  858.             if (err == 0) {
  859.                 if (className == NULL)
  860.                       err = PyFile_WriteString("<unknown>", f);
  861.                 else
  862.                       err = PyFile_WriteObject(className, f,
  863.                                    Py_PRINT_RAW);
  864.             }
  865.         }
  866.         else
  867.             err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
  868.         if (err == 0) {
  869.             if (v != NULL && v != Py_None) {
  870.                 PyObject *s = PyObject_Str(v);
  871.                 /* only print colon if the str() of the
  872.                    object is not the empty string
  873.                 */
  874.                 if (s == NULL)
  875.                     err = -1;
  876.                 else if (!PyString_Check(s) ||
  877.                      PyString_GET_SIZE(s) != 0)
  878.                     err = PyFile_WriteString(": ", f);
  879.                 if (err == 0)
  880.                   err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
  881.                 Py_XDECREF(s);
  882.             }
  883.         }
  884.         if (err == 0)
  885.             err = PyFile_WriteString("\n", f);
  886.     }
  887.     Py_XDECREF(exception);
  888.     Py_XDECREF(v);
  889.     Py_XDECREF(tb);
  890.     /* If an error happened here, don't show it.
  891.        XXX This is wrong, but too many callers rely on this behavior. */
  892.     if (err != 0)
  893.         PyErr_Clear();
  894. }
  895.  
  896. #ifndef WITHOUT_COMPILER
  897. PyObject *
  898. PyRun_String(str, start, globals, locals)
  899.     char *str;
  900.     int start;
  901.     PyObject *globals, *locals;
  902. {
  903.     return run_err_node(PyParser_SimpleParseString(str, start),
  904.                 "<string>", globals, locals);
  905. }
  906.  
  907. PyObject *
  908. PyRun_File(fp, filename, start, globals, locals)
  909.     FILE *fp;
  910.     char *filename;
  911.     int start;
  912.     PyObject *globals, *locals;
  913. {
  914.     return run_err_node(PyParser_SimpleParseFile(fp, filename, start),
  915.                 filename, globals, locals);
  916. }
  917.  
  918. static PyObject *
  919. run_err_node(n, filename, globals, locals)
  920.     node *n;
  921.     char *filename;
  922.     PyObject *globals, *locals;
  923. {
  924.     if (n == NULL)
  925.         return  NULL;
  926.     return run_node(n, filename, globals, locals);
  927. }
  928.  
  929. static PyObject *
  930. run_node(n, filename, globals, locals)
  931.     node *n;
  932.     char *filename;
  933.     PyObject *globals, *locals;
  934. {
  935.     PyCodeObject *co;
  936.     PyObject *v;
  937.     co = PyNode_Compile(n, filename);
  938.     PyNode_Free(n);
  939.     if (co == NULL)
  940.         return NULL;
  941.     v = PyEval_EvalCode(co, globals, locals);
  942.     Py_DECREF(co);
  943.     return v;
  944. }
  945. #endif /* WITHOUT_COMPILER */
  946.  
  947.  
  948. static PyObject *
  949. run_pyc_file(fp, filename, globals, locals)
  950.     FILE *fp;
  951.     char *filename;
  952.     PyObject *globals, *locals;
  953. {
  954.     PyCodeObject *co;
  955.     PyObject *v;
  956.     long magic;
  957.     long PyImport_GetMagicNumber();
  958.  
  959.     magic = PyMarshal_ReadLongFromFile(fp);
  960.     if (magic != PyImport_GetMagicNumber()) {
  961.         PyErr_SetString(PyExc_RuntimeError,
  962.                "Bad magic number in .pyc file");
  963.         return NULL;
  964.     }
  965.     (void) PyMarshal_ReadLongFromFile(fp);
  966.     v = PyMarshal_ReadObjectFromFile(fp);
  967.     fclose(fp);
  968.     if (v == NULL || !PyCode_Check(v)) {
  969.         Py_XDECREF(v);
  970.         PyErr_SetString(PyExc_RuntimeError,
  971.                "Bad code object in .pyc file");
  972.         return NULL;
  973.     }
  974.     co = (PyCodeObject *)v;
  975.     v = PyEval_EvalCode(co, globals, locals);
  976.     Py_DECREF(co);
  977.     return v;
  978. }
  979.  
  980. #ifndef WITHOUT_COMPILER
  981. PyObject *
  982. Py_CompileString(str, filename, start)
  983.     char *str;
  984.     char *filename;
  985.     int start;
  986. {
  987.     node *n;
  988.     PyCodeObject *co;
  989.     n = PyParser_SimpleParseString(str, start);
  990.     if (n == NULL)
  991.         return NULL;
  992.     co = PyNode_Compile(n, filename);
  993.     PyNode_Free(n);
  994.     return (PyObject *)co;
  995. }
  996.  
  997. /* Simplified interface to parsefile -- return node or set exception */
  998.  
  999. node *
  1000. PyParser_SimpleParseFile(fp, filename, start)
  1001.     FILE *fp;
  1002.     char *filename;
  1003.     int start;
  1004. {
  1005.     node *n;
  1006.     perrdetail err;
  1007.     n = PyParser_ParseFile(fp, filename, &_PyParser_Grammar, start,
  1008.                 (char *)0, (char *)0, &err);
  1009.     if (n == NULL)
  1010.         err_input(&err);
  1011.     return n;
  1012. }
  1013.  
  1014.  
  1015. /* Simplified interface to parsestring -- return node or set exception */
  1016.  
  1017. node *
  1018. PyParser_SimpleParseString(str, start)
  1019.     char *str;
  1020.     int start;
  1021. {
  1022.     node *n;
  1023.     perrdetail err;
  1024.     n = PyParser_ParseString(str, &_PyParser_Grammar, start, &err);
  1025.     if (n == NULL)
  1026.         err_input(&err);
  1027.     return n;
  1028. }
  1029. #endif /* WITHOUT_COMPILER */
  1030.  
  1031. /* Set the error appropriate to the given input error code (see errcode.h) */
  1032. #ifndef WITHOUT_COMPILER
  1033.  
  1034. static void
  1035. err_input(err)
  1036.     perrdetail *err;
  1037. {
  1038.     PyObject *v, *w;
  1039.     char *msg = NULL;
  1040.     v = Py_BuildValue("(ziiz)", err->filename,
  1041.                 err->lineno, err->offset, err->text);
  1042.     if (err->text != NULL) {
  1043.         free(err->text);
  1044.         err->text = NULL;
  1045.     }
  1046.     switch (err->error) {
  1047.     case E_SYNTAX:
  1048.         msg = "invalid syntax";
  1049.         break;
  1050.     case E_TOKEN:
  1051.         msg = "invalid token";
  1052.         break;
  1053.     case E_INTR:
  1054.         PyErr_SetNone(PyExc_KeyboardInterrupt);
  1055.         Py_XDECREF(v);
  1056.         return;
  1057.     case E_NOMEM:
  1058.         PyErr_NoMemory();
  1059.         Py_XDECREF(v);
  1060.         return;
  1061.     case E_EOF:
  1062.         msg = "unexpected EOF while parsing";
  1063.         break;
  1064.     case E_INDENT:
  1065.         msg = "inconsistent use of tabs and spaces in indentation";
  1066.         break;
  1067.     default:
  1068.         fprintf(stderr, "error=%d\n", err->error);
  1069.         msg = "unknown parsing error";
  1070.         break;
  1071.     }
  1072.     w = Py_BuildValue("(sO)", msg, v);
  1073.     Py_XDECREF(v);
  1074.     PyErr_SetObject(PyExc_SyntaxError, w);
  1075.     Py_XDECREF(w);
  1076. }
  1077. #endif /* WITHOUT_COMPILER */
  1078.  
  1079. /* Print fatal error message and abort */
  1080.  
  1081. void
  1082. Py_FatalError(msg)
  1083.     char *msg;
  1084. {
  1085.     fprintf(stderr, "Fatal Python error: %s\n", msg);
  1086. #ifdef macintosh
  1087.     for (;;);
  1088. #endif
  1089. #ifdef MS_WIN32
  1090.     OutputDebugString("Fatal Python error: ");
  1091.     OutputDebugString(msg);
  1092.     OutputDebugString("\n");
  1093. #ifdef _DEBUG
  1094.     DebugBreak();
  1095. #endif
  1096. #endif /* MS_WIN32 */
  1097.     abort();
  1098. }
  1099.  
  1100. /* Clean up and exit */
  1101.  
  1102. #ifdef WITH_THREAD
  1103. #include "pythread.h"
  1104. int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
  1105. #endif
  1106.  
  1107. #define NEXITFUNCS 32
  1108. static void (*exitfuncs[NEXITFUNCS])();
  1109. static int nexitfuncs = 0;
  1110.  
  1111. int Py_AtExit(func)
  1112.     void (*func) Py_PROTO((void));
  1113. {
  1114.     if (nexitfuncs >= NEXITFUNCS)
  1115.         return -1;
  1116.     exitfuncs[nexitfuncs++] = func;
  1117.     return 0;
  1118. }
  1119.  
  1120. static void
  1121. call_sys_exitfunc()
  1122. {
  1123.     PyObject *exitfunc = PySys_GetObject("exitfunc");
  1124.  
  1125.     if (exitfunc) {
  1126.         PyObject *res, *f;
  1127.         Py_INCREF(exitfunc);
  1128.         PySys_SetObject("exitfunc", (PyObject *)NULL);
  1129.         f = PySys_GetObject("stderr");
  1130.         res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
  1131.         if (res == NULL) {
  1132.             if (f)
  1133.                 PyFile_WriteString("Error in sys.exitfunc:\n", f);
  1134.             PyErr_Print();
  1135.         }
  1136.         Py_DECREF(exitfunc);
  1137.     }
  1138.  
  1139.     if (Py_FlushLine())
  1140.         PyErr_Clear();
  1141. }
  1142.  
  1143. static void
  1144. call_ll_exitfuncs()
  1145. {
  1146.     while (nexitfuncs > 0)
  1147.         (*exitfuncs[--nexitfuncs])();
  1148.  
  1149.     fflush(stdout);
  1150.     fflush(stderr);
  1151. }
  1152.  
  1153. void
  1154. Py_Exit(sts)
  1155.     int sts;
  1156. {
  1157.     Py_Finalize();
  1158.  
  1159. #ifdef macintosh
  1160.     PyMac_Exit(sts);
  1161. #else
  1162.     exit(sts);
  1163. #endif
  1164. }
  1165.  
  1166. static void
  1167. initsigs()
  1168. {
  1169. #ifdef HAVE_SIGNAL_H
  1170. #ifdef SIGPIPE
  1171.     signal(SIGPIPE, SIG_IGN);
  1172. #endif
  1173. #endif /* HAVE_SIGNAL_H */
  1174.     PyOS_InitInterrupts(); /* May imply initsignal() */
  1175. }
  1176.  
  1177. #ifdef Py_TRACE_REFS
  1178. /* Ask a yes/no question */
  1179.  
  1180. int
  1181. _Py_AskYesNo(prompt)
  1182.     char *prompt;
  1183. {
  1184.     char buf[256];
  1185.     
  1186.     printf("%s [ny] ", prompt);
  1187.     if (fgets(buf, sizeof buf, stdin) == NULL)
  1188.         return 0;
  1189.     return buf[0] == 'y' || buf[0] == 'Y';
  1190. }
  1191. #endif
  1192.  
  1193. #ifdef MPW
  1194.  
  1195. /* Check for file descriptor connected to interactive device.
  1196.    Pretend that stdin is always interactive, other files never. */
  1197.  
  1198. int
  1199. isatty(fd)
  1200.     int fd;
  1201. {
  1202.     return fd == fileno(stdin);
  1203. }
  1204.  
  1205. #endif
  1206.  
  1207. /*
  1208.  * The file descriptor fd is considered ``interactive'' if either
  1209.  *   a) isatty(fd) is TRUE, or
  1210.  *   b) the -i flag was given, and the filename associated with
  1211.  *      the descriptor is NULL or "<stdin>" or "???".
  1212.  */
  1213. int
  1214. Py_FdIsInteractive(fp, filename)
  1215.     FILE *fp;
  1216.     char *filename;
  1217. {
  1218.     if (isatty((int)fileno(fp)))
  1219.         return 1;
  1220.     if (!Py_InteractiveFlag)
  1221.         return 0;
  1222.     return (filename == NULL) ||
  1223.            (strcmp(filename, "<stdin>") == 0) ||
  1224.            (strcmp(filename, "???") == 0);
  1225. }
  1226.