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