blob: 7b9e0e919f989480381718a87db7d8aa45b949e5 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Module object implementation */
2
3#include <stdio.h>
4
5#include "PROTO.h"
6#include "object.h"
7#include "stringobject.h"
8#include "dictobject.h"
9#include "moduleobject.h"
10#include "objimpl.h"
Guido van Rossum2b654f71990-10-14 20:03:32 +000011#include "errors.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
13typedef struct {
14 OB_HEAD
15 object *md_name;
16 object *md_dict;
17} moduleobject;
18
19object *
20newmoduleobject(name)
21 char *name;
22{
23 moduleobject *m = NEWOBJ(moduleobject, &Moduletype);
24 if (m == NULL)
25 return NULL;
26 m->md_name = newstringobject(name);
27 m->md_dict = newdictobject();
28 if (m->md_name == NULL || m->md_dict == NULL) {
29 DECREF(m);
30 return NULL;
31 }
32 return (object *)m;
33}
34
35object *
36getmoduledict(m)
37 object *m;
38{
39 if (!is_moduleobject(m)) {
40 errno = EBADF;
41 return NULL;
42 }
43 return ((moduleobject *)m) -> md_dict;
44}
45
46int
47setmoduledict(m, v)
48 object *m;
49 object *v;
50{
51 if (!is_moduleobject(m))
52 return errno = EBADF;
53 if (!is_dictobject(v))
54 return errno = EINVAL;
55 DECREF(((moduleobject *)m) -> md_dict);
56 INCREF(v);
57 ((moduleobject *)m) -> md_dict = v;
58 return 0;
59}
60
61/* Methods */
62
63static void
64moduledealloc(m)
65 moduleobject *m;
66{
67 if (m->md_name != NULL)
68 DECREF(m->md_name);
69 if (m->md_dict != NULL)
70 DECREF(m->md_dict);
71 free((char *)m);
72}
73
74static void
75moduleprint(m, fp, flags)
76 moduleobject *m;
77 FILE *fp;
78 int flags;
79{
80 fprintf(fp, "<module %s>", getstringvalue(m->md_name));
81}
82
83static object *
84modulerepr(m)
85 moduleobject *m;
86{
87 char buf[100];
88 sprintf(buf, "<module %.80s>", getstringvalue(m->md_name));
89 return newstringobject(buf);
90}
91
92static object *
93modulegetattr(m, name)
94 moduleobject *m;
95 char *name;
96{
97 object *res = dictlookup(m->md_dict, name);
Guido van Rossum2b654f71990-10-14 20:03:32 +000098 if (res == NULL)
99 err_setstr(NameError, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000100 else
101 INCREF(res);
102 return res;
103}
104
105static int
106modulesetattr(m, name, v)
107 moduleobject *m;
108 char *name;
109 object *v;
110{
111 if (v == NULL)
112 return dictremove(m->md_dict, name);
113 else
114 return dictinsert(m->md_dict, name, v);
115}
116
117typeobject Moduletype = {
118 OB_HEAD_INIT(&Typetype)
119 0, /*ob_size*/
120 "module", /*tp_name*/
121 sizeof(moduleobject), /*tp_size*/
122 0, /*tp_itemsize*/
123 moduledealloc, /*tp_dealloc*/
124 moduleprint, /*tp_print*/
125 modulegetattr, /*tp_getattr*/
126 modulesetattr, /*tp_setattr*/
127 0, /*tp_compare*/
128 modulerepr, /*tp_repr*/
129};