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