JSTcl - Javascript Widget For Tcl Table Of Contents

JSTcl - Javascript Widget For Tcl


package require jstcl
jstcl .path ARGS ?-- JSARGS?

ARGS is currently empty or: -noinit. See the init command.


JSTCL is a javascript widget providing a Tcl interface to the NGS Javascript compiler via the builtin type system. Jstcl provides a class sub-command to support the creation of dynamic objects that pass through control to Tcl. The new subcommand can then be used to create instances. There are also additional subcommands to intercept IO and get step by step control, which can be used to implement step tracing and termination control.

This implementation has been motivated by the desire for JS/DOM support in the BrowseX Web browser. Notwithstanding, there are no internal couplings with either BrowseX or Tkhtml. The dynamic approach used means there is virtually no overhead until DOM objects are actually accessed.

For the most part the design has been to passthru to NGS JS as much as possible, so see that documentation and source code for in depth details. One major difference is that I've extended NGS so that the compiler exists in only the first widget created. This is because the compiler is itself implemented as Byte-compiled Javascript and so would add overhead per-instance.


Tcl does not have types (nor syntax, but that's another matter). Since Javascript requires typing, there are places where we may need or want to specify a type other than string. Following are the type names, each of which we can abbreviate to it's first character.
s | string a character string.
i | integer a whole numerical quantity.
f | float a floating point value
b | boolean a boolean value
a | array an array of values
v | variable type is returned as first element in string: see below

Properties and Method Names

Property and method names are normally specified with just alphanumerics. The type of the Property or return type of the Method will default to string. However you can override this with a colon followed by a type specifier, as above, except you can not use array or class (these require parameters). The :v type means you will return the desired type dynamically, eg: i 99. You must use :v to make an array or class.

Properties/Methods get defined with the NGS attributes Static and Mutable. However, you can change these. by appending a :X where is one of the following lettters:

S | Set Static 1 (default)
D | Set Static 0
I | Set Immutable 1
C | Set Immutable 0 (default)
Here is an example:
   .path class teach  -props {prof:If dunc:bD}

which means prof is a immutable float, dunc is a non-static boolean.


After creating the Jstcl widget, the following commands are available. Many of these commands are named the same as the NGS Javascript equivalents, minus the js_ prefix. Which may help explain apparent inconsistency.

For commands that take switch parameters, you may abbreviate to the shortest unique sequence, usually a single chars after the dash. ie. -l means the same as -lencmd.

.path apply FUNC ARGS

Call function with ARGS. All args are presumed string. There is a limit of 20 args. Use result to get returned value.

NGS JS Equivalence: js_apply

.path apply_typed func ??type arg ?type arg? ...?

Like apply, but args have a type specifier (i, f, s, etc), There is a limit of 10 pairs of args.

NGS JS Equivalence: js_apply + ...

.path array name ARGS

Create an array called name. To ease using jstcl from Tcl, the widget accepts round braces interchangeably with square brackets when referencing array members.
-init {V V V ...} Set of values to initialize array with.
-pairs {T V T V ...} Like above, but with Type/Value pairs.
-datacmd CMD Serves the same purpose as -datacmd in class: See Note.
-lencmd CMD Command to call that returns the array length.
-namecmd CMD Command to call that translates string index to integer.
-type TYPE Specify the type of elements for homogenous array.
-size N Specify the size (for homogenous arrays).
You may call the array command multiple times for a given array to modify/extend it's parameters. The lencmd returns the actual size and will be called when the length property is accessed. The array is sparse until elements are actually accessed, or until you invoke one of the builtin array methods for the array object.

Note: The tag argument is always A for arrays.
When an array is created with a -type of class, all values after the -type argument will be passed to the class command. If no -type is specified, then return from -datacmd is presumed to be variable.

NGS JS Equivalence: js_type_make_array+ ...

.path class NAME ARGS

Creates a class with the supplied methods and properties. ARGS for the class command are as follows:
-props LIST define propertys in list
-datacmd CMD call CMD when property accessed
-meths LIST define methods in list
-funccmd CMD call CMD when javascript method called
You may call class multiple times to add additional methods or properties, or to change the CMDs. Attempts to redefine existing properties or methods are silently ignored. When the propcmd CMD is invoked, 5 arguments are appended: idx isset name val:

pcmd return value

The result returned from pcmd is of the form: type args. This gives the unique ability to instantiate the property. Valid return types are:
string a string value
integer a numeric value
float a floating point value
boolean a boolean value
new followed by a class name, and optionally a tag
array an array, with arguments the same as after NAME in the array command.
link plus the name of the property to link to
undef undefined
Returning the array type invokes the array command above, class invokes the class command, etc. In this fashion, we can dynamically build multileveled objects.


In typical usage, we would seed the widget with the toplevel classes. eg. The following simple docs command defines images as an array of type returned by doci: the class Image.

.path class document -datacmd docs -props form table ul ol dl img a

load ./jstcl.so
proc docs {v idx isset name val} {
  puts "docs: $v $idx $isset $name $val"
  switch $name {
    images {
      return {array -d {doci 36}}

# Instantiate an element in array
proc doci {v idx isset name val} {
  puts "doci: $v $idx $isset $name $val"
  if $isset return
  return {new Image}

proc img {v idx isset name val} {
  global imgvar
  if !$isset [ return $imgvar($name)]
  set imgvar($name) $val

jstcl .j -g
.j class document_class -d {docs 37} -p {forms:v images:v}
.j new document_class document
.j class Image -d {img 0} -p {src name width height border}
.j parse {

  ij=new Image;
This instantiates a document object. When an assignment of the form document.images occurs, doci is called , which dynamically instantiates an Image object.

Note: class assigns a unique handle to each class of the form .jscN where N is a unique integer.

NGS JS Equivalence: js_class_create + ...

.path delclass NAME

Delete named class.

NGS JS Equivalence: js_class_destroy

.path delid ID

Delete object with Jstcl id = ID.

.path destroy

Delete the widget.

.path current

Returns the source code for the current or most recently executed section of code. ie. the code at the program counter.

.path errmsg

Return the error message from the last js error.

NGS JS Equivalence: js_error_message

.path eval STR

Evaluate JS program in str.

NGS JS Equivalence: js_eval

.path eval_data STR

Evaluate JS code in str.

NGS JS Equivalence: js_eval_data

.path eval_file FILE

Evaluate JS code in FILE.

NGS JS Equivalence: js_eval_file

.path eval_javascript_file FILE

Evaluate JS program in file.

NGS JS Equivalence: js_eval_javascript_file

.path execute_byte_code_file FILE

NGS JS Equivalence: js_execute_byte_code_file

.path execute_byte_code STR

NGS JS Equivalence: js_execute_byte_code

.path exechook ?proc ?-count N? ?-compile N? ?-linechange N??

Set/query Tcl procedure to get control during execution, after every -count operands are executed (default 1000). Note the following:

Note: not using exechook will result in a hang if run against the following fragment: while (1);

NGS JS Equivalence: NONE

.path function JSFUNC TCLFUNC

Define a javascrip function jsfunc that upon invocation calls the tcl function tclfunc.

NGS JS Equivalence: js_define_method

.path init JSARGS

Used after -noinit creation and iohook. JSARGS is the same as for the js command. Here they are.
Mandatory arguments to long options are mandatory for short options too.
  -a, --annotate-assembler   annotate generated assembler listing with
                             the original source code
  -c, --compile              compile JavaScript input file to byte-code
                             and save the result to the file `FILE.jsc'
  -d, --dispatch=METHOD      use method METHOD for byte-code instruction
                             dispatching one of: jumps, switch, or switch-basic.
  -e, --eval=CODE            evaluate JavaScript code CODE
  -E, --events               print interpreter events
  -f, --file                 evaluate the next argument file and pass
                             all remaining arguments to the interpreter
                             through the ARGS array
  -g, --debug[=INT]          generate debugging information, zero for off
  -h, --help                 print this help and exit
  -l, --load                 evaluate argument files until option `-f',
                             `--file' is encountered
  -N, --no-compiler          do not define compiler to the JavaScript
  -O, --optimize[=LEVEL]     optimize at level LEVEL
  -r, --secure=OPTION        turn on security option OPTION, one of:
			     file, nofile, system, nosystem,
  -s, --stack-size=SIZE      set the interpreter stack size to SIZE nodes
  -S, --assembler            compile JavaScript intput file to assembler
                             and save the result to the file `FILE.jas'
  -t, --stacktrace           print stacktrace on error
  -v, --verbose              tell what the interpreter is doing
  -V, --version              print version number
  -W, --compiler-option=OPTION
                             set compilation option OPTION
  -x, --executable           generate executable byte-code files program

  Report bugs to mtr@ngs.fi
Compiler options which may be prefixed with -no- to disable, include:
deprecated default off
unused-argument default off
unused-variable default on
undefined default on
shadow default on
with-clobber default on
missing-semicolon default off
strict-ecma default off
vars-global default on
The latter, the vars-global option was added to support Web javascript which requires all var variables outside of functions to be global.

.path instance CLASS VARNAME

Creates a new object of type class and assigns it to VARNAME. Unlike the new command, it works with regular JS classes.

.path iohook STDTYPE PROC

Set/query Tcl procedure to get control of IO. STDTYPE is one of stdin, stdout or stderr. Stdin proc is expected to return user input.

NOTE: The -noinit option must be used at widget creation if the iohook command is to be used. Follow this by the init command.

.path link VAR ALIAS

Alias the object VAR to the name ALIAS. Works only with VARs that are instances of JSTcl classes, ie. that have been created with the new command. Link has the same basic effect as assigning an object to a property, (eg, document.foo=document.forms[0]) except that it also causes the -datacmd to be called for the VAR, if required. Link is useful as a return var for -datacmd (see class).


Creates a new object of type class and assigns it to VARNAME. The TAG is passed as a parameter to datacmd and propcmd. new is designed to be used with an jstcl class created with the class command. Checkout instance for other cases.

.path parse STRING ?-line LINE? ?-this OBJECT?

Evaluate JS program in string STRING, which is expected to contain a valid javascript program. Raises an error upon exception. Parse does a few more things. The primary use of -this is to evaluate event handlers within a specific object instance.

NGS JS Equivalence: js_byte_compile+js_exec+js_vm_debug_position...

NGS JS Equivalence: js_byte_compile+js_exec+js_vm_debug_position...

.path result

Return the result from the last js operation.

NGS JS Equivalence: js_result.

.path source

Returns the source code for the all executed code.

.path variable VAR ?VAL ?TYPE??

if VAL is ommitted, gets the javascript global variable. Otherwise, it sets the javascript global variable. TYPE is the type of the variable:
s string
i integer
f floating point value
b boolean
The default type is s or string.

NGS JS Equivalence: js_get_var and js_set_var.

.path version

Return the js version.

NGS JS Equivalence: js_version.

.path verbose N

Set the debugging level for Jstcl.

Table Of Contents

  1. JSTcl - Javascript Widget For Tcl

Copyright 2001 peter@browsex.com