s3/s4 build: Fix Py_RETURN_NONE to work with python versions < 2.4
[tprouty/samba.git] / pidl / lib / Parse / Pidl / Samba4 / Python.pm
1 ###################################################
2 # Python function wrapper generator
3 # Copyright jelmer@samba.org 2007-2008
4 # released under the GNU GPL
5
6 package Parse::Pidl::Samba4::Python;
7
8 use Exporter;
9 @ISA = qw(Exporter);
10
11 use strict;
12 use Parse::Pidl qw(warning fatal error);
13 use Parse::Pidl::Typelist qw(hasType resolveType getType mapTypeName expandAlias);
14 use Parse::Pidl::Util qw(has_property ParseExpr unmake_str);
15 use Parse::Pidl::NDR qw(GetPrevLevel GetNextLevel ContainsDeferred is_charset_array);
16 use Parse::Pidl::CUtil qw(get_value_of get_pointer_to);
17 use Parse::Pidl::Samba4 qw(ArrayDynamicallyAllocated);
18 use Parse::Pidl::Samba4::Header qw(GenerateFunctionInEnv GenerateFunctionOutEnv EnvSubstituteValue GenerateStructEnv);
19
20 use vars qw($VERSION);
21 $VERSION = '0.01';
22
23 sub new($) {
24         my ($class) = @_;
25         my $self = { res => "", res_hdr => "", tabs => "", constants => {},
26                      module_methods => [], module_objects => [], ready_types => [],
27                                  module_imports => [], type_imports => {},
28                                  patch_type_calls => [], readycode => [] };
29         bless($self, $class);
30 }
31
32 sub pidl_hdr ($$)
33 {
34         my $self = shift;
35         $self->{res_hdr} .= shift;
36 }
37
38 sub pidl($$)
39 {
40         my ($self, $d) = @_;
41         if ($d) {
42                 if ((!($d =~ /^#/))) {
43                         $self->{res} .= $self->{tabs};
44                 }
45                 $self->{res} .= $d;
46         }
47         $self->{res} .= "\n";
48 }
49
50 sub indent($)
51 {
52         my ($self) = @_;
53         $self->{tabs} .= "\t";
54 }
55
56 sub deindent($)
57 {
58         my ($self) = @_;
59         $self->{tabs} = substr($self->{tabs}, 0, -1);
60 }
61
62 sub PrettifyTypeName($$)
63 {
64         my ($name, $basename) = @_;
65
66         $name =~ s/^$basename\_//;
67
68         return $name;
69 }
70
71 sub Import
72 {
73         my $self = shift;
74         my @imports = @_;
75         foreach (@imports) {
76                 $_ = unmake_str($_);
77                 s/\.idl$//;
78                 $self->pidl_hdr("#include \"librpc/gen_ndr/$_\.h\"\n");
79                 $self->register_module_import($_);
80         }
81 }
82
83 sub Const($$)
84 {
85     my ($self, $const) = @_;
86         $self->register_constant($const->{NAME}, $const->{DTYPE}, $const->{VALUE});
87 }
88
89 sub register_constant($$$$)
90 {
91         my ($self, $name, $type, $value) = @_;
92
93         $self->{constants}->{$name} = [$type, $value];
94 }
95
96 sub EnumAndBitmapConsts($$$)
97 {
98         my ($self, $name, $d) = @_;
99
100         return unless (defined($d->{ELEMENTS}));
101
102         foreach my $e (@{$d->{ELEMENTS}}) {
103                 $e =~ /^([A-Za-z0-9_]+)/;
104                 my $cname = $1;
105                 
106                 $self->register_constant($cname, $d, $cname);
107         }
108 }
109
110 sub FromUnionToPythonFunction($$$$)
111 {
112         my ($self, $mem_ctx, $type, $switch, $name) = @_;
113
114         $self->pidl("PyObject *ret;");
115         $self->pidl("");
116
117         $self->pidl("switch ($switch) {");
118         $self->indent;
119
120         foreach my $e (@{$type->{ELEMENTS}}) {
121                 $self->pidl("$e->{CASE}:");
122
123                 $self->indent;
124
125                 if ($e->{NAME}) {
126                         $self->ConvertObjectToPython($mem_ctx, {}, $e, "$name->$e->{NAME}", "ret", "return NULL;");
127                 } else {
128                         $self->pidl("ret = Py_None;");
129                 }
130
131                 $self->pidl("return ret;");
132                 $self->pidl("");
133
134                 $self->deindent;
135         }
136
137         $self->deindent;
138         $self->pidl("}");
139
140         $self->pidl("PyErr_SetString(PyExc_TypeError, \"unknown union level\");");
141         $self->pidl("return NULL;");
142 }
143
144 sub FromPythonToUnionFunction($$$$$)
145 {
146         my ($self, $type, $typename, $switch, $mem_ctx, $name) = @_;
147
148         my $has_default = 0;
149
150         $self->pidl("$typename *ret = talloc_zero($mem_ctx, $typename);");
151
152         $self->pidl("switch ($switch) {");
153         $self->indent;
154
155         foreach my $e (@{$type->{ELEMENTS}}) {
156                 $self->pidl("$e->{CASE}:");
157                 if ($e->{CASE} eq "default") { $has_default = 1; }
158                 $self->indent;
159                 if ($e->{NAME}) {
160                         $self->ConvertObjectFromPython({}, $mem_ctx, $e, $name, "ret->$e->{NAME}", "talloc_free(ret); return NULL;");
161                 }
162                 $self->pidl("break;");
163                 $self->deindent;
164                 $self->pidl("");
165         }
166
167         if (!$has_default) {
168                 $self->pidl("default:");
169                 $self->indent;
170                 $self->pidl("PyErr_SetString(PyExc_TypeError, \"invalid union level value\");");
171                 $self->pidl("talloc_free(ret);");
172                 $self->pidl("ret = NULL;");
173                 $self->deindent;
174         }
175
176         $self->deindent;
177         $self->pidl("}");
178         $self->pidl("");
179         $self->pidl("return ret;");
180 }
181
182 sub PythonStruct($$$$$$)
183 {
184         my ($self, $modulename, $prettyname, $name, $cname, $d) = @_;
185
186         my $env = GenerateStructEnv($d, "object");
187
188         $self->pidl("");
189
190         my $getsetters = "NULL";
191
192         if ($#{$d->{ELEMENTS}} > -1) {
193                 foreach my $e (@{$d->{ELEMENTS}}) {
194                         my $varname = "object->$e->{NAME}";
195                         $self->pidl("static PyObject *py_$name\_get_$e->{NAME}(PyObject *obj, void *closure)");
196                         $self->pidl("{");
197                         $self->indent;
198                         $self->pidl("$cname *object = py_talloc_get_ptr(obj);");
199                         $self->pidl("PyObject *py_$e->{NAME};");
200                         $self->ConvertObjectToPython("py_talloc_get_mem_ctx(obj)", $env, $e, $varname, "py_$e->{NAME}", "return NULL;");
201                         $self->pidl("return py_$e->{NAME};");
202                         $self->deindent;
203                         $self->pidl("}");
204                         $self->pidl("");
205
206                         $self->pidl("static int py_$name\_set_$e->{NAME}(PyObject *py_obj, PyObject *value, void *closure)");
207                         $self->pidl("{");
208                         $self->indent;
209                         $self->pidl("$cname *object = py_talloc_get_ptr(py_obj);");
210                         my $mem_ctx = "py_talloc_get_mem_ctx(py_obj)";
211                         my $l = $e->{LEVELS}[0];
212                         my $nl = GetNextLevel($e, $l);
213                         if ($l->{TYPE} eq "POINTER" and 
214                                 not ($nl->{TYPE} eq "ARRAY" and ($nl->{IS_FIXED} or is_charset_array($e, $nl))) and
215                                 not ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE}))) {
216                                 $self->pidl("talloc_free($varname);");
217                         }
218                         $self->ConvertObjectFromPython($env, $mem_ctx, $e, "value", $varname, "return -1;");
219                         $self->pidl("return 0;");
220                         $self->deindent;
221                         $self->pidl("}");
222                         $self->pidl("");
223                 }
224
225                 $getsetters = "py_$name\_getsetters";
226                 $self->pidl("static PyGetSetDef ".$getsetters."[] = {");
227                 $self->indent;
228                 foreach my $e (@{$d->{ELEMENTS}}) {
229                         $self->pidl("{ discard_const_p(char, \"$e->{NAME}\"), py_$name\_get_$e->{NAME}, py_$name\_set_$e->{NAME} },");
230                 }
231                 $self->pidl("{ NULL }");
232                 $self->deindent;
233                 $self->pidl("};");
234                 $self->pidl("");
235         }
236
237         $self->pidl("static PyObject *py_$name\_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
238         $self->pidl("{");
239         $self->indent;
240         $self->pidl("return py_talloc_new($cname, type);");
241         $self->deindent;
242         $self->pidl("}");
243         $self->pidl("");
244
245         my $py_methods = "NULL";
246
247         # If the struct is not public there ndr_pull/ndr_push functions will 
248         # be static so not callable from here
249         if (has_property($d, "public")) {
250                 $self->pidl("static PyObject *py_$name\_ndr_pack(PyObject *py_obj)");
251                 $self->pidl("{");
252                 $self->indent;
253                 $self->pidl("$cname *object = py_talloc_get_ptr(py_obj);");
254                 $self->pidl("DATA_BLOB blob;");
255                 $self->pidl("enum ndr_err_code err;");
256                 $self->pidl("err = ndr_push_struct_blob(&blob, py_talloc_get_mem_ctx(py_obj), NULL, object, (ndr_push_flags_fn_t)ndr_push_$name);");
257                 $self->pidl("if (err != NDR_ERR_SUCCESS) {");
258                 $self->indent;
259                 $self->pidl("PyErr_SetNdrError(err);");
260                 $self->pidl("return NULL;");
261                 $self->deindent;
262                 $self->pidl("}");
263                 $self->pidl("");
264                 $self->pidl("return PyString_FromStringAndSize((char *)blob.data, blob.length);");
265                 $self->deindent;
266                 $self->pidl("}");
267                 $self->pidl("");
268
269                 $self->pidl("static PyObject *py_$name\_ndr_unpack(PyObject *py_obj, PyObject *args)");
270                 $self->pidl("{");
271                 $self->indent;
272                 $self->pidl("$cname *object = py_talloc_get_ptr(py_obj);");
273                 $self->pidl("DATA_BLOB blob;");
274                 $self->pidl("enum ndr_err_code err;");
275                 $self->pidl("if (!PyArg_ParseTuple(args, \"s#:__ndr_unpack__\", &blob.data, &blob.length))");
276                 $self->pidl("\treturn NULL;");
277                 $self->pidl("");
278                 $self->pidl("err = ndr_pull_struct_blob_all(&blob, py_talloc_get_mem_ctx(py_obj), NULL, object, (ndr_pull_flags_fn_t)ndr_pull_$name);");
279                 $self->pidl("if (err != NDR_ERR_SUCCESS) {");
280                 $self->indent;
281                 $self->pidl("PyErr_SetNdrError(err);");
282                 $self->pidl("return NULL;");
283                 $self->deindent;
284                 $self->pidl("}");
285                 $self->pidl("");
286                 $self->pidl("Py_RETURN_NONE;");
287                 $self->deindent;
288                 $self->pidl("}");
289                 $self->pidl("");
290                 $py_methods = "py_$name\_methods";
291                 $self->pidl("static PyMethodDef $py_methods\[] = {");
292                 $self->indent;
293                 $self->pidl("{ \"__ndr_pack__\", (PyCFunction)py_$name\_ndr_pack, METH_NOARGS, \"S.pack() -> blob\\nNDR pack\" },");
294                 $self->pidl("{ \"__ndr_unpack__\", (PyCFunction)py_$name\_ndr_unpack, METH_VARARGS, \"S.unpack(blob) -> None\\nNDR unpack\" },");
295                 $self->pidl("{ NULL, NULL, 0, NULL }");
296                 $self->deindent;
297                 $self->pidl("};");
298                 $self->pidl("");
299         }
300
301         $self->pidl_hdr("staticforward PyTypeObject $name\_Type;\n");
302         $self->pidl("");
303         my $docstring = $self->DocString($d, $name);
304         my $typeobject = "$name\_Type";
305         $self->pidl("static PyTypeObject $typeobject = {");
306         $self->indent;
307         $self->pidl("PyObject_HEAD_INIT(NULL) 0,");
308         $self->pidl(".tp_name = \"$modulename.$prettyname\",");
309         $self->pidl(".tp_basicsize = sizeof(py_talloc_Object),");
310         $self->pidl(".tp_dealloc = py_talloc_dealloc,");
311         $self->pidl(".tp_getset = $getsetters,");
312         $self->pidl(".tp_repr = py_talloc_default_repr,");
313         if ($docstring) {
314                 $self->pidl(".tp_doc = $docstring,");
315         }
316         $self->pidl(".tp_methods = $py_methods,");
317         $self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
318         $self->pidl(".tp_new = py_$name\_new,");
319         $self->deindent;
320         $self->pidl("};");
321
322         $self->pidl("");
323
324         return "&$typeobject";
325 }
326
327 sub get_metadata_var($)
328 {
329         my ($e) = @_;
330         sub get_var($) { my $x = shift; $x =~ s/\*//g; return $x; }
331
332          if (has_property($e, "length_is")) {
333                 return get_var($e->{PROPERTIES}->{length_is});
334          } elsif (has_property($e, "size_is")) {
335                 return get_var($e->{PROPERTIES}->{size_is});
336          }
337
338          return undef;
339 }
340
341 sub find_metadata_args($)
342 {
343         my ($fn) = @_;
344         my $metadata_args = { in => {}, out => {} };
345
346         # Determine arguments that are metadata for other arguments (size_is/length_is)
347         foreach my $e (@{$fn->{ELEMENTS}}) {
348                 foreach my $dir (@{$e->{DIRECTION}}) {
349                          my $main = get_metadata_var($e);
350                          if ($main) { 
351                                  $metadata_args->{$dir}->{$main} = $e->{NAME}; 
352                          }
353                  }
354         }
355
356         return $metadata_args;
357 }
358
359 sub PythonFunctionUnpackOut($$$)
360 {
361         my ($self, $fn, $fnname) = @_;
362
363         my $outfnname = "unpack_$fnname\_args_out";
364         my $signature = "";
365
366         my $metadata_args = find_metadata_args($fn);
367
368         my $env = GenerateFunctionOutEnv($fn, "r->");
369         my $result_size = 0;
370
371         $self->pidl("static PyObject *$outfnname(struct $fn->{NAME} *r)");
372         $self->pidl("{");
373         $self->indent;
374         $self->pidl("PyObject *result = Py_None;");
375         foreach my $e (@{$fn->{ELEMENTS}}) {
376                 next unless (grep(/out/,@{$e->{DIRECTION}}));
377                 next if (($metadata_args->{in}->{$e->{NAME}} and grep(/in/, @{$e->{DIRECTION}})) or 
378                          ($metadata_args->{out}->{$e->{NAME}}) and grep(/out/, @{$e->{DIRECTION}}));
379                 $self->pidl("PyObject *py_$e->{NAME};");
380                 $result_size++;
381         }
382
383         if ($fn->{RETURN_TYPE}) {
384                 $result_size++ unless ($fn->{RETURN_TYPE} eq "WERROR" or $fn->{RETURN_TYPE} eq "NTSTATUS");
385         }
386
387         my $i = 0;
388
389         if ($result_size > 1) {
390                 $self->pidl("result = PyTuple_New($result_size);");
391                 $signature .= "(";
392         } elsif ($result_size == 0) {
393                 $signature .= "None";
394         }
395
396         foreach my $e (@{$fn->{ELEMENTS}}) {
397                 next if ($metadata_args->{out}->{$e->{NAME}});
398                 my $py_name = "py_$e->{NAME}";
399                 if (grep(/out/,@{$e->{DIRECTION}})) {
400                         $self->ConvertObjectToPython("r", $env, $e, "r->out.$e->{NAME}", $py_name, "return NULL;");
401                         if ($result_size > 1) {
402                                 $self->pidl("PyTuple_SetItem(result, $i, $py_name);");
403                                 $i++;
404                                 $signature .= "$e->{NAME}, ";
405                         } else {
406                                 $self->pidl("result = $py_name;");
407                                 $signature .= $e->{NAME};
408                         }
409                 }
410         }
411
412         if (defined($fn->{RETURN_TYPE}) and $fn->{RETURN_TYPE} eq "NTSTATUS") {
413                 $self->handle_ntstatus("r->out.result", "NULL", undef);
414         } elsif (defined($fn->{RETURN_TYPE}) and $fn->{RETURN_TYPE} eq "WERROR") {
415                 $self->handle_werror("r->out.result", "NULL", undef);
416         } elsif (defined($fn->{RETURN_TYPE})) {
417                 my $conv = $self->ConvertObjectToPythonData("r", $fn->{RETURN_TYPE}, "r->out.result");
418                 if ($result_size > 1) {
419                         $self->pidl("PyTuple_SetItem(result, $i, $conv);");
420                 } else {
421                         $self->pidl("result = $conv;");
422                 }
423                 $signature .= "result";
424         }
425
426         if (substr($signature, -2) eq ", ") {
427                 $signature = substr($signature, 0, -2);
428         }
429         if ($result_size > 1) {
430                 $signature .= ")";
431         }
432
433         $self->pidl("return result;");
434         $self->deindent;
435         $self->pidl("}");
436         $self->pidl("");
437
438         return ($outfnname, $signature);
439 }
440
441 sub PythonFunctionPackIn($$$)
442 {
443         my ($self, $fn, $fnname) = @_;
444         my $metadata_args = find_metadata_args($fn);
445
446         my $infnname = "pack_$fnname\_args_in";
447
448         $self->pidl("static bool $infnname(PyObject *args, PyObject *kwargs, struct $fn->{NAME} *r)");
449         $self->pidl("{");
450         $self->indent;
451         my $args_format = "";
452         my $args_string = "";
453         my $args_names = "";
454         my $signature = "";
455
456         foreach my $e (@{$fn->{ELEMENTS}}) {
457                 next unless (grep(/in/,@{$e->{DIRECTION}}));
458                 next if (($metadata_args->{in}->{$e->{NAME}} and grep(/in/, @{$e->{DIRECTION}})) or 
459                                  ($metadata_args->{out}->{$e->{NAME}}) and grep(/out/, @{$e->{DIRECTION}}));
460                 $self->pidl("PyObject *py_$e->{NAME};");
461                 $args_format .= "O";
462                 $args_string .= ", &py_$e->{NAME}";
463                 $args_names .= "\"$e->{NAME}\", ";
464                 $signature .= "$e->{NAME}, ";
465         }
466         if (substr($signature, -2) eq ", ") {
467                 $signature = substr($signature, 0, -2);
468         }
469         $self->pidl("const char *kwnames[] = {");
470         $self->indent;
471         $self->pidl($args_names . "NULL");
472         $self->deindent;
473         $self->pidl("};");
474
475         $self->pidl("");
476         $self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"$args_format:$fn->{NAME}\", discard_const_p(char *, kwnames)$args_string)) {");
477         $self->indent;
478         $self->pidl("return false;");
479         $self->deindent;
480         $self->pidl("}");
481         $self->pidl("");
482
483         my $env = GenerateFunctionInEnv($fn, "r->");
484
485         my $fail = "return false;";
486         foreach my $e (@{$fn->{ELEMENTS}}) {
487                 next unless (grep(/in/,@{$e->{DIRECTION}}));
488                 if ($metadata_args->{in}->{$e->{NAME}}) {
489                         my $py_var = "py_".$metadata_args->{in}->{$e->{NAME}};
490                         $self->pidl("PY_CHECK_TYPE(&PyList_Type, $py_var, $fail);");
491                         my $val = "PyList_Size($py_var)";
492                         if ($e->{LEVELS}[0]->{TYPE} eq "POINTER") {
493                                 $self->pidl("r->in.$e->{NAME} = talloc_ptrtype(r, r->in.$e->{NAME});");
494                                 $self->pidl("*r->in.$e->{NAME} = $val;");
495                         } else {
496                                 $self->pidl("r->in.$e->{NAME} = $val;");
497                         }
498                 } else {
499                         $self->ConvertObjectFromPython($env, "r", $e, "py_$e->{NAME}", "r->in.$e->{NAME}", $fail);
500                 }
501         }
502         $self->pidl("return true;");
503         $self->deindent;
504         $self->pidl("}");
505         $self->pidl("");
506         return ($infnname, $signature);
507 }
508
509 sub PythonFunction($$$)
510 {
511         my ($self, $fn, $iface, $prettyname) = @_;
512
513         my $fnname = "py_$fn->{NAME}";
514         my $docstring = $self->DocString($fn, $fn->{NAME});
515
516         my ($insignature, $outsignature);
517         my ($infn, $outfn);
518
519         if (has_property($fn, "todo")) {
520                 unless ($docstring) { $docstring = "NULL"; }
521                 $infn = "NULL";
522                 $outfn = "NULL";
523         } else {
524                 ($infn, $insignature) = $self->PythonFunctionPackIn($fn, $fnname);
525                 ($outfn, $outsignature) = $self->PythonFunctionUnpackOut($fn, $fnname);
526                 my $signature = "S.$prettyname($insignature) -> $outsignature";
527                 if ($docstring) {
528                         $docstring = "\"$signature\\n\\n\"$docstring";
529                 } else {
530                         $docstring = "\"$signature\"";
531                 }
532         }
533
534         return ($infn, $outfn, $docstring);
535 }
536
537 sub handle_werror($$$$)
538 {
539         my ($self, $var, $retval, $mem_ctx) = @_;
540
541         $self->pidl("if (!W_ERROR_IS_OK($var)) {");
542         $self->indent;
543         $self->pidl("PyErr_SetWERROR($var);");
544         $self->pidl("talloc_free($mem_ctx);") if ($mem_ctx);
545         $self->pidl("return $retval;");
546         $self->deindent;
547         $self->pidl("}");
548         $self->pidl("");
549 }
550
551 sub handle_ntstatus($$$$)
552 {
553         my ($self, $var, $retval, $mem_ctx) = @_;
554
555         $self->pidl("if (NT_STATUS_IS_ERR($var)) {");
556         $self->indent;
557         $self->pidl("PyErr_SetNTSTATUS($var);");
558         $self->pidl("talloc_free($mem_ctx);") if ($mem_ctx);
559         $self->pidl("return $retval;");
560         $self->deindent;
561         $self->pidl("}");
562         $self->pidl("");
563 }
564
565 sub PythonType($$$$)
566 {
567         my ($self, $modulename, $d, $interface, $basename) = @_;
568
569         my $actual_ctype = $d;
570         if ($actual_ctype->{TYPE} eq "TYPEDEF") {
571                 $actual_ctype = $actual_ctype->{DATA};
572         }
573
574         if ($actual_ctype->{TYPE} eq "STRUCT") {
575                 my $typeobject;
576                 my $fn_name = PrettifyTypeName($d->{NAME}, $basename);
577
578                 if ($d->{TYPE} eq "STRUCT") {
579                         $typeobject = $self->PythonStruct($modulename, $fn_name, $d->{NAME}, mapTypeName($d), $d);
580                 } else {
581                         $typeobject = $self->PythonStruct($modulename, $fn_name, $d->{NAME}, mapTypeName($d), $d->{DATA});
582                 }
583
584                 $self->register_module_typeobject($fn_name, $typeobject);
585         }
586
587         if ($d->{TYPE} eq "ENUM" or $d->{TYPE} eq "BITMAP") {
588                 $self->EnumAndBitmapConsts($d->{NAME}, $d);
589         }
590
591         if ($d->{TYPE} eq "TYPEDEF" and ($d->{DATA}->{TYPE} eq "ENUM" or $d->{DATA}->{TYPE} eq "BITMAP")) {
592                 $self->EnumAndBitmapConsts($d->{NAME}, $d->{DATA});
593         }
594
595         if ($actual_ctype->{TYPE} eq "UNION" and defined($actual_ctype->{ELEMENTS})) {
596                 $self->pidl("PyObject *py_import_$d->{NAME}(TALLOC_CTX *mem_ctx, int level, " .mapTypeName($d) . " *in)");
597                 $self->pidl("{");
598                 $self->indent;
599                 $self->FromUnionToPythonFunction("mem_ctx", $actual_ctype, "level", "in") if ($actual_ctype->{TYPE} eq "UNION");
600                 $self->deindent;
601                 $self->pidl("}");
602                 $self->pidl("");
603
604                 $self->pidl(mapTypeName($d) . " *py_export_$d->{NAME}(TALLOC_CTX *mem_ctx, int level, PyObject *in)");
605                 $self->pidl("{");
606                 $self->indent;
607                 $self->FromPythonToUnionFunction($actual_ctype, mapTypeName($d), "level", "mem_ctx", "in") if ($actual_ctype->{TYPE} eq "UNION");
608                 $self->deindent;
609                 $self->pidl("}");
610                 $self->pidl("");
611         }
612 }
613
614 sub DocString($$$)
615 {
616         my ($self, $d, $name) = @_;
617         if (has_property($d, "helpstring")) {
618                 my $docstring = uc("py_doc_$name");
619                 $self->pidl("#define $docstring ".has_property($d, "helpstring"));
620                 return $docstring;
621         }
622
623         return undef;
624 }
625
626 sub Interface($$$)
627 {
628         my($self,$interface,$basename) = @_;
629
630         if (has_property($interface, "pyhelper")) {
631                 $self->pidl("#include \"".unmake_str($interface->{PROPERTIES}->{pyhelper})."\"\n");
632         }
633
634         $self->Const($_) foreach (@{$interface->{CONSTS}});
635
636         foreach my $d (@{$interface->{TYPES}}) {
637                 next if has_property($d, "nopython");
638
639                 $self->PythonType($basename, $d, $interface, $basename);
640         }
641
642         if (defined $interface->{PROPERTIES}->{uuid}) {
643                 $self->pidl_hdr("staticforward PyTypeObject $interface->{NAME}_InterfaceType;\n");
644                 $self->pidl("");
645
646                 my @fns = ();
647
648                 foreach my $d (@{$interface->{FUNCTIONS}}) {
649                         next if not defined($d->{OPNUM});
650                         next if has_property($d, "nopython");
651
652                         my $prettyname = $d->{NAME};
653
654                         $prettyname =~ s/^$interface->{NAME}_//;
655                         $prettyname =~ s/^$basename\_//;
656
657                         my ($infn, $outfn, $fndocstring) = $self->PythonFunction($d, $interface->{NAME}, $prettyname);
658
659                         push (@fns, [$infn, $outfn, "dcerpc_$d->{NAME}", $prettyname, $fndocstring, $d->{OPNUM}]);
660                 }
661
662                 $self->pidl("const struct PyNdrRpcMethodDef py_ndr_$interface->{NAME}\_methods[] = {");
663                 $self->indent;
664                 foreach my $d (@fns) {
665                         my ($infn, $outfn, $callfn, $prettyname, $docstring, $opnum) = @$d;
666                         $self->pidl("{ \"$prettyname\", $docstring, (dcerpc_call_fn)$callfn, (py_data_pack_fn)$infn, (py_data_unpack_fn)$outfn, $opnum, &ndr_table_$interface->{NAME} },");
667                 }
668                 $self->pidl("{ NULL }");
669                 $self->deindent;
670                 $self->pidl("};");
671                 $self->pidl("");
672
673                 $self->pidl("static PyObject *interface_$interface->{NAME}_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
674                 $self->pidl("{");
675                 $self->indent;
676                 $self->pidl("return py_dcerpc_interface_init_helper(type, args, kwargs, &ndr_table_$interface->{NAME});");
677                 $self->deindent;
678                 $self->pidl("}");
679         
680                 $self->pidl("");
681
682                 my $signature = 
683 "\"$interface->{NAME}(binding, lp_ctx=None, credentials=None) -> connection\\n\"
684 \"\\n\"
685 \"binding should be a DCE/RPC binding string (for example: ncacn_ip_tcp:127.0.0.1)\\n\"
686 \"lp_ctx should be a path to a smb.conf file or a param.LoadParm object\\n\"
687 \"credentials should be a credentials.Credentials object.\\n\\n\"";
688
689                 my $docstring = $self->DocString($interface, $interface->{NAME});
690
691                 if ($docstring) {
692                         $docstring = "$signature$docstring";
693                 } else {
694                         $docstring = $signature;
695                 }
696
697                 $self->pidl("static PyTypeObject $interface->{NAME}_InterfaceType = {");
698                 $self->indent;
699                 $self->pidl("PyObject_HEAD_INIT(NULL) 0,");
700                 $self->pidl(".tp_name = \"$basename.$interface->{NAME}\",");
701                 $self->pidl(".tp_basicsize = sizeof(dcerpc_InterfaceObject),");
702                 $self->pidl(".tp_base = &dcerpc_InterfaceType,");
703                 $self->pidl(".tp_doc = $docstring,");
704                 $self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
705                 $self->pidl(".tp_new = interface_$interface->{NAME}_new,");
706                 $self->deindent;
707                 $self->pidl("};");
708
709                 $self->pidl("");
710
711                 $self->register_module_typeobject($interface->{NAME}, "&$interface->{NAME}_InterfaceType");
712                 $self->register_module_readycode(["if (!PyInterface_AddNdrRpcMethods(&$interface->{NAME}_InterfaceType, py_ndr_$interface->{NAME}\_methods))", "\treturn;", ""]);
713         }
714
715         $self->pidl_hdr("\n");
716 }
717
718 sub register_module_method($$$$$)
719 {
720         my ($self, $fn_name, $pyfn_name, $flags, $doc) = @_;
721
722         push (@{$self->{module_methods}}, [$fn_name, $pyfn_name, $flags, $doc])
723 }
724
725 sub register_module_typeobject($$$)
726 {
727         my ($self, $name, $py_name) = @_;
728
729         $self->register_module_object($name, "(PyObject *)$py_name");
730
731         $self->check_ready_type($py_name);
732
733         $self->register_patch_type_call($name, $py_name);
734 }
735
736 sub check_ready_type($$)
737 {
738         my ($self, $py_name) = @_;
739         push (@{$self->{ready_types}}, $py_name) unless (grep(/^$py_name$/,@{$self->{ready_types}}));
740 }
741
742 sub register_module_import($$)
743 {
744         my ($self, $basename) = @_;
745
746         push (@{$self->{module_imports}}, $basename) unless (grep(/^$basename$/,@{$self->{module_imports}}));
747 }
748
749 sub use_type_variable($$)
750 {
751         my ($self, $orig_ctype) = @_;
752         my $ctype = resolveType($orig_ctype);
753         unless (defined($ctype->{BASEFILE})) {
754                 return undef;
755         }
756         # If this is an external type, make sure we do the right imports.
757         if (($ctype->{BASEFILE} ne $self->{BASENAME})) {
758                 $self->register_module_import($ctype->{BASEFILE});
759                 unless (defined($self->{type_imports}->{$ctype->{NAME}})) {
760                         $self->{type_imports}->{$ctype->{NAME}} = $ctype->{BASEFILE};
761                 }
762                 return "$ctype->{NAME}_Type";
763         }
764         return "&$ctype->{NAME}_Type";
765 }
766
767 sub register_patch_type_call($$$)
768 {
769         my ($self, $typename, $cvar) = @_;
770
771         push(@{$self->{patch_type_calls}}, [$typename, $cvar]);
772
773 }
774
775 sub register_module_readycode($$)
776 {
777         my ($self, $code) = @_;
778
779         push (@{$self->{readycode}}, @$code);
780 }
781
782 sub register_module_object($$$)
783 {
784         my ($self, $name, $py_name) = @_;
785
786         push (@{$self->{module_objects}}, [$name, $py_name])
787 }
788
789 sub assign($$$)
790 {
791         my ($self, $dest, $src) = @_;
792         if ($dest =~ /^\&/ and $src eq "NULL") {
793                 $self->pidl("memset($dest, 0, sizeof(" . get_value_of($dest) . "));");
794         } elsif ($dest =~ /^\&/) {
795                 $self->pidl("memcpy($dest, $src, sizeof(" . get_value_of($dest) . "));");
796         } else {
797                 $self->pidl("$dest = $src;");
798         }
799 }
800
801 sub ConvertObjectFromPythonData($$$$$$)
802 {
803         my ($self, $mem_ctx, $cvar, $ctype, $target, $fail) = @_;
804
805         die("undef type for $cvar") unless(defined($ctype));
806
807         $ctype = resolveType($ctype);
808
809         my $actual_ctype = $ctype;
810         if ($actual_ctype->{TYPE} eq "TYPEDEF") {
811                 $actual_ctype = $actual_ctype->{DATA};
812         }
813
814         if ($actual_ctype->{TYPE} eq "ENUM" or $actual_ctype->{TYPE} eq "BITMAP" or 
815                 $actual_ctype->{TYPE} eq "SCALAR" and (
816                 expandAlias($actual_ctype->{NAME}) =~ /^(u?int[0-9]*|hyper|NTTIME|time_t|NTTIME_hyper|NTTIME_1sec|dlong|udlong|udlongr)$/)) {
817                 $self->pidl("PY_CHECK_TYPE(&PyInt_Type, $cvar, $fail);");
818                 $self->pidl("$target = PyInt_AsLong($cvar);");
819                 return;
820         }
821
822         if ($actual_ctype->{TYPE} eq "STRUCT" or $actual_ctype->{TYPE} eq "INTERFACE") {
823                 my $ctype_name = $self->use_type_variable($ctype);
824                 unless (defined ($ctype_name)) {
825                         error(undef, "Unable to determine origin of type " . mapTypeName($ctype));
826                         $self->assign($target, "NULL");
827                         # FIXME:
828                         return;
829                 }
830                 $self->pidl("PY_CHECK_TYPE($ctype_name, $cvar, $fail);");
831                 $self->assign($target, "py_talloc_get_ptr($cvar)");
832                 return;
833         }
834
835         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "DATA_BLOB") {
836                 $self->pidl("$target = data_blob_talloc($mem_ctx, PyString_AsString($cvar), PyString_Size($cvar));");
837                 return;
838         }
839
840         if ($actual_ctype->{TYPE} eq "SCALAR" and 
841                 ($actual_ctype->{NAME} eq "string" or $actual_ctype->{NAME} eq "nbt_string" or $actual_ctype->{NAME} eq "nbt_name" or $actual_ctype->{NAME} eq "wrepl_nbt_name")) {
842                 $self->pidl("$target = talloc_strdup($mem_ctx, PyString_AsString($cvar));");
843                 return;
844         }
845
846         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "ipv4address") {
847                 $self->pidl("$target = PyString_AsString($cvar);");
848                 return;
849                 }
850
851
852         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "NTSTATUS") {
853                 $self->pidl("$target = NT_STATUS(PyInt_AsLong($cvar));");
854                 return;
855         }
856
857         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "WERROR") {
858                 $self->pidl("$target = W_ERROR(PyInt_AsLong($cvar));");
859                 return;
860         }
861
862         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "string_array") {
863                 $self->pidl("$target = PyCObject_AsVoidPtr($cvar);");
864                 return;
865         }
866
867         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "pointer") {
868                 $self->assign($target, "PyCObject_AsVoidPtr($cvar)");
869                 return;
870         }
871
872         fatal($ctype, "unknown type $actual_ctype->{TYPE} for ".mapTypeName($ctype) . ": $cvar");
873
874 }
875
876 sub ConvertObjectFromPythonLevel($$$$$$$$)
877 {
878         my ($self, $env, $mem_ctx, $py_var, $e, $l, $var_name, $fail) = @_;
879         my $nl = GetNextLevel($e, $l);
880
881         if ($l->{TYPE} eq "POINTER") {
882                 if ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE})) {
883                         $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $py_var, $e, $nl, $var_name, $fail);
884                         return;
885                 }
886                 if ($l->{POINTER_TYPE} ne "ref") {
887                         $self->pidl("if ($py_var == Py_None) {");
888                         $self->indent;
889                         $self->pidl("$var_name = NULL;");
890                         $self->deindent;
891                         $self->pidl("} else {");
892                         $self->indent;
893                 }
894                 $self->pidl("$var_name = talloc_ptrtype($mem_ctx, $var_name);");
895                 $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $py_var, $e, $nl, get_value_of($var_name), $fail);
896                 if ($l->{POINTER_TYPE} ne "ref") {
897                         $self->deindent;
898                         $self->pidl("}");
899                 }
900         } elsif ($l->{TYPE} eq "ARRAY") {
901                 my $pl = GetPrevLevel($e, $l);
902                 if ($pl && $pl->{TYPE} eq "POINTER") {
903                         $var_name = get_pointer_to($var_name);
904                 }
905
906                 if (is_charset_array($e, $l)) {
907                         $self->pidl("PY_CHECK_TYPE(&PyUnicode_Type, $py_var, $fail);");
908                         # FIXME: Use Unix charset setting rather than utf-8
909                         $self->pidl($var_name . " = PyString_AsString(PyUnicode_AsEncodedString($py_var, \"utf-8\", \"ignore\"));");
910                 } else {
911                         my $counter = "$e->{NAME}_cntr_$l->{LEVEL_INDEX}";
912                         $self->pidl("PY_CHECK_TYPE(&PyList_Type, $py_var, $fail);");
913                         $self->pidl("{");
914                         $self->indent;
915                         $self->pidl("int $counter;");
916                         if (ArrayDynamicallyAllocated($e, $l)) {
917                                 $self->pidl("$var_name = talloc_array_ptrtype($mem_ctx, $var_name, PyList_Size($py_var));");
918                         }
919                         $self->pidl("for ($counter = 0; $counter < PyList_Size($py_var); $counter++) {");
920                         $self->indent;
921                         $self->ConvertObjectFromPythonLevel($env, $var_name, "PyList_GetItem($py_var, $counter)", $e, GetNextLevel($e, $l), $var_name."[$counter]", $fail);
922                         $self->deindent;
923                         $self->pidl("}");
924                         $self->deindent;
925                         $self->pidl("}");
926                 }
927         } elsif ($l->{TYPE} eq "DATA") {
928
929                 if (not Parse::Pidl::Typelist::is_scalar($l->{DATA_TYPE})) {
930                         $var_name = get_pointer_to($var_name);
931                 }
932                 $self->ConvertObjectFromPythonData($mem_ctx, $py_var, $l->{DATA_TYPE}, $var_name, $fail);
933         } elsif ($l->{TYPE} eq "SWITCH") {
934                 $var_name = get_pointer_to($var_name);
935                 my $switch = ParseExpr($l->{SWITCH_IS}, $env, $e);
936                 $self->assign($var_name, "py_export_" . GetNextLevel($e, $l)->{DATA_TYPE} . "($mem_ctx, $switch, $py_var)");
937         } elsif ($l->{TYPE} eq "SUBCONTEXT") {
938                 $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $py_var, $e, GetNextLevel($e, $l), $var_name, $fail);
939         } else {
940                 die("unknown level type $l->{TYPE}");
941         }
942 }
943
944 sub ConvertObjectFromPython($$$$$$$)
945 {
946         my ($self, $env, $mem_ctx, $ctype, $cvar, $target, $fail) = @_;
947
948         $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $cvar, $ctype, $ctype->{LEVELS}[0], $target, $fail);
949 }
950
951 sub ConvertScalarToPython($$$)
952 {
953         my ($self, $ctypename, $cvar) = @_;
954
955         die("expected string for $cvar, not $ctypename") if (ref($ctypename) eq "HASH");
956
957         $ctypename = expandAlias($ctypename);
958
959         if ($ctypename =~ /^(char|u?int[0-9]*|hyper|dlong|udlong|udlongr|time_t|NTTIME_hyper|NTTIME|NTTIME_1sec)$/) {
960                 return "PyInt_FromLong($cvar)";
961         }
962
963         if ($ctypename eq "DATA_BLOB") {
964                 return "PyString_FromStringAndSize((char *)($cvar).data, ($cvar).length)";
965         }
966
967         if ($ctypename eq "NTSTATUS") {
968                 return "PyErr_FromNTSTATUS($cvar)";
969         }
970
971         if ($ctypename eq "WERROR") {
972                 return "PyErr_FromWERROR($cvar)";
973         }
974
975         if (($ctypename eq "string" or $ctypename eq "nbt_string" or $ctypename eq "nbt_name" or $ctypename eq "wrepl_nbt_name")) {
976                 return "PyString_FromString($cvar)";
977         }
978
979         # Not yet supported
980         if ($ctypename eq "string_array") { return "PyCObject_FromVoidPtr($cvar)"; }
981         if ($ctypename eq "ipv4address") { return "PyString_FromString($cvar)"; }
982         if ($ctypename eq "pointer") {
983                 return "PyCObject_FromVoidPtr($cvar, talloc_free)";
984         }
985
986         die("Unknown scalar type $ctypename");
987 }
988
989 sub ConvertObjectToPythonData($$$$$)
990 {
991         my ($self, $mem_ctx, $ctype, $cvar) = @_;
992
993         die("undef type for $cvar") unless(defined($ctype));
994
995         $ctype = resolveType($ctype);
996
997         my $actual_ctype = $ctype;
998         if ($actual_ctype->{TYPE} eq "TYPEDEF") {
999                 $actual_ctype = $actual_ctype->{DATA};
1000         } 
1001         
1002         if ($actual_ctype->{TYPE} eq "ENUM") {
1003                 return $self->ConvertScalarToPython(Parse::Pidl::Typelist::enum_type_fn($actual_ctype), $cvar);
1004         } elsif ($actual_ctype->{TYPE} eq "BITMAP") {
1005                 return $self->ConvertScalarToPython(Parse::Pidl::Typelist::bitmap_type_fn($actual_ctype), $cvar);
1006         } elsif ($actual_ctype->{TYPE} eq "SCALAR") {
1007                 return $self->ConvertScalarToPython($actual_ctype->{NAME}, $cvar);
1008         } elsif ($actual_ctype->{TYPE} eq "UNION") {
1009                 fatal($ctype, "union without discriminant: " . mapTypeName($ctype) . ": $cvar");
1010         } elsif ($actual_ctype->{TYPE} eq "STRUCT" or $actual_ctype->{TYPE} eq "INTERFACE") {
1011                 my $ctype_name = $self->use_type_variable($ctype);
1012                 unless (defined($ctype_name)) {
1013                         error(undef, "Unable to determine origin of type " . mapTypeName($ctype));
1014                         return "NULL"; # FIXME!
1015                 }
1016                 return "py_talloc_import_ex($ctype_name, $mem_ctx, $cvar)";
1017         }
1018
1019         fatal($ctype, "unknown type $actual_ctype->{TYPE} for ".mapTypeName($ctype) . ": $cvar");
1020 }
1021
1022 sub fail_on_null($$$)
1023 {
1024         my ($self, $var, $fail) = @_;
1025         $self->pidl("if ($var == NULL) {");
1026         $self->indent;
1027         $self->pidl($fail);
1028         $self->deindent;
1029         $self->pidl("}");
1030 }
1031
1032 sub ConvertObjectToPythonLevel($$$$$$)
1033 {
1034         my ($self, $mem_ctx, $env, $e, $l, $var_name, $py_var, $fail) = @_;
1035         my $nl = GetNextLevel($e, $l);
1036
1037         if ($l->{TYPE} eq "POINTER") {
1038                 if ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE})) {
1039                         $self->ConvertObjectToPythonLevel($var_name, $env, $e, $nl, $var_name, $py_var, $fail);
1040                         return;
1041                 }
1042                 if ($l->{POINTER_TYPE} ne "ref") {
1043                         $self->pidl("if ($var_name == NULL) {");
1044                         $self->indent;
1045                         $self->pidl("$py_var = Py_None;");
1046                         $self->deindent;
1047                         $self->pidl("} else {");
1048                         $self->indent;
1049                 }
1050                 $self->ConvertObjectToPythonLevel($var_name, $env, $e, $nl, get_value_of($var_name), $py_var, $fail);
1051                 if ($l->{POINTER_TYPE} ne "ref") {
1052                         $self->deindent;
1053                         $self->pidl("}");
1054                 }
1055         } elsif ($l->{TYPE} eq "ARRAY") {
1056                 my $pl = GetPrevLevel($e, $l);
1057                 if ($pl && $pl->{TYPE} eq "POINTER") {
1058                         $var_name = get_pointer_to($var_name);
1059                 }
1060
1061                 if (is_charset_array($e, $l)) {
1062                         # FIXME: Use Unix charset setting rather than utf-8
1063                         $self->pidl("$py_var = PyUnicode_Decode($var_name, strlen($var_name), \"utf-8\", \"ignore\");");
1064                 } else {
1065                         die("No SIZE_IS for array $var_name") unless (defined($l->{SIZE_IS}));
1066                         my $length = $l->{SIZE_IS};
1067                         if (defined($l->{LENGTH_IS})) {
1068                                 $length = $l->{LENGTH_IS};
1069                         }
1070
1071                         $length = ParseExpr($length, $env, $e);
1072                         $self->pidl("$py_var = PyList_New($length);");
1073                         $self->fail_on_null($py_var, $fail);
1074                         $self->pidl("{");
1075                         $self->indent;
1076                         my $counter = "$e->{NAME}_cntr_$l->{LEVEL_INDEX}";
1077                         $self->pidl("int $counter;");
1078                         $self->pidl("for ($counter = 0; $counter < $length; $counter++) {");
1079                         $self->indent;
1080                         my $member_var = "py_$e->{NAME}_$l->{LEVEL_INDEX}";
1081                         $self->pidl("PyObject *$member_var;");
1082                         $self->ConvertObjectToPythonLevel($var_name, $env, $e, GetNextLevel($e, $l), $var_name."[$counter]", $member_var, $fail);
1083                         $self->pidl("PyList_SetItem($py_var, $counter, $member_var);");
1084                         $self->deindent;
1085                         $self->pidl("}");
1086                         $self->deindent;
1087                         $self->pidl("}");
1088                 }
1089         } elsif ($l->{TYPE} eq "SWITCH") {
1090                 $var_name = get_pointer_to($var_name);
1091                 my $switch = ParseExpr($l->{SWITCH_IS}, $env, $e);
1092                 $self->pidl("$py_var = py_import_" . GetNextLevel($e, $l)->{DATA_TYPE} . "($mem_ctx, $switch, $var_name);");
1093                 $self->fail_on_null($py_var, $fail);
1094
1095         } elsif ($l->{TYPE} eq "DATA") {
1096                 if (not Parse::Pidl::Typelist::is_scalar($l->{DATA_TYPE})) {
1097                         $var_name = get_pointer_to($var_name);
1098                 }
1099                 my $conv = $self->ConvertObjectToPythonData($mem_ctx, $l->{DATA_TYPE}, $var_name);
1100                 $self->pidl("$py_var = $conv;");
1101         } elsif ($l->{TYPE} eq "SUBCONTEXT") {
1102                 $self->ConvertObjectToPythonLevel($mem_ctx, $env, $e, GetNextLevel($e, $l), $var_name, $py_var, $fail);
1103         } else {
1104                 die("Unknown level type $l->{TYPE} $var_name");
1105         }
1106 }
1107
1108 sub ConvertObjectToPython($$$$$$)
1109 {
1110         my ($self, $mem_ctx, $env, $ctype, $cvar, $py_var, $fail) = @_;
1111
1112         $self->ConvertObjectToPythonLevel($mem_ctx, $env, $ctype, $ctype->{LEVELS}[0], $cvar, $py_var, $fail);
1113 }
1114
1115 sub Parse($$$$$)
1116 {
1117     my($self,$basename,$ndr,$ndr_hdr,$hdr) = @_;
1118
1119         $self->{BASENAME} = $basename;
1120
1121     $self->pidl_hdr("
1122 /* Python wrapper functions auto-generated by pidl */
1123 #include \"includes.h\"
1124 #include \"../lib/util/python_util.h\"
1125 #include \"librpc/rpc/dcerpc.h\"
1126 #include \"lib/talloc/pytalloc.h\"
1127 #include \"librpc/rpc/pyrpc.h\"
1128 #include \"$hdr\"
1129 #include \"$ndr_hdr\"
1130
1131 ");
1132
1133         foreach my $x (@$ndr) {
1134                 ($x->{TYPE} eq "IMPORT") && $self->Import(@{$x->{PATHS}});
1135             ($x->{TYPE} eq "INTERFACE") && $self->Interface($x, $basename);
1136         }
1137         
1138         $self->pidl("static PyMethodDef $basename\_methods[] = {");
1139         $self->indent;
1140         foreach (@{$self->{module_methods}}) {
1141                 my ($fn_name, $pyfn_name, $flags, $doc) = @$_;
1142                 $self->pidl("{ \"$fn_name\", (PyCFunction)$pyfn_name, $flags, $doc },");
1143         }
1144
1145         $self->pidl("{ NULL, NULL, 0, NULL }");
1146         $self->deindent;
1147         $self->pidl("};");
1148
1149         $self->pidl("");
1150
1151         $self->pidl("void init$basename(void)");
1152         $self->pidl("{");
1153         $self->indent;
1154         $self->pidl("PyObject *m;");
1155         foreach (@{$self->{module_imports}}) {
1156                 $self->pidl("PyObject *dep_$_;");
1157         }
1158         $self->pidl("");
1159
1160         foreach (@{$self->{module_imports}}) {
1161                 $self->pidl("dep_$_ = PyImport_ImportModule(\"samba.dcerpc.$_\");");
1162                 $self->pidl("if (dep_$_ == NULL)");
1163                 $self->pidl("\treturn;");
1164                 $self->pidl("");
1165         }
1166
1167         foreach (keys %{$self->{type_imports}}) {
1168                 my $basefile = $self->{type_imports}->{$_};
1169                 $self->pidl_hdr("static PyTypeObject *$_\_Type;\n");
1170                 my $pretty_name = PrettifyTypeName($_, $basefile);
1171                 $self->pidl("$_\_Type = (PyTypeObject *)PyObject_GetAttrString(dep_$basefile, \"$pretty_name\");");
1172                 $self->pidl("if ($_\_Type == NULL)");
1173                 $self->pidl("\treturn;");
1174                 $self->pidl("");
1175         }
1176
1177         foreach (@{$self->{ready_types}}) {
1178                 $self->pidl("if (PyType_Ready($_) < 0)");
1179                 $self->pidl("\treturn;");
1180         }
1181
1182         $self->pidl($_) foreach (@{$self->{readycode}});
1183
1184         foreach (@{$self->{patch_type_calls}}) {
1185                 my ($typename, $cvar) = @$_;
1186                 $self->pidl("#ifdef PY_".uc($typename)."_PATCH");
1187                 $self->pidl("PY_".uc($typename)."_PATCH($cvar);");
1188                 $self->pidl("#endif");
1189         }
1190
1191         $self->pidl("");
1192
1193         $self->pidl("m = Py_InitModule3(\"$basename\", $basename\_methods, \"$basename DCE/RPC\");");
1194         $self->pidl("if (m == NULL)");
1195         $self->pidl("\treturn;");
1196         $self->pidl("");
1197         foreach my $name (keys %{$self->{constants}}) {
1198                 my $py_obj;
1199                 my ($ctype, $cvar) = @{$self->{constants}->{$name}};
1200                 if ($cvar =~ /^[0-9]+$/ or $cvar =~ /^0x[0-9a-fA-F]+$/) {
1201                         $py_obj = "PyInt_FromLong($cvar)";
1202                 } elsif ($cvar =~ /^".*"$/) {
1203                         $py_obj = "PyString_FromString($cvar)";
1204                 } else {
1205                         $py_obj = $self->ConvertObjectToPythonData("NULL", expandAlias($ctype), $cvar);
1206                 }
1207
1208                 $self->pidl("PyModule_AddObject(m, \"$name\", $py_obj);");
1209         }
1210
1211         foreach (@{$self->{module_objects}}) {
1212                 my ($object_name, $c_name) = @$_;
1213                 $self->pidl("Py_INCREF($c_name);");
1214                 $self->pidl("PyModule_AddObject(m, \"$object_name\", $c_name);");
1215         }
1216
1217         $self->pidl("#ifdef PY_MOD_".uc($basename)."_PATCH");
1218         $self->pidl("PY_MOD_".uc($basename)."_PATCH(m);");
1219         $self->pidl("#endif");
1220
1221         $self->pidl("");
1222         $self->deindent;
1223         $self->pidl("}");
1224     return ($self->{res_hdr} . $self->{res});
1225 }
1226
1227 1;