Click here to Skip to main content
Click here to Skip to main content

TIScript language, a gentle extension of JavaScript

, 6 Dec 2009 BSD
Rate this:
Please Sign up or sign in to vote.
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, 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: 

  • 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 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; }  // 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 the class 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 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();  // 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 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; // 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:

  • Single statement lambda function:
  • ':' [param-list] ':' <statement>;
  • Lambda function block:
  • ':' [param-list] '{' <statement-list> '}'
  • Classic anonymous function:
  • 'function(' [param-list] ')' '{' <statement-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) // 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 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 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 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; // 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

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
  • 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".

  • Bytes
  • An instance of the Bytes object is an array of bytes.

  • Storage and Index
  • 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.

  • Symbol (also known as Atom)
  • 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]; // and
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); // 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 a WYSIWYG HTML editor, Scapp (short for Sciter application), which can be found in Sciter SDK/scapps/blocknote.net. Therefore, the TIScript VM was running to help write it:

License

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

Share

About the Author

c-smile
Founder Terra Informatica Software
Canada Canada
Andrew Fedoniouk.
 
MS in Physics and Applied Mathematics.
Designing software applications and systems since 1991.
 
W3C HTML5 Working Group, Invited Expert.
 
Terra Informatica Software, Inc.
http://terrainformatica.com

Comments and Discussions

 
QuestionTIScript vs JavaScript vs Dart Pinmemberc-smile7-Feb-12 21:18 
GeneralAnd yet: "stringizer" functions. Pinmemberc-smile13-Dec-09 12:00 
Generaldebugging Pinmemberoleguaua13-Dec-09 10:48 
GeneralRe: debugging Pinmemberc-smile13-Dec-09 11:21 
GeneralRe: debugging Pinmemberc-smile13-Dec-09 14:10 
GeneralBTW: multi-returns Pinmemberc-smile8-Dec-09 14:44 
QuestionRe: BTW: multi-returns PinmemberNeville Franks9-Dec-09 10:27 
AnswerRe: BTW: multi-returns Pinmemberc-smile9-Dec-09 17:55 
AnswerRe: BTW: multi-returns Pinmemberc-smile10-Dec-09 9:21 
GeneralAmazing work PinmemberMarcelo Ricardo de Oliveira7-Dec-09 12:18 
Hi Andrew
 
You have fine features in TIScript... keep it up! BTW, does it have unit testing features?
 
My mom always told me to keep away from people who invented programming languages, but you deserved 5 from me Smile | :)
 
Take a look at full source code C# Snooker game here in Code Project.

GeneralRe: Amazing work Pinmemberc-smile8-Dec-09 14:32 
GeneralGood stuff... PinmemberErnest Laurentin7-Dec-09 6:55 
GeneralRe: Good stuff... Pinmemberc-smile8-Dec-09 14:24 
GeneralNice Work Pinmembersam.hill6-Dec-09 17:06 
GeneralGreat article! PinmemberJim Crafton26-Feb-09 6:46 
GeneralRe: Great article! Pinmemberc-smile26-Feb-09 7:23 
GeneralAnother example: SQLite Pinmemberc-smile26-Feb-09 10:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141216.1 | Last Updated 6 Dec 2009
Article Copyright 2009 by c-smile
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid