a2ad3c650808c55daca8e54da8258efd922e6c66
[ira/wip.git] / source / 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::Typelist qw(hasType getType mapTypeName expandAlias);
13 use Parse::Pidl::Util qw(has_property ParseExpr);
14 use Parse::Pidl::NDR qw(GetPrevLevel GetNextLevel ContainsDeferred is_charset_array);
15 use Parse::Pidl::CUtil qw(get_value_of get_pointer_to);
16 use Parse::Pidl::Samba4::Header qw(GenerateFunctionInEnv GenerateFunctionOutEnv EnvSubstituteValue GenerateStructEnv);
17
18 use vars qw($VERSION);
19 $VERSION = '0.01';
20
21 sub new($) {
22         my ($class) = @_;
23         my $self = { res => "", res_hdr => "", tabs => "", constants => {},
24                      module_methods => []};
25         bless($self, $class);
26 }
27
28 sub pidl_hdr ($$)
29 {
30         my $self = shift;
31         $self->{res_hdr} .= shift;
32 }
33
34 sub pidl($$)
35 {
36         my ($self, $d) = @_;
37         if ($d) {
38                 $self->{res} .= $self->{tabs};
39                 $self->{res} .= $d;
40         }
41         $self->{res} .= "\n";
42 }
43
44 sub indent($)
45 {
46         my ($self) = @_;
47         $self->{tabs} .= "\t";
48 }
49
50 sub deindent($)
51 {
52         my ($self) = @_;
53         $self->{tabs} = substr($self->{tabs}, 0, -1);
54 }
55
56 sub Import
57 {
58         my $self = shift;
59         my @imports = @_;
60         foreach (@imports) {
61                 s/\.idl\"$//;
62                 s/^\"//;
63                 $self->pidl_hdr("#include \"librpc/gen_ndr/py_$_\.h\"\n");
64         }
65 }
66
67 sub Const($$)
68 {
69     my ($self, $const) = @_;
70         $self->register_constant($const->{NAME}, $const->{DTYPE}, $const->{VALUE});
71 }
72
73 sub register_constant($$$$)
74 {
75         my ($self, $name, $type, $value) = @_;
76
77         $self->{constants}->{$name} = [$type, $value];
78 }
79
80 sub EnumAndBitmapConsts($$$)
81 {
82         my ($self, $name, $d) = @_;
83
84         return unless (defined($d->{ELEMENTS}));
85
86         foreach my $e (@{$d->{ELEMENTS}}) {
87                 $e =~ /^([A-Za-z0-9_]+)=(.*)$/;
88                 my $cname = $1;
89                 
90                 $self->register_constant($cname, $d, $cname);
91         }
92 }
93
94 sub FromUnionToPythonFunction($$$)
95 {
96         my ($self, $type, $switch, $name) = @_;
97
98         $self->pidl("PyObject *ret;");
99         $self->pidl("");
100
101         $self->pidl("switch ($switch) {");
102         $self->indent;
103
104         foreach my $e (@{$type->{ELEMENTS}}) {
105                 if (defined($e->{CASE})) {
106                         $self->pidl("$e->{CASE}:");
107                 } else {
108                         $self->pidl("default:");
109                 }
110
111                 $self->indent;
112
113                 if ($e->{NAME}) {
114                         $self->ConvertObjectToPython({}, $e, "$name->$e->{NAME}", "ret");
115                 } else {
116                         $self->pidl("ret = Py_None;");
117                 }
118
119                 $self->pidl("return ret;");
120                 $self->pidl("");
121
122                 $self->deindent;
123         }
124
125         $self->deindent;
126         $self->pidl("}");
127
128         $self->pidl("PyErr_SetString(PyExc_TypeError, \"unknown union level\");");
129         $self->pidl("return NULL;");
130 }
131
132 sub FromPythonToUnionFunction($$$$$)
133 {
134         my ($self, $type, $typename, $switch, $mem_ctx, $name) = @_;
135
136         my $has_default = 0;
137
138         $self->pidl("$typename *ret = talloc_zero($mem_ctx, $typename);");
139
140         $self->pidl("switch ($switch) {");
141         $self->indent;
142
143         foreach my $e (@{$type->{ELEMENTS}}) {
144                 if (defined($e->{CASE})) {
145                         $self->pidl("$e->{CASE}:");
146                 } else {
147                         $has_default = 1;
148                         $self->pidl("default:");
149                 }
150                 $self->indent;
151                 if ($e->{NAME}) {
152                         $self->ConvertObjectFromPython({}, $mem_ctx, $e, $name, "ret->$e->{NAME}", "talloc_free(ret); return NULL;");
153                 }
154                 $self->pidl("break;");
155                 $self->deindent;
156                 $self->pidl("");
157         }
158
159         if (!$has_default) {
160                 $self->pidl("default:");
161                 $self->indent;
162                 $self->pidl("PyErr_SetString(PyExc_TypeError, \"invalid union level value\");");
163                 $self->pidl("talloc_free(ret);");
164                 $self->pidl("ret = NULL;");
165                 $self->deindent;
166         }
167
168         $self->deindent;
169         $self->pidl("}");
170         $self->pidl("");
171         $self->pidl("return ret;");
172 }
173
174 sub PythonStruct($$$$)
175 {
176         my ($self, $name, $cname, $d) = @_;
177
178         my $env = GenerateStructEnv($d, "object");
179
180         $self->pidl("");
181
182         $self->pidl("static PyObject *py_$name\_getattr(PyObject *obj, char *name)");
183         $self->pidl("{");
184         $self->indent;
185         $self->pidl("$cname *object = py_talloc_get_type(obj, $cname);");
186         foreach my $e (@{$d->{ELEMENTS}}) {
187                 $self->pidl("if (!strcmp(name, \"$e->{NAME}\")) {");
188                 my $varname = "object->$e->{NAME}";
189                 $self->indent;
190                 $self->pidl("PyObject *py_$e->{NAME};");
191                 $self->ConvertObjectToPython($env, $e, $varname, "py_$e->{NAME}");
192                 $self->pidl("return py_$e->{NAME};");
193                 $self->deindent;
194                 $self->pidl("}");
195         }
196         $self->pidl("PyErr_SetString(PyExc_AttributeError, \"no such attribute\");");
197         $self->pidl("return NULL;");
198         $self->deindent;
199         $self->pidl("}");
200         $self->pidl("");
201
202         $self->pidl("static int py_$name\_setattr(PyObject *py_obj, char *name, PyObject *value)");
203         $self->pidl("{");
204         $self->indent;
205         $self->pidl("$cname *object = py_talloc_get_type(py_obj, $cname);");
206         my $mem_ctx = "py_talloc_get_mem_ctx(py_obj)";
207         foreach my $e (@{$d->{ELEMENTS}}) {
208                 $self->pidl("if (!strcmp(name, \"$e->{NAME}\")) {");
209                 my $varname = "object->$e->{NAME}";
210                 $self->indent;
211                 if ($e->{ORIGINAL}->{POINTERS} > 0) {
212                         $self->pidl("talloc_free($varname);");
213                 }
214                 $self->ConvertObjectFromPython($env, $mem_ctx, $e, "value", $varname, "return -1;");
215                 $self->pidl("return 0;");
216                 $self->deindent;
217                 $self->pidl("}");
218         }
219         $self->pidl("PyErr_SetString(PyExc_AttributeError, \"no such attribute\");");
220         $self->pidl("return -1;");
221         $self->deindent;
222         $self->pidl("}");
223         $self->pidl("");
224
225         $self->pidl_hdr("PyAPI_DATA(PyTypeObject) $name\_Type;\n");
226         $self->pidl_hdr("#define $name\_Check(op) PyObject_TypeCheck(op, &$name\_Type)\n");
227         $self->pidl_hdr("#define $name\_CheckExact(op) ((op)->ob_type == &$name\_Type)\n");
228         $self->pidl_hdr("\n");
229         $self->pidl("PyTypeObject $name\_Type = {");
230         $self->indent;
231         $self->pidl("PyObject_HEAD_INIT(NULL) 0,");
232         $self->pidl(".tp_name = \"$name\",");
233         $self->pidl(".tp_basicsize = sizeof(py_talloc_Object),");
234         $self->pidl(".tp_dealloc = py_talloc_dealloc,");
235         $self->pidl(".tp_getattr = py_$name\_getattr,");
236         $self->pidl(".tp_setattr = py_$name\_setattr,");
237         $self->pidl(".tp_repr = py_talloc_default_repr,");
238         $self->deindent;
239         $self->pidl("};");
240
241         $self->pidl("");
242
243         my $py_fnname = "py_$name";
244         $self->pidl("static PyObject *$py_fnname(PyObject *self, PyObject *args)");
245         $self->pidl("{");
246         $self->indent;
247         $self->pidl("$cname *ret = talloc_zero(NULL, $cname);");
248         $self->pidl("return py_talloc_import(&$name\_Type, ret);");
249         $self->deindent;
250         $self->pidl("}");
251         $self->pidl("");
252
253         return $py_fnname;
254 }
255
256 sub PythonFunction($$$)
257 {
258         my ($self, $fn, $iface) = @_;
259
260         $self->pidl("static PyObject *py_$fn->{NAME}(PyObject *self, PyObject *args, PyObject *kwargs)");
261         $self->pidl("{");
262         $self->indent;
263         $self->pidl("$iface\_InterfaceObject *iface = ($iface\_InterfaceObject *)self;");
264         $self->pidl("NTSTATUS status;");
265         $self->pidl("TALLOC_CTX *mem_ctx = talloc_new(NULL);");
266         $self->pidl("struct $fn->{NAME} r;");
267         $self->pidl("PyObject *result;");
268
269         my $env = GenerateFunctionInEnv($fn, "r.");
270         my $result_size = 0;
271
272         my $args_format = "";
273         my $args_string = "";
274         my $args_names = "";
275
276         foreach my $e (@{$fn->{ELEMENTS}}) {
277                 $self->pidl("PyObject *py_$e->{NAME};");
278                 if (grep(/out/,@{$e->{DIRECTION}})) {
279                         $result_size++;
280                 }
281                 if (grep(/in/,@{$e->{DIRECTION}})) {
282                         $args_format .= "O";
283                         $args_string .= ", &py_$e->{NAME}";
284                         $args_names .= "\"$e->{NAME}\", ";
285                 }
286         }
287         $self->pidl("const char *kwnames[] = {");
288         $self->indent;
289         $self->pidl($args_names . "NULL");
290         $self->deindent;
291         $self->pidl("};");
292
293         $self->pidl("");
294         $self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"$args_format:$fn->{NAME}\", discard_const_p(char *, kwnames)$args_string)) {");
295         $self->indent;
296         $self->pidl("return NULL;");
297         $self->deindent;
298         $self->pidl("}");
299
300         if ($result_size > 0) {
301                 $self->pidl("");
302                 $self->pidl("ZERO_STRUCT(r.out);");
303         }
304         if ($fn->{RETURN_TYPE}) {
305                 $result_size++;
306         }
307
308         foreach my $e (@{$fn->{ELEMENTS}}) {
309                 if (grep(/in/,@{$e->{DIRECTION}})) {
310                         $self->ConvertObjectFromPython($env, "mem_ctx", $e, "py_$e->{NAME}", "r.in.$e->{NAME}", "talloc_free(mem_ctx); return NULL;");
311                 }
312         }
313         $self->pidl("status = dcerpc_$fn->{NAME}(iface->pipe, mem_ctx, &r);");
314         $self->handle_ntstatus("status", "NULL", "mem_ctx");
315
316         $self->pidl("result = PyTuple_New($result_size);");
317
318         $env = GenerateFunctionOutEnv($fn, "r.");
319         my $i = 0;
320
321         foreach my $e (@{$fn->{ELEMENTS}}) {
322                 if (grep(/out/,@{$e->{DIRECTION}})) {
323                         $self->ConvertObjectToPython($env, $e, "r.out.$e->{NAME}", "py_$e->{NAME}");
324                         $self->pidl("PyTuple_SetItem(result, $i, py_$e->{NAME});");
325
326                         $i++;
327                 }
328         }
329
330         if (defined($fn->{RETURN_TYPE})) {
331                 $self->pidl("PyTuple_SetItem(result, $i, " . $self->ConvertObjectToPythonData($fn->{RETURN_TYPE}, "r.out.result") . ");");
332         }
333
334         $self->pidl("talloc_free(mem_ctx);");
335         $self->pidl("return result;");
336         $self->deindent;
337         $self->pidl("}");
338         $self->pidl("");
339 }
340
341 sub handle_ntstatus($$$$)
342 {
343         my ($self, $var, $retval, $mem_ctx) = @_;
344
345         $self->pidl("if (NT_STATUS_IS_ERR($var)) {");
346         $self->indent;
347         $self->pidl("PyErr_SetString(PyExc_RuntimeError, nt_errstr($var));");
348         $self->pidl("talloc_free($mem_ctx);") if ($mem_ctx);
349         $self->pidl("return $retval;");
350         $self->deindent;
351         $self->pidl("}");
352         $self->pidl("");
353 }
354
355 sub PythonType($$$)
356 {
357         my ($self, $d, $interface, $basename) = @_;
358
359         my $actual_ctype = $d;
360         if ($actual_ctype->{TYPE} eq "TYPEDEF") {
361                 $actual_ctype = $actual_ctype->{DATA};
362         }
363
364         if ($actual_ctype->{TYPE} eq "STRUCT") {
365                 my $py_fnname;
366                 if ($d->{TYPE} eq "STRUCT") {
367                         $py_fnname = $self->PythonStruct($d->{NAME}, mapTypeName($d), $d);
368                 } else {
369                         $py_fnname = $self->PythonStruct($d->{NAME}, mapTypeName($d), $d->{DATA});
370                 }
371
372                 my $fn_name = $d->{NAME};
373
374                 $fn_name =~ s/^$interface->{NAME}_//;
375                 $fn_name =~ s/^$basename\_//;
376
377                 $self->register_module_method($fn_name, $py_fnname, "METH_NOARGS", "NULL");
378         }
379
380         if ($d->{TYPE} eq "ENUM" or $d->{TYPE} eq "BITMAP") {
381                 $self->EnumAndBitmapConsts($d->{NAME}, $d);
382         }
383
384         if ($d->{TYPE} eq "TYPEDEF" and ($d->{DATA}->{TYPE} eq "ENUM" or $d->{DATA}->{TYPE} eq "BITMAP")) {
385                 $self->EnumAndBitmapConsts($d->{NAME}, $d->{DATA});
386         }
387
388         if ($actual_ctype->{TYPE} eq "UNION") {
389                 $self->pidl("PyObject *py_import_$d->{NAME}(int level, " .mapTypeName($d) . " *in)");
390                 $self->pidl("{");
391                 $self->indent;
392                 $self->FromUnionToPythonFunction($actual_ctype, "level", "in") if ($actual_ctype->{TYPE} eq "UNION");
393                 $self->deindent;
394                 $self->pidl("}");
395                 $self->pidl("");
396
397                 $self->pidl(mapTypeName($d) . " *py_export_$d->{NAME}(TALLOC_CTX *mem_ctx, int level, PyObject *in)");
398                 $self->pidl("{");
399                 $self->indent;
400                 $self->FromPythonToUnionFunction($actual_ctype, mapTypeName($d), "level", "mem_ctx", "in") if ($actual_ctype->{TYPE} eq "UNION");
401                 $self->deindent;
402                 $self->pidl("}");
403                 $self->pidl("");
404         }
405 }
406
407 sub Interface($$$)
408 {
409         my($self,$interface,$basename) = @_;
410
411         $self->pidl_hdr("#ifndef _HEADER_PYTHON_$interface->{NAME}\n");
412         $self->pidl_hdr("#define _HEADER_PYTHON_$interface->{NAME}\n\n");
413
414         $self->pidl_hdr("\n");
415
416         $self->Const($_) foreach (@{$interface->{CONSTS}});
417
418         foreach my $d (@{$interface->{TYPES}}) {
419                 next if has_property($d, "nopython");
420
421                 $self->PythonType($d, $interface, $basename);
422         }
423
424         $self->pidl_hdr("PyAPI_DATA(PyTypeObject) $interface->{NAME}_InterfaceType;\n");
425         $self->pidl("typedef struct {");
426         $self->indent;
427         $self->pidl("PyObject_HEAD");
428         $self->pidl("struct dcerpc_pipe *pipe;");
429         $self->deindent;
430         $self->pidl("} $interface->{NAME}_InterfaceObject;");
431
432         $self->pidl("");
433
434         foreach my $d (@{$interface->{FUNCTIONS}}) {
435                 next if not defined($d->{OPNUM});
436                 next if has_property($d, "nopython");
437
438                 $self->PythonFunction($d, $interface->{NAME});
439         }
440
441         $self->pidl("static PyMethodDef interface_$interface->{NAME}\_methods[] = {");
442         $self->indent;
443         foreach my $d (@{$interface->{FUNCTIONS}}) {
444                 next if not defined($d->{OPNUM});
445                 next if has_property($d, "nopython");
446
447                 my $fn_name = $d->{NAME};
448
449                 $fn_name =~ s/^$interface->{NAME}_//;
450
451                 $self->pidl("{ \"$fn_name\", (PyCFunction)py_$d->{NAME}, METH_VARARGS|METH_KEYWORDS, NULL },");
452         }
453         $self->pidl("{ NULL, NULL, 0, NULL }");
454         $self->deindent;
455         $self->pidl("};");
456         $self->pidl("");
457
458         $self->pidl("static void interface_$interface->{NAME}_dealloc(PyObject* self)");
459         $self->pidl("{");
460         $self->indent;
461         $self->pidl("$interface->{NAME}_InterfaceObject *interface = ($interface->{NAME}_InterfaceObject *)self;");
462         $self->pidl("talloc_free(interface->pipe);");
463         $self->pidl("PyObject_Del(self);");
464         $self->deindent;
465         $self->pidl("}");
466         $self->pidl("");
467
468         $self->pidl("static PyObject *interface_$interface->{NAME}_getattr(PyObject *obj, char *name)");
469         $self->pidl("{");
470         $self->indent;
471         $self->pidl("return Py_FindMethod(interface_$interface->{NAME}\_methods, obj, name);");
472         $self->deindent;
473         $self->pidl("}");
474
475         $self->pidl("");
476
477         $self->pidl("PyTypeObject $interface->{NAME}_InterfaceType = {");
478         $self->indent;
479         $self->pidl("PyObject_HEAD_INIT(NULL) 0,");
480         $self->pidl(".tp_name = \"$interface->{NAME}\",");
481         $self->pidl(".tp_basicsize = sizeof($interface->{NAME}_InterfaceObject),");
482         $self->pidl(".tp_dealloc = interface_$interface->{NAME}_dealloc,");
483         $self->pidl(".tp_getattr = interface_$interface->{NAME}_getattr,");
484         $self->deindent;
485         $self->pidl("};");
486
487         $self->pidl("");
488
489         $self->register_module_method($interface->{NAME}, "interface_$interface->{NAME}", "METH_VARARGS|METH_KEYWORDS", "NULL");
490         $self->pidl("static PyObject *interface_$interface->{NAME}(PyObject *self, PyObject *args)");
491         $self->pidl("{");
492         $self->indent;
493         $self->pidl("$interface->{NAME}_InterfaceObject *ret;");
494         $self->pidl("const char *binding_string;");
495         $self->pidl("struct cli_credentials *credentials;");
496         $self->pidl("struct loadparm_context *lp_ctx;");
497         $self->pidl("TALLOC_CTX *mem_ctx = NULL;");
498         $self->pidl("NTSTATUS status;");
499         $self->pidl("");
500
501         # FIXME: Arguments: binding string, credentials, loadparm context
502         $self->pidl("ret = PyObject_New($interface->{NAME}_InterfaceObject, &$interface->{NAME}_InterfaceType);");
503         $self->pidl("");
504
505         $self->pidl("status = dcerpc_pipe_connect(NULL, &ret->pipe, binding_string, ");
506         $self->pidl("             &ndr_table_$interface->{NAME}, credentials, NULL, lp_ctx);");
507         $self->handle_ntstatus("status", "NULL", "mem_ctx");
508
509         $self->pidl("return (PyObject *)ret;");
510         $self->deindent;
511         $self->pidl("}");
512         
513         $self->pidl("");
514
515         $self->pidl_hdr("\n");
516         $self->pidl_hdr("#endif /* _HEADER_NDR_$interface->{NAME} */\n");
517 }
518
519 sub register_module_method($$$$$)
520 {
521         my ($self, $fn_name, $pyfn_name, $flags, $doc) = @_;
522
523         push (@{$self->{module_methods}}, [$fn_name, $pyfn_name, $flags, $doc])
524 }
525
526 sub ConvertObjectFromPythonData($$$$$$)
527 {
528         my ($self, $mem_ctx, $cvar, $ctype, $target, $fail) = @_;
529
530         die("undef type for $cvar") unless(defined($ctype));
531
532         if (ref($ctype) ne "HASH") {
533                 $ctype = getType($ctype);
534         }
535
536         if (ref($ctype) ne "HASH") {
537                 $self->pidl("$target = FIXME($cvar);");
538                 return;
539         }
540
541         my $actual_ctype = $ctype;
542         if ($ctype->{TYPE} eq "TYPEDEF") {
543                 $actual_ctype = $ctype->{DATA};
544         }
545
546         if ($actual_ctype->{TYPE} eq "ENUM" or $actual_ctype->{TYPE} eq "BITMAP" or 
547                 $actual_ctype->{TYPE} eq "SCALAR" and (
548                 expandAlias($actual_ctype->{NAME}) =~ /^(u?int[0-9]+|hyper|NTTIME|time_t|NTTIME_hyper|NTTIME_1sec|dlong|udlong|udlongr)$/)) {
549                 $self->pidl("PY_CHECK_TYPE(PyInt, $cvar, $fail);");
550                 $self->pidl("$target = PyInt_AsLong($cvar);");
551                 return;
552         }
553
554         if ($actual_ctype->{TYPE} eq "STRUCT") {
555                 $self->pidl("PY_CHECK_TYPE($ctype->{NAME}, $cvar, $fail);");
556                 $self->pidl("$target = py_talloc_get_ptr($cvar);");
557                 return;
558         }
559
560         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "DATA_BLOB") {
561                 $self->pidl("$target = data_blob_talloc($mem_ctx, PyString_AsString($cvar), PyString_Size($cvar));");
562                 return;
563         }
564
565         if ($actual_ctype->{TYPE} eq "SCALAR" and 
566                 ($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")) {
567                 $self->pidl("$target = talloc_strdup($mem_ctx, PyString_AsString($cvar));");
568                 return;
569         }
570
571         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "ipv4address") {
572                 $self->pidl("$target = FIXME($cvar);");
573                 return;
574                 }
575
576
577         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "NTSTATUS") {
578                 $self->pidl("$target = PyInt_AsLong($cvar);");
579                 return;
580         }
581
582         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "WERROR") {
583                 $self->pidl("$target = PyInt_AsLong($cvar);");
584                 return;
585         }
586
587         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "string_array") {
588                 $self->pidl("$target = FIXME($cvar);");
589                 return;
590         }
591
592         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "pointer") {
593                 $self->pidl("$target = PyCObject_AsVoidPtr($cvar);");
594                 return;
595         }
596
597         die("unknown type ".mapTypeName($ctype) . ": $cvar");
598
599 }
600
601 sub ConvertObjectFromPythonLevel($$$$$$$$)
602 {
603         my ($self, $env, $mem_ctx, $py_var, $e, $l, $var_name, $fail) = @_;
604
605         if ($l->{TYPE} eq "POINTER") {
606                 if ($l->{POINTER_TYPE} ne "ref") {
607                         $self->pidl("if ($py_var == Py_None) {");
608                         $self->indent;
609                         $self->pidl("$var_name = NULL;");
610                         $self->deindent;
611                         $self->pidl("} else {");
612                         $self->indent;
613                 }
614                 $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $py_var, $e, GetNextLevel($e, $l), get_value_of($var_name), $fail);
615                 if ($l->{POINTER_TYPE} ne "ref") {
616                         $self->deindent;
617                         $self->pidl("}");
618                 }
619         } elsif ($l->{TYPE} eq "ARRAY") {
620                 if (is_charset_array($e, $l)) {
621                         $self->pidl(get_pointer_to($var_name) . " = PyString_AsString(PyUnicode_AsEncodedString($py_var, \"utf-8\", \"ignore\"));");
622                 } else {
623                         my $counter = "$e->{NAME}_cntr_$l->{LEVEL_INDEX}";
624                         $self->pidl("{");
625                         $self->indent;
626                         $self->pidl("int $counter;");
627                         $self->pidl("$var_name = talloc_array($mem_ctx, FIXME, PyList_Size($py_var));");
628                         $self->pidl("for ($counter = 0; $counter < PyList_Size($py_var); $counter++) {");
629                         $self->indent;
630                         $self->ConvertObjectFromPythonLevel($env, $var_name, "PyList_GetItem($py_var, $counter)", $e, GetNextLevel($e, $l), $var_name."[$counter]", $fail);
631                         $self->deindent;
632                         $self->pidl("}");
633                         $self->deindent;
634                         $self->pidl("}");
635                 }
636         } elsif ($l->{TYPE} eq "DATA") {
637
638                 if (not Parse::Pidl::Typelist::is_scalar($l->{DATA_TYPE}) or 
639                         Parse::Pidl::Typelist::scalar_is_reference($l->{DATA_TYPE})) {
640                         $var_name = get_pointer_to($var_name);
641                 }
642                 $self->ConvertObjectFromPythonData($mem_ctx, $py_var, $l->{DATA_TYPE}, $var_name, $fail);
643         } elsif ($l->{TYPE} eq "SWITCH") {
644                 $var_name = get_pointer_to($var_name);
645                 my $switch = ParseExpr($l->{SWITCH_IS}, $env, $e);
646                 $self->pidl("$var_name = py_export_" . GetNextLevel($e, $l)->{DATA_TYPE} . "($mem_ctx, $switch, $py_var);");
647         } elsif ($l->{TYPE} eq "SUBCONTEXT") {
648                 $self->pidl("FIXME");
649         } else {
650                 die("unknown level type $l->{TYPE}");
651         }
652 }
653
654 sub ConvertObjectFromPython($$$$$$$)
655 {
656         my ($self, $env, $mem_ctx, $ctype, $cvar, $target, $fail) = @_;
657
658         $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $cvar, $ctype, $ctype->{LEVELS}[0], $target, $fail);
659 }
660
661 sub ConvertScalarToPython($$$)
662 {
663         my ($self, $ctypename, $cvar) = @_;
664
665         die("expected string for $cvar, not $ctypename") if (ref($ctypename) eq "HASH");
666
667         $ctypename = expandAlias($ctypename);
668
669         if ($ctypename =~ /^(int|long|char|u?int[0-9]+|hyper|dlong|udlong|udlongr|time_t|NTTIME_hyper|NTTIME|NTTIME_1sec)$/) {
670                 return "PyInt_FromLong($cvar)";
671         }
672
673         if ($ctypename eq "DATA_BLOB") {
674                 return "PyString_FromStringAndSize($cvar->data, $cvar->length)";
675         }
676
677         if ($ctypename eq "NTSTATUS") {
678                 return "PyInt_FromLong(NT_STATUS_V($cvar))";
679         }
680
681         if ($ctypename eq "WERROR") {
682                 return "PyInt_FromLong(W_ERROR_V($cvar))";
683         }
684
685         if (($ctypename eq "string" or $ctypename eq "nbt_string" or $ctypename eq "nbt_name" or $ctypename eq "wrepl_nbt_name")) {
686                 return "PyString_FromString($cvar)";
687         }
688
689         if ($ctypename eq "string_array") { return "FIXME($cvar)"; }
690
691         if ($ctypename eq "ipv4address") { return "FIXME($cvar)"; }
692         if ($ctypename eq "pointer") {
693                 return "PyCObject_FromVoidPtr($cvar, talloc_free)";
694         }
695
696         die("Unknown scalar type $ctypename");
697 }
698
699 sub ConvertObjectToPythonData($$$$)
700 {
701         my ($self, $ctype, $cvar) = @_;
702
703         die("undef type for $cvar") unless(defined($ctype));
704
705         if (ref($ctype) ne "HASH") {
706                 if (not hasType($ctype)) {
707                         if (ref($ctype) eq "HASH") {
708                                 return "py_import_$ctype->{TYPE}_$ctype->{NAME}($cvar)";
709                         } else {
710                                 return "py_import_$ctype($cvar)"; # best bet
711                         }
712                 }
713
714                 $ctype = getType($ctype);
715         }
716
717         my $actual_ctype = $ctype;
718         if ($ctype->{TYPE} eq "TYPEDEF") {
719                 $actual_ctype = $ctype->{DATA};
720         }
721
722         if ($actual_ctype->{TYPE} eq "ENUM") {
723                 return $self->ConvertScalarToPython(Parse::Pidl::Typelist::enum_type_fn($actual_ctype), $cvar);
724         }
725
726         if ($actual_ctype->{TYPE} eq "BITMAP") {
727                 return $self->ConvertScalarToPython(Parse::Pidl::Typelist::bitmap_type_fn($actual_ctype), $cvar);
728         }
729
730         if ($actual_ctype->{TYPE} eq "SCALAR") {
731                 return $self->ConvertScalarToPython($actual_ctype->{NAME}, $cvar);
732         }
733
734         if ($actual_ctype->{TYPE} eq "STRUCT") {
735                 # FIXME: if $cvar is not a pointer, do a talloc_dup()
736                 return "py_talloc_import(&$ctype->{NAME}_Type, $cvar)";
737         }
738
739         die("unknown type ".mapTypeName($ctype) . ": $cvar");
740 }
741
742 sub ConvertObjectToPythonLevel($$$$)
743 {
744         my ($self, $env, $e, $l, $var_name, $py_var) = @_;
745
746         if ($l->{TYPE} eq "POINTER") {
747                 if ($l->{POINTER_TYPE} ne "ref") {
748                         $self->pidl("if ($var_name == NULL) {");
749                         $self->indent;
750                         $self->pidl("$py_var = Py_None;");
751                         $self->deindent;
752                         $self->pidl("} else {");
753                         $self->indent;
754                 }
755                 $self->ConvertObjectToPythonLevel($env, $e, GetNextLevel($e, $l), get_value_of($var_name), $py_var);
756                 if ($l->{POINTER_TYPE} ne "ref") {
757                         $self->deindent;
758                         $self->pidl("}");
759                 }
760         } elsif ($l->{TYPE} eq "ARRAY") {
761                 if (is_charset_array($e, $l)) {
762                         $var_name = get_pointer_to($var_name);
763                         $self->pidl("$py_var = PyUnicode_Decode($var_name, strlen($var_name), \"utf-8\", \"ignore\");");
764                 } else {
765                         die("No SIZE_IS for array $var_name") unless (defined($l->{SIZE_IS}));
766                         my $length = $l->{SIZE_IS};
767                         if (defined($l->{LENGTH_IS})) {
768                                 $length = $l->{LENGTH_IS};
769                         }
770
771                         $length = ParseExpr($length, $env, $e);
772                         $self->pidl("$py_var = PyList_New($length);");
773                         $self->pidl("{");
774                         $self->indent;
775                         my $counter = "$e->{NAME}_cntr_$l->{LEVEL_INDEX}";
776                         $self->pidl("int $counter;");
777                         $self->pidl("for ($counter = 0; $counter < $length; $counter++) {");
778                         $self->indent;
779                         my $member_var = "py_$e->{NAME}_$l->{LEVEL_INDEX}";
780                         $self->pidl("PyObject *$member_var;");
781                         $self->ConvertObjectToPythonLevel($env, $e, GetNextLevel($e, $l), $var_name."[$counter]", $member_var);
782                         $self->pidl("PyList_SetItem($py_var, $counter, $member_var);");
783                         $self->deindent;
784                         $self->pidl("}");
785                         $self->deindent;
786                         $self->pidl("}");
787                 }
788         } elsif ($l->{TYPE} eq "SWITCH") {
789                 $var_name = get_pointer_to($var_name);
790                 my $switch = ParseExpr($l->{SWITCH_IS}, $env, $e);
791                 $self->pidl("$py_var = py_import_" . GetNextLevel($e, $l)->{DATA_TYPE} . "($switch, $var_name);");
792         } elsif ($l->{TYPE} eq "DATA") {
793                 if (not Parse::Pidl::Typelist::is_scalar($l->{DATA_TYPE}) or 
794                         Parse::Pidl::Typelist::scalar_is_reference($l->{DATA_TYPE})) {
795                         $var_name = get_pointer_to($var_name);
796                 }
797                 $self->pidl("$py_var = ".$self->ConvertObjectToPythonData($l->{DATA_TYPE}, $var_name) . ";");
798         } elsif ($l->{TYPE} eq "SUBCONTEXT") {
799                 $self->pidl("FIXME");
800         } else {
801                 die("Unknown level type $l->{TYPE} $var_name");
802         }
803 }
804
805 sub ConvertObjectToPython($$$$$)
806 {
807         my ($self, $env, $ctype, $cvar, $py_var) = @_;
808
809         $self->ConvertObjectToPythonLevel($env, $ctype, $ctype->{LEVELS}[0], $cvar, $py_var);
810 }
811
812 sub Parse($$$$$)
813 {
814     my($self,$basename,$ndr,$ndr_hdr,$hdr) = @_;
815     
816     my $py_hdr = $hdr;
817     $py_hdr =~ s/ndr_([^\/]+)$/py_$1/g;
818
819     $self->pidl_hdr("/* header auto-generated by pidl */\n\n");
820         
821     $self->pidl("
822 /* Python wrapper functions auto-generated by pidl */
823 #include \"includes.h\"
824 #include <Python.h>
825 #include \"librpc/rpc/dcerpc.h\"
826 #include \"scripting/python/pytalloc.h\"
827 #include \"$hdr\"
828 #include \"$ndr_hdr\"
829 #include \"$py_hdr\"
830
831 #define PY_CHECK_TYPE(type, var, fail) \\
832         if (!type ## _Check(var)) {\\
833                 PyErr_Format(PyExc_TypeError, \"Expected type %s\", type ## _Type.tp_name); \\
834                 fail; \\
835         }
836 ");
837
838         foreach my $x (@$ndr) {
839             ($x->{TYPE} eq "INTERFACE") && $self->Interface($x, $basename);
840                 ($x->{TYPE} eq "IMPORT") && $self->Import(@{$x->{PATHS}});
841         }
842         
843         $self->pidl("static PyMethodDef $basename\_methods[] = {");
844         $self->indent;
845         foreach (@{$self->{module_methods}}) {
846                 my ($fn_name, $pyfn_name, $flags, $doc) = @$_;
847                 $self->pidl("{ \"$fn_name\", (PyCFunction)$pyfn_name, $flags, $doc },");
848         }
849         
850         $self->pidl("{ NULL, NULL, 0, NULL }");
851         $self->deindent;
852         $self->pidl("};");
853
854         $self->pidl("");
855
856         $self->pidl("void init$basename(void)");
857         $self->pidl("{");
858         $self->indent;
859         $self->pidl("PyObject *m;");
860         $self->pidl("m = Py_InitModule(\"$basename\", $basename\_methods);");
861         foreach my $name (keys %{$self->{constants}}) {
862                 my $py_obj;
863                 my ($ctype, $cvar) = @{$self->{constants}->{$name}};
864                 if ($cvar =~ /^[0-9]+$/ or $cvar =~ /^0x[0-9a-fA-F]+$/) {
865                         $py_obj = "PyInt_FromLong($cvar)";
866                 } elsif ($cvar =~ /^".*"$/) {
867                         $py_obj = "PyString_FromString($cvar)";
868                 } else {
869                         $py_obj = $self->ConvertObjectToPythonData($ctype, $cvar);
870                 }
871
872                 $self->pidl("PyModule_AddObject(m, \"$name\", $py_obj);");
873         }
874         $self->deindent;
875         $self->pidl("}");
876     return ($self->{res_hdr}, $self->{res});
877 }
878
879 1;