3 # code generator to help with writing Tcl extensions
4 # Copyright 2006-2012 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, see <http://www.gnu.org/licenses/>.
20 # Input format is line-based, ws-significant, offside rule (some kind
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.
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
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);
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
48 # cht_ret_... must convert the value back to a new Tcl_Obj. It may
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
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
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 "..".
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
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 ]
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
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).
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)
112 # and also generates and uses a standard dispatch function.
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
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.
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.
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.
135 # NoEntryDefine C-ENTRY-TYPE
136 # Prevents the definition of C-ENTRY-TYPE by Table.
137 # The C type must be defined elsewhere.
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.
157 parse('builtins','DATA');
161 if (m/^\-p([-_0-9a-z]+)$/) {
164 } elsif (m/^\-w(c|h)$/) {
166 } elsif (m/^\-o(.+)$/) {
169 die "unknown option $_\n";
171 if (!defined $prefix) { $prefix= $_; $prefix =~ s/\.[^.]+$//; }
172 $x= new IO::File $_,'r' or die "$_: $!\n";
177 die "must say -w<something>\n" if !defined $write;
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';
193 return ($a_tab, $ee_type, $estr);
198 while (defined($_= $f->getline)) {
202 while (s/\t/ ' 'x(8 - (length $`) % 8) /e) { }
205 $this_indent= length $&;
206 while (@i && $this_indent < $i[0]) {
209 if ($this_indent && (!@i || $this_indent > $i[0])) {
210 unshift @i, $this_indent;
213 if (@i==0 && m/^Table\s+(\*?)(\w+)\s+(\w+)$/) {
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$/) {
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+)$/) {
227 } elsif (@i==0 && m/^NoEntryDefine\s+(\w+)$/) {
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]+$/) {
235 } elsif (m/^([-_0-9A-Za-z]+)\s+(\S.*)$/) {
237 $tables{$c_table}{$c_entry}{I} .= ", $2";
239 badsyntax($wh,$.,"bad entry");
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) {
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.*)//) {
268 } elsif (@i==0 && s/^Fini\s+(\w+)\s+(\S.*)//) {
271 badsyntax($wh,$., sprintf
272 "bad directive (indent level %d)", scalar @i);
275 $f->error and die $!;
279 #print Dumper(\%tables),"\n";
280 #print Dumper(\%types),"\n";
282 foreach $t (sort keys %types) {
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;
292 $decl= "Tcl_Obj *cht_ret_$t(Tcl_Interp *ip, ".subst_in_decl('val',$c);
293 $decl .= ", $xta" if length $xta;
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");
302 "struct $c_entrytype {\n".
303 " const char *name;\n".
304 " Tcl_ObjCmdProc *func;\n".
305 $entrytype_x{$c_entrytype}.
309 foreach $c_table (sort keys %tables) {
310 $r_table= $tables{$c_table};
311 $x_table= $table_x{$c_table};
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}";
323 $do_decl= "int $pa_func(";
324 @do_al= ('ClientData cd', 'Tcl_Interp *ip');
327 $pa_argc= " objc--; objv++;\n";
328 $pa_vars= " int rc;\n";
338 $pa_hint .= "$c_table " if length $c_table &&
339 !length $table_x{$c_table}{T};
341 foreach $arg (@{ $r_entry->{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");
354 $pa_body .= " if (!objc--) goto end_optional;\n";
358 $pa_body .= " if (!objc--) goto wrong_count_args;\n";
366 $pa_vars .= " const void *v_$n= 0;\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");
373 if (exists $type_fini{$t}) {
374 $pa_fini .= ' '.subst_in("a_$n", $type_fini{$t})."\n";
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";
381 if (exists $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";
389 $pa_body .= " if (objc) goto wrong_count_args;\n";
394 $pa_body .= "end_optional:\n";
396 if (exists $r_entry->{R}) {
399 push @do_al, make_decl("*result", $t, "cht_do_al result");
400 $pa_vars .= make_decl_init("result", $t, $xta, \$pa_init,
402 push @do_aa, "&result";
403 $pa_rslt .= " Tcl_SetObjResult(ip, cht_ret_$t(ip, result";
404 $pa_rslt .= ", $xta" if length $xta;
408 $pa_body .= " rc= $pa_func(";
409 $pa_body .= join ', ', @do_aa;
411 $pa_body .= " if (rc) goto rc_err;\n";
413 $pa_rslt .= " rc= TCL_OK;\n\n";
414 $pa_rslt .= "rc_err:\n";
416 $pa_fini .= " return rc;\n";
418 $pa_fini .= "\nwrong_count_args:\n";
419 $pa_fini .= " e=\"wrong # args: should be \\\"$pa_hint\\\"\";\n";
420 $pa_fini .= " goto e_err;";
424 $pa_vars .= " const char *e;\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";
431 $pa_init .= "\n" if length $pa_init;
434 if (length $c_table) {
438 o('h',90, "$pa_decl;\n");
441 $static.$pa_decl." {\n".
449 $do_decl .= join ', ', @do_al;
452 if (exists $r_entry->{D}) {
453 my $subcmdtype= $r_entry->{D};
454 if (!exists $dispatch_done{$subcmdtype}) {
456 $di_body .= "static $do_decl {\n";
457 $di_body .= " return subcmd->func(0,ip,objc,objv);\n";
459 o('c',50, $di_body) or die $!;
462 o('h',100, $do_decl.";\n") or die $!;
465 $op_tab .= sprintf(" { %-20s %-40s%s },\n",
467 "pa_${c_table}_${c_entry_c}",
470 if (length $c_table) {
471 $decl= "const $x_table->{C} cht_${c_table}_entries[]";
472 o('h', 500, "extern $decl;\n");
481 o(c, 0, "#include \"$prefix.h\"\n");
484 "#ifndef INCLUDED_\U${prefix}_H\n".
485 "#define INCLUDED_\U${prefix}_H\n\n");
488 "#endif /*INCLUDED_\U${prefix}_H*/\n");
490 if (defined $output) {
491 $oh= new IO::File "$output.tmp", 'w' or die "$output.tmp: $!\n";
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 $!;
503 die $! unless $oh->close;
505 if (defined $output) {
506 rename "$output.tmp", $output or die $!;
510 my ($wh,$pr,$s) = @_;
511 $o{$wh}{sprintf "%010d", $pr} .= $s;
514 sub split_type_args ($) {
517 if ($type =~ m/^\w+$/) {
519 } elsif ($type =~ m/^(\w+)\((.+)\)$/) {
523 badsyntax($wh,$.,"bad type name/args \`$type'\n");
525 return ($type,$xtypeargs);
528 sub make_decl_init ($$$$$) {
529 my ($n, $t, $a, $initcode, $why) = @_;
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"
542 sub make_decl ($$$$) {
543 my ($n, $t, $ta, $why) = @_;
546 ($a_tab, $ee_type, $estr) = enumargs($ta);
547 $c= "const $ee_type* @";
549 defined $types{$t} or die "unknown type $t ($why)\n";
552 return subst_in_decl($n,$c);
555 sub subst_in_decl ($$$) {
556 my ($val, $pat, $why) = @_;
557 local ($_) = subst_in($val, $pat, $why);
563 my ($val, $pat, $why) = @_;
564 $pat =~ m/\@/ or die "$pat for $val in $why ?";
569 sub badsyntax ($$$) {
570 die "$_[0]:$_[1]: $_[2]\n";