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