aboutsummaryrefslogtreecommitdiff
path: root/make-c-ext.tcl
blob: 29f11072d34fc786f44c6d5aa775dd9018239e3b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/usr/bin/env tclsh

# Usage: make-c-ext.tcl source.tcl >jim-source.c

# Converts a Tcl source file into C source suitable
# for loading as a static extension.

lassign $argv source

if {![string match *.tcl $source]} {
	error "Source $source is not a .tcl file"
}

# Read the Tcl source and convert to C
# Note that no lines are removed in order to preserve line numbering
set sourcelines {}
set f [open $source]
while {[gets $f buf] >= 0} {
	# Remove comment lines
	regsub {^[ \t]*#.*$} $buf "" buf
	# Escape quotes and backlashes
	set buf [string map [list \\ \\\\ \" \\"] $buf]
	lappend sourcelines \"$buf\\n\"
}
close $f

lappend lines {/* autogenerated - do not edit */}
lappend lines {#include <jim.h>}
lappend lines "static const char basename\[\] = \"[file tail $source]\";"
lappend lines "static const char pkgname\[\] = \"[file rootname [file tail $source]]\";"

lappend lines {static const char source[] = }
lappend lines {*}$sourcelines \;

lappend lines "int Jim_[file rootname [file tail $source]]Init(Jim_Interp *interp)"
lappend lines \
{{
	if (Jim_PackageProvide(interp, pkgname, "1.0", JIM_ERRMSG)) return JIM_ERR;
	return Jim_Eval_Named(interp, source, basename, 1);
}}

puts [join $lines \n]