chiark / gitweb /
95329dd4e543ae9442f9e5882f23ba25989e6cc5
[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 #  ExtraEntry C-ENTRY-TYPE
93 #     Introduces a section of additional C code which will be inserted
94 #     into the definition of C-ENTRY-TYPE by `Table'.  The C
95 #     code, which follows on several indented lines, should be
96 #     structure member definitions.
97 #
98 #     When ExtraEntry is used, in the corresponding Table, each
99 #     ENTRYNAME should be followed on the same line by whitespace and
100 #     EXTRA-VALUES; the EXTRA-VALUES are used as initialisers for the
101 #     additional structure elements.
102 #
103 #  NoEntryDefine C-ENTRY-TYPE
104 #     Prevents the definition of C-ENTRY-TYPE by Table.
105 #     The C type must be defined elsewhere.
106 #
107 #  Also expected are these functions:
108 #    void cht_setstringresult(Tcl_Interp*, const char*);
109 #        sets the Tcl result from the supplied string
110 #    int cht_pat_enum(Tcl_Interp*, Tcl_Obj*, const void **c_e_t_array,
111 #                 const void *c_e_t_return, size_t c_e_t_sz, const char *what);
112 #        scans a table of C-ENTRY-TYPEs looking for the
113 #        string matching the string supplied by the script
114 #        (as a Tcl_Obj).  On error sets the result, using
115 #        what (a noun phrase describing the type of thing).
116 #        Assumes (unportably!) that the name and func members
117 #        are in the same places no matter what the rest of
118 #        the struct contains.
119 #  and the two predefined types `int' (C `int') and `obj' (Tcl_Obj*,
120 #  unmodified.)  The corresponding definitions are in tcmdiflib.c.
121
122 use IO;
123 use Data::Dumper;
124
125 parse('builtins','DATA');
126
127 while (@ARGV) {
128     $_= shift @ARGV;
129     if (m/^\-p([-_0-9a-z]+)$/) {
130         $prefix= $1;
131         $prefix =~ y/-/_/;
132     } elsif (m/^\-w(c|h)$/) {
133         $write= $1;
134     } elsif (m/^\-o(.+)$/) {
135         $output= $1;
136     } elsif (m/^\-/) {
137         die "unknown option $_\n";
138     } else {
139         if (!defined $prefix) { $prefix= $_;  $prefix =~ s/\.[^.]+$//; }
140         $x= new IO::File $_,'r' or die "$_: $!\n";
141         parse($_,$x);
142     }
143 }
144
145 die "must say -w<something>\n" if !defined $write;
146
147 sub zilch () {
148     undef $c_table;
149     undef $c_entryextra;
150     undef $c_of;
151 }
152
153 sub enumargs ($) {
154     my ($a) = @_;
155     $a =~ m:/(.*),: or die "invalid enum type \`$a'\n";
156     my ($a_tab, $ee_type, $estr) = ($`,$1,$');
157     if ($ee_type !~ m/^[^_]/) {
158         $ee_type= $a_tab.$ee_type;
159         $a_tab= lc($a_tab).'_entries';
160     }
161     return ($a_tab, $ee_type, $estr);
162 }
163
164 sub parse ($$) {
165     my ($wh,$f) = @_;
166     while (defined($_= $f->getline)) {
167         chomp; s/\s+$//;
168         next if m/^\s*\#/;
169         next if !m/\S/;
170         while (s/\t/ ' 'x(8 - (length $`) % 8) /e) { }
171
172         s/^\s*//;
173         $this_indent= length $&;
174         while (@i && $this_indent < $i[0]) {
175             shift @i;
176         }
177         if ($this_indent && (!@i || $this_indent > $i[0])) {
178             unshift @i, $this_indent;
179         }
180
181         if (@i==0 && m/^Table\s+(\w+)\s+(\w+)$/) {
182             zilch();
183             $c_table= $1;
184             $table_x{$c_table}{C}= $2;
185             $entrytype_x{$2}= '' unless exists $entrytype_x{$2};
186         } elsif (@i==0 && m/^Untabled$/) {
187             zilch();
188             $c_table= '';
189         } elsif (@i==0 && m/^(C|H)\-Include\s+(\S.*)$/) {
190             o(lc $1, 30, "#include $2\n");
191         } elsif (@i==0 && m/^EntryExtra\s+(\w+)$/) {
192             zilch();
193             $c_entryextra= $1;
194         } elsif (@i==0 && m/^NoEntryDefine\s+(\w+)$/) {
195             zilch();
196             $entrytype_x{$1}= " ";
197         } elsif (@i>=1 && defined $c_entryextra) {
198             $entrytype_x{$c_entryextra} .= "  $_\n";
199         } elsif (@i==1 && m/^[a-z].*$/ && defined $c_table) {
200             if (m/^[-_0-9A-Za-z]+$/) {
201                 $c_entry= $_;
202             } elsif (m/^([-_0-9A-Za-z]+)\s+(\S.*)$/) {
203                 $c_entry= $1;
204                 $tables{$c_table}{$c_entry}{I} .= ", $2";
205             } else {
206                 badsyntax($wh,$.,"bad entry");
207             }
208             $tables{$c_table}{$c_entry}{A} = [ ];
209         } elsif (@i==2 && m/^\.\.\.\s+(\w+)$/ && defined $c_entry) {
210             $tables{$c_table}{$c_entry}{V}= $1;
211         } elsif (@i==2 && m/^(\??)([a-z]\w*)\s*(\S.*)/
212                  && defined $c_entry) {
213             ($opt, $var, $type) = ($1,$2,$3);
214             ($type, $xtypeargs) = split_type_args($type);
215             push @{ $tables{$c_table}{$c_entry}{A} },
216                 { N => $var, T => $type, A => $xtypeargs, O => ($opt eq '?') };
217         } elsif (@i==2 && m/^\=\>\s*(\S.*)$/ && defined $c_entry) {
218             ($type, $xtypeargs) = split_type_args($1);
219             $tables{$c_table}{$c_entry}{R}= $type;
220             $tables{$c_table}{$c_entry}{X}= $xtypeargs;
221         } elsif (@i==0 && m/^Type\s+([^\:]+)\:\s+(\S.*)$/) {
222             ($typename,$ctype)= ($1,$2);
223             $ctype .= ' @' unless $ctype =~ m/\@/;
224             ($typename,$xtypeargs) = split_type_args($typename);
225             $types{$typename}= { C => $ctype, X => $xtypeargs };
226         } elsif (@i==0 && s/^Init\s+(\w+)\s+(\S.*)//) {
227             $type_init{$1}= $2;
228         } elsif (@i==0 && s/^Fini\s+(\w+)\s+(\S.*)//) {
229             $type_fini{$1}= $2;
230         } else {
231             badsyntax($wh,$., sprintf
232                       "bad directive (indent level %d)", scalar @i);
233         }
234     }
235     $f->error and die $!;
236     $f->close;
237 }
238
239 #print Dumper(\%tables),"\n";
240 #print Dumper(\%types),"\n";
241
242 foreach $t (sort keys %types) {
243     $type= $types{$t};
244     $c= $type->{C};
245     $xta= $type->{X};
246     $decl= "int cht_pat_$t(Tcl_Interp *ip, Tcl_Obj *obj, ";
247     $decl .= subst_in_decl('*val', $c, "type $t");
248     $decl .= ", $xta",  if length $xta;
249     $decl .= ");\n";
250     o('h',160, $decl);
251
252     $decl= "Tcl_Obj *cht_ret_$t(Tcl_Interp *ip, ".subst_in_decl('val',$c);
253     $decl .= ", $xta" if length $xta;
254     $decl .= ");\n";
255     o('h',170, $decl);
256 }
257
258 foreach $c_entrytype (sort keys %entrytype_x) {
259     next if $entrytype_x{$c_entrytype} =~ m/^\s$/;
260     o('h', 20, "typedef struct $c_entrytype $c_entrytype;\n");
261     o('h', 100,
262       "struct $c_entrytype {\n".
263       "  const char *name;\n".
264       "  Tcl_ObjCmdProc *func;\n".
265       $entrytype_x{$c_entrytype}.
266       "};\n\n");
267 }
268
269 foreach $c_table (sort keys %tables) {
270     $r_table= $tables{$c_table};
271     $x_table= $table_x{$c_table};
272     $op_tab= '';
273
274     foreach $c_entry (sort keys %$r_table) {
275         $c_entry_c= $c_entry; $c_entry_c =~ y/-/_/;
276         $r_entry= $r_table->{$c_entry};
277         $pa_decl= "int pa_${c_table}_${c_entry_c}(ClientData cd,".
278             " Tcl_Interp *ip, int objc, Tcl_Obj *const *objv)";
279         $do_decl= "int cht_do_${c_table}_${c_entry_c}(";
280         @do_al= ('ClientData cd', 'Tcl_Interp *ip');
281         @do_aa= qw(cd ip);
282         $pa_init= '';
283         $pa_argc= "  objc--; objv++;\n";
284         $pa_vars= "  int rc;\n";
285         $pa_body= '';
286         $pa_rslt= '';
287         $pa_free= '';
288         $pa_fini= '';
289         $any_mand= 0;
290         $any_optl= 0;
291         $any_eerr= 0;
292         $any_eargc= 0;
293         $pa_hint= '';
294         $pa_hint .= "$c_table " if length $c_table;
295         $pa_hint.= $c_entry;
296         foreach $arg (@{ $r_entry->{A} }) {
297             $n= $arg->{N};
298             $t= $arg->{T};
299             $a= $arg->{A};
300             push @do_al, make_decl($n, $t, $arg->{A},
301                                    "table $c_table entry $c_entry arg $n");
302             $pa_vars .= make_decl_init("a_$n", $t, $a, \$pa_init, "pa_vars");
303             if ($arg->{O}) {
304                 $pa_hint .= " ?$n?";
305                 if ($any_mand) {
306                     $any_mand= 0;
307                     $any_eerr= 1;
308                 }
309                 $pa_body .= "  if (!objc--) goto end_optional;\n";
310                 $any_optl= 1;
311             } else {
312                 $pa_hint .= " $n";
313                 $pa_body .= "  if (!objc--) goto wrong_count_args;\n";
314                 $any_mand++;
315                 $any_eargc= 1;
316                 die if $any_optl;
317             }
318             $paarg= "&a_$n";
319             $pafin= '';
320             if ($t eq 'enum') {
321                 $pa_vars .= "  const void *v_$n= 0;\n";
322                 $paarg= "&v_$n";
323                 $pafin= "\n  a_$n= v_$n; ";
324                 ($a_tab, $ee_type, $estr) = enumargs($a);
325                 $a = "cht_$a_tab, sizeof($ee_type), $estr";
326                 o('h', 210, "extern const $ee_type cht_$a_tab".'[]'.";\n");
327             }
328             if (exists $type_fini{$t}) {
329                 $pa_fini .= '  '.subst_in("a_$n", $type_fini{$t})."\n";
330             }
331             $pa_body .= "  rc= cht_pat_$t(ip, *objv++, $paarg";
332             $pa_body .= ", ".$a if length $a;
333             $pa_body .= ");$pafin if (rc) goto rc_err;\n";
334             push @do_aa, "a_$n";
335         }
336         if (exists $r_entry->{V}) {
337             $pa_hint .= " ...";
338             $va= $r_entry->{V};
339             push @do_al, subst_in_decl("${va}c", 'int @');
340             push @do_al, subst_in_decl("${va}v", 'Tcl_Obj *const *@');
341             push @do_aa, "objc+1", "objv-1";
342         } else {
343             if (!$any_optl) {
344                 $pa_body .= "  if (objc) goto wrong_count_args;\n";
345                 $any_eargc= 1;
346             }
347         }
348         if ($any_optl) {
349             $pa_body .= "end_optional:\n";
350         }
351         if (exists $r_entry->{R}) {
352             $t= $r_entry->{R};
353             $xta= $r_entry->{X};
354             push @do_al, make_decl("*result", $t, "cht_do_al result");
355             $pa_vars .= make_decl_init("result", $t, $xta, \$pa_init,
356                                        "pa_vars result");
357             push @do_aa, "&result";
358             $pa_rslt .= "  Tcl_SetObjResult(ip, cht_ret_$t(ip, result";
359             $pa_rslt .= ", $xta" if length $xta;
360             $pa_rslt .= "));\n";
361         }
362         $pa_body .= "\n";
363         $pa_body .= "  rc= cht_do_${c_table}_${c_entry_c}(";
364         $pa_body .= join ', ', @do_aa;
365         $pa_body .= ");\n";
366         $pa_body .= "  if (rc) goto rc_err;\n";
367
368         $pa_rslt .= "  rc= TCL_OK;\n\n";
369         $pa_rslt .= "rc_err:\n";
370         
371         $pa_fini .= "  return rc;\n";
372         if ($any_eargc) {
373             $pa_fini .= "\nwrong_count_args:\n";
374             $pa_fini .= "  e=\"wrong # args: should be \\\"$pa_hint\\\"\";\n";
375             $pa_fini .= "  goto e_err;";
376             $any_eerr= 1;
377         }
378         if ($any_eerr) {
379             $pa_vars .= "  const char *e;\n";
380             $pa_fini .= "\n";
381             $pa_fini .= "e_err:\n";
382             $pa_fini .= "  cht_setstringresult(ip,e);\n";
383             $pa_fini .= "  rc= TCL_ERROR; goto rc_err;\n";
384         }
385         $pa_vars .= "\n";
386         $pa_init .= "\n" if length $pa_init;
387         $pa_fini .= "}\n\n";
388
389         if (length $c_table) {
390             $static= 'static ';
391         } else {
392             $static= '';
393             o('h',90, "$pa_decl;\n");
394         }
395         o('c',100,
396           $static.$pa_decl." {\n".
397           $pa_vars.
398           $pa_init.
399           $pa_argc.
400           $pa_body.
401           $pa_rslt.
402           $pa_free.
403           $pa_fini);
404         $do_decl .= join ', ', @do_al;
405         $do_decl .= ")";
406         o('h',100, $do_decl.";\n") or die $!;
407         
408
409         $op_tab .= sprintf("  { %-20s %-40s%s },\n",
410                            "\"$c_entry\",",
411                            "pa_${c_table}_${c_entry_c}",
412                            $r_entry->{I});
413     }
414     if (length $c_table) {
415         $decl= "const $x_table->{C} cht_${c_table}_entries[]";
416         o('h', 500, "extern $decl;\n");
417         o('c', 100,
418           "$decl = {\n".
419           $op_tab.
420           "  { 0 }\n".
421           "};\n\n");
422     }
423 }
424
425 o(c, 0, "#include \"$prefix.h\"\n");
426
427 o(h, 0,
428   "#ifndef INCLUDED_\U${prefix}_H\n".
429   "#define INCLUDED_\U${prefix}_H\n\n".
430   "#include <tcl8.3/tcl.h>\n");
431
432 o(h, 999,
433   "#endif /*INCLUDED_\U${prefix}_H*/\n");
434
435 if (defined $output) {
436     $oh= new IO::File "$output.tmp", 'w' or die "$output.tmp: $!\n";
437 } else {
438     $oh= 'STDOUT';
439 }
440
441 print $oh "/* AUTOGENERATED - DO NOT EDIT */\n" or die $!;
442 foreach $pr (sort keys %{ $o{$write} }) {
443     print $oh "\n" or die $!;
444     print $oh $o{$write}{$pr} or die $!;
445 }
446
447 die if $oh->error;
448 die $! unless $oh->close;
449
450 if (defined $output) {
451     rename "$output.tmp", $output or die $!;
452 }
453
454 sub o ($$) {
455     my ($wh,$pr,$s) = @_;
456     $o{$wh}{sprintf "%010d", $pr} .= $s;
457 }
458
459 sub split_type_args ($) {
460     my ($type) = @_;
461     my ($xtypeargs);
462     if ($type =~ m/^\w+$/) {
463         $xtypeargs='';
464     } elsif ($type =~ m/^(\w+)\((.+)\)$/) {
465         $type= $1;
466         $xtypeargs= $2;
467     } else {
468         badsyntax($wh,$.,"bad type name/args \`$type'\n");
469     }
470     return ($type,$xtypeargs);
471 }
472
473 sub make_decl_init ($$$$$) {
474     my ($n, $t, $a, $initcode, $why) = @_;
475     my ($o,$init);
476     $o= make_decl($n,$t,$a,"$why _init");
477     if (exists $type_init{$t}) {
478         $init= $type_init{$t};
479         $$initcode .= "  ".subst_in("$n", $init)."\n"
480             if length $init;
481     } else {
482         $o .= ' =0';
483     }
484     return "  ".$o.";\n";
485 }
486
487 sub make_decl ($$$$) {
488     my ($n, $t, $ta, $why) = @_;
489     my ($type);
490     if ($t eq 'enum') {
491         ($a_tab, $ee_type, $estr) = enumargs($ta);
492         $c= "const $ee_type* @";
493     } else { 
494         defined $types{$t} or die "unknown type $t ($why)\n";
495         $c= $types{$t}{C};
496     }
497     return subst_in_decl($n,$c);
498 }
499
500 sub subst_in_decl ($$$) {
501     my ($val, $pat, $why) = @_;
502     local ($_) = subst_in($val, $pat, $why);
503     s/ *(\**) *$/$1/;
504     return $_;
505 }
506     
507 sub subst_in ($$$) {
508     my ($val, $pat, $why) = @_;
509     $pat =~ m/\@/ or die "$pat for $val in $why ?";
510     $pat =~ s/\@/$val/g;
511     return $pat;
512 }
513
514 sub badsyntax ($$$) {
515     die "$_[0]:$_[1]: $_[2]\n";
516 }
517
518 __DATA__
519 Type int:       int
520 Type obj:       Tcl_Obj *@