type: Add missing space for printing complex types.
[cparser] / wrappergen / write_jna.c
1 /*
2  * This file is part of cparser.
3  * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
18  * 02111-1307, USA.
19  */
20 #include <config.h>
21
22 #include <errno.h>
23 #include <string.h>
24
25 #include "adt/strutil.h"
26 #include "write_jna.h"
27 #include "symbol_t.h"
28 #include "ast_t.h"
29 #include "type_t.h"
30 #include "entity_t.h"
31 #include "type.h"
32 #include "printer.h"
33 #include "adt/error.h"
34 #include "adt/xmalloc.h"
35 #include "adt/pset_new.h"
36 #include "separator_t.h"
37
38 typedef struct output_limit {
39         const char          *filename;
40         struct output_limit *next;
41 } output_limit;
42
43 static const scope_t *global_scope;
44 static FILE          *out;
45 static pset_new_t     avoid_symbols;
46 static output_limit  *output_limits;
47 static const char    *libname;
48
49 static bool is_system_header(const char *fname)
50 {
51         if (strstart(fname, "/usr/include"))
52                 return true;
53         if (fname == builtin_position.input_name)
54                 return true;
55         return false;
56 }
57
58 static const char *fix_builtin_names(const char *name)
59 {
60         if (streq(name, "class")) {
61                 return "_class";
62         } else if (streq(name, "this")) {
63                 return "_this";
64         } else if (streq(name, "public")) {
65                 return "_public";
66         } else if (streq(name, "protected")) {
67                 return "_protected";
68         } else if (streq(name, "private")) {
69                 return "_private";
70         } else if (streq(name, "final")) {
71                 return "_final";
72         }
73         /* TODO put all reserved names here */
74         return name;
75 }
76
77 static const char *get_atomic_type_string(const atomic_type_kind_t type)
78 {
79         switch(type) {
80         case ATOMIC_TYPE_VOID:        return "void";
81         case ATOMIC_TYPE_CHAR:        return "byte";
82         case ATOMIC_TYPE_SCHAR:       return "byte";
83         case ATOMIC_TYPE_UCHAR:       return "byte";
84         case ATOMIC_TYPE_SHORT:       return "short";
85         case ATOMIC_TYPE_USHORT:      return "short";
86         case ATOMIC_TYPE_INT:         return "int";
87         case ATOMIC_TYPE_UINT:        return "int";
88         case ATOMIC_TYPE_LONG:        return "com.sun.jna.NativeLong";
89         case ATOMIC_TYPE_ULONG:       return "com.sun.jna.NativeLong";
90         case ATOMIC_TYPE_LONGLONG:    return "long";
91         case ATOMIC_TYPE_ULONGLONG:   return "long";
92         case ATOMIC_TYPE_FLOAT:       return "float";
93         case ATOMIC_TYPE_DOUBLE:      return "double";
94         case ATOMIC_TYPE_BOOL:        return "boolean";
95         default:                      panic("unsupported atomic type");
96         }
97 }
98
99 static void write_atomic_type(const atomic_type_t *type)
100 {
101         fputs(get_atomic_type_string(type->akind), out);
102 }
103
104 static void write_pointer_type(const pointer_type_t *type)
105 {
106         type_t *points_to = skip_typeref(type->points_to);
107         if (is_type_atomic(points_to, ATOMIC_TYPE_CHAR)) {
108                 fputs("String", out);
109                 return;
110         }
111         if (is_type_pointer(points_to)) {
112                 /* hack... */
113                 fputs("java.nio.Buffer", out);
114                 return;
115         }
116         fputs("Pointer", out);
117 }
118
119 static entity_t *find_typedef(const type_t *type)
120 {
121         /* first: search for a matching typedef in the global type... */
122         entity_t *entity = global_scope->entities;
123         for ( ; entity != NULL; entity = entity->base.next) {
124                 if (entity->kind != ENTITY_TYPEDEF)
125                         continue;
126                 if (entity->typedefe.type == type)
127                         break;
128         }
129
130         return entity;
131 }
132
133 static entity_t *find_enum_typedef(const enum_t *enume)
134 {
135         /* first: search for a matching typedef in the global type... */
136         entity_t *entity = global_scope->entities;
137         for ( ; entity != NULL; entity = entity->base.next) {
138                 if (entity->kind != ENTITY_TYPEDEF)
139                         continue;
140                 type_t *type = entity->typedefe.type;
141                 if (type->kind != TYPE_ENUM)
142                         continue;
143
144                 enum_t *e_entity = type->enumt.enume;
145                 if (e_entity == enume)
146                         break;
147         }
148
149         return entity;
150 }
151
152 static void write_compound_type(const compound_type_t *type)
153 {
154         entity_t *entity = find_typedef((const type_t*) type);
155         if(entity != NULL) {
156                 fputs(entity->base.symbol->string, out);
157                 return;
158         }
159
160         /* does the struct have a name? */
161         symbol_t *symbol = type->compound->base.symbol;
162         if(symbol != NULL) {
163                 /* TODO: make sure we create a struct for it... */
164                 fputs(symbol->string, out);
165                 return;
166         }
167         /* TODO: create a struct and use its name here... */
168         fputs("/* TODO anonymous struct */byte", out);
169 }
170
171 static void write_enum_name(const enum_type_t *type)
172 {
173         entity_t *entity = find_typedef((const type_t*) type);
174         if (entity != NULL) {
175                 fputs(entity->base.symbol->string, out);
176                 return;
177         }
178
179         /* does the enum have a name? */
180         symbol_t *symbol = type->enume->base.symbol;
181         if (symbol != NULL) {
182                 /* TODO: make sure we create an enum for it... */
183                 fputs(symbol->string, out);
184                 return;
185         }
186
187         /* now we have a problem as we don't know how we'll call the anonymous
188          * enum */
189         panic("can't reference entries from anonymous enums yet");
190 }
191
192 static void write_enum_type(const enum_type_t *type)
193 {
194         entity_t *entity = find_typedef((const type_t*) type);
195         if (entity != NULL) {
196                 fprintf(out, "/* %s */int", entity->base.symbol->string);
197                 return;
198         }
199
200         /* does the enum have a name? */
201         symbol_t *symbol = type->enume->base.symbol;
202         if (symbol != NULL) {
203                 /* TODO: make sure we create an enum for it... */
204                 fprintf(out, "/* %s */int", symbol->string);
205                 return;
206         }
207         fprintf(out, "/* anonymous enum */int");
208 }
209
210 static void write_type(type_t *type)
211 {
212         type = skip_typeref(type);
213         switch(type->kind) {
214         case TYPE_ATOMIC:
215                 write_atomic_type(&type->atomic);
216                 return;
217         case TYPE_POINTER:
218                 write_pointer_type(&type->pointer);
219                 return;
220         case TYPE_COMPOUND_UNION:
221         case TYPE_COMPOUND_STRUCT:
222                 write_compound_type(&type->compound);
223                 return;
224         case TYPE_ENUM:
225                 write_enum_type(&type->enumt);
226                 return;
227         case TYPE_ERROR:
228         case TYPE_TYPEOF:
229         case TYPE_TYPEDEF:
230                 panic("invalid type");
231         case TYPE_ARRAY:
232         case TYPE_REFERENCE:
233         case TYPE_FUNCTION:
234         case TYPE_COMPLEX:
235         case TYPE_IMAGINARY:
236                 fprintf(out, "/* TODO type */Pointer");
237                 break;
238         }
239 }
240
241 #if 0
242 static void write_compound_entry(const entity_t *entity)
243 {
244         fprintf(out, "\t%s : ", entity->base.symbol->string);
245         write_type(entity->declaration.type);
246         fprintf(out, "\n");
247 }
248
249 static void write_compound(const symbol_t *symbol, const compound_type_t *type)
250 {
251         fprintf(out, "%s %s:\n",
252                 type->base.kind == TYPE_COMPOUND_STRUCT ? "struct" : "union",
253                         symbol->string);
254
255         const entity_t *entity = type->compound->members.entities;
256         for ( ; entity != NULL; entity = entity->base.next) {
257                 write_compound_entry(entity);
258         }
259
260         fprintf(out, "\n");
261 }
262 #endif
263
264 static void write_expression(const expression_t *expression);
265
266 static void write_unary_expression(const unary_expression_t *expression)
267 {
268         switch(expression->base.kind) {
269         case EXPR_UNARY_NEGATE:
270                 fputc('-', out);
271                 break;
272         case EXPR_UNARY_NOT:
273                 fputc('!', out);
274                 break;
275         case EXPR_UNARY_CAST:
276                 write_expression(expression->value);
277                 return;
278         default:
279                 panic("unimplemented unary expression");
280         }
281         write_expression(expression->value);
282 }
283
284 static void write_binary_expression(const binary_expression_t *expression)
285 {
286         fputs("(", out);
287         write_expression(expression->left);
288         fputc(' ', out);
289         switch(expression->base.kind) {
290         case EXPR_BINARY_BITWISE_OR:  fputs("|", out); break;
291         case EXPR_BINARY_BITWISE_AND: fputs("&", out); break;
292         case EXPR_BINARY_BITWISE_XOR: fputs("^", out); break;
293         case EXPR_BINARY_SHIFTLEFT:   fputs("<<", out); break;
294         case EXPR_BINARY_SHIFTRIGHT:  fputs(">>", out); break;
295         case EXPR_BINARY_ADD:         fputs("+", out); break;
296         case EXPR_BINARY_SUB:         fputs("-", out); break;
297         case EXPR_BINARY_MUL:         fputs("*", out); break;
298         case EXPR_BINARY_DIV:         fputs("/", out); break;
299         default:
300                 panic("unimplemented binexpr");
301         }
302         fputc(' ', out);
303         write_expression(expression->right);
304         fputs(")", out);
305 }
306
307 static void write_integer(const literal_expression_t *literal)
308 {
309         for (const char *c = literal->value.begin; c != literal->suffix; ++c) {
310                 fputc(*c, out);
311         }
312 }
313
314 static void write_expression(const expression_t *expression)
315 {
316         /* TODO */
317         switch(expression->kind) {
318         case EXPR_LITERAL_INTEGER:
319                 write_integer(&expression->literal);
320                 break;
321
322         case EXPR_ENUM_CONSTANT: {
323                 /* UHOH... hacking */
324                 entity_t *entity = expression->reference.entity;
325                 write_enum_name(& entity->enum_value.enum_type->enumt);
326                 fprintf(out, ".%s.val", entity->base.symbol->string);
327                 break;
328         }
329         case EXPR_UNARY_CASES:
330                 write_unary_expression(&expression->unary);
331                 break;
332         case EXPR_BINARY_CASES:
333                 write_binary_expression(&expression->binary);
334                 break;
335         default:
336                 panic("not implemented expression");
337         }
338 }
339
340 static void write_enum(const symbol_t *symbol, const enum_t *entity)
341 {
342         char buf[128];
343         const char *name;
344
345         if (symbol == NULL) {
346                 static int lastenum = 0;
347                 snprintf(buf, sizeof(buf), "AnonEnum%d", lastenum++);
348                 name = buf;
349         } else {
350                 name = symbol->string;
351         }
352
353         fprintf(out, "\tpublic static enum %s {\n", name);
354
355         entity_t *entry = entity->base.next;
356         for ( ; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
357                         entry = entry->base.next) {
358                 fprintf(out, "\t\t%s", entry->base.symbol->string);
359                 fprintf(out, "(");
360                 if(entry->enum_value.value != NULL) {
361                         write_expression(entry->enum_value.value);
362                 }
363                 fprintf(out, ")");
364                 if (entry->base.next != NULL
365                                 && entry->base.next->kind == ENTITY_ENUM_VALUE) {
366                         fputs(",\n", out);
367                 } else {
368                         fputs(";\n", out);
369                 }
370         }
371         fprintf(out, "\t\tpublic final int val;\n");
372         fprintf(out, "\n");
373         fprintf(out, "\t\tprivate static class C {\n");
374         fprintf(out, "\t\t\tstatic int next_val;\n");
375         fprintf(out, "\t\t}\n");
376         fprintf(out, "\n");
377         fprintf(out, "\t\t%s(int val) {\n", name);
378         fprintf(out, "\t\t\tthis.val = val;\n");
379         fprintf(out, "\t\t\tC.next_val = val + 1;\n");
380         fprintf(out, "\t\t}\n");
381         fprintf(out, "\n");
382         fprintf(out, "\t\t%s() {\n", name);
383         fprintf(out, "\t\t\tthis.val = C.next_val++;\n");
384         fprintf(out, "\t\t}\n");
385         fprintf(out, "\n");
386         fprintf(out, "\t\tpublic static %s getEnum(int val) {\n", name);
387         fprintf(out, "\t\t\tfor (%s entry : values()) {\n", name);
388         fprintf(out, "\t\t\t\tif (val == entry.val)\n");
389         fprintf(out, "\t\t\t\t\treturn entry;\n");
390         fprintf(out, "\t\t\t}\n");
391         fprintf(out, "\t\t\treturn null;\n");
392         fprintf(out, "\t\t}\n");
393         fprintf(out, "\t}\n");
394         fprintf(out, "\n");
395 }
396
397 #if 0
398 static void write_variable(const entity_t *entity)
399 {
400         fprintf(out, "var %s : ", entity->base.symbol->string);
401         write_type(entity->declaration.type);
402         fprintf(out, "\n");
403 }
404 #endif
405
406 static void write_function(const entity_t *entity)
407 {
408         if (entity->function.body != NULL) {
409                 fprintf(stderr, "Warning: can't convert function bodies (at %s)\n",
410                         entity->base.symbol->string);
411                 return;
412         }
413
414
415         const function_type_t *function_type
416                 = (const function_type_t*) entity->declaration.type;
417
418         fputc('\n', out);
419         fprintf(out, "\tpublic static native ");
420         type_t *return_type = skip_typeref(function_type->return_type);
421         write_type(return_type);
422         fprintf(out, " %s(", entity->base.symbol->string);
423
424         entity_t   *parameter = entity->function.parameters.entities;
425         separator_t sep       = { "", ", " };
426         int         n         = 0;
427         for ( ; parameter != NULL; parameter = parameter->base.next) {
428                 assert(parameter->kind == ENTITY_PARAMETER);
429                 fputs(sep_next(&sep), out);
430                 write_type(parameter->declaration.type);
431                 if(parameter->base.symbol != NULL) {
432                         fprintf(out, " %s", fix_builtin_names(parameter->base.symbol->string));
433                 } else {
434                         fprintf(out, " _%d", n++);
435                 }
436         }
437         if(function_type->variadic) {
438                 fputs(sep_next(&sep), out);
439                 fputs("Object ... args", out);
440         }
441         fprintf(out, ");\n");
442 }
443
444 void jna_limit_output(const char *filename)
445 {
446         output_limit *limit = xmalloc(sizeof(limit[0]));
447         limit->filename = filename;
448
449         limit->next   = output_limits;
450         output_limits = limit;
451 }
452
453 void jna_set_libname(const char *new_libname)
454 {
455         libname = new_libname;
456 }
457
458 void write_jna_decls(FILE *output, const translation_unit_t *unit)
459 {
460         out          = output;
461         global_scope = &unit->scope;
462
463         pset_new_init(&avoid_symbols);
464
465         print_to_file(out);
466         fprintf(out, "/* WARNING: Automatically generated file */\n");
467         fputs("import com.sun.jna.Native;\n", out);
468         fputs("import com.sun.jna.Pointer;\n", out);
469         fputs("\n", out);
470
471         const char *register_libname = libname;
472         if (register_libname == NULL)
473                 register_libname = "library";
474
475         /* TODO: where to get the name from? */
476         fputs("public class binding {\n", out);
477         fputs("\tstatic {\n", out);
478         fprintf(out, "\t\tNative.register(\"%s\");\n", register_libname);
479         fputs("\t}\n", out);
480         fputs("\n", out);
481
482         /* read the avoid list */
483         FILE *avoid = fopen("avoid.config", "r");
484         if (avoid != NULL) {
485                 while (!feof(avoid)) {
486                         char buf[1024];
487                         char *res = fgets(buf, sizeof(buf), avoid);
488                         if (res == NULL)
489                                 break;
490                         if (buf[0] == 0)
491                                 continue;
492
493                         size_t len = strlen(buf);
494                         if (buf[len-1] == '\n')
495                                 buf[len-1] = 0;
496
497                         char *str = malloc(len+1);
498                         memcpy(str, buf, len+1);
499                         symbol_t *symbol = symbol_table_insert(str);
500                         pset_new_insert(&avoid_symbols, symbol);
501                 }
502                 fclose(avoid);
503         }
504
505         /* write structs,unions + enums */
506         entity_t *entity = unit->scope.entities;
507         for ( ; entity != NULL; entity = entity->base.next) {
508                 if (entity->kind == ENTITY_ENUM) {
509                         if (find_enum_typedef(&entity->enume) != NULL)
510                                 continue;
511                         write_enum(entity->base.symbol, &entity->enume);
512                 } else if (entity->kind == ENTITY_TYPEDEF) {
513                         type_t *type = entity->typedefe.type;
514                         if (type->kind == TYPE_ENUM) {
515                                 write_enum(entity->base.symbol, type->enumt.enume);
516                         }
517                 }
518
519 #if 0
520                 if (is_type_compound(type)) {
521                         write_compound(entity->base.symbol, &type->compound);
522                 }
523 #endif
524         }
525
526         /* write functions */
527         entity = unit->scope.entities;
528         for ( ; entity != NULL; entity = entity->base.next) {
529                 if (entity->kind != ENTITY_FUNCTION)
530                         continue;
531                 const char *input_name = entity->base.pos.input_name;
532                 if (is_system_header(input_name))
533                         continue;
534                 if (entity->function.elf_visibility != ELF_VISIBILITY_DEFAULT)
535                         continue;
536                 if (output_limits != NULL) {
537                         bool in_limits = false;
538                         for (output_limit *limit = output_limits; limit != NULL;
539                              limit = limit->next) {
540                             if (streq(limit->filename, input_name)) {
541                                         in_limits = true;
542                                         break;
543                                 }
544                         }
545                         if (!in_limits)
546                                 continue;
547                 }
548
549                 if (pset_new_contains(&avoid_symbols, entity->base.symbol))
550                         continue;
551                 write_function(entity);
552         }
553
554         fputs("}\n", out);
555
556         pset_new_destroy(&avoid_symbols);
557 }