home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 7 / Apprentice-Release7.iso / Source Code / C / Applications / Python 1.4 / Python 1.4 source / Python / import.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-10-28  |  21.7 KB  |  1,047 lines  |  [TEXT/CWIE]

  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. /* Module definition and import implementation */
  33.  
  34. #include "allobjects.h"
  35.  
  36. /* XXX Some of the following are duplicate with allobjects.h... */
  37. #include "node.h"
  38. #include "token.h"
  39. #include "graminit.h"
  40. #include "import.h"
  41. #include "errcode.h"
  42. #include "sysmodule.h"
  43. #include "bltinmodule.h"
  44. #include "pythonrun.h"
  45. #include "marshal.h"
  46. #include "compile.h"
  47. #include "eval.h"
  48. #include "osdefs.h"
  49. #include "importdl.h"
  50. #ifdef macintosh
  51. /* 'argument' is a grammar symbol, but also used in some mac header files */
  52. #undef argument
  53. #include "macglue.h"
  54. #endif
  55.  
  56. extern long getmtime(); /* In getmtime.c */
  57.  
  58. /* Magic word to reject .pyc files generated by other Python versions */
  59. /* Change for each incompatible change */
  60. /* The value of CR and LF is incorporated so if you ever read or write
  61.    a .pyc file in text mode the magic number will be wrong; also, the
  62.    Apple MPW compiler swaps their values, botching string constants */
  63. /* XXX Perhaps the magic number should be frozen and a version field
  64.    added to the .pyc file header? */
  65. #define MAGIC (5892 | ((long)'\r'<<16) | ((long)'\n'<<24))
  66.  
  67. object *import_modules; /* This becomes sys.modules */
  68.  
  69.  
  70. /* Initialize things */
  71.  
  72. void
  73. initimport()
  74. {
  75.     if (import_modules != NULL)
  76.         fatal("duplicate initimport() call");
  77.     if ((import_modules = newdictobject()) == NULL)
  78.         fatal("no mem for dictionary of modules");
  79. }
  80.  
  81.  
  82. /* Un-initialize things, as good as we can */
  83.  
  84. void
  85. doneimport()
  86. {
  87.     if (import_modules != NULL) {
  88.         object *tmp = import_modules;
  89.         import_modules = NULL;
  90.         /* This deletes all modules from sys.modules.
  91.            When a module is deallocated, it in turn clears its dictionary,
  92.            thus hopefully breaking any circular references between modules
  93.            and between a module's dictionary and its functions.
  94.            Note that "import" will fail while we are cleaning up.
  95.            */
  96.         mappingclear(tmp);
  97.         DECREF(tmp);
  98.     }
  99. }
  100.  
  101.  
  102. /* Helper for pythonrun.c -- return magic number */
  103.  
  104. long
  105. get_pyc_magic()
  106. {
  107.     return MAGIC;
  108. }
  109.  
  110.  
  111. /* Helper for sysmodule.c -- return modules dictionary */
  112.  
  113. object *
  114. get_modules()
  115. {
  116.     return import_modules;
  117. }
  118.  
  119.  
  120. /* Get the module object corresponding to a module name.
  121.    First check the modules dictionary if there's one there,
  122.    if not, create a new one and insert in in the modules dictionary.
  123.    Because the former action is most common, THIS DOES NOT RETURN A
  124.    'NEW' REFERENCE! */
  125.  
  126. object *
  127. add_module(name)
  128.     char *name;
  129. {
  130.     object *m;
  131.  
  132.     if (import_modules == NULL) {
  133.         err_setstr(SystemError, "sys.modules has been deleted");
  134.         return NULL;
  135.     }
  136.     if ((m = dictlookup(import_modules, name)) != NULL &&
  137.         is_moduleobject(m))
  138.         return m;
  139.     m = newmoduleobject(name);
  140.     if (m == NULL)
  141.         return NULL;
  142.     if (dictinsert(import_modules, name, m) != 0) {
  143.         DECREF(m);
  144.         return NULL;
  145.     }
  146.     DECREF(m); /* Yes, it still exists, in modules! */
  147.  
  148.     return m;
  149. }
  150.  
  151.  
  152. /* Execute a code object in a module and return the module object
  153.    WITH INCREMENTED REFERENCE COUNT */
  154.  
  155. object *
  156. exec_code_module(name, co)
  157.     char *name;
  158.     object *co;
  159. {
  160.     object *m, *d, *v;
  161.  
  162.     m = add_module(name);
  163.     if (m == NULL)
  164.         return NULL;
  165.     d = getmoduledict(m);
  166.     if (dictlookup(d, "__builtins__") == NULL) {
  167.         if (dictinsert(d, "__builtins__", getbuiltins()) != 0)
  168.             return NULL;
  169.     }
  170.     /* Remember the filename as the __file__ attribute */
  171.     if (dictinsert(d, "__file__", ((codeobject *)co)->co_filename) != 0)
  172.         err_clear(); /* Not important enough to report */
  173.     v = eval_code((codeobject *)co, d, d); /* XXX owner? */
  174.     if (v == NULL)
  175.         return NULL;
  176.     DECREF(v);
  177.     INCREF(m);
  178.  
  179.     return m;
  180. }
  181.  
  182.  
  183. /* Given a pathname for a Python source file, fill a buffer with the
  184.    pathname for the corresponding compiled file.  Return the pathname
  185.    for the compiled file, or NULL if there's no space in the buffer.
  186.    Doesn't set an exception. */
  187.  
  188. static char *
  189. make_compiled_pathname(pathname, buf, buflen)
  190.     char *pathname;
  191.     char *buf;
  192.     int buflen;
  193. {
  194.     int len;
  195.  
  196.     len = strlen(pathname);
  197.     if (len+2 > buflen)
  198.         return NULL;
  199.     strcpy(buf, pathname);
  200.     strcpy(buf+len, "c");
  201.  
  202.     return buf;
  203. }
  204.  
  205.  
  206. /* Given a pathname for a Python source file, its time of last
  207.    modification, and a pathname for a compiled file, check whether the
  208.    compiled file represents the same version of the source.  If so,
  209.    return a FILE pointer for the compiled file, positioned just after
  210.    the header; if not, return NULL.
  211.    Doesn't set an exception. */
  212.  
  213. static FILE *
  214. check_compiled_module(pathname, mtime, cpathname)
  215.     char *pathname;
  216.     long mtime;
  217.     char *cpathname;
  218. {
  219.     FILE *fp;
  220.     long magic;
  221.     long pyc_mtime;
  222.  
  223.     fp = fopen(cpathname, "rb");
  224.     if (fp == NULL)
  225.         return NULL;
  226.     magic = rd_long(fp);
  227.     if (magic != MAGIC) {
  228.         if (verbose)
  229.             fprintf(stderr, "# %s has bad magic\n", cpathname);
  230.         fclose(fp);
  231.         return NULL;
  232.     }
  233.     pyc_mtime = rd_long(fp);
  234.     if (pyc_mtime != mtime) {
  235.         if (verbose)
  236.             fprintf(stderr, "# %s has bad mtime\n", cpathname);
  237.         fclose(fp);
  238.         return NULL;
  239.     }
  240.     if (verbose)
  241.         fprintf(stderr, "# %s matches %s\n", cpathname, pathname);
  242.     return fp;
  243. }
  244.  
  245.  
  246. /* Read a code object from a file and check it for validity */
  247.  
  248. static codeobject *
  249. read_compiled_module(fp)
  250.     FILE *fp;
  251. {
  252.     object *co;
  253.  
  254.     co = rd_object(fp);
  255.     /* Ugly: rd_object() may return NULL with or without error */
  256.     if (co == NULL || !is_codeobject(co)) {
  257.         if (!err_occurred())
  258.             err_setstr(ImportError,
  259.                    "Non-code object in .pyc file");
  260.         XDECREF(co);
  261.         return NULL;
  262.     }
  263.     return (codeobject *)co;
  264. }
  265.  
  266.  
  267. /* Load a module from a compiled file, execute it, and return its
  268.    module object WITH INCREMENTED REFERENCE COUNT */
  269.  
  270. static object *
  271. load_compiled_module(name, cpathname, fp)
  272.     char *name;
  273.     char *cpathname;
  274.     FILE *fp;
  275. {
  276.     long magic;
  277.     codeobject *co;
  278.     object *m;
  279.  
  280.     magic = rd_long(fp);
  281.     if (magic != MAGIC) {
  282.         err_setstr(ImportError, "Bad magic number in .pyc file");
  283.         return NULL;
  284.     }
  285.     (void) rd_long(fp);
  286.     co = read_compiled_module(fp);
  287.     if (co == NULL)
  288.         return NULL;
  289.     if (verbose)
  290.         fprintf(stderr, "import %s # precompiled from %s\n",
  291.             name, cpathname);
  292.     m = exec_code_module(name, (object *)co);
  293.     DECREF(co);
  294.  
  295.     return m;
  296. }
  297.  
  298. /* Parse a source file and return the corresponding code object */
  299.  
  300. static codeobject *
  301. parse_source_module(pathname, fp)
  302.     char *pathname;
  303.     FILE *fp;
  304. {
  305.     codeobject *co;
  306.     node *n;
  307.  
  308.     n = parse_file(fp, pathname, file_input);
  309.     if (n == NULL)
  310.         return NULL;
  311.     co = compile(n, pathname);
  312.     freetree(n);
  313.  
  314.     return co;
  315. }
  316.  
  317.  
  318. /* Write a compiled module to a file, placing the time of last
  319.    modification of its source into the header.
  320.    Errors are ignored, if a write error occurs an attempt is made to
  321.    remove the file. */
  322.  
  323. static void
  324. write_compiled_module(co, cpathname, mtime)
  325.     codeobject *co;
  326.     char *cpathname;
  327.     long mtime;
  328. {
  329.     FILE *fp;
  330.  
  331.     fp = fopen(cpathname, "wb");
  332.     if (fp == NULL) {
  333.         if (verbose)
  334.             fprintf(stderr,
  335.                 "# can't create %s\n", cpathname);
  336.         return;
  337.     }
  338.     wr_long(MAGIC, fp);
  339.     /* First write a 0 for mtime */
  340.     wr_long(0L, fp);
  341.     wr_object((object *)co, fp);
  342.     if (ferror(fp)) {
  343.         if (verbose)
  344.             fprintf(stderr, "# can't write %s\n", cpathname);
  345.         /* Don't keep partial file */
  346.         fclose(fp);
  347.         (void) unlink(cpathname);
  348.         return;
  349.     }
  350.     /* Now write the true mtime */
  351.     fseek(fp, 4L, 0);
  352.     wr_long(mtime, fp);
  353.     fflush(fp);
  354.     fclose(fp);
  355.     if (verbose)
  356.         fprintf(stderr, "# wrote %s\n", cpathname);
  357. #ifdef macintosh
  358.     setfiletype(cpathname, 'Pyth', 'PYC ');
  359. #endif
  360. }
  361.  
  362.  
  363. /* Load a source module from a given file and return its module
  364.    object WITH INCREMENTED REFERENCE COUNT.  If there's a matching
  365.    byte-compiled file, use that instead. */
  366.  
  367. static object *
  368. load_source_module(name, pathname, fp)
  369.     char *name;
  370.     char *pathname;
  371.     FILE *fp;
  372. {
  373.     long mtime;
  374.     FILE *fpc;
  375.     char buf[MAXPATHLEN+1];
  376.     char *cpathname;
  377.     codeobject *co;
  378.     object *m;
  379.  
  380.     mtime = getmtime(pathname);
  381.     cpathname = make_compiled_pathname(pathname, buf, MAXPATHLEN+1);
  382.     if (cpathname != NULL &&
  383.         (fpc = check_compiled_module(pathname, mtime, cpathname))) {
  384.         co = read_compiled_module(fpc);
  385.         fclose(fpc);
  386.         if (co == NULL)
  387.             return NULL;
  388.         if (verbose)
  389.             fprintf(stderr, "import %s # precompiled from %s\n",
  390.                 name, cpathname);
  391.     }
  392.     else {
  393.         co = parse_source_module(pathname, fp);
  394.         if (co == NULL)
  395.             return NULL;
  396.         if (verbose)
  397.             fprintf(stderr, "import %s # from %s\n",
  398.                 name, pathname);
  399.         write_compiled_module(co, cpathname, mtime);
  400.     }
  401.     m = exec_code_module(name, (object *)co);
  402.     DECREF(co);
  403.  
  404.     return m;
  405. }
  406.  
  407.  
  408. /* Search the path (default sys.path) for a module.  Return the
  409.    corresponding filedescr struct, and (via return arguments) the
  410.    pathname and an open file.  Return NULL if the module is not found. */
  411.  
  412. static struct filedescr *
  413. find_module(name, path, buf, buflen, p_fp)
  414.     char *name;
  415.     object *path;
  416.     /* Output parameters: */
  417.     char *buf;
  418.     int buflen;
  419.     FILE **p_fp;
  420. {
  421.     int i, npath, len, namelen;
  422.     struct filedescr *fdp;
  423.     FILE *fp = NULL;
  424.  
  425. #ifdef MS_COREDLL
  426.     if ((fp=PyWin_FindRegisteredModule(name, &fdp, buf, buflen))!=NULL) {
  427.         *p_fp = fp;
  428.         return fdp;
  429.     }
  430. #endif
  431.  
  432.  
  433.     if (path == NULL)
  434.         path = sysget("path");
  435.     if (path == NULL || !is_listobject(path)) {
  436.         err_setstr(ImportError,
  437.                "sys.path must be a list of directory names");
  438.         return NULL;
  439.     }
  440.     npath = getlistsize(path);
  441.     namelen = strlen(name);
  442.     for (i = 0; i < npath; i++) {
  443.         object *v = getlistitem(path, i);
  444.         if (!is_stringobject(v))
  445.             continue;
  446.         len = getstringsize(v);
  447.         if (len + 2 + namelen + import_maxsuffixsize >= buflen)
  448.             continue; /* Too long */
  449.         strcpy(buf, getstringvalue(v));
  450.         if (strlen(buf) != len)
  451.             continue; /* v contains '\0' */
  452. #ifdef macintosh
  453.         if ( PyMac_FindResourceModule(name, buf) ) {
  454.             static struct filedescr resfiledescr = { "", "", PY_RESOURCE};
  455.             
  456.             return &resfiledescr;
  457.         }
  458. #endif
  459.         if (len > 0 && buf[len-1] != SEP)
  460.             buf[len++] = SEP;
  461. #ifdef IMPORT_8x3_NAMES
  462.         /* see if we are searching in directory dos_8x3 */
  463.         if (len > 7 && !strncmp(buf + len - 8, "dos_8x3", 7)){
  464.             int j;
  465.             char ch;  /* limit name to eight lower-case characters */
  466.             for (j = 0; (ch = name[j]) && j < 8; j++)
  467.                 if (isupper(ch))
  468.                     buf[len++] = tolower(ch);
  469.                 else
  470.                     buf[len++] = ch;
  471.         }
  472.         else /* Not in dos_8x3, use the full name */
  473. #endif
  474.         {
  475.             strcpy(buf+len, name);
  476.             len += namelen;
  477.         }
  478.         for (fdp = import_filetab; fdp->suffix != NULL; fdp++) {
  479.             strcpy(buf+len, fdp->suffix);
  480.             if (verbose > 1)
  481.                 fprintf(stderr, "# trying %s\n", buf);
  482.             fp = fopen(buf, fdp->mode);
  483.             if (fp != NULL)
  484.                 break;
  485.         }
  486.         if (fp != NULL)
  487.             break;
  488.     }
  489.     if (fp == NULL) {
  490.         char buf[256];
  491.         sprintf(buf, "No module named %.200s", name);
  492.         err_setstr(ImportError, buf);
  493.         return NULL;
  494.     }
  495.  
  496.     *p_fp = fp;
  497.     return fdp;
  498. }
  499.  
  500.  
  501. /* Load an external module using the default search path and return
  502.    its module object WITH INCREMENTED REFERENCE COUNT */
  503.  
  504. static object *
  505. load_module(name)
  506.     char *name;
  507. {
  508.     char buf[MAXPATHLEN+1];
  509.     struct filedescr *fdp;
  510.     FILE *fp = NULL;
  511.     object *m;
  512.  
  513.     fdp = find_module(name, (object *)NULL, buf, MAXPATHLEN+1, &fp);
  514.     if (fdp == NULL)
  515.         return NULL;
  516.  
  517.     switch (fdp->type) {
  518.  
  519.     case PY_SOURCE:
  520.         m = load_source_module(name, buf, fp);
  521.         break;
  522.  
  523.     case PY_COMPILED:
  524.         m = load_compiled_module(name, buf, fp);
  525.         break;
  526.  
  527.     case C_EXTENSION:
  528.         m = load_dynamic_module(name, buf, fp);
  529.         break;
  530.  
  531. #ifdef macintosh
  532.     case PY_RESOURCE:
  533.         m = PyMac_LoadResourceModule(name, buf);
  534.         break;
  535. #endif
  536.  
  537.     default:
  538.         err_setstr(SystemError,
  539.                "find_module returned unexpected result");
  540.         m = NULL;
  541.  
  542.     }
  543.     if ( fp )
  544.         fclose(fp);
  545.  
  546.     return m;
  547. }
  548.  
  549.  
  550. /* Initialize a built-in module.
  551.    Return 1 for succes, 0 if the module is not found, and -1 with
  552.    an exception set if the initialization failed. */
  553.  
  554. static int
  555. init_builtin(name)
  556.     char *name;
  557. {
  558.     int i;
  559.     for (i = 0; inittab[i].name != NULL; i++) {
  560.         if (strcmp(name, inittab[i].name) == 0) {
  561.             if (inittab[i].initfunc == NULL) {
  562.                 err_setstr(ImportError,
  563.                        "Cannot re-init internal module");
  564.                 return -1;
  565.             }
  566.             if (verbose)
  567.                 fprintf(stderr, "import %s # builtin\n",
  568.                     name);
  569.             (*inittab[i].initfunc)();
  570.             if (err_occurred())
  571.                 return -1;
  572.             return 1;
  573.         }
  574.     }
  575.     return 0;
  576. }
  577.  
  578.  
  579. /* Frozen modules */
  580.  
  581. static struct _frozen *
  582. find_frozen(name)
  583.     char *name;
  584. {
  585.     struct _frozen *p;
  586.  
  587.     for (p = frozen_modules; ; p++) {
  588.         if (p->name == NULL)
  589.             return NULL;
  590.         if (strcmp(p->name, name) == 0)
  591.             break;
  592.     }
  593.     return p;
  594. }
  595.  
  596. static object *
  597. get_frozen_object(name)
  598.     char *name;
  599. {
  600.     struct _frozen *p = find_frozen(name);
  601.  
  602.     if (p == NULL) {
  603.         err_setstr(ImportError, "No such frozen object");
  604.         return NULL;
  605.     }
  606.     return rds_object((char *)p->code, p->size);
  607. }
  608.  
  609. /* Initialize a frozen module.
  610.    Return 1 for succes, 0 if the module is not found, and -1 with
  611.    an exception set if the initialization failed.
  612.    This function is also used from frozenmain.c */
  613.  
  614. int
  615. init_frozen(name)
  616.     char *name;
  617. {
  618.     struct _frozen *p = find_frozen(name);
  619.     object *co;
  620.     object *m;
  621.  
  622.     if (p == NULL)
  623.         return 0;
  624.     if (verbose)
  625.         fprintf(stderr, "import %s # frozen\n", name);
  626.     co = rds_object((char *)p->code, p->size);
  627.     if (co == NULL)
  628.         return -1;
  629.     if (!is_codeobject(co)) {
  630.         DECREF(co);
  631.         err_setstr(TypeError, "frozen object is not a code object");
  632.         return -1;
  633.     }
  634.     m = exec_code_module(name, co);
  635.     DECREF(co);
  636.     if (m == NULL)
  637.         return -1;
  638.     DECREF(m);
  639.     return 1;
  640. }
  641.  
  642.  
  643. /* Import a module, either built-in, frozen, or external, and return
  644.    its module object WITH INCREMENTED REFERENCE COUNT */
  645.  
  646. object *
  647. import_module(name)
  648.     char *name;
  649. {
  650.     object *m;
  651.  
  652.     if (import_modules == NULL) {
  653.         err_setstr(SystemError, "sys.modules has been deleted");
  654.         return NULL;
  655.     }
  656.     if ((m = dictlookup(import_modules, name)) != NULL) {
  657.         INCREF(m);
  658.     }
  659.     else {
  660.         int i;
  661.         if ((i = init_builtin(name)) || (i = init_frozen(name))) {
  662.             if (i < 0)
  663.                 return NULL;
  664.             if ((m = dictlookup(import_modules, name)) == NULL) {
  665.                 if (err_occurred() == NULL)
  666.                     err_setstr(SystemError,
  667.                  "built-in module not initialized properly");
  668.             }
  669.             else
  670.                 INCREF(m);
  671.         }
  672.         else
  673.             m = load_module(name);
  674.     }
  675.  
  676.     return m;
  677. }
  678.  
  679.  
  680. /* Re-import a module of any kind and return its module object, WITH
  681.    INCREMENTED REFERENCE COUNT */
  682.  
  683. object *
  684. reload_module(m)
  685.     object *m;
  686. {
  687.     char *name;
  688.     int i;
  689.  
  690.     if (m == NULL || !is_moduleobject(m)) {
  691.         err_setstr(TypeError, "reload() argument must be module");
  692.         return NULL;
  693.     }
  694.     name = getmodulename(m);
  695.     if (name == NULL)
  696.         return NULL;
  697.     if (import_modules == NULL) {
  698.         err_setstr(SystemError, "sys.modules has been deleted");
  699.         return NULL;
  700.     }
  701.     if (m != dictlookup(import_modules, name)) {
  702.         err_setstr(ImportError, "reload() module not in sys.modules");
  703.         return NULL;
  704.     }
  705.     /* Check for built-in and frozen modules */
  706.     if ((i = init_builtin(name)) || (i = init_frozen(name))) {
  707.         if (i < 0)
  708.             return NULL;
  709.         INCREF(m);
  710.     }
  711.     else
  712.         m = load_module(name);
  713.     return m;
  714. }
  715.  
  716.  
  717. /* Module 'imp' provides Python access to the primitives used for
  718.    importing modules.
  719. */
  720.  
  721. static object *
  722. imp_get_magic(self, args)
  723.     object *self;
  724.     object *args;
  725. {
  726.     char buf[4];
  727.  
  728.     if (!newgetargs(args, ""))
  729.         return NULL;
  730.     buf[0] = (MAGIC >>  0) & 0xff;
  731.     buf[1] = (MAGIC >>  8) & 0xff;
  732.     buf[2] = (MAGIC >> 16) & 0xff;
  733.     buf[3] = (MAGIC >> 24) & 0xff;
  734.  
  735.     return newsizedstringobject(buf, 4);
  736. }
  737.  
  738. static object *
  739. imp_get_suffixes(self, args)
  740.     object *self;
  741.     object *args;
  742. {
  743.     object *list;
  744.     struct filedescr *fdp;
  745.  
  746.     if (!newgetargs(args, ""))
  747.         return NULL;
  748.     list = newlistobject(0);
  749.     if (list == NULL)
  750.         return NULL;
  751.     for (fdp = import_filetab; fdp->suffix != NULL; fdp++) {
  752.         object *item = mkvalue("ssi",
  753.                        fdp->suffix, fdp->mode, fdp->type);
  754.         if (item == NULL) {
  755.             DECREF(list);
  756.             return NULL;
  757.         }
  758.         if (addlistitem(list, item) < 0) {
  759.             DECREF(list);
  760.             DECREF(item);
  761.             return NULL;
  762.         }
  763.         DECREF(item);
  764.     }
  765.     return list;
  766. }
  767.  
  768. static object *
  769. imp_find_module(self, args)
  770.     object *self;
  771.     object *args;
  772. {
  773.     extern int fclose PROTO((FILE *));
  774.     char *name;
  775.     object *path = NULL;
  776.     object *fob, *ret;
  777.     struct filedescr *fdp;
  778.     char pathname[MAXPATHLEN+1];
  779.     FILE *fp;
  780.     if (!newgetargs(args, "s|O!", &name, &Listtype, &path))
  781.         return NULL;
  782.     fdp = find_module(name, path, pathname, MAXPATHLEN+1, &fp);
  783.     if (fdp == NULL)
  784.         return NULL;
  785.     fob = newopenfileobject(fp, pathname, fdp->mode, fclose);
  786.     if (fob == NULL) {
  787.         fclose(fp);
  788.         return NULL;
  789.     }
  790.     ret = mkvalue("Os(ssi)",
  791.               fob, pathname, fdp->suffix, fdp->mode, fdp->type);
  792.     DECREF(fob);
  793.     return ret;
  794. }
  795.  
  796. static object *
  797. imp_init_builtin(self, args)
  798.     object *self;
  799.     object *args;
  800. {
  801.     char *name;
  802.     int ret;
  803.     object *m;
  804.     if (!newgetargs(args, "s", &name))
  805.         return NULL;
  806.     ret = init_builtin(name);
  807.     if (ret < 0)
  808.         return NULL;
  809.     if (ret == 0) {
  810.         INCREF(None);
  811.         return None;
  812.     }
  813.     m = add_module(name);
  814.     XINCREF(m);
  815.     return m;
  816. }
  817.  
  818. static object *
  819. imp_init_frozen(self, args)
  820.     object *self;
  821.     object *args;
  822. {
  823.     char *name;
  824.     int ret;
  825.     object *m;
  826.     if (!newgetargs(args, "s", &name))
  827.         return NULL;
  828.     ret = init_frozen(name);
  829.     if (ret < 0)
  830.         return NULL;
  831.     if (ret == 0) {
  832.         INCREF(None);
  833.         return None;
  834.     }
  835.     m = add_module(name);
  836.     XINCREF(m);
  837.     return m;
  838. }
  839.  
  840. static object *
  841. imp_get_frozen_object(self, args)
  842.     object *self;
  843.     object *args;
  844. {
  845.     char *name;
  846.  
  847.     if (!newgetargs(args, "s", &name))
  848.         return NULL;
  849.     return get_frozen_object(name);
  850. }
  851.  
  852. static object *
  853. imp_is_builtin(self, args)
  854.     object *self;
  855.     object *args;
  856. {
  857.     int i;
  858.     char *name;
  859.     if (!newgetargs(args, "s", &name))
  860.         return NULL;
  861.     for (i = 0; inittab[i].name != NULL; i++) {
  862.         if (strcmp(name, inittab[i].name) == 0) {
  863.             if (inittab[i].initfunc == NULL)
  864.                 return newintobject(-1);
  865.             else
  866.                 return newintobject(1);
  867.         }
  868.     }
  869.     return newintobject(0);
  870. }
  871.  
  872. static object *
  873. imp_is_frozen(self, args)
  874.     object *self;
  875.     object *args;
  876. {
  877.     struct _frozen *p;
  878.     char *name;
  879.     if (!newgetargs(args, "s", &name))
  880.         return NULL;
  881.     for (p = frozen_modules; ; p++) {
  882.         if (p->name == NULL)
  883.             break;
  884.         if (strcmp(p->name, name) == 0)
  885.             return newintobject(1);
  886.     }
  887.     return newintobject(0);
  888. }
  889.  
  890. static FILE *
  891. get_file(pathname, fob, mode)
  892.     char *pathname;
  893.     object *fob;
  894.     char *mode;
  895. {
  896.     FILE *fp;
  897.     if (fob == NULL) {
  898.         fp = fopen(pathname, mode);
  899.         if (fp == NULL)
  900.             err_errno(IOError);
  901.     }
  902.     else {
  903.         fp = getfilefile(fob);
  904.         if (fp == NULL)
  905.             err_setstr(ValueError, "bad/closed file object");
  906.     }
  907.     return fp;
  908. }
  909.  
  910. static object *
  911. imp_load_compiled(self, args)
  912.     object *self;
  913.     object *args;
  914. {
  915.     char *name;
  916.     char *pathname;
  917.     object *fob = NULL;
  918.     object *m;
  919.     FILE *fp;
  920.     if (!newgetargs(args, "ssO!", &name, &pathname, &Filetype, &fob))
  921.         return NULL;
  922.     fp = get_file(pathname, fob, "rb");
  923.     if (fp == NULL)
  924.         return NULL;
  925.     m = load_compiled_module(name, pathname, fp);
  926.     return m;
  927. }
  928.  
  929. static object *
  930. imp_load_dynamic(self, args)
  931.     object *self;
  932.     object *args;
  933. {
  934.     char *name;
  935.     char *pathname;
  936.     object *fob = NULL;
  937.     object *m;
  938.     FILE *fp = NULL;
  939.     if (!newgetargs(args, "ss|O!", &name, &pathname, &Filetype, &fob))
  940.         return NULL;
  941.     if (fob)
  942.         fp = get_file(pathname, fob, "r");
  943.     m = load_dynamic_module(name, pathname, fp);
  944.     return m;
  945. }
  946.  
  947. static object *
  948. imp_load_source(self, args)
  949.     object *self;
  950.     object *args;
  951. {
  952.     char *name;
  953.     char *pathname;
  954.     object *fob = NULL;
  955.     object *m;
  956.     FILE *fp;
  957.     if (!newgetargs(args, "ssO!", &name, &pathname, &Filetype, &fob))
  958.         return NULL;
  959.     fp = get_file(pathname, fob, "r");
  960.     if (fp == NULL)
  961.         return NULL;
  962.     m = load_source_module(name, pathname, fp);
  963.     return m;
  964. }
  965.  
  966. #ifdef macintosh
  967. static object *
  968. imp_load_resource(self, args)
  969.     object *self;
  970.     object *args;
  971. {
  972.     char *name;
  973.     char *pathname;
  974.     object *m;
  975.  
  976.     if (!newgetargs(args, "ss", &name, &pathname))
  977.         return NULL;
  978.     m = PyMac_LoadResourceModule(name, pathname);
  979.     return m;
  980. }
  981. #endif /* macintosh */
  982.  
  983. static object *
  984. imp_new_module(self, args)
  985.     object *self;
  986.     object *args;
  987. {
  988.     char *name;
  989.     if (!newgetargs(args, "s", &name))
  990.         return NULL;
  991.     return newmoduleobject(name);
  992. }
  993.  
  994. static struct methodlist imp_methods[] = {
  995.     {"get_frozen_object",    imp_get_frozen_object,    1},
  996.     {"get_magic",        imp_get_magic,        1},
  997.     {"get_suffixes",    imp_get_suffixes,    1},
  998.     {"find_module",        imp_find_module,    1},
  999.     {"init_builtin",    imp_init_builtin,    1},
  1000.     {"init_frozen",        imp_init_frozen,    1},
  1001.     {"is_builtin",        imp_is_builtin,        1},
  1002.     {"is_frozen",        imp_is_frozen,        1},
  1003.     {"load_compiled",    imp_load_compiled,    1},
  1004.     {"load_dynamic",    imp_load_dynamic,    1},
  1005.     {"load_source",        imp_load_source,    1},
  1006.     {"new_module",        imp_new_module,        1},
  1007. #ifdef macintosh
  1008.     {"load_resource",    imp_load_resource,    1},
  1009. #endif
  1010.     {NULL,            NULL}        /* sentinel */
  1011. };
  1012.  
  1013. void
  1014. initimp()
  1015. {
  1016.     object *m, *d, *v;
  1017.  
  1018.     m = initmodule("imp", imp_methods);
  1019.     d = getmoduledict(m);
  1020.  
  1021.     v = newintobject(SEARCH_ERROR);
  1022.     dictinsert(d, "SEARCH_ERROR", v);
  1023.     XDECREF(v);
  1024.  
  1025.     v = newintobject(PY_SOURCE);
  1026.     dictinsert(d, "PY_SOURCE", v);
  1027.     XDECREF(v);
  1028.  
  1029.     v = newintobject(PY_COMPILED);
  1030.     dictinsert(d, "PY_COMPILED", v);
  1031.     XDECREF(v);
  1032.  
  1033.     v = newintobject(C_EXTENSION);
  1034.     dictinsert(d, "C_EXTENSION", v);
  1035.     XDECREF(v);
  1036.  
  1037. #ifdef macintosh
  1038.     v = newintobject(PY_RESOURCE);
  1039.     dictinsert(d, "PY_RESOURCE", v);
  1040.     XDECREF(v);
  1041. #endif
  1042.  
  1043.  
  1044.     if (err_occurred())
  1045.         fatal("imp module initialization failed");
  1046. }
  1047.