TIScript Language, A Gentle Extension of JavaScript
How the TIScript language is different from its prototype - JavaScript
Introduction
As a language, TIScript is an extended version of ECMAScript (JavaScript 1.X). You could think of it as JavaScript++, if you wish.
The design of TIScript was based on the analysis of practical JavaScript use cases. In some areas, it simplifies and harmonizes JavaScript features. For example, theprototype mechanism was simplified. In other cases, it extends JavaScript, while preserving the original "look-and-feel" of JS.
The TIScript Engine consists of:
- compiler that produces byte code
- virtual machine (VM) that executes this byte code
- heap manager that uses a copying garbage collector (GC)
- runtime which is an implementation of native object classes
Sources of the TIScript Engine are available atTIScript on GoogleCode repository.
This article describes the major features of TIScript that do not exist or differ from JavaScript. You should be familiar with at least the basics of JavaScript, or any other dynamic language, such as Python, Perl, Lua, Ruby, etc.
Namespaces
Namespaces are declared by using thenamespace
keyword. They can contain classes, functions, variables, and constants:
namespace MyNamespace{ var nsVar = 1; function Foo() { nsVar = 2; } // sets nsVar to 2}MyNamespace.Foo(); // invokes Foo
JavaScript does not support namespaces. You can emulate them by using objects, but that is just an emulation indeed.
Namespaces in TIScript are simply named scopes. For example, while handling the assignment to something that looks like a global variable, the TIScript runtime first makes an attempt to find that variable in the current namespace chain this function belongs to.
Classes, Constructors, and Properties
TIScript introduces real classes. A class is declared by theclass
keyword, and may contain functions, property-functions, variables, constants, and other classes:
class Bar{ function this() { // the function named 'this' is this._one = 1; // a constructor of objects in } // the class being defined function foo(p1) { // a method this._one = p1; } property one(v) { // property-function get { return this._one; } // has getter and set { this._one = v; } // setter sections }}
Note theproperty
function above. This is a special kind of function, used for declaring computable properties. Properties wrapped in such functions are accessible normally:
var bar = new Bar(); // invokes Bar.this()bar.one = 2; // invokes Bar.one()::set section
There are situations when a set of properties is unknown at design time. TIScript allows you to implement accessors for such properties via theproperty undefined()
method:
class Recordset{ function getFieldValue(idx) { ... } function getFieldIdx(byName) { ... } property undefined(name, val) { get { var fieldIdx = this.getFieldIdx(name); return this.getFieldValue(fieldIdx); } }}
This property handler can be used as follows:
var rs = DB.exec( "SELECT one, two FROM sometable" );var one = rs.one; // access the column named "one" in the recordset // via the special handler above
Lightweight Anonymous Functions
TIScript introduces a lightweight syntax for defining anonymous (lambda) functions. This makes for a total of three ways of declaring anonymous functions in TIScript:
':' [param-list] ':' <statement>;':' [param-list] '{' <statement-list> '}''function(' [param-list] ')' '{' <statement-list> '}'
- Single statement lambda function:
- Lambda function block:
- Classic anonymous function:
Here is an example of how you would sort an array in descending order by using a comparator function that is defined in-place:
var arr = [1,2,3];arr.sort( :a,b: a < b? 1:-1 );
Here,:a,b: a < b? 1:-1
is an inplace declaration of a lambda function that will be passed to theArray.sort()
method.
Decorators
Decorators are a sort of meta-programming feature that was borrowed from the Python language. In TIScript, a decorator is an ordinary function. Its name must start with the '@' character, and it must have at least one parameter. That parameter (the first one) is a reference to some other function (or class) that is being decorated. Here is an example of a decorator function declaration:
function @KEY(func, keyCode){ function t(event) // wraps a call to func() { // into a filter function if(event.keyCode == keyCode) func(); if(t.next) t.next.call(this,event); } t.next = this.onKey; // establishes the chain this.onKey = t; // of event handlers}
If we have something like this in place, then we can define code blocks that will be activated on different keys pressed on the widget:
class MyWidget : Widget{ @KEY 'A' : { this.doSelectAll(); } @KEY 'B' : { this.doSomethingWhenB(); }}
Here, the two@KEY
entries decorate two anonymous functions (see the previous section). The code above assumes that there is aWidget
defined somewhere with the callback methodonKey(event)
.
Decorators is an advanced feature, and may require some effort to understand. When established, decorators may significantly increase the expressiveness of your code. More detail about decorators can be foundhere andhere.
Iterators
JavaScript (and so TIScript) has a pretty handyfor-each
statement:for( var item in collection ){..}
, where thecollection
is an instance of an object or an array.
In TIScript, a list of enumerable objects is extended by function instances. Thus, the statementfor( var item infunc)
will call thefunc
and execute the body of the loop with its value on each iteration. Example, this function:
function range( from, to ){ var idx = from - 1; return function() { if( ++idx <= to ) return idx; }}
will generate consecutive numbers in the range[from..to]
. So if you will write something like this:
for( var item in range(12,24) )stdout << item << " ";
then you will get numbers from 12 to 24, printed one by one instdout
.
Here is another example of a class-collection that allows to enumerate its members in two directions:
class Fruits{ function this() { this._data = ["apple","orange","lime","lemon", "pear","banan","kiwi","pineapple"]; } property forward(v) { get { var items = this._data; var idx = -1; // return function that will supply "next" value // on each invocation return function() { if( ++idx < items.length ) return items[idx]; } } } property backward(v) { get { var items = this._data; var idx = items.length; return function() { if( --idx >= 0 ) return items[idx]; } } }}
As you may see, the class above has two properties that return iterators allowing to scan the collection in both directions:
var fruits = new Fruits(); stdout << "Fruits:\n";for( var item infruits.forward ) stdout << item << "\n"; stdout << "Fruits in opposite direction:\n";for( var item infruits.backward ) stdout << item << "\n";
People from Mozilla introduced their version ofIterators in Spider Monkey that was, I believe, borrowed "as is" from Python. I think that my version of iterators better suits the JavaScript spirit. At least, it does not introduce new entities and classes.
The Prototype Property
Compared with JavaScript, the prototyping mechanism has been simplified in TIScript.
Each object in TIScript has a property namedprototype
. The prototype of an object is a reference to its class, which is also simply an object. The prototype of a class is a reference to its superclass. Similarly, the prototype of a namespace (which is an object, like anything else) is a reference to its parent namespace.
For example, all these statements evaluate totrue
:
"somestring".prototype === String; // prototype of the string is String class object.{ some:"object", literal:true }.prototype === Object;
And for user defined classes:
class Foo { ... }var foo = new Foo(); foo.prototype === Foo;
Type System
Thenumber
type of JavaScript unifies integer and float numbers into one. In TIScript, it's split into two distinct classes:Integer
andFloat
, as they really represent two distinct entities.
TIScript also introduces a number of new types:
Stream is a sequence of characters or bytes. The TIScript runtime supports three types of streams: in-memory (a.k.a.String stream
), socketstream
, and filestream
. In-memorystream
s are an effective way of generating text. They are introduced for the same purposes as theStringBuffer
/StringBuilder
classes in the "big Java".
An instance of theBytes
object is an array of bytes.
These two classes make up the core of the TIScript built-in persistence. A TIScript object (and all objects it refers to) can be made persistent by assigning it to thestorage.root
property. The whole tree of objects is transparently placed in a storage file on the hard drive. Essentially, this is an Object Oriented Database (OODB). I call this JSON-DB, as only a JSON subset of JS objects can be persistent. For example, the socketstream
is not persistent by nature.
Almost all dynamic languages have a concept of atoms in one form or another. TIScript has them too.
Symbols
A name of an object is astring
of allowed characters. A symbol is a number associated with the name.TIScript
maintains a global map of suchname<->int
pairs (implemented internally as aternary search tree). At compile time, each name gets translated into anInt32
number - its symbol.
In some cases, you may want to declare symbols explicitly. In this case, symbol literals come in handy. The symbol literal is a sequence of characters that starts with the '#' character. It can contain alpha-numeric characters, underscores ('_'), and dashes ('-'). Dashes are used in symbols for compatibility with CSS (Cascading Style Sheets), where they are parts of name tokens.
Example of symbol use:
function ChangeMode( mode ){ if( mode ==#edit ) this.readOnly = false; else if( mode ==#read-only ) this.readOnly = true; else throw mode.toString() + " - bad symbol!";}
As you can see, symbols may be used as self descriptive, convenient, and effective auto-enum
values.
Another feature that makes symbols quite useful is theaccess-by-symbol notation.
Constructions like:
var aa = obj#name;obj#name = val;
get translated into:
var aa = obj[#name]; // andobj[#name] = val
statements. Not too much, but will make code a bit more readable.
This is often used inSciter, which is an embeddable HTML/CSS/Scripting engine. For example, to access style (CSS) attributes of DOM elements:
var elem = self.select("#some");elem.style#display = "block";elem.style#border-left-width = px(1); // or elem.style[#border-left-width] = "1px";elem.style#border-right-width = px(2);...
Conclusion
This concludes a brief overview of TIScript. In the next article, I will explain how to embed the TIScript engine into your application.
This article was written in aSciter's WYSIWYG HTML editor - Scapp (short forSciterapplication). Therefore, the TIScript VM was running to help write it: