3 # code generator to help with writing Tcl extensions
4 # Copyright 2006 Ian Jackson
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.
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.
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
22 # Input format is line-based, ws-significant, offside rule (some kind
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.
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
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);
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
50 # cht_ret_... must convert the value back to a new Tcl_Obj. It may
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
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
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 "..".
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
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 ]
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).
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
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.
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.
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.
126 # NoEntryDefine C-ENTRY-TYPE
127 # Prevents the definition of C-ENTRY-TYPE by Table.
128 # The C type must be defined elsewhere.
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.
148 parse('builtins','DATA');
152 if (m/^\-p([-_0-9a-z]+)$/) {
155 } elsif (m/^\-w(c|h)$/) {
157 } elsif (m/^\-o(.+)$/) {
160 die "unknown option $_\n";
162 if (!defined $prefix) { $prefix= $_; $prefix =~ s/\.[^.]+$//; }
163 $x= new IO::File $_,'r' or die "$_: $!\n";
168 die "must say -w<something>\n" if !defined $write;
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';
184 return ($a_tab, $ee_type, $estr);
189 while (defined($_= $f->getline)) {
193 while (s/\t/ ' 'x(8 - (length $`) % 8) /e) { }
196 $this_indent= length $&;
197 while (@i && $this_indent < $i[0]) {
200 if ($this_indent && (!@i || $this_indent > $i[0])) {
201 unshift @i, $this_indent;
204 if (@i==0 && m/^Table\s+(\*?)(\w+)\s+(\w+)$/) {
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$/) {
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+)$/) {
218 } elsif (@i==0 && m/^NoEntryDefine\s+(\w+)$/) {
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]+$/) {
226 } elsif (m/^([-_0-9A-Za-z]+)\s+(\S.*)$/) {
228 $tables{$c_table}{$c_entry}{I} .= ", $2";
230 badsyntax($wh,$.,"bad entry");
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.*)//) {
252 } elsif (@i==0 && s/^Fini\s+(\w+)\s+(\S.*)//) {
255 badsyntax($wh,$., sprintf
256 "bad directive (indent level %d)", scalar @i);
259 $f->error and die $!;
263 #print Dumper(\%tables),"\n";
264 #print Dumper(\%types),"\n";
266 foreach $t (sort keys %types) {
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;
276 $decl= "Tcl_Obj *cht_ret_$t(Tcl_Interp *ip, ".subst_in_decl('val',$c);
277 $decl .= ", $xta" if length $xta;
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");
286 "struct $c_entrytype {\n".
287 " const char *name;\n".
288 " Tcl_ObjCmdProc *func;\n".
289 $entrytype_x{$c_entrytype}.
293 foreach $c_table (sort keys %tables) {
294 $r_table= $tables{$c_table};
295 $x_table= $table_x{$c_table};
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');
307 $pa_argc= " objc--; objv++;\n";
308 $pa_vars= " int rc;\n";
318 $pa_hint .= "$c_table " if length $c_table &&
319 !length $table_x{$c_table}{T};
321 foreach $arg (@{ $r_entry->{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");
334 $pa_body .= " if (!objc--) goto end_optional;\n";
338 $pa_body .= " if (!objc--) goto wrong_count_args;\n";
346 $pa_vars .= " const void *v_$n= 0;\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");
353 if (exists $type_fini{$t}) {
354 $pa_fini .= ' '.subst_in("a_$n", $type_fini{$t})."\n";
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";
361 if (exists $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";
369 $pa_body .= " if (objc) goto wrong_count_args;\n";
374 $pa_body .= "end_optional:\n";
376 if (exists $r_entry->{R}) {
379 push @do_al, make_decl("*result", $t, "cht_do_al result");
380 $pa_vars .= make_decl_init("result", $t, $xta, \$pa_init,
382 push @do_aa, "&result";
383 $pa_rslt .= " Tcl_SetObjResult(ip, cht_ret_$t(ip, result";
384 $pa_rslt .= ", $xta" if length $xta;
388 $pa_body .= " rc= cht_do_${c_table}_${c_entry_c}(";
389 $pa_body .= join ', ', @do_aa;
391 $pa_body .= " if (rc) goto rc_err;\n";
393 $pa_rslt .= " rc= TCL_OK;\n\n";
394 $pa_rslt .= "rc_err:\n";
396 $pa_fini .= " return rc;\n";
398 $pa_fini .= "\nwrong_count_args:\n";
399 $pa_fini .= " e=\"wrong # args: should be \\\"$pa_hint\\\"\";\n";
400 $pa_fini .= " goto e_err;";
404 $pa_vars .= " const char *e;\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";
411 $pa_init .= "\n" if length $pa_init;
414 if (length $c_table) {
418 o('h',90, "$pa_decl;\n");
421 $static.$pa_decl." {\n".
429 $do_decl .= join ', ', @do_al;
431 o('h',100, $do_decl.";\n") or die $!;
434 $op_tab .= sprintf(" { %-20s %-40s%s },\n",
436 "pa_${c_table}_${c_entry_c}",
439 if (length $c_table) {
440 $decl= "const $x_table->{C} cht_${c_table}_entries[]";
441 o('h', 500, "extern $decl;\n");
450 o(c, 0, "#include \"$prefix.h\"\n");
453 "#ifndef INCLUDED_\U${prefix}_H\n".
454 "#define INCLUDED_\U${prefix}_H\n\n");
457 "#endif /*INCLUDED_\U${prefix}_H*/\n");
459 if (defined $output) {
460 $oh= new IO::File "$output.tmp", 'w' or die "$output.tmp: $!\n";
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 $!;
472 die $! unless $oh->close;
474 if (defined $output) {
475 rename "$output.tmp", $output or die $!;
479 my ($wh,$pr,$s) = @_;
480 $o{$wh}{sprintf "%010d", $pr} .= $s;
483 sub split_type_args ($) {
486 if ($type =~ m/^\w+$/) {
488 } elsif ($type =~ m/^(\w+)\((.+)\)$/) {
492 badsyntax($wh,$.,"bad type name/args \`$type'\n");
494 return ($type,$xtypeargs);
497 sub make_decl_init ($$$$$) {
498 my ($n, $t, $a, $initcode, $why) = @_;
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"
511 sub make_decl ($$$$) {
512 my ($n, $t, $ta, $why) = @_;
515 ($a_tab, $ee_type, $estr) = enumargs($ta);
516 $c= "const $ee_type* @";
518 defined $types{$t} or die "unknown type $t ($why)\n";
521 return subst_in_decl($n,$c);
524 sub subst_in_decl ($$$) {
525 my ($val, $pat, $why) = @_;
526 local ($_) = subst_in($val, $pat, $why);
532 my ($val, $pat, $why) = @_;
533 $pat =~ m/\@/ or die "$pat for $val in $why ?";
538 sub badsyntax ($$$) {
539 die "$_[0]:$_[1]: $_[2]\n";