critcl(3tcl) | C Runtime In Tcl (CriTcl) | critcl(3tcl) |
critcl - Critcl - Package Reference
package require Tcl 8.4
package require critcl ?3.1.18?
package require platform ?1.0.2?
package require md5 ?2?
::critcl::ccode fragment
::critcl::ccommand tclname cname
::critcl::ccommand tclname arguments body ?option value...?
::critcl::cdata tclname data
::critcl::cconst tclname resulttype value
::critcl::cdefines list of glob patterns ?namespace?
::critcl::cproc name arguments resulttype body ?option value...?
::critcl::cproc name arguments resulttype
::critcl::cinit text externals
::critcl::include path
::critcl::api import name version
::critcl::api function resulttype name arguments
::critcl::api header ?glob pattern...?
::critcl::api extheader ?file...?
::critcl::license author ?text...?
::critcl::summary text
::critcl::description text
::critcl::subject ?key...?
::critcl::meta key ?word...?
::critcl::meta? key
::critcl::buildrequirement script
::critcl::cheaders ?arg...?
::critcl::csources ?glob pattern...?
::critcl::clibraries ?glob pattern...?
::critcl::source glob pattern
::critcl::tsources glob pattern...
::critcl::owns glob pattern...
::critcl::cflags ?arg...?
::critcl::ldflags ?arg...?
::critcl::framework ?arg...?
::critcl::tcl version
::critcl::tk
::critcl::preload lib...
::critcl::debug area...
::critcl::check ?label? text
::critcl::checklink ?label? text
::critcl::msg ?-nonewline? msg
::critcl::print ?-nonewline? ?chan? msg
::critcl::compiled
::critcl::compiling
::critcl::done
::critcl::failed
::critcl::load
::critcl::config option ?val?
::critcl::cache ?path?
::critcl::clean_cache ?pattern...?
::critcl::readconfig path
::critcl::showconfig ?chan?
::critcl::showallconfig ?chan?
::critcl::chooseconfig target ?nomatcherr?
::critcl::setconfig target
::critcl::actualtarget
::critcl::buildforpackage ?flag?
::critcl::cnothingtodo file
::critcl::cresults ?file?
::critcl::crosscheck
::critcl::error msg
::critcl::knowntargets
::critcl::sharedlibext
::critcl::targetconfig
::critcl::buildplatform
::critcl::targetplatform
::critcl::cobjects ?glob pattern...?
::critcl::scan path
::critcl::name2c name
::critcl::argnames arguments
::critcl::argcnames arguments
::critcl::argcsignature arguments
::critcl::argvardecls arguments
::critcl::argconversion arguments ?n?
::critcl::argoptional arguments
::critcl::argdefaults arguments
::critcl::argsupport arguments
::critcl::userconfig define name description type ?default?
::critcl::userconfig query name
::critcl::userconfig set name value
::critcl::at::caller
::critcl::at::caller offset
::critcl::at::caller offset level
::critcl::at::here
::critcl::at::get*
::critcl::at::get
::critcl::at::= file line
::critcl::at::incr n...
::critcl::at::incrt str...
::critcl::at::caller!
::critcl::at::caller! offset
::critcl::at::caller! offset level
::critcl::at::here!
::critcl::collect_begin
::critcl::collect_end
::critcl::collect script
::critcl::make path contents
::critcl::has-resulttype name
::critcl::resulttype name body ?ctype?
::critcl::resulttype name = origname
::critcl::has-argtype name
::critcl::argtype name body ?ctype? ?ctypefun?
::critcl::argtype name = origname
::critcl::argtypesupport name code ?guard?
::critcl::argtyperelease name code
::preload library
C Runtime In Tcl, or CriTcl , is a system for compiling C code embedded in Tcl on the fly and either loading the resulting objects into Tcl for immediate use or packaging them for distribution. Use CriTcl to improve performance by rewriting in C those routines that are performance bottlenecks.
The critcl package is the core of the system. For an overview of the complete system, see Introduction To CriTcl. For the usage of the standalone critcl program, see CriTcl Application. This core package maybe be used to embed C code into Tcl scripts. It also provides access to the internals that other parts of the core use and which are of interest to those wishing to understand the internal workings of the core and of the API it provides to the CriTcl Application. These advanced sections are marked as such so that those simply wishing to use the package can skip them.
This package resides in the Core Package Layer of CriTcl.
+----------------+ |Applications | | critcl | | critcl::app | +----------------+ *================* |Core Packages | | critcl | | critcl::util | *================* +----------------+ |Support Packages| | stubs::* | | md5, platform | | ... | +----------------+
A short note ahead of the documentation: Instead of repeatedly talking about "a Tcl script with embbedded C code", or "a Tcl script containing Critcl commands", we call such a script a Critcl script. A file containing a Critcl script usually has the extension .tcl or .critcl.
The following commands append C code fragments to the current module. Fragments appear in the module in the order they are appended, so the earlier fragments (variables, functions, macros, etc.) are visible to later fragments.
aguments is a list of zero to four names for the standard arguments clientdata, interp, objc, and objv. The standard default names are used in place of any missing names. This is a more low-level way than critcl::cproc to define a command, as processing of the items in objv is left to the author, affording complete control over the handling of the arguments to the command. See section Runtime Behaviour.
Returns the empty string.
Each option may be one of:
Returns the empty string.
cproc $tclname {} $resulttype "return $value ;"
This is more efficient than critcl::cproc since there is no C function generated.
Returns the empty string.
The Tcl variables are created when the module is compiled, using the preprocessor in order to properly find all matching C definitions.
Produces no C code. The desired C definitions must already exist.
Returns the empty string.
Critcl type | C type | Tcl type | Notes ------------- | -------------- | --------- | ------------------------------ void | n/a | n/a | Always OK. Body sets result ok | int | n/a | Result code. Body sets result ------------- | -------------- | --------- | ------------------------------ int | int | Int | boolean | | | Alias of int above bool | | | Alias of int above long | long | Long | wideint | Tcl_WideInt | WideInt | double | double | Double | float | float | Double | ------------- | -------------- | --------- | ------------------------------ char* | char* | String | Makes a copy vstring | | | Alias of char* above const char* | const char* | | Behavior of char* above ------------- | -------------- | --------- | ------------------------------ string | | String | Freeable string set directly
| | | No copy is made dstring | | | Alias of string above ------------- | -------------- | --------- | ------------------------------
| | | For all below: Null is ERROR
| | | Body has to set any message Tcl_Obj* | Tcl_Obj* | Any | refcount -- object | | | Alias of Tcl_Obj* above Tcl_Obj*0 | | Any | refcount unchanged object0 | | | Alias of Tcl_Obj*0 above ------------- | -------------- | --------- | ------------------------------ known-channel | Tcl_Channel | String | Assumes to already be registered new-channel | Tcl_Channel | String | New channel, will be registered
Note that setting an error message requires the function body to have access to the interpreter the function is running in. See the argument type Tcl_Interp* for the details on how to make that happen.
Note further that the returned Tcl_Obj* should have a reference count greater than 0. This is because the converter decrements the reference count to release possession after setting the interpreter result. It assumes that the function incremented the reference count of the returned Tcl_Obj*. If a Tcl_Obj* with a reference count of 0 were returned, the reference count would become 1 when set as the interpreter result, and immediately thereafter be decremented to 0 again, causing the memory to be freed. The system is then likely to crash at some point after the return due to reuse of the freed memory.
Note that setting an error message requires the function body to have access to the interpreter the function is running in. See the argument type Tcl_Interp* for the details on how to make that happen.
int x int y
Each argument name must be a valid C identifier.
If the name is a list containing two items, the first item is the name and the second item is the default value. A limited form of variadic arguments can be accomplished using such default values. For example:
int {x 1}
Argument conversion is completely bypassed when the argument is not provided, so a custom converter doing validation does not get the chance to validate the default value. In this case, the value should be checked in the body of the function.
Each argument type may be one of the following predefined types or a custom type. For the latter see Advanced: Extending cproc. Before going into the details first a quick overview:
Critcl type | C type | Tcl type | Notes ----------- | -------------- | --------- | ------------------------------ Tcl_Interp* | Tcl_Interp* | n/a | Special, only first ----------- | -------------- | --------- | ------------------------------ Tcl_Obj* | Tcl_Obj* | Any | Read-only object | | | Alias of Tcl_Obj* above list | critcl_list | List | Read-only ----------- | -------------- | --------- | ------------------------------ char* | const char* | Any | Read-only, string rep pstring | critcl_pstring | Any | Read-only bytes | critcl_bytes | ByteArray | Read-only ----------- | -------------- | --------- | ------------------------------ int | int | Int | long | long | Long | wideint | Tcl_WideInt | WideInt | double | double | Double | float | float | Double | ----------- | -------------- | --------- | ------------------------------ X > 0 | | | For X in int ... float above. X >= 0 | | | C types as per the base type X. X < 0 | | | Allowed argument values are X <= 0 | | | restricted as per the shown X > 1 | | | relation X >= 1 | | | X < 1 | | | This is not a general mechanism X <= 1 | | | open to other values. Only 0/1. ----------- | -------------- | --------- | ------------------------------ boolean | int | Boolean | bool | | | Alias of boolean above ----------- | -------------- | --------- | ------------------------------ bytearray | | | DEPRECATED rawchar | | | DEPRECATED rawchar* | | | DEPRECATED double* | | | DEPRECATED float* | | | DEPRECATED int* | | | DEPRECATED void* | | | DEPRECATED
When used, the argument will contain a reference to the current interpreter that the function body may use. Furthermore the argument will not be an argument of the Tcl command for the function.
This is useful when the function has to do more than simply returning a value. Examples would be setting up error messages on failure, or querying the interpreter for variables and other data.
typedef struct critcl_pstring {
Tcl_Obj* o;
const char* s;
int len; } critcl_pstring;
typedef struct critcl_list {
Tcl_Obj* o;
Tcl_Obj* const* v;
int c; } critcl_list;
Note the const. The list is read-only. Any modification can have arbitrary effects, from pulling out the rug under the script because of string value and internal representation not matching anymore, up to crashes anytime later.
Attention: These types are considered DEPRECATED. It is planned to remove their documentation in release 3.2, and their implementation in release 3.3. Their deprecation can be undone if good use cases are shown.
The function takes an argument of type critcl_bytes containing the original Tcl_Obj* reference of the Tcl argument, plus the length of the byte array and a pointer to the byte data.
typedef struct critcl_bytes {
Tcl_Obj* o;
const unsigned char* s;
int len; } critcl_list;
Note the const. The bytes are read-only. Any modification can have arbitrary effects, from pulling out the rug under the script because of string value and internal representation not matching anymore, up to crashes anytime later.
Note the const. The string is read-only. Any modification can have arbitrary effects, from pulling out the rug under the script because of string value and internal representation not matching anymore, up to crashes anytime later.
Beyond that the channel must not be shared by multiple interpreters, an error is thrown otherwise.
Beyond that the code removes the channel from the current interpreter without closing it, and disables all pre-existing event handling for it.
With this the function takes full ownership of the channel in question, taking it away from the interpreter invoking it. It is then responsible for the lifecycle of the channel, up to and including closing it.
Should the system the function is a part of wish to return control of the channel back to the interpeter it then has to use the result type return-channel. This will undo the registration changes made by this argument type. Note however that the removal of pre-existing event handling done here cannot be undone.
Attention Removal from the interpreter without closing the channel is effected by incrementing the channel's reference count without providing an interpreter, before decrementing the same for the current interpreter. This leaves the overall reference count intact without causing Tcl to close it when it is removed from the interpreter structures. At this point the channel is effectively a globally-owned part of the system not associated with any interpreter.
The complementary result type then runs this sequence in reverse. And if the channel is never returned to Tcl either the function or the system it is a part of have to unregister the global reference when they are done with it.
Attention: These types are considered DEPRECATED. It is planned to remove their documentation in release 3.2, and their implementation in release 3.3. Their deprecation can be undone if good use cases are shown.
The C code in text is placed into the body of the initialization function of the shared library backing the Critcl script, and is executed when this library is loaded into the interpreter. It has access to the variable Tcl_Interp* interp referencing the Tcl interpreter currently being initialized.
externals is placed outside and just before the initialization function, making it a good place for any external symbols required by initialization function, but which should not be accessible by any other parts of the C code.
Calls to this command are cumulative.
Returns the empty string.
critcl::code {
#include <${path}> }
Critcl versions 3 and later provide critcl::api to create and manipulate stubs tables, Tcl's dynamic linking mechanism handling the resolution of symbols between C extensions. See http://wiki.tcl-lang.org/285 for an introduction, and section Stubs Tables for the details of Critcl's particular variant.
Importing stubs tables, i.e. APIs, from another extension:
Important: If name is a fully-qualified name in a non-global namespace, e.g. "c::stack", the namespace separators "::" are converted into underscores ("_") in path names, C code, etc.
name/nameDecls.h contains the stubs table type declarations, mapping macros, etc., and may include package-specific headers. See critcl::api header, below. An #include directive is added at the beginning of the generated code for Critcl script and at the beginning of each of its companion ".c" files.
name/nameStubLib.h contains the stubs table variable definition and the function to initialize it. An #include directive for it is added to the initialization code for the Critcl script , along with a call to the initializer function.
If "name/name.decls" accompanies name/nameDecls.h, it should contain the external representation of the stubs table used to generate the headers. The file is read and the internal representation of the stubs table returned for use by the importing package. Otherwise, the empy string is returned.
One possible use would be the automatic generation of C code calling on the functions listed in the imported API.
When generating a TEA package the names of the imported APIs are used to declare configure options with which the user can declare a non-standard directory for the headers of the API. Any API name is translated into a single configure option --with-name-include.
Declaration and export of a stubs table, i.e. API, for the Critcl script:
arguments is a multidict where each key is an argument type and its value is the argument name, and resulttype is a C type.
A pattern for a relative path is resolved relative to the directory containing the Critcl script.
As with the headers for an imported API, an #include directive is added to the generated code for the Critcl script and to each companion ".c" file.
In "compile & run" mode the generated header files and any companion headers are placed in the Result Cache subdirectory for the Critcl script. This directory is added to the include search path of any other package importing this API and and building in mode "compile & run".
In "generate package" mode -includedir specifies the subdirectory in the package to place the generated headers in. This directory is added to the search paths for header files, ensuring that a package importing an API finds it if the package exporting that API used the same setting for -includedir.
In "generate TEA" mode the static scanner recognizes critcl::api header as a source of companion files. It also uses data from calls to critcl::api import to add support for --with-foo-include options into the generated "configure(.in)" so that a user may specify custom locations for the headers of any imported API.
Critcl versions 3 and later can create TEApot meta-data to be placed into "teapot.txt" in a format suitable for use by the TEApot tools [http://docs.activestate.com/activetcl/8.5/tpm/toc.html].
In version 2, some meta data support was already present through ::critcl::license, but this was only used to generate "license.txt".
In "generate package" mode provides information about the author of the package and the license for the package.
text arguments are concatenated to form the text of the license, which is written to "license.terms" in the same directory as "pkgIndex.tcl". If no text is provided the license is read from "license.terms" in the same directory as the Critcl script.
This information takes precedence over any information specified through the generic API ::critcl::meta. It is additionally placed into the meta data file "teapot.txt" under the keys as::author and license.
In "generate package" mode places a short, preferably one-line description of the package into the meta data file "teapot.txt" under the key summary. This information takes precedence over information specified through the generic API ::critcl::meta.
In "generate package" mode places a longer description of the package into the meta data file "teapot.txt", under the key description. The data specified by this command takes precedence over any information specified through the generic API ::critcl::meta.
In "generate package" mode places each key into the meta data file "teapot.txt", under the key subject. This information takes precedence over any information specified through the generic API ::critcl::meta.
Calls to this command are cumulative.
While it is possible to declare information for one of the reserved keys with this command such data is ignored when the final meta data is assembled and written.
Use the commands ::critcl::license, ::critcl::summary, ::critcl::description ::critcl::subject, package require, and package provide to declare data for the reserved keys.
The information for the reserved keys as::build::date and platform is automatically generated by critcl itself.
Used primarily to retrieve the name of the package from within utility packages having to adapt C code templates to their environment. For example, critcl::class uses does this.
These commands control the details of compilation and linking a Critcl script. The information is used only to compile/link the object for the Critcl script. For example, information for "FOO.tcl" is kept separate from information for "BAR.tcl".
Each argument is a glob pattern. If an argument begins with - it is an argument to the compiler. Otherwise the parent directory of each matching path is a directory to be searched for header files. Returns an error if a pattern matches no files. A pattern for a relative path is resolved relative to the directory containing the Critcl script.
#include lines are not automatically generated for matching header files. Use critcl::include or critcl::ccode as necessary to add them.
Calls to this command are cumulative.
Calls to this command are cumulative.
Calls to this command are cumulative.
Matching paths are made available to the generated shared library when it is loaded for the current Critcl script. Returns an error if a pattern matches no files. A pattern for a relative path is resolved relative to the directory containing the Critcl script.
Calls to this command are cumulative.
After the shared library has been loaded, the declared files are sourced in the same order that they were provided as arguments.
Each arg is an argument to the compiler.
Calls to this command are cumulative.
Each arg is an argument to the linker.
Calls to this command are cumulative.
Calls to this command are cumulative.
Calls to this command are cumulative.
Each library FOO is searched for in the directories listed below, in the order listed. The search stops at the first existing path. Additional notes:
The following commands control compilation and linking.
For example, the newest revisions of Kettle [https://chiselapp.com/user/andreas_kupries/repository/Kettle/index] use this to highlight build warnings.
Enables a Critcl script used as its own Tcl companion file (see critcl::tsources) to distinguish between being sourced for compilation in compile & run mode and being sourced from either the result of generate package mode or during the load phase of compile & run mode. The result is false in the first case and true in the later two cases.
See also Modes Of Operation/Use.
The following command manages global settings, i.e. configuration options which are independent of any Critcl script.
This command should not be needed to write a Critcl script. It is a management command which is only useful to the CriTcl Application or similar tools.
This facility requires the use of a tclsh that provides info frame. Otherwise, no #line directives are emitted. The command is supported by Tcl 8.5 and higher. It is also supported by Tcl 8.4 provided that it was compiled with the define -DTCL_TIP280. An example of such is ActiveState's ActiveTcl.
Developers of higher-level packages generating their own C code, either directly or indirectly through critcl, should also read section Advanced: Location management to see how critcl helps them in generating their directives. Examples of such packages come with critcl itself. See critcl::iassoc and critcl::class.
The following commands control the Result Cache. These commands are not needed to simply write a Critcl script.
The default location is "~/.critcl/[platform::generic]" and usually does not require any changes.
The following commands manage the build configuration, i.e. the per-platform information about compilers, linkers, and their commandline options. These commands are not needed to simply write a Critcl script.
The following commands provide tools like CriTcl Application or similar with deeper access to the package's internals. These commands are not needed to simply write a Critcl script.
A pattern for a relative path is resolved relative to the directory containing the Critcl script.
Calls to this command are cumulative.
Scans path and returns a dictionary containing the following items:
For use by utilities that provide Tcl commands without going through standard commands like critcl::ccommand or critcl::cproc. critcl::class does this.
For advanced use, the following commands used by critcl::cproc itself are exposed.
The generated code assumes that the procedure arguments start at index n of the objv array. The default is 1.
This package provides one command for the management of package-specific, i.e. developer-specified custom build configuration options.
The type can be either bool, or a list of values.
The description serves as in-code documentation of the meaning of the option and is otherwise ignored. When generating a TEA wrapper the description is used for the configure option derived from the option declared by the command.
A boolean option FOO are translated into a pair of configure options, --enable-FOO and --disable-FOO, whereas an option whose type is a list of values is translated into a single configure option --with-FOO.
It is at this point that definitions and set values are brought together, with the latter validated against the definition.
At the time this command is used only the association between option name and value is recorded, and nothing else is done. This behaviour is necessary as the system may not know if an option of the specified name exists when the command is invoked, nor its type.
Any and all validation is defered to when the value of an option is asked for via ::critcl::userconfig query.
This means that it is possible to set values for any option we like, and the value will take effect only if such an option is both defined and used later on.
First a small introduction for whose asking themselves ´what is location management' ?
By default critcl embeds #line directives into the generated C code so that any errors, warnings and notes found by the C compiler during compilation will refer to the ".critcl" file the faulty code comes from, instead of the generated ".c" file.
This facility requires the use of a tclsh that provides info frame. Otherwise, no #line directives are emitted. The command is supported by Tcl 8.5 and higher. It is also supported by Tcl 8.4 provided that it was compiled with the define -DTCL_TIP280. An example of such is ActiveState's ActiveTcl.
Most users will not care about this feature beyond simply wanting it to work and getting proper code references when reading compiler output.
Developers of higher-level packages generating their own C code however should care about this, to ensure that their generated code contains proper references as well. Especially as this is key to separating bugs concerning code generated by the package itself and bug in the user's code going into the package, if any.
Examples of such packages come with critcl itself, see the implementation of packages critcl::iassoc and critcl::class.
To help such developers eight commands are provided to manage such location information. These are listed below.
A main concept is that they all operate on a single stored location, setting, returning and clearing it. Note that this location information is completely independent of the generation of #line directives within critcl itself.
In terms of ::critcl::at::caller this is equivalent to
critcl::at::caller 0 1
For proper nesting and use it is recommended that such directives are always added to the beginning of a code fragment. This way, should deeper layers add their own directives these will come before ours and thus be inactive. End result is that the outermost layer generating a directive will 'win', i.e. have its directive used. As it should be.
Diversions are for higher-level packages generating their own C code, to make their use of critcl's commands generating Embedded C Code easier.
These commands normally generate all of their C code for the current ".critcl" file, which may not be what is wanted by a higher-level package.
With a diversion the generator output can be redirected into memory and from there on then handled and processed as the caller desires before it is committed to an actual ".c" file.
An example of such a package comes with critcl itself, see the implementation of package critcl::class.
To help such developers three commands are provided to manage diversions and the collection of C code in memory. These are:
The result of the command is the empty string.
Multiple calls are allowed, with each call opening a new nesting level of diversion.
If multiple levels of diversion are open the call only closes and returns the data from the last level.
The command will throw an error if no diversion is active, indicating a mismatch in the pairing of collect_begin and collect_end.
While file generation is related to the diversions explained in the previous section they are not the same. Even so, like diversions this feature is for higher-level packages generating their own C code.
Three examples of utility packages using this facility comes with critcl itself. See the implementations of packages critcl::literals, critcl::bitmap, and critcl::enum.
When splitting a package implementation into pieces it is often sensible to have a number of pure C companion files containing low-level code, yet these files may require information about the code in the main ".critcl" file. Such declarations are normally not exportable and using the stub table support does not make sense, as this is completely internal to the package.
With the file generation command below the main ".critcl" file can generate any number of header files for the C companions to pick up.
The generated file will contain the specified contents.
While the critcl::cproc command understands the most common C types (see section Embedded C Code), sometimes this is not enough.
To get around this limitation the commands in this section enable users of critcl to extend the set of argument and result types understood by critcl::cproc. In other words, they allow them to define their own, custom, types.
If name is already declared an error is thrown. Attention! The standard result type void is special as it has no accompanying result variable. This cannot be expressed by this extension command.
The body's responsibility is the conversion of the functions result into a Tcl result and a Tcl status. The first has to be set into the interpreter we are in, and the second has to be returned.
The C code of body is guaranteed to be called last in the wrapper around the actual implementation of the cproc in question and has access to the following environment:
resulttype int { Tcl_SetObjResult(interp, Tcl_NewIntObj(rv)); return TCL_OK;
}
resulttype ok { /* interp result must be set by cproc body */ return rv;
} int
If name is already declared an error is thrown.
body is a C code fragment that converts a Tcl_Obj* into a C value which is stored in a helper variable in the underlying function.
body is called inside its own code block to isolate local variables, and the following items are in scope:
argtype int { if (Tcl_GetIntFromObj(interp, @@, &@A) != TCL_OK) return TCL_ERROR;
}
argtype float { double t; if (Tcl_GetDoubleFromObj(interp, @@, &t) != TCL_OK) return TCL_ERROR; @A = (float) t;
}
CriTcl can be used in three different modes of operation, called
Compile & Run was the original mode and is the default for critcl_pkg. Collects the C fragments from the Critcl script, builds them as needed, and caches the results to improve load times later.
The second mode, Generate Package, was introduced to enable the creation of (prebuilt) deliverable packages which do not depend on the existence of a build system, i.e. C compiler, on the target machine. This was originally done through the experimental Critbind tool, and is now handled by the CriTcl Application, also named critcl.
Newly introduced with Critcl version 3 is Generate TEA Package. This mode constructs a directory hierarchy from the package which can later be built like a regular TEA package, i.e. using
.../configure --prefix ... make all isntall
Regarding the caching of results please read the section about the Result Cache fore more details.
The default behaviour of critcl, the package is to defer the compilation, linking, and loading of any C code as much as possible, given that this is an expensive operation, mainly in the time required. In other words, the C code embedded into a ".critcl" file is built only when the first C command or procedure it provides is invoked. This part of the system uses standard functionality built into the Tcl core, i.e. the auto_index variable to map from commands to scripts providing them and the unknown command using this information when the command is needed.
A limitation of this behaviour is that it is not possible to just use info commands check for the existence of a critcl defined command. It is also necessary to search in the auto_index array, in case it has not been build yet.
This behaviour can be changed by using the control command critcl::load. When invoked, the building, including loading of the result, is forced. After this command has been invoked for a ".critcl" file further definition of C code in this file is not allowed any longer.
Each ".critcl" file is backed by a single private ".c" file containing that code, plus the boilerplate necessary for its compilation and linking as a single shared library.
The Embedded C Code fragments appear in that file in the exact same order they were defined in the ".critcl" file, with one exception. The C code provided via critcl::cinit is put after all other fragments. In other words all fragments have access to the symbols defined by earlier fragments, and the critcl::cinit fragment has access to all, regardless of its placement in the ".critcl" file.
Note: A limitation of the current system is the near impossibility of C level access between different critcl-based packages. The issue is not the necessity of writing and sharing the proper extern statements, but that the management (export and import) of package-specific stubs-tables is not supported. This means that dependent parts have to be forcibly loaded before their user, with all that entails. See section Runtime Behaviour for the relevant critcl limitation, and remember that many older platforms do not support the necessary resolution of symbols, the reason why stubs were invented for Tcl in the first place.
The compilation of C code is time-consuming critcl not only defers it as much as possible, as described in section Runtime Behaviour, but also caches the results.
This means that on the first use of a ".critcl" file "FOO.tcl" the resulting object file and shared library are saved into the cache, and on future uses of the same file reused, i.e. loaded directly without requiring compilation, provided that the contents of "FOO.tcl" did not change.
The change detection is based MD5 hashes. A single hash is computed for each ".critcl" file, based on hashes for all C code fragments and configuration options, i.e. everything which affects the resulting binary.
As long as the input file doesn't change as per the hash a previously built shared library found in the cache is reused, bypassing the compilation and link stages.
The command to manage the cache are found in section Result Cache Management. Note however that they are useful only to tools based on the package, like the CriTcl Application. Package writers have no need of them.
As a last note, the default directory for the cache is chosen based on the chosen build target. This means that the cache can be put on a shared (network) filesystem without having to fear interference between machines of different architectures.
The audience of this section are developers wishing to understand and possibly modify the internals of critcl package and application. Package writers can skip this section.
It explains how the preloading of external libraries is realized.
Whenever a package declares libraries for preloading critcl will build a supporting shared library providing a Tcl package named "preload". This package is not distributed separately, but as part of the package requiring the preload functionality. This support package exports a single Tcl command
On windows the command will further use the Tcl command ::critcl::runtime::precopy to copy the library to the disk, should its path be in a virtual filesystem which doesn't directly support the loading of a shared library from it.
The command ::critcl::runtime::precopy is provided by the file "critcl-rt.tcl" in the generated package, as is the command ::critcl::runtime::loadlib which generates the ifneeded script expected by Tcl's package management. This generated ifneeded script contains the invocations of ::preload.
The C code for the supporting library is found in the file "critcl_c/preload.c", which is part of the critcl package.
The Tcl code for the supporting runtime "critcl-rt.tcl" is found in the file "runtime.tcl", which is part of the critcl::app package.
The audience of this section are developers wishing to understand and possibly modify the internals of critcl package and application. Package writers can skip this section.
It explains the syntax of configuration files and the configuration keys used by critcl to configure its build backend, i.e. how this part of the system accesses compiler, linker, etc.
It is recommended to open the file containing the standard configurations ("path/to/critcl/Config") in the editor of your choice when reading this section of the documentation, using it as an extended set of examples going beyond the simple defaults shown here.
First, the keys and the meaning of their values, plus examples drawn from the standard configurations distributed with the package. Note that when writing a custom configuration it is not necessary to specify all the keys listed below, but only those whose default values are wrong or insufficient for the platform in question.
gcc -v
gcc -c -fPIC
-DTCL_MEM_DEBUG
-g
-I
-DUSE_TCL_STUBS
-DUSE_TK_STUBS
-DUSE_THREAD_ALLOC=1 -D_REENTRANT=1 -D_THREAD_SAFE=1
-DHAVE_PTHREAD_ATTR_SETSTACKSIZE=1 -DHAVE_READDIR_R=1
-DTCL_THREADS=1
-DNDEBUG
-O2
-o [list $outfile]
NOTE the use of Tcl commands and variables here. At the time critcl uses the value of this key the value of the referenced variable is substituted into it. The named variable is the only variable whose value is defined for this substitution.
.o
gcc -E -dM
gcc -E
gcc -shared
--unresolved-symbols=ignore-in-shared-libs
-Wl,-s
-debug:full -debugtype:cv
-release -opt:ref -opt:icf,3 -ws:aggressive
[info sharedlibextension]
[platform::generic]
The syntax expected from configuration files is governed by the rules below. Again, it is recommended to open the file containing the standard configurations ("path/to/critcl/Config") in the editor of your choice when reading this section of the documentation, using it as an extended set of examples for the syntax>
If the build platform is not a prefix of platform, nor vice versa the whole block is ignored. Otherwise the expression is evaluated via expr, in the same safe interpreter used to run any set and if commands found in the configuration file (see above).
If the expression evaluates to true this configuration block is considered to be the build platform fo the host and chosen as the default configuration. An large example of of this feature is the handling of OS X found in the standard configuration file, where it selects the architectures to build based on the version of the operating system, the available SDK, etc. I.e. it chooses whether the output is universal or not, and whether it is old-style (ix86 + ppc) versus new-style (ix86 32+64) of universality.
The copied values can be overridden later in the configuration file. Multiple copy lines may exist for a platform and be intermixed with normal configuration definitions. Only the last definition of a variable is used.
also wishing to interface with stubs as they are understood and used by critcl, either by exporting their own stubs table to a critcl-based extension, or importing a stubs table of a critcl-based extension into their own.
To this end we describe the stubs table information of a package foo.
critcl is able to use such a file to give the importing package programmatic access to the imported API, for automatic code generation and the like.
These macros must be defined if, and only if, the C preprocessor macro USE_FOO_STUBS is defined. Package foo does not define this macro, as it is allowed to use the exported functions directly. All importing packages however must define this macro, to ensure that they do not use any of the exported functions directly, but only through the stubs table.
A very reduced, yet also complete example, from a package for low-level random number generator functions can be found at the end of this section.
const FooStubs* fooStubsPtr;
char * Foo_InitStubs(Tcl_Interp *interp, CONST char *version, int exact) {
/*
* Boiler plate C code initalizing the stubs table variable,
* i.e. "fooStubsPtr".
*/
CONST char *actualVersion;
actualVersion = Tcl_PkgRequireEx(interp, "foo", version, exact, (ClientData *) &fooStubsPtr);
if (!actualVersion) { return NULL;
}
if (!fooStubsPtr) { Tcl_SetResult(interp, "This implementation of Foo does not support stubs", TCL_STATIC); return NULL;
}
return (char*) actualVersion; }
The importing package's initialization function must further contain a statement like
if (!Foo_InitStubs (ip, "1", 0)) {
return TCL_ERROR; }
For a complete example of such a header file see below, at the end of this section.
IMVHO critcl's approach is simpler, using only header files found in a single location, vs. header files and static library found in multiple, different locations.
A second simplification is that we avoid having to extend critcl's compiler backend with settings for the creation of static libraries.
Below is a complete set of example header files, reduced, yet still complete, from a package for low-level random number generator functions:
#ifndef rng_DECLS_H #define rng_DECLS_H #include <tcl.h> /*
* Exported function declarations:
*/ /* 0 */ EXTERN void rng_bernoulli(double p, int*v); typedef struct RngStubs {
int magic;
const struct RngStubHooks *hooks;
void (*rng_bernoulli) (double p, int*v); /* 0 */ } RngStubs; #ifdef __cplusplus extern "C" { #endif extern const RngStubs *rngStubsPtr; #ifdef __cplusplus } #endif #if defined(USE_RNG_STUBS) /*
* Inline function declarations:
*/ #define rng_bernoulli (rngStubsPtr->rng_bernoulli) /* 0 */ #endif /* defined(USE_RNG_STUBS) */ #endif /* rng_DECLS_H */
/*
* rngStubLib.c --
*
* Stub object that will be statically linked into extensions that wish
* to access rng.
*/ #ifndef USE_TCL_STUBS #define USE_TCL_STUBS #endif #undef USE_TCL_STUB_PROCS #include <tcl.h> #ifndef USE_RNG_STUBS #define USE_RNG_STUBS #endif #undef USE_RNG_STUB_PROCS #include "rngDecls.h" /*
* Ensure that Rng_InitStubs is built as an exported symbol. The other stub
* functions should be built as non-exported symbols.
*/ #undef TCL_STORAGE_CLASS #define TCL_STORAGE_CLASS DLLEXPORT const RngStubs* rngStubsPtr; /*
*----------------------------------------------------------------------
*
* Rng_InitStubs --
*
* Checks that the correct version of Rng is loaded and that it
* supports stubs. It then initialises the stub table pointers.
*
* Results:
* The actual version of Rng that satisfies the request, or
* NULL to indicate that an error occurred.
*
* Side effects:
* Sets the stub table pointers.
*
*----------------------------------------------------------------------
*/ #ifdef Rng_InitStubs #undef Rng_InitStubs #endif char * Rng_InitStubs(Tcl_Interp *interp, CONST char *version, int exact) {
CONST char *actualVersion;
actualVersion = Tcl_PkgRequireEx(interp, "rng", version, exact, (ClientData *) &rngStubsPtr);
if (!actualVersion) { return NULL;
}
if (!rngStubsPtr) { Tcl_SetResult(interp, "This implementation of Rng does not support stubs", TCL_STATIC); return NULL;
}
return (char*) actualVersion; }
See section "Embedding C" in Using CriTcl.
The latest changes are found at the top.
Example: int > 0 is now a viable type name.
This is actually more limited than the description might let you believe.
See the package reference for the details.
Extended critcl::cproc's argument handling to treat an argument args as variadic if it is the last argument of the procedure.
Further fixed the generated header to handle multiple inclusion.
Bumped version to 1.1.
Fixed the generated header to handle multiple inclusion.
Bumped version to 1.0.1.
Note that mode "compile & run" is not as blessed and still uses content-hasing with md5 to ensure unique file names in its per-user object cache.
As part of this the signature of command critcl::name2c changed. The command now delivers a list of four values instead of three. The new value was added at the end.
Further adapted the implementation of package critcl::class, a user of critcl::name2c. This package is now at version 1.0.6 and requires critcl 3.1.6
Lastly fixed the mis-handling of option -cname in critcl::ccommand, and critcl::cproc.
This package simplifies the creation of code associating data with an interpreter via Tcl's Tcl_(Get|Set)AssocData() APIs. The user can concentrate on his data while all the necessary boilerplate C code to support this is generated by the package.
This package uses several of the new features which were added to the core critcl package, see below.
This package simplifies the creation of C level objects with class and instance commands. The user can write a class definition with class- and instance-variables and -methods similar to a TclOO class, with all the necessary boilerplate C code to support this generated by the package.
This package uses several of the new features which were added to the core critcl package, see below.
The new packages critcl::iassoc and critcl::class (see above) are users of this command.
The new package critcl::class (see above) is a user of this command.
See the section Advanced: Diversions for details of the provided commands.
The new package critcl::class (see above) is a user of these facilities.
See the section Advanced: Location management for details of the provided commands.
The new packages critcl::iassoc and critcl::class (see above) are users of these facilities.
See the section Advanced: Extending cproc for details of the provided commands.
This new option, and -pkg, exclude each other. If both are specified the last used option takes precedence.
The generated package directory hierarchy is mostly self-contained, but not fully. It requires not only a working installation of Tcl, but also working installations of the packages md5 and cmdline. Both of these are provided by the Tcllib bundle. Not required, but recommended to have installed are any of the packages which can accelerate md5's operation, i.e. cryptkit, tcllibc, or Trf.
Note that this is a static scan. While the other build modes can (must) execute the ".critcl" file and make platform-specific decisions regarding the assembled C code, companion files, etc. the TEA wrap mode is not in a position to make platform-specific decisions. It has to wrap everything which might conceivably be needed when actually building. Hence the static scan. This has however its own set of problems, namely the inability to figure out any dynamic construction of companion file paths, at least on its own. Thus:
Please see section Stubs Table Management of the critcl package documentation for details.
Please see section Custom Build Configuration of the critcl package documentation for details.
Please see section Package Meta Data of the critcl package documentation for details.
Note that after using critcl::load / critcl::failed in a ".critcl" file it is not possible to use critcl commands in that file anymore. Doing so will throw an error.
Envisioned use is for the reporting of results determined by critcl::check and critcl::checklink during building, to help with debugging when something goes wrong with a check.
Jean Claude Wippler, Steve Landers, Andreas Kupries
This document, and the package it describes, will undoubtedly contain bugs and other problems. Please report them at https://github.com/andreas-kupries/critcl/issues. Ideas for enhancements you may have for either package, application, and/or the documentation are also very welcome and should be reported at https://github.com/andreas-kupries/critcl/issues as well.
C code, Embedded C Code, code generator, compile & run, compiler, dynamic code generation, dynamic compilation, generate package, linker, on demand compilation, on-the-fly compilation
Glueing/Embedded C code
Copyright (c) Jean-Claude Wippler Copyright (c) Steve Landers Copyright (c) 2011-2018 Andreas Kupries
3.1.18 | doc |