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