9f6a7847b1bb49b7197d4fd31d92912861aea344
[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 resolveType 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, $mem_ctx, $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($mem_ctx, {}, $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_ptr(obj);");
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("py_talloc_get_mem_ctx(obj)", $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_ptr(py_obj);");
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 = talloc_zero(mem_ctx, struct $fn->{NAME});");
267         $self->pidl("PyObject *result = Py_None;");
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 ($fn->{RETURN_TYPE}) {
301                 $result_size++ unless ($fn->{RETURN_TYPE} eq "WERROR" or $fn->{RETURN_TYPE} eq "NTSTATUS");
302         }
303
304         foreach my $e (@{$fn->{ELEMENTS}}) {
305                 if (grep(/in/,@{$e->{DIRECTION}})) {
306                         $self->ConvertObjectFromPython($env, "mem_ctx", $e, "py_$e->{NAME}", "r->in.$e->{NAME}", "talloc_free(mem_ctx); return NULL;");
307                 }
308         }
309         $self->pidl("status = dcerpc_$fn->{NAME}(iface->pipe, mem_ctx, r);");
310         $self->handle_ntstatus("status", "NULL", "mem_ctx");
311
312         $env = GenerateFunctionOutEnv($fn, "r->");
313         my $i = 0;
314
315         if ($result_size > 1) {
316                 $self->pidl("result = PyTuple_New($result_size);");
317         }
318
319         foreach my $e (@{$fn->{ELEMENTS}}) {
320                 my $py_name = "py_$e->{NAME}";
321                 if (grep(/out/,@{$e->{DIRECTION}})) {
322                         $self->ConvertObjectToPython("r", $env, $e, "r->out.$e->{NAME}", $py_name);
323                         if ($result_size > 1) {
324                                 $self->pidl("PyTuple_SetItem(result, $i, $py_name);");
325                                 $i++;
326                         } else {
327                                 $self->pidl("result = $py_name;");
328                         }
329                 }
330         }
331
332         if (defined($fn->{RETURN_TYPE}) and $fn->{RETURN_TYPE} eq "NTSTATUS") {
333                 $self->handle_ntstatus("r->out.result", "NULL", "mem_ctx");
334         } elsif (defined($fn->{RETURN_TYPE}) and $fn->{RETURN_TYPE} eq "WERROR") {
335                 $self->handle_werror("r->out.result", "NULL", "mem_ctx");
336         } elsif (defined($fn->{RETURN_TYPE})) {
337                 my $conv = $self->ConvertObjectToPythonData("r", $fn->{RETURN_TYPE}, "r->out.result");
338                 if ($result_size > 1) {
339                         $self->pidl("PyTuple_SetItem(result, $i, $conv);");
340                 } else {
341                         $self->pidl("result = $conv;");
342                 }
343         }
344
345         $self->pidl("talloc_free(mem_ctx);");
346         $self->pidl("return result;");
347         $self->deindent;
348         $self->pidl("}");
349         $self->pidl("");
350 }
351
352 sub handle_werror($$$$)
353 {
354         my ($self, $var, $retval, $mem_ctx) = @_;
355
356         $self->pidl("if (!W_ERROR_IS_OK($var)) {");
357         $self->indent;
358         $self->pidl("PyErr_SetString(PyExc_RuntimeError, win_errstr($var));");
359         $self->pidl("talloc_free($mem_ctx);") if ($mem_ctx);
360         $self->pidl("return $retval;");
361         $self->deindent;
362         $self->pidl("}");
363         $self->pidl("");
364 }
365
366 sub handle_ntstatus($$$$)
367 {
368         my ($self, $var, $retval, $mem_ctx) = @_;
369
370         $self->pidl("if (NT_STATUS_IS_ERR($var)) {");
371         $self->indent;
372         $self->pidl("PyErr_SetString(PyExc_RuntimeError, nt_errstr($var));");
373         $self->pidl("talloc_free($mem_ctx);") if ($mem_ctx);
374         $self->pidl("return $retval;");
375         $self->deindent;
376         $self->pidl("}");
377         $self->pidl("");
378 }
379
380 sub PythonType($$$)
381 {
382         my ($self, $d, $interface, $basename) = @_;
383
384         my $actual_ctype = $d;
385         if ($actual_ctype->{TYPE} eq "TYPEDEF") {
386                 $actual_ctype = $actual_ctype->{DATA};
387         }
388
389         if ($actual_ctype->{TYPE} eq "STRUCT") {
390                 my $py_fnname;
391                 if ($d->{TYPE} eq "STRUCT") {
392                         $py_fnname = $self->PythonStruct($d->{NAME}, mapTypeName($d), $d);
393                 } else {
394                         $py_fnname = $self->PythonStruct($d->{NAME}, mapTypeName($d), $d->{DATA});
395                 }
396
397                 my $fn_name = $d->{NAME};
398
399                 $fn_name =~ s/^$interface->{NAME}_//;
400                 $fn_name =~ s/^$basename\_//;
401
402                 $self->register_module_method($fn_name, $py_fnname, "METH_NOARGS", "NULL");
403         }
404
405         if ($d->{TYPE} eq "ENUM" or $d->{TYPE} eq "BITMAP") {
406                 $self->EnumAndBitmapConsts($d->{NAME}, $d);
407         }
408
409         if ($d->{TYPE} eq "TYPEDEF" and ($d->{DATA}->{TYPE} eq "ENUM" or $d->{DATA}->{TYPE} eq "BITMAP")) {
410                 $self->EnumAndBitmapConsts($d->{NAME}, $d->{DATA});
411         }
412
413         if ($actual_ctype->{TYPE} eq "UNION" and defined($actual_ctype->{ELEMENTS})) {
414                 $self->pidl("PyObject *py_import_$d->{NAME}(TALLOC_CTX *mem_ctx, int level, " .mapTypeName($d) . " *in)");
415                 $self->pidl("{");
416                 $self->indent;
417                 $self->FromUnionToPythonFunction("mem_ctx", $actual_ctype, "level", "in") if ($actual_ctype->{TYPE} eq "UNION");
418                 $self->deindent;
419                 $self->pidl("}");
420                 $self->pidl("");
421
422                 $self->pidl(mapTypeName($d) . " *py_export_$d->{NAME}(TALLOC_CTX *mem_ctx, int level, PyObject *in)");
423                 $self->pidl("{");
424                 $self->indent;
425                 $self->FromPythonToUnionFunction($actual_ctype, mapTypeName($d), "level", "mem_ctx", "in") if ($actual_ctype->{TYPE} eq "UNION");
426                 $self->deindent;
427                 $self->pidl("}");
428                 $self->pidl("");
429         }
430 }
431
432 sub Interface($$$)
433 {
434         my($self,$interface,$basename) = @_;
435
436         $self->pidl_hdr("#ifndef _HEADER_PYTHON_$interface->{NAME}\n");
437         $self->pidl_hdr("#define _HEADER_PYTHON_$interface->{NAME}\n\n");
438
439         $self->pidl_hdr("\n");
440
441         $self->Const($_) foreach (@{$interface->{CONSTS}});
442
443         foreach my $d (@{$interface->{TYPES}}) {
444                 next if has_property($d, "nopython");
445
446                 $self->PythonType($d, $interface, $basename);
447         }
448
449         if (defined $interface->{PROPERTIES}->{uuid}) {
450                 $self->pidl_hdr("PyAPI_DATA(PyTypeObject) $interface->{NAME}_InterfaceType;\n");
451                 $self->pidl("typedef struct {");
452                 $self->indent;
453                 $self->pidl("PyObject_HEAD");
454                 $self->pidl("struct dcerpc_pipe *pipe;");
455                 $self->deindent;
456                 $self->pidl("} $interface->{NAME}_InterfaceObject;");
457
458                 $self->pidl("");
459
460                 foreach my $d (@{$interface->{FUNCTIONS}}) {
461                         next if not defined($d->{OPNUM});
462                         next if has_property($d, "nopython");
463
464                         $self->PythonFunction($d, $interface->{NAME});
465                 }
466
467                 $self->pidl("static PyMethodDef interface_$interface->{NAME}\_methods[] = {");
468                 $self->indent;
469                 foreach my $d (@{$interface->{FUNCTIONS}}) {
470                         next if not defined($d->{OPNUM});
471                         next if has_property($d, "nopython");
472
473                         my $fn_name = $d->{NAME};
474
475                         $fn_name =~ s/^$interface->{NAME}_//;
476                         $fn_name =~ s/^$basename\_//;
477
478                         $self->pidl("{ \"$fn_name\", (PyCFunction)py_$d->{NAME}, METH_VARARGS|METH_KEYWORDS, NULL },");
479                 }
480                 $self->pidl("{ NULL, NULL, 0, NULL }");
481                 $self->deindent;
482                 $self->pidl("};");
483                 $self->pidl("");
484
485                 $self->pidl("static void interface_$interface->{NAME}_dealloc(PyObject* self)");
486                 $self->pidl("{");
487                 $self->indent;
488                 $self->pidl("$interface->{NAME}_InterfaceObject *interface = ($interface->{NAME}_InterfaceObject *)self;");
489                 $self->pidl("talloc_free(interface->pipe);");
490                 $self->pidl("PyObject_Del(self);");
491                 $self->deindent;
492                 $self->pidl("}");
493                 $self->pidl("");
494
495                 $self->pidl("static PyObject *interface_$interface->{NAME}_getattr(PyObject *obj, char *name)");
496                 $self->pidl("{");
497                 $self->indent;
498                 $self->pidl("return Py_FindMethod(interface_$interface->{NAME}\_methods, obj, name);");
499                 $self->deindent;
500                 $self->pidl("}");
501
502                 $self->pidl("");
503
504                 $self->pidl("PyTypeObject $interface->{NAME}_InterfaceType = {");
505                 $self->indent;
506                 $self->pidl("PyObject_HEAD_INIT(NULL) 0,");
507                 $self->pidl(".tp_name = \"$interface->{NAME}\",");
508                 $self->pidl(".tp_basicsize = sizeof($interface->{NAME}_InterfaceObject),");
509                 $self->pidl(".tp_dealloc = interface_$interface->{NAME}_dealloc,");
510                 $self->pidl(".tp_getattr = interface_$interface->{NAME}_getattr,");
511                 $self->deindent;
512                 $self->pidl("};");
513
514                 $self->pidl("");
515
516                 $self->register_module_method($interface->{NAME}, "interface_$interface->{NAME}", "METH_VARARGS|METH_KEYWORDS", "NULL");
517                 $self->pidl("static PyObject *interface_$interface->{NAME}(PyObject *self, PyObject *args, PyObject *kwargs)");
518                 $self->pidl("{");
519                 $self->indent;
520                 $self->pidl("$interface->{NAME}_InterfaceObject *ret;");
521                 $self->pidl("const char *binding_string;");
522                 $self->pidl("struct cli_credentials *credentials;");
523                 $self->pidl("struct loadparm_context *lp_ctx = NULL;");
524                 $self->pidl("PyObject *py_lp_ctx = NULL, *py_credentials = Py_None;");
525                 $self->pidl("TALLOC_CTX *mem_ctx = NULL;");
526                 $self->pidl("NTSTATUS status;");
527                 $self->pidl("");
528                 $self->pidl("const char *kwnames[] = {");
529                 $self->indent;
530                 $self->pidl("\"binding\", \"lp_ctx\", \"credentials\", NULL");
531                 $self->deindent;
532                 $self->pidl("};");
533                 $self->pidl("extern struct loadparm_context *lp_from_py_object(PyObject *py_obj);");
534                 $self->pidl("extern struct cli_credentials *cli_credentials_from_py_object(PyObject *py_obj);");
535                 $self->pidl("");
536                 $self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"sO|O:$interface->{NAME}\", discard_const_p(char *, kwnames), &binding_string, &py_lp_ctx, &py_credentials)) {");
537                 $self->indent;
538                 $self->pidl("return NULL;");
539                 $self->deindent;
540                 $self->pidl("}");
541                 $self->pidl("");
542                 $self->pidl("if (py_lp_ctx != NULL) {");
543                 $self->indent;
544                 $self->pidl("lp_ctx = lp_from_py_object(py_lp_ctx);");
545                 $self->pidl("if (lp_ctx == NULL) {");
546                 $self->indent;
547                 $self->pidl("PyErr_SetString(PyExc_TypeError, \"Expected loadparm context\");");
548                 $self->pidl("return NULL;");
549                 $self->deindent;
550                 $self->pidl("}");
551                 $self->deindent;
552                 $self->pidl("}");
553                 $self->pidl("");
554
555                 $self->pidl("credentials = cli_credentials_from_py_object(py_credentials);");
556                 $self->pidl("if (credentials == NULL) {");
557                 $self->indent;
558                 $self->pidl("PyErr_SetString(PyExc_TypeError, \"Expected credentials\");");
559                 $self->pidl("return NULL;");
560                 $self->deindent;
561                 $self->pidl("}");
562
563                 $self->pidl("ret = PyObject_New($interface->{NAME}_InterfaceObject, &$interface->{NAME}_InterfaceType);");
564                 $self->pidl("");
565
566                 $self->pidl("status = dcerpc_pipe_connect(NULL, &ret->pipe, binding_string, ");
567                 $self->pidl("             &ndr_table_$interface->{NAME}, credentials, NULL, lp_ctx);");
568                 $self->handle_ntstatus("status", "NULL", "mem_ctx");
569
570                 $self->pidl("ret->pipe->conn->flags |= DCERPC_NDR_REF_ALLOC;");
571
572                 $self->pidl("return (PyObject *)ret;");
573                 $self->deindent;
574                 $self->pidl("}");
575                 
576                 $self->pidl("");
577         }
578
579         $self->pidl_hdr("\n");
580         $self->pidl_hdr("#endif /* _HEADER_NDR_$interface->{NAME} */\n");
581 }
582
583 sub register_module_method($$$$$)
584 {
585         my ($self, $fn_name, $pyfn_name, $flags, $doc) = @_;
586
587         push (@{$self->{module_methods}}, [$fn_name, $pyfn_name, $flags, $doc])
588 }
589
590 sub assign($$$)
591 {
592         my ($self, $dest, $src) = @_;
593         if ($dest =~ /^\&/) {
594                 $self->pidl("memcpy($dest, $src, sizeof(*$dest));");
595         } else {
596                 $self->pidl("$dest = $src;");
597         }
598 }
599
600 sub ConvertObjectFromPythonData($$$$$$)
601 {
602         my ($self, $mem_ctx, $cvar, $ctype, $target, $fail) = @_;
603
604         die("undef type for $cvar") unless(defined($ctype));
605
606         $ctype = resolveType($ctype);
607
608         if (ref($ctype) ne "HASH") {
609                 $self->pidl("$target = FIXME($cvar);");
610                 return;
611         }
612
613         my $actual_ctype = $ctype;
614         if ($ctype->{TYPE} eq "TYPEDEF") {
615                 $actual_ctype = $ctype->{DATA};
616         }
617
618         if ($actual_ctype->{TYPE} eq "ENUM" or $actual_ctype->{TYPE} eq "BITMAP" or 
619                 $actual_ctype->{TYPE} eq "SCALAR" and (
620                 expandAlias($actual_ctype->{NAME}) =~ /^(u?int[0-9]+|hyper|NTTIME|time_t|NTTIME_hyper|NTTIME_1sec|dlong|udlong|udlongr)$/)) {
621                 $self->pidl("PY_CHECK_TYPE(PyInt, $cvar, $fail);");
622                 $self->pidl("$target = PyInt_AsLong($cvar);");
623                 return;
624         }
625
626         if ($actual_ctype->{TYPE} eq "STRUCT") {
627                 $self->pidl("PY_CHECK_TYPE($ctype->{NAME}, $cvar, $fail);");
628                 $self->assign($target, "py_talloc_get_ptr($cvar)");
629                 return;
630         }
631
632         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "DATA_BLOB") {
633                 $self->pidl("$target = data_blob_talloc($mem_ctx, PyString_AsString($cvar), PyString_Size($cvar));");
634                 return;
635         }
636
637         if ($actual_ctype->{TYPE} eq "SCALAR" and 
638                 ($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")) {
639                 $self->pidl("$target = talloc_strdup($mem_ctx, PyString_AsString($cvar));");
640                 return;
641         }
642
643         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "ipv4address") {
644                 $self->pidl("$target = FIXME($cvar);");
645                 return;
646                 }
647
648
649         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "NTSTATUS") {
650                 $self->pidl("$target = PyInt_AsLong($cvar);");
651                 return;
652         }
653
654         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "WERROR") {
655                 $self->pidl("$target = PyInt_AsLong($cvar);");
656                 return;
657         }
658
659         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "string_array") {
660                 $self->pidl("$target = FIXME($cvar);");
661                 return;
662         }
663
664         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "pointer") {
665                 $self->assign($target, "PyCObject_AsVoidPtr($cvar)");
666                 return;
667         }
668
669         die("unknown type ".mapTypeName($ctype) . ": $cvar");
670
671 }
672
673 sub ConvertObjectFromPythonLevel($$$$$$$$)
674 {
675         my ($self, $env, $mem_ctx, $py_var, $e, $l, $var_name, $fail) = @_;
676
677         if ($l->{TYPE} eq "POINTER") {
678                 if ($l->{POINTER_TYPE} ne "ref") {
679                         $self->pidl("if ($py_var == Py_None) {");
680                         $self->indent;
681                         $self->pidl("$var_name = NULL;");
682                         $self->deindent;
683                         $self->pidl("} else {");
684                         $self->indent;
685                 }
686                 $self->pidl("$var_name = talloc_ptrtype($mem_ctx, $var_name);");
687                 $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $py_var, $e, GetNextLevel($e, $l), get_value_of($var_name), $fail);
688                 if ($l->{POINTER_TYPE} ne "ref") {
689                         $self->deindent;
690                         $self->pidl("}");
691                 }
692         } elsif ($l->{TYPE} eq "ARRAY") {
693                 if (is_charset_array($e, $l)) {
694                         $self->pidl("PY_CHECK_TYPE(PyUnicode, $py_var, $fail);");
695                         # FIXME: Use Unix charset setting rather than utf-8
696                         $self->pidl(get_pointer_to($var_name) . " = PyString_AsString(PyUnicode_AsEncodedString($py_var, \"utf-8\", \"ignore\"));");
697                 } else {
698                         my $pl = GetPrevLevel($e, $l);
699                         if ($pl && $pl->{TYPE} eq "POINTER") {
700                                 $var_name = get_pointer_to($var_name);
701                         }
702
703                         my $counter = "$e->{NAME}_cntr_$l->{LEVEL_INDEX}";
704                         $self->pidl("PY_CHECK_TYPE(PyList, $py_var, $fail);");
705                         $self->pidl("{");
706                         $self->indent;
707                         $self->pidl("int $counter;");
708                         if (!$l->{IS_FIXED}) {
709                                 $self->pidl("$var_name = talloc_array_ptrtype($mem_ctx, $var_name, PyList_Size($py_var));");
710                         }
711                         $self->pidl("for ($counter = 0; $counter < PyList_Size($py_var); $counter++) {");
712                         $self->indent;
713                         $self->ConvertObjectFromPythonLevel($env, $var_name, "PyList_GetItem($py_var, $counter)", $e, GetNextLevel($e, $l), $var_name."[$counter]", $fail);
714                         $self->deindent;
715                         $self->pidl("}");
716                         $self->deindent;
717                         $self->pidl("}");
718                 }
719         } elsif ($l->{TYPE} eq "DATA") {
720
721                 if (not Parse::Pidl::Typelist::is_scalar($l->{DATA_TYPE})) {
722                         $var_name = get_pointer_to($var_name);
723                 }
724                 $self->ConvertObjectFromPythonData($mem_ctx, $py_var, $l->{DATA_TYPE}, $var_name, $fail);
725         } elsif ($l->{TYPE} eq "SWITCH") {
726                 $var_name = get_pointer_to($var_name);
727                 my $switch = ParseExpr($l->{SWITCH_IS}, $env, $e);
728                 $self->pidl("$var_name = py_export_" . GetNextLevel($e, $l)->{DATA_TYPE} . "($mem_ctx, $switch, $py_var);");
729         } elsif ($l->{TYPE} eq "SUBCONTEXT") {
730                 $self->pidl("#error Subcontext not yet supported");
731         } else {
732                 die("unknown level type $l->{TYPE}");
733         }
734 }
735
736 sub ConvertObjectFromPython($$$$$$$)
737 {
738         my ($self, $env, $mem_ctx, $ctype, $cvar, $target, $fail) = @_;
739
740         $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $cvar, $ctype, $ctype->{LEVELS}[0], $target, $fail);
741 }
742
743 sub ConvertScalarToPython($$$)
744 {
745         my ($self, $ctypename, $cvar) = @_;
746
747         die("expected string for $cvar, not $ctypename") if (ref($ctypename) eq "HASH");
748
749         $ctypename = expandAlias($ctypename);
750
751         if ($ctypename =~ /^(int|long|char|u?int[0-9]+|hyper|dlong|udlong|udlongr|time_t|NTTIME_hyper|NTTIME|NTTIME_1sec)$/) {
752                 return "PyInt_FromLong($cvar)";
753         }
754
755         if ($ctypename eq "DATA_BLOB") {
756                 return "PyString_FromStringAndSize($cvar->data, $cvar->length)";
757         }
758
759         if ($ctypename eq "NTSTATUS") {
760                 return "PyInt_FromLong(NT_STATUS_V($cvar))";
761         }
762
763         if ($ctypename eq "WERROR") {
764                 return "PyInt_FromLong(W_ERROR_V($cvar))";
765         }
766
767         if (($ctypename eq "string" or $ctypename eq "nbt_string" or $ctypename eq "nbt_name" or $ctypename eq "wrepl_nbt_name")) {
768                 return "PyString_FromString($cvar)";
769         }
770
771         # Not yet supported
772         if ($ctypename eq "string_array") { return "PyCObject_FromVoidPtr($cvar)"; }
773         if ($ctypename eq "ipv4address") { return "PyCObject_FromVoidPtr($cvar)"; }
774         if ($ctypename eq "pointer") {
775                 return "PyCObject_FromVoidPtr($cvar, talloc_free)";
776         }
777
778         die("Unknown scalar type $ctypename");
779 }
780
781 sub ConvertObjectToPythonData($$$$$)
782 {
783         my ($self, $mem_ctx, $ctype, $cvar) = @_;
784
785         die("undef type for $cvar") unless(defined($ctype));
786
787         $ctype = resolveType($ctype);
788
789         my $actual_ctype = $ctype;
790         if ($ctype->{TYPE} eq "TYPEDEF") {
791                 $actual_ctype = $ctype->{DATA};
792         } 
793         
794         if ($actual_ctype->{TYPE} eq "ENUM") {
795                 return $self->ConvertScalarToPython(Parse::Pidl::Typelist::enum_type_fn($actual_ctype), $cvar);
796         } elsif ($actual_ctype->{TYPE} eq "BITMAP") {
797                 return $self->ConvertScalarToPython(Parse::Pidl::Typelist::bitmap_type_fn($actual_ctype), $cvar);
798         } elsif ($actual_ctype->{TYPE} eq "SCALAR") {
799                 return $self->ConvertScalarToPython($actual_ctype->{NAME}, $cvar);
800         } elsif ($actual_ctype->{TYPE} eq "STRUCT") {
801                 return "py_talloc_import_ex(&$ctype->{NAME}_Type, $mem_ctx, $cvar)";
802         }
803
804         die("unknown type ".mapTypeName($ctype) . ": $cvar");
805 }
806
807 sub ConvertObjectToPythonLevel($$$$$)
808 {
809         my ($self, $mem_ctx, $env, $e, $l, $var_name, $py_var) = @_;
810
811         if ($l->{TYPE} eq "POINTER") {
812                 if ($l->{POINTER_TYPE} ne "ref") {
813                         $self->pidl("if ($var_name == NULL) {");
814                         $self->indent;
815                         $self->pidl("$py_var = Py_None;");
816                         $self->deindent;
817                         $self->pidl("} else {");
818                         $self->indent;
819                 }
820                 $self->ConvertObjectToPythonLevel($var_name, $env, $e, GetNextLevel($e, $l), get_value_of($var_name), $py_var);
821                 if ($l->{POINTER_TYPE} ne "ref") {
822                         $self->deindent;
823                         $self->pidl("}");
824                 }
825         } elsif ($l->{TYPE} eq "ARRAY") {
826                 if (is_charset_array($e, $l)) {
827                         $var_name = get_pointer_to($var_name);
828                         # FIXME: Use Unix charset setting rather than utf-8
829                         $self->pidl("$py_var = PyUnicode_Decode($var_name, strlen($var_name), \"utf-8\", \"ignore\");");
830                 } else {
831                         my $pl = GetPrevLevel($e, $l);
832                         if ($pl && $pl->{TYPE} eq "POINTER") {
833                                 $var_name = get_pointer_to($var_name);
834                         }
835
836                         die("No SIZE_IS for array $var_name") unless (defined($l->{SIZE_IS}));
837                         my $length = $l->{SIZE_IS};
838                         if (defined($l->{LENGTH_IS})) {
839                                 $length = $l->{LENGTH_IS};
840                         }
841
842                         $length = ParseExpr($length, $env, $e);
843                         $self->pidl("$py_var = PyList_New($length);");
844                         $self->pidl("{");
845                         $self->indent;
846                         my $counter = "$e->{NAME}_cntr_$l->{LEVEL_INDEX}";
847                         $self->pidl("int $counter;");
848                         $self->pidl("for ($counter = 0; $counter < $length; $counter++) {");
849                         $self->indent;
850                         my $member_var = "py_$e->{NAME}_$l->{LEVEL_INDEX}";
851                         $self->pidl("PyObject *$member_var;");
852                         $self->ConvertObjectToPythonLevel($var_name, $env, $e, GetNextLevel($e, $l), $var_name."[$counter]", $member_var);
853                         $self->pidl("PyList_SetItem($py_var, $counter, $member_var);");
854                         $self->deindent;
855                         $self->pidl("}");
856                         $self->deindent;
857                         $self->pidl("}");
858                 }
859         } elsif ($l->{TYPE} eq "SWITCH") {
860                 $var_name = get_pointer_to($var_name);
861                 my $switch = ParseExpr($l->{SWITCH_IS}, $env, $e);
862                 $self->pidl("$py_var = py_import_" . GetNextLevel($e, $l)->{DATA_TYPE} . "($mem_ctx, $switch, $var_name);");
863         } elsif ($l->{TYPE} eq "DATA") {
864                 if (not Parse::Pidl::Typelist::is_scalar($l->{DATA_TYPE})) {
865                         $var_name = get_pointer_to($var_name);
866                 }
867                 my $conv = $self->ConvertObjectToPythonData($mem_ctx, $l->{DATA_TYPE}, $var_name);
868                 $self->pidl("$py_var = $conv;");
869         } elsif ($l->{TYPE} eq "SUBCONTEXT") {
870                 $self->pidl("FIXME");
871         } else {
872                 die("Unknown level type $l->{TYPE} $var_name");
873         }
874 }
875
876 sub ConvertObjectToPython($$$$$$)
877 {
878         my ($self, $mem_ctx, $env, $ctype, $cvar, $py_var) = @_;
879
880         $self->ConvertObjectToPythonLevel($mem_ctx, $env, $ctype, $ctype->{LEVELS}[0], $cvar, $py_var);
881 }
882
883 sub Parse($$$$$)
884 {
885     my($self,$basename,$ndr,$ndr_hdr,$hdr) = @_;
886     
887     my $py_hdr = $hdr;
888     $py_hdr =~ s/ndr_([^\/]+)$/py_$1/g;
889
890     $self->pidl_hdr("/* header auto-generated by pidl */\n\n");
891         
892     $self->pidl("
893 /* Python wrapper functions auto-generated by pidl */
894 #include \"includes.h\"
895 #include <Python.h>
896 #include \"librpc/rpc/dcerpc.h\"
897 #include \"scripting/python/pytalloc.h\"
898 #include \"$hdr\"
899 #include \"$ndr_hdr\"
900 #include \"$py_hdr\"
901
902 #define PY_CHECK_TYPE(type, var, fail) \\
903         if (!type ## _Check(var)) {\\
904                 PyErr_Format(PyExc_TypeError, \"Expected type %s\", type ## _Type.tp_name); \\
905                 fail; \\
906         }
907 ");
908
909         foreach my $x (@$ndr) {
910             ($x->{TYPE} eq "INTERFACE") && $self->Interface($x, $basename);
911                 ($x->{TYPE} eq "IMPORT") && $self->Import(@{$x->{PATHS}});
912         }
913         
914         $self->pidl("static PyMethodDef $basename\_methods[] = {");
915         $self->indent;
916         foreach (@{$self->{module_methods}}) {
917                 my ($fn_name, $pyfn_name, $flags, $doc) = @$_;
918                 $self->pidl("{ \"$fn_name\", (PyCFunction)$pyfn_name, $flags, $doc },");
919         }
920         
921         $self->pidl("{ NULL, NULL, 0, NULL }");
922         $self->deindent;
923         $self->pidl("};");
924
925         $self->pidl("");
926
927         $self->pidl("void init$basename(void)");
928         $self->pidl("{");
929         $self->indent;
930         $self->pidl("PyObject *m;");
931         $self->pidl("m = Py_InitModule(\"$basename\", $basename\_methods);");
932         foreach my $name (keys %{$self->{constants}}) {
933                 my $py_obj;
934                 my ($ctype, $cvar) = @{$self->{constants}->{$name}};
935                 if ($cvar =~ /^[0-9]+$/ or $cvar =~ /^0x[0-9a-fA-F]+$/) {
936                         $py_obj = "PyInt_FromLong($cvar)";
937                 } elsif ($cvar =~ /^".*"$/) {
938                         $py_obj = "PyString_FromString($cvar)";
939                 } else {
940                         $py_obj = $self->ConvertObjectToPythonData("NULL", $ctype, $cvar);
941                 }
942
943                 $self->pidl("PyModule_AddObject(m, \"$name\", $py_obj);");
944         }
945         $self->deindent;
946         $self->pidl("}");
947     return ($self->{res_hdr}, $self->{res});
948 }
949
950 1;