tcltcc

tcltcc is a Tcl extension wrapping tcc. tcc4tcl is the currently-active fork.

Attributes

website
https://github.com/mpcjanssen/tcltcc/
license
LGPL

See Also

ci - a tiny C interpreter
A C interpreter based on tcltcc
unload
Critcl
embed C code into Tcl scripts. critcl currently can't use tcc. Contributions welcome.
tcc4tcl
A fork of tcltcc that is actively developed.

Documentation

tcltcc , Tcl Programming
presents a couple of tcltcc examples

Description

tcltcc includes a fork of tcc that has been modified by MJ to include the following features:

  • can do file I/O via VFS
  • is loadable as a Tcl extension
  • uses Tcl's ck* memory allocation commands

MJ 2009-08-10: TCC has two major drawbacks for further development:

  • It does not compile in passes, so reusing either the parsing part or the code emitter is hard.
  • It is not BSD licensed which is a bad thing for widespread use in Tcl software. (AMG: Though this is changing!)

Like Odyce, it also comes with a partial Critcl API emulation, so hopefully (at least some time in the future) people can just code against a subset of the Critcl API and run it with any of the three :^)

These are reason enough for me to abandon tcc, however I am looking into a similar extension (possibly with similar API) based on pcc [L1 ] which does not have these drawbacks.

tinycc is making progress towards being relicensed under a bsd-style license. RELICENSING , in the repository, contains the new license and a list of contributors who have officially agreed to the license. Rob Landley has also stated that Fabrice Bellard has licensed the code to him under BSD license terms.

MJ 2007-10-09 - Tclcc now also builds and works (passes the testsuite) on Linux

Installation

jgz: How to install the package ?

RS: I'd suspect the usual .../configure; make; make install, but for Win32 a complete package is included (see package directory).

jgz: Installation for Win32 tcl/tk 8.4.16. Running D:\tcl\lib\tcctcl0.2\install\tcc.tcl runs into error because of extra chars after close brace in statement

set dir [file join {*}[lrange [file split [info script]] 0 end-1]]

what did I wrong?

MJ: Use a more recent version from SVN, {*} is an 8.5 specific feature, which is not used in later versions of tcltcc. Also make install has not been tested yet, it may or may not work.


Building, 2013

RS 2013-11-02 - Six years later. The latest download at GoogleCode [L2 ] is still tcltcc0.4.zip dated Nov. 2007, so time has stood still there...

I downloaded it to my x86 Lubuntu netbook and got it to work after some tweaking.

suchenwi@suchenwi-NC10:~/tcltcc$ sudo ./configure
checking for correct TEA configuration... ok (TEA 3.6)
checking for Tcl configuration... configure: WARNING: Can't find Tcl configuration definitions

suchenwi@suchenwi-NC10:~/tcltcc$ sudo ./configure --with-tcl=/usr/lib/tcl8.5
(((lots of output...)))
$ make
(((lots of output...)))
$ make test
(((some output, then: )))
---- errorInfo: In file included from <string>:2:
In file included from /home/suchenwi/tcltcc/tests/../include/tcl.h:141:
In file included from /usr/include/stdio.h:27:
In file included from /usr/include/features.h:341:
/usr/include/stdc-predef.h:30: include file 'bits/predefs.h' not found

 # So I did (quoting from history)
  734  sudo ln -s /usr/include/i386-linux-gnu/bits /usr/include/
  737  sudo ln -s /usr/include/i386-linux-gnu/sys /usr/include/
  740  sudo ln -s /usr/include/i386-linux-gnu/gnu /usr/include/

$ make test
...
Tests ended at Sat Nov 02 11:49:26 CET 2013
all.tcl:        Total        21        Passed        18        Skipped        3        Failed        0

 # Good, but in a tclsh, "tcl.h" cannot be found. tcc::dir already points at /usr/lib/tcc0.4. So:
suchenwi@suchenwi-NC10:~/tcltcc$ sudo cp -r include/ /usr/lib/tcc0.4/
suchenwi@suchenwi-NC10:~/tcltcc$ sudo cp -r lib /usr/lib/tcc0.4/

suchenwi@suchenwi-NC10:~/tcltcc$ rlwrap -c tclsh
% package require tcc
0.4
% # There must be a compiler instance
% tcc $tcc::dir tcc1
% # And now, finally...
% tcc::cproc mul {int a int b} int {return a*b;}
% mul 6 7
42

Phew! :^D

damkerngt 2013-11-05 - Here are similar fixes as RS's version above for MinGW and Ubuntu, but in a more batch-like fashion:

MinGW (assuming ActiveTcl 8.5 installed in c:/Tcl85):

 configure --with-tcl=/c/tcl85/lib
 sed -i '1176 i\
 TCC_OUTPUT_OBJ == st->output_type || ' generic/win32/tccpe.c
 sed -i 's/tcc02.dll/tcc04.dll/' tcc.tcl
 rm tcc.o 
 make install
 cp tcc.tcl /c/tcl85/lib/tcc0.4/
 cp -pR include /c/tcl85/lib/tcc0.4/include
 cp -pR lib /c/tcl85/lib/tcc0.4/lib

NOTE: That fix on line 1176 in tccpe.c isn't necessary, unless you want to generate .o file from tcltcc.

Ubuntu 12.04:

 sh configure --with-tcl=/usr/lib/tcl8.5
 sed -i 's/libtcc0.2.so/libtcc0.4.so/' tcc.tcl
 rm tcc.o
 make
 sudo make install
 sudo cp tcc.tcl /usr/lib/tcc0.4/
 sudo cp -pR include /usr/lib/tcc0.4/include
 sudo cp -pR lib /usr/lib/tcc0.4/lib
 sudo ln -s /usr/include/i386-linux-gnu/bits /usr/include/
 sudo ln -s /usr/include/i386-linux-gnu/sys /usr/include/
 sudo ln -s /usr/include/i386-linux-gnu/gnu /usr/include/

Usage

tcltcc has a single command tcc to create a compiler instance:

tcc tcc_library_path ?output_type? handle

A good default library_path is in the variable $::tcc::dir. Output_type defaults to memory, if not given, and can be one of:

memory
exe
dll
obj
preprocess

handle is a string provided by the user to name this instance

Once you have an instance (e.g. h), it accepts the following methods:

h add_include_path path
h add_file filename
h add_library filename
h add_library_path path
h add_symbol
h command tclname cname
create a Tcl command tclname which calls cname
h compile code
this is the main action, can only be called once per instance
h define symbol value
similar to #define
h get_symbol
h output_file filename
write DLL or EXE file
h undefine symbol
similar to #undef

To delete a tcc instance:

rename h {}

In addition, there's a scripted layer on top of these that emulates part of the Critcl API, for in-memory compilation:

tcc::ccode code
keeps the code buffered for the following compilations, until tcc::reset.
tcc::cproc name argl rtype body
Creates code to implement a Tcl command name with typed arguments argl of C return type rtype with the specified C body, and compiles and registers it.
tcc::reset
Clears all code that has been buffered by calls to tcc::ccode

Example: Compile to Memory

The first (and pretty unique) use case for tcc is that it can compile directly into memory, even in an interactive session. Example:

~ $ tclsh
% packa re tcc
0.2
% tcc::cproc sigid {int i} char* {return Tcl_SignalId(i);}
% sigid 4
SIGILL

<tcl.h> is always included, so if you run into an interesting C function there, it's evidently extremely easy to wrap it up and try it out. Like in Odyce (which also builds on tcc), even simple things can substantially reduce runtime if done in C:

% tcc::cproc cadd {double a double b} double {return a+b;}
% proc tadd {a b} {expr {$a+$b}}
% time {cadd 1.2 3.4} 1000
19.777 microseconds per iteration
% time {tadd 1.2 3.4} 1000
43.138 microseconds per iteration

Simple API for building DLLs

RS 2007-10-13: In the last few days, tcltcc has added the ability to build shared libraries (currently only DLLs for Windows, tested on Windows 95). Here's a cute and simple API for that:

Prepares the making of a DLL. Name is generated if not given, and in any case returned:

package require tcc
set n [tcc::dll ?name?]

Add the string (which can be many lines) to the source buffer. Useful for #include/#define etc. preprocessor directives, static internal functions, etc:

$n ccode string

Creates code to implement a Tcl command name with typed arguments argl of C return type rtype with the specified C body, and appends that to the source buffer:

$n cproc name argl rtype body

Produce the DLL $path/$name[info sharedlibextension] by compiling the source buffer, creating an Init function which registers the commands as specified by cproc calls, and optionally adding the initialization code in string. After this call, no other ccode/cproc/write calls are useful.

$n write ?-name str -dir path -code string?

Working example (from the test suite):

test tcc-10.3 "new DLL interface" {
    set d [tcc::dll]
    $d ccode {static int fib(int n) {return n <= 2? 1 : fib(n-1) + fib(n-2);}}
    $d cproc fiboy {int n} int   {return fib(n);}
    $d cproc hello {}      char* {return "world";}
    $d write -name fiboy -code {Tcl_Eval(interp,"puts {hello Fiboy!}");}
    load fiboy[info sharedlibextension]
    list [fiboy 20] [hello]
} {6765 world}

For introspection and debugging, no cleanup takes place yet. You can see the generated code with

set tcc::dll::${d}::code

Ah, tcc is great fun... :^) - In the Tcl chatroom, Gerald Lester asked for the converse functionality: wrap Tcl code into a C function that relieves the user of explicit Tcl_Eval. See Tcl to C functions

Building executables

Before there is a simple API like the one for DLLs above, the following session transcript shows how to build and test an .exe main program pedestrianly:

% tcc . exe t
% t add_file c/crt1.c
% t compile {int main(int argc,char*argv[]){printf("hello world %d\n",argc);return(0);}}
% t output_file hello.exe
% exec hello.exe a b c
hello world 4
%

Well, that was a dirt simple executable. How about building a complete tclsh with an extra [square] command? That's takes about 16 lines:

test tcc-9.2  {a little tclsh} {
    set code [tcc::wrapCmd square {double x} double x_square {return x*x;}]
    append code {
        int AppInit(Tcl_Interp *interp) {
            Tcl_CreateObjCommand(interp,"square",x_square,NULL,NULL);
            return Tcl_Init(interp);
        }
        int main(int argc, char *argv[]) {
            Tcl_Main(argc, argv, AppInit);
            return 0;
        }
    }
    tcc $::tcc::dir exe t
    t add_file    $::tcc::dir/c/crt1.c
    t add_library tcl8.5
    t compile     $code
    t output_file mytclsh.exe
    exec mytclsh.exe {<<puts [square 5]}
} 25.0

For the record: mytclsh.exe is just 2KB, but seems to inherit all packages etc. from my Tcl 8.5 installation... looks good, generally.


RS 2007-10-15: current tcltcc passes all tests (tcc.test, pingpong.test) on W95 and Win XP.


RLH 2008-02-22: The current tcc doesn't work on OSX for 8.5.1:

Main console display active (Tcl8.5.1 / Tk8.5.1)
(robert) 37 % package require tcc
image not found 
NSCreateObjectFileImageFromFile() error: not a Mach-O MH_BUNDLE file
(robert) 38 % 

I installed it via teacup on my Intel Mac...