chiark / gitweb /
better changelog comment
[chiark-tcl.git] / base / tcmdifgen
1 #!/usr/bin/perl
2
3 # code generator to help with writing Tcl extensions
4 # Copyright 2006 Ian Jackson
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License as
8 # published by the Free Software Foundation; either version 2 of the
9 # License, or (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 # General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this library; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
19 # 02110-1301, USA.
20
21
22 # Input format is line-based, ws-significant, offside rule (some kind
23 #  of, anyway).
24 #
25 #  Type TYPE:       C-TYPE-DECLARATOR
26 #     Defines TYPE as a type (for arguments and return values)
27 #     which corresponds to the C type specified.  C-TYPE-DECLARATOR
28 #     must contain one `@' where the identifier would go.
29 #     The type may contain allocated memory, etc., in which case
30 #     `Init' and `Fini' must be used.
31 #
32 #     TYPE may be either TYPENAME or TYPENAME(ARGS) - in this case,
33 #     ARGS should be C argument declarations as for in a function
34 #     prototype, of extra arguments for the application-supplied
35 #     parser/returner functions.  Each time a TYPE is used elsewhere,
36 #     the ARGS should be the actual arguments to pass, and will be
37 #     textually copied into the calls to the parser/returner
38 #     functions.
39 #
40 #     `Type' causes declarations in the .h file of these functions:
41 #        int cht_pat_TYPENAME(Tcl_Interp*, Tcl_Obj *obj, C-TYPE *val, ARGS);
42 #        Tcl_Obj *cht_ret_TYPENAME(Tcl_Interp*, C-TYPE val, ARGS);
43 #
44 #     cht_pat_... must attempt to parse obj into the appropriate type.
45 #     val will already have been initialised with `Init' statements if
46 #     relevant.  Whether cht_pat_... fails or succeeds it may allocate
47 #     memory into the object and must leave the object valid (for
48 #     `Fini').
49 #
50 #     cht_ret_... must convert the value back to a new Tcl_Obj.  It may
51 #     not fail.
52 #
53 #  Init TYPENAME    C-STATEMENTS
54 #     Provides some statements which are used to initialise a variable
55 #     of type TYPENAME.  C-STATEMENTS should contain one or more `@',
56 #     which will be replaced by the actual variable name.  The
57 #     variable will have been declared with the C declarator specified
58 #     with `Type'.  C-STATEMENTS may not fail or longjmp, and they may
59 #     not allocate memory or other resources.  If no `Init' is
60 #     supplied then there is no invariant (so no `Fini' may be
61 #     supplied either, and the type is `flat' - no memory, external
62 #     refs, etc.)
63 #
64 #  Fini TYPENAME    C-STATEMENTS
65 #     Provides some statements (like `Init') which are used to free a
66 #     variable of type TYPENAME.  The variable will already have been
67 #     initialised with the `Init' statements, and may have been
68 #     modified since by application per-type or per-command code.  Its
69 #     invariant will be satisfied before C-STATEMENTS.  Afterwards the
70 #     invariant may or may not be satisfied, but it may not have any
71 #     memory or other resources allocated.  C-STATEMENTS may not fail
72 #     or longjmp.
73 #
74 #  H-Include    C-INCLUDE-SPECIFIER
75 #     Arranges for generated .h files to #include the specified
76 #     file.  C-INCLUDE-SPECIFIER should include the <..> or "..".
77 #
78 #  Table [*]TABLENAME C-ENTRY-TYPE
79 #     Starts a table of commands or subcommands.  The generated .h
80 #     will contain a definition of C-ENTRY-TYPE containing
81 #         const char *name;
82 #         Tcl_ObjCmdProc *func;
83 #     and the generated .c will contain
84 #         const C-ENTRY-TYPE C-ARRAY-NAME[];
85 #     where C-ARRAY-NAME is TABLENAME, with `_entries' appended
86 #     and `cht_' prepended.  The entries are indented one level (one
87 #     or more spaces) and look like this:
88 #        ENTRYNAME [ C-EXTRA-ENTRY-VALUES ]
89 #            FORMALARGNAME   TYPE
90 #            ...
91 #          [ =>  RESULT-TYPE ]
92 #     This will cause the declaration of
93 #        int cht_do_TABLENAME_ENTRYNAME(ClientData cd, Tcl_Interp *ip,
94 #                                   FORMAL-ARGUMENTS, RESULT-C-TYPE*);
95 #     which is the procedure which the application must supply to
96 #     implement the function.  If the `=> RESULT-TYPE' is omitted, so
97 #     is the result argument to the function.  Each argument to the
98 #     function is of the C type corresponding to the specified type.
99 #     The cht_do_... function should not eat any memory associated with
100 #     the arguments.  The result buffer (if any) will be initialised
101 #     using the `Init' and should on success contain the relevant
102 #     result.  On failure it should leave the result unmodified (or at
103 #     least, not in need of freeing).
104 #
105 #     There will be an entry in C-ARRAY-NAME for every table entry.
106 #     The name will be ENTRYNAME, and the func will be a function
107 #     suitable for use as a Tcl command procedure, which parses the
108 #     arguments, processes the command, and sets any result, as
109 #     applicable.
110 #
111 #     `*' should be used if the table name is not useful for error
112 #     messages.  It suppresses `TABLENAME ' from the front of the
113 #     autogenerated argument parsing error strings.
114 #
115 #  EntryExtra C-ENTRY-TYPE
116 #     Introduces a section of additional C code which will be inserted
117 #     into the definition of C-ENTRY-TYPE by `Table'.  The C
118 #     code, which follows on several indented lines, should be
119 #     structure member definitions.
120 #
121 #     When EntryExtra is used, in the corresponding Table, each
122 #     ENTRYNAME should be followed on the same line by whitespace and
123 #     EXTRA-VALUES; the EXTRA-VALUES are used as initialisers for the
124 #     additional structure elements.
125 #
126 #  NoEntryDefine C-ENTRY-TYPE
127 #     Prevents the definition of C-ENTRY-TYPE by Table.
128 #     The C type must be defined elsewhere.
129 #
130 #  Also expected are these functions:
131 #    void cht_setstringresult(Tcl_Interp*, const char*);
132 #        sets the Tcl result from the supplied string
133 #    int cht_pat_enum(Tcl_Interp*, Tcl_Obj*, const void **c_e_t_array,
134 #                 const void *c_e_t_return, size_t c_e_t_sz, const char *what);
135 #        scans a table of C-ENTRY-TYPEs looking for the
136 #        string matching the string supplied by the script
137 #        (as a Tcl_Obj).  On error sets the result, using
138 #        what (a noun phrase describing the type of thing).
139 #        Assumes (unportably!) that the name and func members
140 #        are in the same places no matter what the rest of
141 #        the struct contains.
142 #  and the two predefined types `int' (C `int') and `obj' (Tcl_Obj*,
143 #  unmodified.)  The corresponding definitions are in tcmdiflib.c.
144
145 use IO;
146 use Data::Dumper;
147
148 parse('builtins','DATA');
149
150 while (@ARGV) {
151     $_= shift @ARGV;
152     if (m/^\-p([-_0-9a-z]+)$/) {
153         $prefix= $1;
154         $prefix =~ y/-/_/;
155     } elsif (m/^\-w(c|h)$/) {
156         $write= $1;
157     } elsif (m/^\-o(.+)$/) {
158         $output= $1;
159     } elsif (m/^\-/) {
160         die "unknown option $_\n";
161     } else {
162         if (!defined $prefix) { $prefix= $_;  $prefix =~ s/\.[^.]+$//; }
163         $x= new IO::File $_,'r' or die "$_: $!\n";
164         parse($_,$x);
165     }
166 }
167
168 die "must say -w<something>\n" if !defined $write;
169
170 sub zilch () {
171     undef $c_table;
172     undef $c_entryextra;
173     undef $c_of;
174 }
175
176 sub enumargs ($) {
177     my ($a) = @_;
178     $a =~ m:/(.*),: or die "invalid enum type \`$a'\n";
179     my ($a_tab, $ee_type, $estr) = ($`,$1,$');
180     if ($ee_type !~ m/^[^_]/) {
181         $ee_type= $a_tab.$ee_type;
182         $a_tab= lc($a_tab).'_entries';
183     }
184     return ($a_tab, $ee_type, $estr);
185 }
186
187 sub parse ($$) {
188     my ($wh,$f) = @_;
189     while (defined($_= $f->getline)) {
190         chomp; s/\s+$//;
191         next if m/^\s*\#/;
192         next if !m/\S/;
193         while (s/\t/ ' 'x(8 - (length $`) % 8) /e) { }
194
195         s/^\s*//;
196         $this_indent= length $&;
197         while (@i && $this_indent < $i[0]) {
198             shift @i;
199         }
200         if ($this_indent && (!@i || $this_indent > $i[0])) {
201             unshift @i, $this_indent;
202         }
203
204         if (@i==0 && m/^Table\s+(\*?)(\w+)\s+(\w+)$/) {
205             zilch();
206             $c_table= $2;
207             $table_x{$c_table}{T}= $1;
208             $table_x{$c_table}{C}= $3;
209             $entrytype_x{$3}= '' unless exists $entrytype_x{$3};
210         } elsif (@i==0 && m/^Untabled$/) {
211             zilch();
212             $c_table= '';
213         } elsif (@i==0 && m/^(C|H)\-Include\s+(\S.*)$/) {
214             o(lc $1, 30, "#include $2\n");
215         } elsif (@i==0 && m/^EntryExtra\s+(\w+)$/) {
216             zilch();
217             $c_entryextra= $1;
218         } elsif (@i==0 && m/^NoEntryDefine\s+(\w+)$/) {
219             zilch();
220             $entrytype_x{$1}= " ";
221         } elsif (@i>=1 && defined $c_entryextra) {
222             $entrytype_x{$c_entryextra} .= "  $_\n";
223         } elsif (@i==1 && m/^[a-z].*$/ && defined $c_table) {
224             if (m/^[-_0-9A-Za-z]+$/) {
225                 $c_entry= $_;
226             } elsif (m/^([-_0-9A-Za-z]+)\s+(\S.*)$/) {
227                 $c_entry= $1;
228                 $tables{$c_table}{$c_entry}{I} .= ", $2";
229             } else {
230                 badsyntax($wh,$.,"bad entry");
231             }
232             $tables{$c_table}{$c_entry}{A} = [ ];
233         } elsif (@i==2 && m/^\.\.\.\s+(\w+)$/ && defined $c_entry) {
234             $tables{$c_table}{$c_entry}{V}= $1;
235         } elsif (@i==2 && m/^(\??)([a-z]\w*)\s*(\S.*)/
236                  && defined $c_entry) {
237             ($opt, $var, $type) = ($1,$2,$3);
238             ($type, $xtypeargs) = split_type_args($type);
239             push @{ $tables{$c_table}{$c_entry}{A} },
240                 { N => $var, T => $type, A => $xtypeargs, O => ($opt eq '?') };
241         } elsif (@i==2 && m/^\=\>\s*(\S.*)$/ && defined $c_entry) {
242             ($type, $xtypeargs) = split_type_args($1);
243             $tables{$c_table}{$c_entry}{R}= $type;
244             $tables{$c_table}{$c_entry}{X}= $xtypeargs;
245         } elsif (@i==0 && m/^Type\s+([^\:]+)\:\s+(\S.*)$/) {
246             ($typename,$ctype)= ($1,$2);
247             $ctype .= ' @' unless $ctype =~ m/\@/;
248             ($typename,$xtypeargs) = split_type_args($typename);
249             $types{$typename}= { C => $ctype, X => $xtypeargs };
250         } elsif (@i==0 && s/^Init\s+(\w+)\s+(\S.*)//) {
251             $type_init{$1}= $2;
252         } elsif (@i==0 && s/^Fini\s+(\w+)\s+(\S.*)//) {
253             $type_fini{$1}= $2;
254         } else {
255             badsyntax($wh,$., sprintf
256                       "bad directive (indent level %d)", scalar @i);
257         }
258     }
259     $f->error and die $!;
260     $f->close;
261 }
262
263 #print Dumper(\%tables),"\n";
264 #print Dumper(\%types),"\n";
265
266 foreach $t (sort keys %types) {
267     $type= $types{$t};
268     $c= $type->{C};
269     $xta= $type->{X};
270     $decl= "int cht_pat_$t(Tcl_Interp *ip, Tcl_Obj *obj, ";
271     $decl .= subst_in_decl('*val', $c, "type $t");
272     $decl .= ", $xta",  if length $xta;
273     $decl .= ");\n";
274     o('h',160, $decl);
275
276     $decl= "Tcl_Obj *cht_ret_$t(Tcl_Interp *ip, ".subst_in_decl('val',$c);
277     $decl .= ", $xta" if length $xta;
278     $decl .= ");\n";
279     o('h',170, $decl);
280 }
281
282 foreach $c_entrytype (sort keys %entrytype_x) {
283     next if $entrytype_x{$c_entrytype} =~ m/^\s$/;
284     o('h', 20, "typedef struct $c_entrytype $c_entrytype;\n");
285     o('h', 100,
286       "struct $c_entrytype {\n".
287       "  const char *name;\n".
288       "  Tcl_ObjCmdProc *func;\n".
289       $entrytype_x{$c_entrytype}.
290       "};\n\n");
291 }
292
293 foreach $c_table (sort keys %tables) {
294     $r_table= $tables{$c_table};
295     $x_table= $table_x{$c_table};
296     $op_tab= '';
297
298     foreach $c_entry (sort keys %$r_table) {
299         $c_entry_c= $c_entry; $c_entry_c =~ y/-/_/;
300         $r_entry= $r_table->{$c_entry};
301         $pa_decl= "int pa_${c_table}_${c_entry_c}(ClientData cd,".
302             " Tcl_Interp *ip, int objc, Tcl_Obj *const *objv)";
303         $do_decl= "int cht_do_${c_table}_${c_entry_c}(";
304         @do_al= ('ClientData cd', 'Tcl_Interp *ip');
305         @do_aa= qw(cd ip);
306         $pa_init= '';
307         $pa_argc= "  objc--; objv++;\n";
308         $pa_vars= "  int rc;\n";
309         $pa_body= '';
310         $pa_rslt= '';
311         $pa_free= '';
312         $pa_fini= '';
313         $any_mand= 0;
314         $any_optl= 0;
315         $any_eerr= 0;
316         $any_eargc= 0;
317         $pa_hint= '';
318         $pa_hint .= "$c_table " if length $c_table &&
319             !length $table_x{$c_table}{T};
320         $pa_hint.= $c_entry;
321         foreach $arg (@{ $r_entry->{A} }) {
322             $n= $arg->{N};
323             $t= $arg->{T};
324             $a= $arg->{A};
325             push @do_al, make_decl($n, $t, $arg->{A},
326                                    "table $c_table entry $c_entry arg $n");
327             $pa_vars .= make_decl_init("a_$n", $t, $a, \$pa_init, "pa_vars");
328             if ($arg->{O}) {
329                 $pa_hint .= " ?$n?";
330                 if ($any_mand) {
331                     $any_mand= 0;
332                     $any_eerr= 1;
333                 }
334                 $pa_body .= "  if (!objc--) goto end_optional;\n";
335                 $any_optl= 1;
336             } else {
337                 $pa_hint .= " $n";
338                 $pa_body .= "  if (!objc--) goto wrong_count_args;\n";
339                 $any_mand++;
340                 $any_eargc= 1;
341                 die if $any_optl;
342             }
343             $paarg= "&a_$n";
344             $pafin= '';
345             if ($t eq 'enum') {
346                 $pa_vars .= "  const void *v_$n= 0;\n";
347                 $paarg= "&v_$n";
348                 $pafin= "\n  a_$n= v_$n; ";
349                 ($a_tab, $ee_type, $estr) = enumargs($a);
350                 $a = "cht_$a_tab, sizeof($ee_type), $estr";
351                 o('h', 210, "extern const $ee_type cht_$a_tab".'[]'.";\n");
352             }
353             if (exists $type_fini{$t}) {
354                 $pa_fini .= '  '.subst_in("a_$n", $type_fini{$t})."\n";
355             }
356             $pa_body .= "  rc= cht_pat_$t(ip, *objv++, $paarg";
357             $pa_body .= ", ".$a if length $a;
358             $pa_body .= ");$pafin if (rc) goto rc_err;\n";
359             push @do_aa, "a_$n";
360         }
361         if (exists $r_entry->{V}) {
362             $pa_hint .= " ...";
363             $va= $r_entry->{V};
364             push @do_al, subst_in_decl("${va}c", 'int @');
365             push @do_al, subst_in_decl("${va}v", 'Tcl_Obj *const *@');
366             push @do_aa, "objc+1", "objv-1";
367         } else {
368             if (!$any_optl) {
369                 $pa_body .= "  if (objc) goto wrong_count_args;\n";
370                 $any_eargc= 1;
371             }
372         }
373         if ($any_optl) {
374             $pa_body .= "end_optional:\n";
375         }
376         if (exists $r_entry->{R}) {
377             $t= $r_entry->{R};
378             $xta= $r_entry->{X};
379             push @do_al, make_decl("*result", $t, "cht_do_al result");
380             $pa_vars .= make_decl_init("result", $t, $xta, \$pa_init,
381                                        "pa_vars result");
382             push @do_aa, "&result";
383             $pa_rslt .= "  Tcl_SetObjResult(ip, cht_ret_$t(ip, result";
384             $pa_rslt .= ", $xta" if length $xta;
385             $pa_rslt .= "));\n";
386         }
387         $pa_body .= "\n";
388         $pa_body .= "  rc= cht_do_${c_table}_${c_entry_c}(";
389         $pa_body .= join ', ', @do_aa;
390         $pa_body .= ");\n";
391         $pa_body .= "  if (rc) goto rc_err;\n";
392
393         $pa_rslt .= "  rc= TCL_OK;\n\n";
394         $pa_rslt .= "rc_err:\n";
395         
396         $pa_fini .= "  return rc;\n";
397         if ($any_eargc) {
398             $pa_fini .= "\nwrong_count_args:\n";
399             $pa_fini .= "  e=\"wrong # args: should be \\\"$pa_hint\\\"\";\n";
400             $pa_fini .= "  goto e_err;";
401             $any_eerr= 1;
402         }
403         if ($any_eerr) {
404             $pa_vars .= "  const char *e;\n";
405             $pa_fini .= "\n";
406             $pa_fini .= "e_err:\n";
407             $pa_fini .= "  cht_setstringresult(ip,e);\n";
408             $pa_fini .= "  rc= TCL_ERROR; goto rc_err;\n";
409         }
410         $pa_vars .= "\n";
411         $pa_init .= "\n" if length $pa_init;
412         $pa_fini .= "}\n\n";
413
414         if (length $c_table) {
415             $static= 'static ';
416         } else {
417             $static= '';
418             o('h',90, "$pa_decl;\n");
419         }
420         o('c',100,
421           $static.$pa_decl." {\n".
422           $pa_vars.
423           $pa_init.
424           $pa_argc.
425           $pa_body.
426           $pa_rslt.
427           $pa_free.
428           $pa_fini);
429         $do_decl .= join ', ', @do_al;
430         $do_decl .= ")";
431         o('h',100, $do_decl.";\n") or die $!;
432         
433
434         $op_tab .= sprintf("  { %-20s %-40s%s },\n",
435                            "\"$c_entry\",",
436                            "pa_${c_table}_${c_entry_c}",
437                            $r_entry->{I});
438     }
439     if (length $c_table) {
440         $decl= "const $x_table->{C} cht_${c_table}_entries[]";
441         o('h', 500, "extern $decl;\n");
442         o('c', 100,
443           "$decl = {\n".
444           $op_tab.
445           "  { 0 }\n".
446           "};\n\n");
447     }
448 }
449
450 o(c, 0, "#include \"$prefix.h\"\n");
451
452 o(h, 0,
453   "#ifndef INCLUDED_\U${prefix}_H\n".
454   "#define INCLUDED_\U${prefix}_H\n\n");
455
456 o(h, 999,
457   "#endif /*INCLUDED_\U${prefix}_H*/\n");
458
459 if (defined $output) {
460     $oh= new IO::File "$output.tmp", 'w' or die "$output.tmp: $!\n";
461 } else {
462     $oh= 'STDOUT';
463 }
464
465 print $oh "/* AUTOGENERATED - DO NOT EDIT */\n" or die $!;
466 foreach $pr (sort keys %{ $o{$write} }) {
467     print $oh "\n" or die $!;
468     print $oh $o{$write}{$pr} or die $!;
469 }
470
471 die if $oh->error;
472 die $! unless $oh->close;
473
474 if (defined $output) {
475     rename "$output.tmp", $output or die $!;
476 }
477
478 sub o ($$) {
479     my ($wh,$pr,$s) = @_;
480     $o{$wh}{sprintf "%010d", $pr} .= $s;
481 }
482
483 sub split_type_args ($) {
484     my ($type) = @_;
485     my ($xtypeargs);
486     if ($type =~ m/^\w+$/) {
487         $xtypeargs='';
488     } elsif ($type =~ m/^(\w+)\((.+)\)$/) {
489         $type= $1;
490         $xtypeargs= $2;
491     } else {
492         badsyntax($wh,$.,"bad type name/args \`$type'\n");
493     }
494     return ($type,$xtypeargs);
495 }
496
497 sub make_decl_init ($$$$$) {
498     my ($n, $t, $a, $initcode, $why) = @_;
499     my ($o,$init);
500     $o= make_decl($n,$t,$a,"$why _init");
501     if (exists $type_init{$t}) {
502         $init= $type_init{$t};
503         $$initcode .= "  ".subst_in("$n", $init)."\n"
504             if length $init;
505     } else {
506         $o .= ' =0';
507     }
508     return "  ".$o.";\n";
509 }
510
511 sub make_decl ($$$$) {
512     my ($n, $t, $ta, $why) = @_;
513     my ($type);
514     if ($t eq 'enum') {
515         ($a_tab, $ee_type, $estr) = enumargs($ta);
516         $c= "const $ee_type* @";
517     } else { 
518         defined $types{$t} or die "unknown type $t ($why)\n";
519         $c= $types{$t}{C};
520     }
521     return subst_in_decl($n,$c);
522 }
523
524 sub subst_in_decl ($$$) {
525     my ($val, $pat, $why) = @_;
526     local ($_) = subst_in($val, $pat, $why);
527     s/ *(\**) *$/$1/;
528     return $_;
529 }
530     
531 sub subst_in ($$$) {
532     my ($val, $pat, $why) = @_;
533     $pat =~ m/\@/ or die "$pat for $val in $why ?";
534     $pat =~ s/\@/$val/g;
535     return $pat;
536 }
537
538 sub badsyntax ($$$) {
539     die "$_[0]:$_[1]: $_[2]\n";
540 }
541
542 __DATA__
543 Type int:       int
544 Type obj:       Tcl_Obj *@