moduleobject.c revision 73531a3bae554998dd7d6d5d782d44fbf0da2ee8
1/* Module object implementation */ 2 3#include "allobjects.h" 4 5typedef struct { 6 OB_HEAD 7 object *md_name; 8 object *md_dict; 9} moduleobject; 10 11object * 12newmoduleobject(name) 13 char *name; 14{ 15 moduleobject *m = NEWOBJ(moduleobject, &Moduletype); 16 if (m == NULL) 17 return NULL; 18 m->md_name = newstringobject(name); 19 m->md_dict = newdictobject(); 20 if (m->md_name == NULL || m->md_dict == NULL) { 21 DECREF(m); 22 return NULL; 23 } 24 return (object *)m; 25} 26 27object * 28getmoduledict(m) 29 object *m; 30{ 31 if (!is_moduleobject(m)) { 32 err_badcall(); 33 return NULL; 34 } 35 return ((moduleobject *)m) -> md_dict; 36} 37 38char * 39getmodulename(m) 40 object *m; 41{ 42 if (!is_moduleobject(m)) { 43 err_badarg(); 44 return NULL; 45 } 46 return getstringvalue(((moduleobject *)m) -> md_name); 47} 48 49/* Methods */ 50 51static void 52module_dealloc(m) 53 moduleobject *m; 54{ 55 if (m->md_name != NULL) 56 DECREF(m->md_name); 57 if (m->md_dict != NULL) 58 DECREF(m->md_dict); 59 free((char *)m); 60} 61 62static void 63module_print(m, fp, flags) 64 moduleobject *m; 65 FILE *fp; 66 int flags; 67{ 68 fprintf(fp, "<module '%s'>", getstringvalue(m->md_name)); 69} 70 71static object * 72module_repr(m) 73 moduleobject *m; 74{ 75 char buf[100]; 76 sprintf(buf, "<module '%.80s'>", getstringvalue(m->md_name)); 77 return newstringobject(buf); 78} 79 80static object * 81module_getattr(m, name) 82 moduleobject *m; 83 char *name; 84{ 85 object *res; 86 if (strcmp(name, "__dict__") == 0) { 87 INCREF(m->md_dict); 88 return m->md_dict; 89 } 90 if (strcmp(name, "__name__") == 0) { 91 INCREF(m->md_name); 92 return m->md_name; 93 } 94 res = dictlookup(m->md_dict, name); 95 if (res == NULL) 96 err_setstr(NameError, name); 97 else 98 INCREF(res); 99 return res; 100} 101 102static int 103module_setattr(m, name, v) 104 moduleobject *m; 105 char *name; 106 object *v; 107{ 108 if (strcmp(name, "__dict__") == 0 || strcmp(name, "__name__") == 0) { 109 err_setstr(NameError, "can't assign to reserved member name"); 110 return -1; 111 } 112 if (v == NULL) 113 return dictremove(m->md_dict, name); 114 else 115 return dictinsert(m->md_dict, name, v); 116} 117 118typeobject Moduletype = { 119 OB_HEAD_INIT(&Typetype) 120 0, /*ob_size*/ 121 "module", /*tp_name*/ 122 sizeof(moduleobject), /*tp_size*/ 123 0, /*tp_itemsize*/ 124 module_dealloc, /*tp_dealloc*/ 125 module_print, /*tp_print*/ 126 module_getattr, /*tp_getattr*/ 127 module_setattr, /*tp_setattr*/ 128 0, /*tp_compare*/ 129 module_repr, /*tp_repr*/ 130}; 131