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