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