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