TIScript Language, A Gentle Extension of JavaScript (original) (raw)

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, the prototype mechanism was simplified. In other cases, it extends JavaScript, while preserving the original "look-and-feel" of JS.

The TIScript Engine consists of:

Sources of the TIScript Engine are available at TIScript 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 the namespace keyword. They can contain classes, functions, variables, and constants:

namespace MyNamespace { var nsVar = 1; function Foo() { nsVar = 2; }
} MyNamespace.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 the class keyword, and may contain functions, property-functions, variables, constants, and other classes:

class Bar { function this() {
this._one = 1;
}
function foo(p1) {
this._one = p1; } property one(v) {
get { return this._one; } set { this._one = v; }
} }

Note the property 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();
bar.one = 2;

There are situations when a set of properties is unknown at design time. TIScript allows you to implement accessors for such properties via the property 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;

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] ':' ;

':' [param-list] '{' '}'

'function(' [param-list] ')' '{' '}'

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 the Array.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) {
if(event.keyCode == keyCode) func(); if(t.next) t.next.call(this,event); } t.next = this.onKey; this.onKey = t;
}

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 a class Widget defined somewhere with the callback method onKey(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 found here and here.

Iterators

JavaScript (and so TIScript) has a pretty handy for-each statement: for( var item in collection ){..}, where the _collection_ is an instance of an object or an array.

In TIScript, a list of enumerable objects is extended by function instances. Thus, the statement for( var item in _func_) will call the _func_ 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 in stdout.

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() { 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 in fruits.forward ) stdout << item << "\n"; stdout << "Fruits in opposite direction:\n"; for( var item in fruits.backward ) stdout << item << "\n";

People from Mozilla introduced their version of Iterators 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 named prototype. 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 to true:

"somestring".prototype === String; { some:"object", literal:true }.prototype === Object;

And for user defined classes:

class Foo { ... } var foo = new Foo(); foo.prototype === Foo;

Type System

The number type of JavaScript unifies integer and float numbers into one. In TIScript, it's split into two distinct classes: Integer and Float, 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), socket stream, and file stream. In-memory streams are an effective way of generating text. They are introduced for the same purposes as the StringBuffer/StringBuilder classes in the "big Java".

An instance of the Bytes 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 the storage.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 socket stream 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 a string of allowed characters. A symbol is a number associated with the name. TIScript maintains a global map of such name<->int pairs (implemented internally as a ternary search tree). At compile time, each name gets translated into an Int32 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 the access-by-symbol notation.

Constructions like:

var aa = obj#name; obj#name = val;

get translated into:

var aa = obj[#name]; obj[#name] = val

statements. Not too much, but will make code a bit more readable.

This is often used in Sciter, 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); 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 a Sciter's WYSIWYG HTML editor - Scapp (short for Sciter application). Therefore, the TIScript VM was running to help write it:

Image 1

This article, along with any associated source code and files, is licensed under The BSD License