\input texinfo   @c -*-texinfo-*-
@c %**start of header
@setfilename js.info
@settitle js
@setchapternewpage on
@c %**end of header

@c (save-excursion (replace-regexp "^@\\(end \\)?cartouche" "@c \\&"))
@c (save-excursion (replace-regexp "^@c \\(@\\(end \\)?cartouche\\)" "\\1"))

@include version.texi

@set ECMA	ECMA-262 Version 2 draft 22-Apr-98
@set JSREF	Netscape JavaScript Reference 12-Dec-97
@set NGS	NGS JavaScript Interpreter @value{VERSION}

@dircategory NGS JavaScript Interpreter
@direntry
* libjs: (js).			The JavaScript interpreter library.
* js: (js)The js Program.	JavaScript interpreter.
@end direntry

@c Combine function and variable indexes to the Concept index.
@synindex fn cp
@synindex vr cp

@ifinfo
This file documents NGS JavaScript interpreter @value{VERSION}

Copyright (C) 1998 New Generation Software (NGS) Oy

Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
are preserved on all copies.

@ignore
Permission is granted to process this file through TeX and print the
results, provided the printed document carries copying permission
notice identical to this one except for the removal of this paragraph


@end ignore
Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.

Permission is granted to copy and distribute translations of this manual
into another language, under the above conditions for modified versions,
except that this permission notice may be stated in a translation approved
by the Foundation.
@end ifinfo


@titlepage
@title NGS JavaScript Interpreter
@subtitle For version @value{VERSION}, @value{UPDATED}
@author Markku Rossi

@page
@vskip 0pt plus 1filll
Copyright @copyright{} 1998 New Generation Software (NGS) Oy
@sp 2
This is the first edition of the NGS JavaScript documentation,@*
and is consistent with NGS JavaScript Interpreter @value{VERSION}.@*

Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
are preserved on all copies.

Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.

Permission is granted to copy and distribute translations of this manual
into another language, under the above conditions for modified versions,
except that this permission notice may be stated in a translation
approved by the Free Software Foundation.
@end titlepage

@ifinfo
@node Top, Introduction, (dir), (dir)
@comment  node-name,  next,  previous,  up
@top NGS JavaScript Interpreter

This file documents the NGS JavaScript interpreter.  This edition
documents version @value{VERSION}.

@menu
* Introduction::
* NGS JavaScript Language::
* The js Program::
* The jsas Program::
* The jsdas Program::
* The jswrap Program::
* JavaScript API::
* Virtual Machine::
* JavaScript Compiler::
* GNU Library General Public License::
* Index::
@end menu

@end ifinfo

@c ----------------------------------------------------------------------
@node Introduction, NGS JavaScript Language, Top, Top
@chapter Introduction

@itemize @bullet
@item overall
@item design goals
@item structure: virtual machine, JSC$, JS glue
@end itemize

@c ----------------------------------------------------------------------
@node NGS JavaScript Language, The js Program, Introduction, Top
@chapter NGS JavaScript Language

@menu
* Language::
* Global Methods and Properties::
* Native Objects::
* Extensions::
@end menu

@c ----------------------------------------------------------------------
@node Language, Global Methods and Properties, NGS JavaScript Language, NGS JavaScript Language
@section Language

@menu
* Lexical Conventions::
* Function Definition::
* Statements::
* Expressions::
@end menu

@node Lexical Conventions, Function Definition, Language, Language
@subsection Lexical Conventions

@menu
* White Space::
* Comments::
* Reserved Words::
* Identifiers::
* Punctuators::
* Literals::
* Automatic Semicolon Insertion::
@end menu

@node White Space, Comments, Lexical Conventions, Lexical Conventions
@subsubsection White Space

@node Comments, Reserved Words, White Space, Lexical Conventions
@subsubsection Comments

@node Reserved Words, Identifiers, Comments, Lexical Conventions
@subsubsection Reserved Words

@node Identifiers, Punctuators, Reserved Words, Lexical Conventions
@subsubsection Identifiers

@node Punctuators, Literals, Identifiers, Lexical Conventions
@subsubsection Punctuators

@node Literals, Automatic Semicolon Insertion, Punctuators, Lexical Conventions
@subsubsection Literals

@node Automatic Semicolon Insertion,  , Literals, Lexical Conventions
@subsubsection Automatic Semicolon Insertion

Certain ECMAScript statements must be terminated with a semicolon.  Such
a semicolon may always appear explicitly in the source text.  For pain
of the compiler implementator, however, such semicolons may be omitted
from the source text in certain situations.  These situations are
described in details in the @value{ECMA} standard.  Here is
@email{mtr@@ngs.fi}'s interpretation of the rules:

Insert semicolons as you would do in the C language.  Now, you can omit
them:

@enumerate
@item before '@code{@}}' character
@item from the end of the line
@item from the end of the file
@end enumerate

@noindent The automatic semicolon insertion sets some restrictions how
you can insert whitespace to you code.  You can't insert line breaks:

@enumerate
@item between @var{LeftHandSideExpression} and @code{++} or @code{--}
operator
@item between @code{return} and the returned @var{Expression}
@end enumerate


@node Function Definition, Statements, Lexical Conventions, Language
@subsection Function Definition


@node Statements, Expressions, Function Definition, Language
@subsection Statements

@menu
* Block::
* Variable Statement::
* Empty Statement::
* The if Statement::
* The do...while Statement::
* The while Statement::
* The for Statement::
* The for...in Statement::
* The continue Statement::
* The break Statement::
* The return Statement::
* The with Statement::
* The switch Statement::
* Labeled Statements::
* The throw Statement::
* The try Statement::
@end menu

@node Block, Variable Statement, Statements, Statements
@subsubsection Block

@node Variable Statement, Empty Statement, Block, Statements
@subsubsection Variable Statement

@node Empty Statement, The if Statement, Variable Statement, Statements
@subsubsection Empty Statement

@node The if Statement, The do...while Statement, Empty Statement, Statements
@subsubsection The @code{if} Statement

@node The do...while Statement, The while Statement, The if Statement, Statements
@subsubsection The @code{do}@dots{}@code{while} Statement

@node The while Statement, The for Statement, The do...while Statement, Statements
@subsubsection The @code{while} Statement

@node The for Statement, The for...in Statement, The while Statement, Statements
@subsubsection The @code{for} Statement

@node The for...in Statement, The continue Statement, The for Statement, Statements
@subsubsection The @code{for}@dots{}@code{in} Statement

@node The continue Statement, The break Statement, The for...in Statement, Statements
@subsubsection The @code{continue} Statement

@node The break Statement, The return Statement, The continue Statement, Statements
@subsubsection The @code{break} Statement

@node The return Statement, The with Statement, The break Statement, Statements
@subsubsection The @code{return} Statement

@node The with Statement, The switch Statement, The return Statement, Statements
@subsubsection The @code{with} Statement

The syntax of the @code{with}-statement is:

@example
with (@var{expr}) @var{statement}
@end example

@c @cartouche
@example
with (Math)
  @{
    result = sin (PI);
    result -= tan (45);
  @}
@end example
@c @end cartouche

@node The switch Statement, Labeled Statements, The with Statement, Statements
@subsubsection The @code{switch} Statement

@node Labeled Statements, The throw Statement, The switch Statement, Statements
@subsubsection Labeled Statements

@node The throw Statement, The try Statement, Labeled Statements, Statements
@subsubsection The @code{throw} Statement

@node The try Statement,  , The throw Statement, Statements
@subsubsection The @code{try} Statement



@node Expressions,  , Statements, Language
@subsection Expressions

@menu
* Primary Expressions::
* Left-Hand-Side Expressions::
* Postfix Expressions::
* Unary Operators::
* Multiplicative Operators::
* Additive Operators::
* Bitwise Shift Operators::
* Relational Operators::
* Equality Operators::
* Binary Bitwise Operators::
* Binary Logical Operators::
* Conditional Operator::
* Assignment Operators::
* Comma Operator::
@end menu

@node Primary Expressions, Left-Hand-Side Expressions, Expressions, Expressions
@subsubsection Primary Expressions

@node Left-Hand-Side Expressions, Postfix Expressions, Primary Expressions, Expressions
@subsubsection Left-Hand-Side Expressions

@node Postfix Expressions, Unary Operators, Left-Hand-Side Expressions, Expressions
@subsubsection Postfix Expressions

@node Unary Operators, Multiplicative Operators, Postfix Expressions, Expressions
@subsubsection Unary Operators

@node Multiplicative Operators, Additive Operators, Unary Operators, Expressions
@subsubsection Multiplicative Operators

@node Additive Operators, Bitwise Shift Operators, Multiplicative Operators, Expressions
@subsubsection Additive Operators

@node Bitwise Shift Operators, Relational Operators, Additive Operators, Expressions
@subsubsection Bitwise Shift Operators

@node Relational Operators, Equality Operators, Bitwise Shift Operators, Expressions
@subsubsection Relational Operators

@node Equality Operators, Binary Bitwise Operators, Relational Operators, Expressions
@subsubsection Equality Operators

@node Binary Bitwise Operators, Binary Logical Operators, Equality Operators, Expressions
@subsubsection Binary Bitwise Operators

@node Binary Logical Operators, Conditional Operator, Binary Bitwise Operators, Expressions
@subsubsection Binary Logical Operators

@node Conditional Operator, Assignment Operators, Binary Logical Operators, Expressions
@subsubsection Conditional Operator

@node Assignment Operators, Comma Operator, Conditional Operator, Expressions
@subsubsection Assignment Operators

@node Comma Operator,  , Assignment Operators, Expressions
@subsubsection Comma Operator


@c ----------------------------------------------------------------------
@node Global Methods and Properties, Native Objects, Language, NGS JavaScript Language
@section Global Methods and Properties

@table @strong
@item Standard
@value{ECMA}
@end table

@c --- Properties -------------------------------------------------------

@defcv Property Global NaN
The @emph{not a number} value.
@end defcv

@defcv Property Global Infinity
The @emph{positive infinity} value.
@end defcv

@c --- Methods ----------------------------------------------------------

@defun eval (any)
@end defun

@defun parseInt (string, radix)
@end defun

@defun parseFloat (string)
@end defun

@defun escape (string)
@end defun

@defun unescape (string)
@end defun

@defun isNaN (any)
@end defun

@defun isFinite (any)
@end defun


@defun debug (any)

@table @strong
@item Standard
@value{JSREF}
@end table

@end defun


@defun print (any[,@dots{}])

@table @strong
@item Standard
@value{JSREF} ???
@end table

@end defun


@defun error (message)

@table @strong
@item Standard
@value{JSREF} ???
@end table

@end defun


@defun float (any)

@table @strong
@item Standard
@value{NGS}
@end table

@end defun


@defun int (any)

@table @strong
@item Standard
@value{NGS}
@end table

@end defun


@defun isFloat (any)

@table @strong
@item Standard
@value{NGS}
@end table

@end defun


@defun isInt (any)

@table @strong
@item Standard
@value{NGS}
@end table

@end defun

@defun load (file@dots{})

@table @strong
@item Standard
@value{NGS}
@end table

@end defun


@defun loadClass (class_spec@dots{})

@table @strong
@item Standard
@value{NGS}
@end table

Extend interpreter by calling an initialization function from shared
library @var{class_spec}.  The argument @var{class_spec} can be given in
the following formats:

@table @code
@item @var{library}:@var{function}

The argument @var{library} specifies the shared library from which
function @var{function} is called.  The library specification can be
given in absolute or relative formats.

@item @var{library}
The argument @var{library} specifies both the shared library, and the
name of the entry function.  The name of the entry function is the name
of the library, without the possible leading directory path and any
suffixes.
@end table

@c @cartouche
@example
loadClass ("libexts.so:init_all");
@result{} @var{call function @code{init_all} from library @file{libexts.so}}

loadClass ("/usr/local/lib/libexts.so:init_all");
@result{} @var{call function @code{init_all} from library @file{/usr/local/lib/libexts.so}}

loadClass ("/usr/local/lib/libdbexts.so");
@result{} @var{call function @code{dbexts} from library @file{/usr/local/lib/libexts.so}}
@end example
@c @end cartouche

The initialization function must be a void function that takes one
argument that is a pointer to the interpreter.

@c @cartouche
@example
void
entry (JSInterpPtr interp)
@{
  @var{Initialize extensions using normal @file{js.h} and @file{jsint.h}}
  @var{interfaces.}
@}
@end example
@c @end cartouche
@end defun


@defun callMethod (object, method, arguments)

@table @strong
@item Standard
@value{NGS}
@end table

Call method @var{method} from object @var{object} with arguments
@var{arguments}.

@c @cartouche
@example
callMethod (System.stdout, "writeln", ["Hello, world!"]);
@print{} Hello, world!
@end example
@c @end cartouche
@end defun




@c ----------------------------------------------------------------------
@node Native Objects, Extensions, Global Methods and Properties, NGS JavaScript Language
@section Native Objects

@menu
* Array::
* Boolean::
* Date::
* File::
* Directory::
* Function::
* Math::
* Number::
* Object::
* RegExp::
* String::
* System::
* VM::
@end menu

@c ----------------------------------------------------------------------
@node Array, Boolean, Native Objects, Native Objects
@subsection Array

@table @strong
@item Standard
@value{ECMA}
@item Incompatibilities
@itemize @bullet
@item The @code{toSource()} method is missing.
@item The constructor doesn't set the [[Prototype]] and [[Class]]
properties.
@end itemize
@end table

@defun Array (count)
@defunx Array (item@dots{})
Do exactly the same as the expression @code{new Array()} called with the
same arguments.
@end defun

@c --- Constructors -----------------------------------------------------

@deffn Constructor Array (count)
@deffnx Constructor Array (item@dots{})

Create a new array object.  The first form creates a new array which
length is @var{count}.  All items are set to value @samp{undefined}.
The second form creates an array that contains the given items as its
values.

@c @cartouche
@example
var a = new Array (5);
a.length;
@result{} 5
a.toString ();
@result{} undefined,undefined,undefined,undefined,undefined

a = new Array (1, 2, "hello");
a.length;
@result{} 3
a.toString ();
@result{} 1,2,hello
@end example
@c @end cartouche
@end deffn

@c --- Methods ----------------------------------------------------------

@defmethod Array concat (array[, @dots{}])
Create a new array object from the items of the called array object and
the argument arrays @var{array}, @dots{}.  The contents of the argument
arrays are not modified.

@c @cartouche
@example
var a = new Array (1, 2, 3);
var b = a.concat (new Array (4, 5));
b.length;
@result{} 5;
b.toString ();
@result{} 1,2,3,4,5
@end example
@c @end cartouche
@end defmethod

@defmethod Array join ([glue])
Convert the array to a string.  Individual items of the array are
combined with the string @var{glue}.  If the argument @var{glue} is
omitted, string @code{","} is used.

@c @cartouche
@example
var a = new Array (1, 2, "three");
a.join ();
@result{} "1,2,three"

a.join ("-");
@result{} "1-2-three"
@end example
@c @end cartouche
@end defmethod

@defmethod Array pop ()
Remove the last item of the array.  The method returns the item removed.
If the array is empty, value @code{undefined} is returned.

@c @cartouche
@example
a = new Array (1, 2, 3);
a.pop ();
@result{} 3
a.length;
@result{} 2
@end example
@c @end cartouche
@end defmethod

@defmethod Array push (any@dots{})
Insert items to the end of the array.  The method returns the last item
pushed.

@c @cartouche
@example
a = new Array (1, 2);
a.push (7);
@result{} 7
a.push (7, 8, 9);
@result{} 9
System.print (a.join (", "), "\n");
@print{} 1, 2, 7, 7, 8, 9
@end example
@c @end cartouche
@end defmethod

@defmethod Array reverse ()
Reverse the array.

@c @cartouche
@example
a = new Array (1, 2, 3);
a.reverse ();
System.print (a.join (""), "\n");
@print{} 321
@end example
@c @end cartouche
@end defmethod

@defmethod Array shift ()
Remove item from the beginning of the array.  The method returns the
item removed, or value @samp{undefined} if the array was empty.

@c @cartouche
@example
a = new Array (1, 2, 3);
a.shift ();
@result{} 1
@end example
@c @end cartouche
@end defmethod

@defmethod Array slice (start[, end])
Return a new array containing items between @var{start} (inclusively)
and @var{end} (exclusively) in the array.  If the argument @var{end} is
negative, it is counted from the end of the array.  If the argument
@var{end} is omitted, the method extract items from the position
@var{start} to the end of the array.

@c @cartouche
@example
a = new Array (1, 2, 3, 4, 5);
b = a.slice (1, 4);
System.print (b.join (", "), "\n");
@print{} 2, 3, 4
b = a.slice (1, -2);
System.print (b.join (", "), "\n");
@print{} 2, 3
b = a.slice (2);
System.print (b.join (", "), "\n");
@print{} 3, 4, 5
@end example
@c @end cartouche
@end defmethod

@defmethod Array splice (index, remove[, any@dots{}])
Modify array by removing old items and by inserting new ones.  The
argument @var{index} specifies the index from which the array is
modified.  The argument @var{remove} specifies how many old items are
removed.  If the argument @var{remove} is 0, no old items are removed
and at least one new item must have been given.  After the items are
removed, all remaining arguments are inserted after the position
@var{index}.

@c @cartouche
@example
var a = new Array (1, 2, 3);
a.splice (1, 1);
@result{} 1, 3
a.splice (1, 0, "new item");
@result{} 1, "new item", 2, 3

var a = new Array (1, 2, 3, 4);
a.splice (1, 2, "new item");
@result{} 1, "new item", 4
@end example
@c @end cartouche
@end defmethod

@defmethod Array sort ([sort_function])
Sort the array to the order specified by the argument function
@var{sort_function}.  The comparison function @var{sort_function} takes
two arguments and it must return one of the following codes:

@table @code
@item -1
the first argument items is smaller than the second item (must come
before the second item)
@item 0
the items are equal
@item 1
the first argument item is bigger than the second item (it must come
after the second item)
@end table

@noindent If the argument @var{sort_function} is omitted, the items are
sorted to an alphabetical (lexicographical) order.

@c @cartouche
@example
a = new Array ("Jukka-Pekka", "Jukka", "Kari", "Markku");
a.sort ();
System.print (a, "\n");
@print{} Jukka,Jukka-Pekka,Kari,Markku
a = new Array (1, 2, 10, 20, 100, 200);
a.sort ();
System.stdout.writeln (a.toString ());
@print{} 1,10,100,2,20,200
@end example
@c @end cartouche

The sort method is stable in that sense that, if the comparison function
returns 0 for two items, their original order in the array is preserved.
For example, if a list of person objects is sorted first by their names,
and second by their ages, all persons with the same age will remain
sorted in an alphabetical order.

@c @cartouche
@example
function by_age (a, b)
@{
  return a.age - b.age;
@}

function by_name (a, b)
@{
  if (a.name < b.name)
    return -1;
  if (a.name > b.name)
    return 1;
  return 0;
@}

function Person (name, age)
@{
  this.name = name;
  this.age = age;
@}

a = new Array (new Person ("Smith", 30),
               new Person ("Jones", 31),
               new Person ("Bob", 30),
               new Person ("Chris", 29));

a.sort (by_name);
a.sort (by_age);

for (i in a)
  System.print (i.name, ", ", i.age, "\n");
@print{} Chris, 29
@print{} Bob, 30
@print{} Smith, 30
@print{} Jones, 31
@end example
@c @end cartouche
@end defmethod

@defmethod Array toSource ()
@end defmethod

@defmethod Array toString ()
Convert the array to a string.  The method converts each item of the
array to string and combines them with the string @code{","}.

@c @cartouche
@example
var a = new Array (1, "foo", 2, new Array (7, 8));
a.toString ();
@result{} 1,foo,2,7,8
@end example
@c @end cartouche
@end defmethod

@defmethod Array unshift (any@dots{})
Insert items @var{any}@dots{} to the beginning of the array.  The method
returns the new length of the array.

@c @cartouche
@example
a = new Array (1, 2, 3);
System.print (a.unshift (7, 8, 9), "\n");
@print{} 6
@end example
@c @end cartouche
@end defmethod

@defcv Property Array length
The length of the array.

@c @cartouche
@example
var a = new Array (1, 2);
a.length;
@result{} 2
a.push (3, 4, 5);
a.length;
@result{} 5
@end example
@c @end cartouche
@end defcv

@c ----------------------------------------------------------------------
@node Boolean, Date, Array, Native Objects
@subsection Boolean

@table @strong
@item Standard
@value{ECMA}
@item Incompatibilities
@itemize @bullet
@item The constructor doesn't set the [[Prototype]] and [[Class]]
properties.
@end itemize
@end table

@defun Boolean ()
Return @code{false}.
@end defun

@defun Boolean (value)
@end defun

@c --- Constructors -----------------------------------------------------

@deffn Constructor Boolean ()
@deffnx Constructor Boolean (value)
Create a new boolean object.  If no arguments are given, the returned
object will have value @samp{false}.  If the argument @var{value} is
given, the initial value of the object is determined by the type of the
argument and its value.  If the argument @var{value} is
@code{undefined}, @code{null}, @code{false}, @code{""} (an empty
string), or @code{0}, the value of the object will be @samp{false}.  All
other values for the argument @var{value} will set the initial value of
the object to @samp{true}.
@end deffn

@defmethod Boolean toString ()
Return a string presentation of the boolean object.  The method will
return string @code{"true"} or @code{"false"} according to the value of
the object.
@end defmethod

@defmethod Boolean valueOf ()
@end defmethod


@c ----------------------------------------------------------------------
@node Date, File, Boolean, Native Objects
@subsection Date

@table @strong
@item Standard
@value{ECMA}
@item Incompatibilities
XXX Check all methods and properties.
@end table

@defun MakeTime (hour, min, sec, ms)
@end defun

@defun MakeDay (year, month, date)
@end defun

@defun MakeDate (day, time)
@end defun

@defun TimeClip (time)
@end defun

@defun Date ([a1[, a2[, a3[, a4[, a5[, a6[, a7]]]]]]])
When the @code{Date} constructor is called as a function, it ignores
arguments @var{a1}@dots{}@var{a7} and returns the result of expression:

@example
new Date ().toString()
@end example
@end defun

@deffn Constructor Date ()
@deffnx Constructor Date ("@var{month} @var{day}, @var{year} @var{hours}:@var{minutes}:@var{seconds}")
@deffnx Constructor Date (@var{yr_num}, @var{mo_num}, @var{day_num})
@deffnx Constructor Date (@var{yr_num}, @var{mo_num}, @var{day_num}, @var{hr_num}, @var{min_num}, @var{sec_num})
@end deffn

@defop {Static Method} Date UTC (@var{year}, @var{month}, @var{day}, @var{hrs}, @var{min}, @var{sec})
@end defop

@defmethod Date format (format)
@end defmethod

@defmethod Date formatGMT (format)
@end defmethod

@defmethod Date getDate ()
@end defmethod

@defmethod Date getDay ()
@end defmethod

@defmethod Date getHours ()
@end defmethod

@defmethod Date getMinutes ()
@end defmethod

@defmethod Date getMonth ()
@end defmethod

@defmethod Date getSeconds ()
@end defmethod

@defmethod Date getTime ()
@end defmethod

@defmethod Date getTimezoneOffset ()
@end defmethod

@defmethod Date getYear ()
@end defmethod

@defmethod Date parse (string)
@end defmethod

@defmethod Date setDate (day)
@end defmethod

@defmethod Date setHours (hours)
@end defmethod

@defmethod Date setMinutes (minutes)
@end defmethod

@defmethod Date setMonths (months)
@end defmethod

@defmethod Date setSeconds (seconds)
@end defmethod

@defmethod Date setTime (time)
@end defmethod

@defmethod Date setYear (year)
@end defmethod

@defmethod Date toGMTString ()
@end defmethod

@defmethod Date toLocaleString ()
@end defmethod

@c ----------------------------------------------------------------------
@node File, Directory, Date, Native Objects
@subsection File

@table @strong
@item Standard
@value{JSREF}
@item Incompatibilities
XXX Check all methods and properties.
@end table


@deffn Constructor File (path)
@end deffn


@defop {Static Method} File byteToString (byte)
@end defop

@defop {Static Method} File chmod (path, mode)

@table @strong
@item Standard
@value{NGS}
@end table

Change permissions of file @var{path} to @var{mode}.  The modes are
specifeid by or'ing the following values:

@table @code
@item 04000
set user ID on execution
@item 02000
set group ID on execution
@item 01000
sticky bit

@item 00400
read by owner
@item 00200
write by owner
@item 00100
execute / search by owner

@item 00040
read by group
@item 00020
write by group
@item 00010
execute / search by group

@item 00004
read by others
@item 00002
write by others
@item 00001
execute / search by others
@end table
@end defop

@defop {Static Method} File lstat (path)

@table @strong
@item Standard
@value{NGS}
@end table

@end defop

@defop {Static Method} File remove (path)

@table @strong
@item Standard
@value{NGS}
@end table

@end defop

@defop {Static Method} File rename (path)

@table @strong
@item Standard
@value{NGS}
@end table

@end defop

@defop {Static Method} File stat (path)

@table @strong
@item Standard
@value{NGS}
@end table

Return statistics about the file @var{file}.  The method returns a 13
element array containing the statistics, or @samp{false} if the file
couldn't be inspected.

The returned array contains the following items:

@table @code
@item dev
Device that contains a directory entry for this file.

@item ino
Index of this file on its device.  A file is uniquely identified by
specifying its @code{dev} and @code{ino}.

@item mode
The mode of the file.

@item nlink
The number of hard links to the file.

@item uid
The ID of the file owner.

@item gid
The ID of the file group.

@item rdev
The ID of the device.

@item size
The size of the file.

@item atime
The time when the data was last accessed.

@item mtime
The time when the data was last modified.

@item ctime
The time when the file status was last changed.

@item blksize
Preferred blocksize for file system I/O.

@item blocks
The number of blocks the file actually uses.
@end table

@c @cartouche
@example
fields = new Array ("dev", "ino", "mode", "nlink", "uid",
                    "gid", "rdev", "size", "atime",
                    "mtime", "ctime", "blksize", "blocks");

var a = File.stat ("js");
if (a)
  @{
    var i;
    for (i = 0; i < a.length; i++)
      System.print (fields[i], "=", a[i], " ");
    System.print ("\n");
  @}

@print{} dev=655368 ino=370741 mode=33261 nlink=1 uid=201 gid=200
@print{} rdev=2979328 size=731370 atime=893159080 mtime=893158537
@print{} ctime=893158537 blksize=4096 blocks=1432
@end example
@c @end cartouche
@end defop


@defop {Static Method} File stringToByte (string)
@end defop



@defmethod File open (mode)

The argument @var{mode} must have one of the following values:

@table @r
@item @code{r}[@code{b}]
@item @code{w}[@code{b}]
@item @code{a}[@code{b}]
@item @code{r+}[@code{b}]
@item @code{w+}[@code{b}]
@item @code{a+}[@code{b}]
@end table

@end defmethod

@defmethod File close ()
@end defmethod

@defmethod File setPosition (position[, whence])
@end defmethod

@defmethod File getPosition ()
@end defmethod

@defmethod File eof ()
@end defmethod

@defmethod File read (size)
@end defmethod

@defmethod File readln ()
@end defmethod

@defmethod File readByte ()
@end defmethod

@defmethod File toString ()
@end defmethod

@defmethod File write (string)
@end defmethod

@defmethod File writeln (string)
@end defmethod

@defmethod File writeByte (byte)
@end defmethod

@defmethod File ungetByte (byte)

@table @strong
@item Standard
@value{NGS}
@end table

@end defmethod

@defmethod File flush ()
@end defmethod

@defmethod File getLength ()
@end defmethod

@defmethod File exists ()
@end defmethod

@defmethod File error ()
@end defmethod

@defmethod File clearError ()
@end defmethod

@defcv Property File autoFlush

@table @strong
@item Standard
@value{NGS}
@end table

Flag that specifies whether the stream should automatically flush its
buffers after a write.
@end defcv

@defcv Property File bufferSize

@table @strong
@item Standard
@value{NGS}
@end table

The I/O buffer size of the stream.  The buffer size can be changed at
the runtime.
@end defcv

@c ----------------------------------------------------------------------
@node Directory, Function, File, Native Objects
@subsection Directory

@table @strong
@item Standard
@value{NGS}
@end table

@deffn Constructor Directory (path)
@end deffn

@defmethod Directory close ()
@end defmethod

@defmethod Directory open ()
@end defmethod

@defmethod Directory read ()
@end defmethod

@defmethod Directory rewind ()
@end defmethod

@defmethod Directory seek (pos)
@end defmethod

@defmethod Directory tell ()
@end defmethod


@c ----------------------------------------------------------------------
@node Function, Math, Directory, Native Objects
@subsection Function

@c ----------------------------------------------------------------------
@node Math, Number, Function, Native Objects
@subsection Math

@table @strong
@item Standard
@value{ECMA}
@end table

@defop {Static Method} Math abs (@var{x})
@end defop

@defop {Static Method} Math acos (@var{x})
@end defop

@defop {Static Method} Math asin (@var{x})
@end defop

@defop {Static Method} Math atan (@var{x})
@end defop

@defop {Static Method} Math atan2 (@var{y}, @var{x})
@end defop

@defop {Static Method} Math ceil (@var{x})
@end defop

@defop {Static Method} Math cos (@var{x})
@end defop

@defop {Static Method} Math exp (@var{x})
@end defop

@defop {Static Method} Math floor (@var{x})
@end defop

@defop {Static Method} Math log (@var{x})
@end defop

@defop {Static Method} Math max (@var{x}, @var{y})
@end defop

@defop {Static Method} Math min (@var{x}, @var{y})
@end defop

@defop {Static Method} Math pow (@var{x}, @var{y})
@end defop

@defop {Static Method} Math random ()
@end defop

@defop {Static Method} Math round (@var{x})
@end defop

@defop {Static Method} Math seed (@var{x})

@table @strong
@item Standard
@value{NGS}
@end table

@end defop

@defop {Static Method} Math sin (@var{x})
@end defop

@defop {Static Method} Math sqrt (@var{x})
@end defop

@defop {Static Method} Math tan (@var{x})
@end defop



@defcv {Static Property} Math E
@end defcv

@defcv {Static Property} Math LN10
@end defcv

@defcv {Static Property} Math LN2
@end defcv

@defcv {Static Property} Math LOG10E
@end defcv

@defcv {Static Property} Math LOG2E
@end defcv

@defcv {Static Property} Math PI
@end defcv

@defcv {Static Property} Math SQRT1_2
@end defcv

@defcv {Static Property} Math SQRT2
@end defcv

@c ----------------------------------------------------------------------
@node Number, Object, Math, Native Objects
@subsection Number

@table @strong
@item Standard
@value{ECMA}
@end table

@defun Number()
Return value @code{0}.
@end defun

@defun Number (value)
@end defun

@c --- Constructors -----------------------------------------------------

@deffn Constructor Number ()
@deffnx Constructor Number (@var{value})
Create a new number object.  If no argument is given, the constructor
returns value @code{+0}.  If the argument @var{value} is given, the
constructor returns @code{ToNumber(@var{value})}.

@example
new Number ();
@result{} 0
new Number (3.1415);
@result{} 3.1415
new Number (true);
@result{} 1
@end example

@end deffn

@defmethod Number toString ([@var{radix}])
Convert the number to its textual presentation.  If the argument
@var{radix} is given, it specifies the radix to which the number is
formatted.  If the argument @var{radix} is not given, it defaults to
@code{10}.

@example
System.stdout.writeln ((193).toString ());
@print{} 193
System.stdout.writeln ((193).toString (8));
@print{} 301
System.stdout.writeln ((193).toString (16));
@print{} c1
System.stdout.writeln ((193).toString (2));
@print{} 11000001
@end example
@end defmethod

@defmethod Number valueOf ()
Return the value of the number object.
@end defmethod


@defcv {Static Property} Number MAX_VALUE
@end defcv

@defcv {Static Property} Number MIN_VALUE
@end defcv

@defcv {Static Property} Number NaN
@end defcv

@defcv {Static Property} Number NEGATIVE_INFINITY
@end defcv

@defcv {Static Property} Number POSITIVE_INFINITY
@end defcv


@c ----------------------------------------------------------------------
@node Object, RegExp, Number, Native Objects
@subsection Object

@table @strong
@item Standard
@value{ECMA}
@item Incompatibilities
@itemize @bullet
@item The @code{toString()} and @code{toSource()} methods are missing.
@item The constructor doesn't set the [[Prototype]] and [[Class]]
properties.
@end itemize
@end table


@defun Object ([@var{value}])
@end defun

@c --- Constructors -----------------------------------------------------

@deffn Constructor Object ([@var{value}])
Create a new object.

@example
var o = new Object ();
@end example
@end deffn

@c --- Methods ----------------------------------------------------------

@defmethod Object toString ()
@end defmethod

@defmethod Object toSource ()
@end defmethod

@defmethod Object valueOf ()
@end defmethod


@c ----------------------------------------------------------------------
@node RegExp, String, Object, Native Objects
@subsection RegExp

@table @strong
@item Standard
@value{ECMA}

@item Incompatibilities
@itemize @bullet
@item The regular expression engine -- taken from the GNU Emacs -- might
not support all features that are required.
@item XXX Check all methods and properties.
@end itemize
@end table

@deffn Constructor RegExp (pattern[, flags])

Create a new regular expression from string @var{pattern}.  The optional
argument string @var{flags} can contain the following options:

@table @code
@item i
Ignore case; the matching is case-insensitive.

@item g
Global search.  This allows you to iterate over all matches of the
expression by executing the @code{exec} method multiple times against
the string.
@end table
@end deffn

@defmethod RegExp compile (@var{pattern}[, @var{flags}])
Create a new regular expression from string @var{pattern} using optional
options @var{flags}.  The method can be used to change the regular
expression pattern or its flags in the regular expression object.
The method returns an error if the string @var{pattern} do not specify a
well-formed regular expression.

@strong{Note!}  All regular expressions are always compiled in this
implementation.  This holds also for the expressions, created with the
@code{RegExp()} constructor.

@c @cartouche
@example
var re = new RegExp ("ab*");
re.compile ("ab*", "i");
@end example
@c @end cartouche
@end defmethod

@defmethod RegExp exec ([string])
Match the expression against the string @var{string}.  If the argument
@var{string} is omitted, the regular expression is matched against the
@code{RegExp.input} string.  The method returns an array that holds the
matched portions of the expression.

@c @cartouche
@example
var re = new RegExp ("d(b+)(d)", "ig");
var a = re.exec ("cdbBdbsbz");
a.toString ();
@result{} "dbBd,bB,d"
@end example
@c @end cartouche
@end defmethod

In the previous example, the result array @samp{a} has the following
items:

@table @code
@item dbBd
The substring that matched the regular expression.  This string can also
be retrieved as @samp{RegExp.lastMatch}.

@item bB
The matched substring for the first parenthesized subexpression
@samp{(b+)}.  This match can also be found as @samp{RegExp.$1}.

@item d
The matched substring for the second parentsized subexpression
@samp{(d)}.  This match can also be found as @samp{RegExp.$2}.
@end table

The option @samp{g} of the regular expression can be used to iterate
over multiple matches of the expression on at a time.  For example, the
following code fragment searches for the expression @samp{a(b*)} from
the string @samp{str}.  In the inial state -- when the expression is
create with the constructor -- the object's @samp{lastIndex} property is
set to 0.  When the expression is matched against the string, the
@samp{lastIndex} property is updated to point to the next index from
which the matching should be continued.  Therefore, the following
example iterates over all matches in the string @samp{str}.

@c @cartouche
@example
var re = new RegExp ("a(b*)", "g");
var str = "abbcdefabh";
while (a = re.exec (str))
  System.print ("Found ", a, ". Next match starts at ", re.lastIndex,
		    ".\n");
@print{} Found abb. Next match starts at 3.
@print{} Found ab. Next match starts at 9.
@end example
@c @end cartouche

The property @samp{@var{regexp}.lastIndex} can also be set explicitly to
start the matching from a pre-defined position.


@defmethod RegExp test ([string])
Test whether the regular expression matches for the string @var{string}.
If the argument @var{string} is omitted, the regular expression is
tested against the @code{RegExp.input} string.

@c @cartouche
@example
var re = new RegExp ("fo*bar");
re.test ("fbar");
@result{} true
re.test ("fooBar");
@result{} false

re = new RegExp ("fo*bar", "i");
re.test ("FOObAR");
@result{} true

RegExp.input = "#include <stdio.h>";
re = new RegExp ("^#");
re.test ();
@result{} true
@end example
@c @end cartouche
@end defmethod

@defcv {Static Property} RegExp {$1}
@defcvx {Static Property} RegExp {$2}
@defcvx {Static Property} RegExp {$3}
@defcvx {Static Property} RegExp {$4}
@defcvx {Static Property} RegExp {$5}
@defcvx {Static Property} RegExp {$6}
@defcvx {Static Property} RegExp {$7}
@defcvx {Static Property} RegExp {$8}
@defcvx {Static Property} RegExp {$9}
The matching substring for the @i{n}:th parenthesized subexpression.  If
the latest regular expression didn't have that many parenthesized
subexpressions, the property has value @samp{undefined}.
@end defcv

@defcv {Static Property} RegExp {$_}
@defcvx {Static Property} RegExp {input}
The string against which the expression was tested.  The @samp{input}
property is also used, if no string argument was given for the
@samp{test()} or @samp{exec()} methods.

@c @cartouche
@example
var str = file.readln ();
re.test (str);
RegExp.input;
@result{} @var{The string returned by the @samp{file.readln()} method.}
@end example
@c @end cartouche
@end defcv

@defcv {Static Property} RegExp lastMatch
The substring that matched the whole expression in the last regular
expression matching.
@end defcv

@defcv {Static Property} RegExp lastParen
The last parenthesized subexpression of the last regular expression
matching.
@end defcv

@defcv {Static Property} RegExp leftContext
The substring from the beginning of the input string to the beginning of
the matching substring of the last regular expression.

@c @cartouche
@example
var re = new RegExp ("foo");
var str = "garbage foo tail garbage";
re.exec (str);
RegExp.leftContext;
@result{} "garbage "
@end example
@c @end cartouche
@end defcv

@defcv {Static Property} RegExp multiline
@end defcv

@defcv {Static Property} RegExp rightContext
The substring from the end of the matching substring to the end the
input string.

@c @cartouche
@example
var re = new RegExp ("foo");
var str = "garbage foo tail garbage";
re.exec (str);
RegExp.rightContext;
@result{} " tail garbage"
@end example
@c @end cartouche
@end defcv

@defcv Property RegExp global
Flag that tells if the option @samp{g} was given for the constructor or
for the @code{compile} method.
@end defcv

@defcv Property RegExp ignoreCase
Flat that tells if the option @samp{i} was given for the construtor or
for the @code{compile} method.
@end defcv

@defcv Property RegExp lastIndex
The index from which the matching is continued with the global
(@samp{g}) expressions.
@end defcv

@defcv Property RegExp source
The source string from which the regular expression object was created.
@end defcv



@c ----------------------------------------------------------------------
@node String, System, RegExp, Native Objects
@subsection String

@table @strong
@item Standard
@value{ECMA}
@item Incompatibilities
@itemize @bullet
@item The constructor doesn't set the [[Prototype]] and [[Class]]
properties.
@end itemize
@end table

@deffn Constructor String (string)
Create a new string object and set its data to @var{string}.

@c @cartouche
@example
var str = new String ("Hello, world");
@result{} "Hello, world!"
@end example
@c @end cartouche
@end deffn


@defop {Static Method} String fromCharCode (code@dots{})
Create a new string object from the character codes @var{code}@dots{}.

@c @cartouche
@example
var str = String.fromCharCode (72, 101, 108, 108, 111, 33);
@result{} "Hello!"
@end example
@c @end cartouche
@end defop

@defop {Static Method} String pack (format, arg[, @dots{}])

@table @strong
@item Standard
@value{NGS}
@end table

Create a new string by packing values @var{arg}@dots{} to a string
according to the format string @var{format}.

The format is a sequence of characters that specify the type of values
as follows:

@table @code
@item C
an unsigned char value

@item n
a short in "network" (big-endian) order

@item N
a long in "network" (big-endian) order

@item d
a double-precision float in the native format
@end table
@end defop


@defmethod String append (string)

@table @strong
@item Standard
@value{NGS}
@end table

Append string @var{string} to the end of the string object.  The string
object must be a dynamic string, not a constant string literal.

@c @cartouche
@example
var str = new String ("");
str.append ("foo");
str.append ("-");
str.append ("bar");
@result{} "foo-bar"
@end example
@c @end cartouche
@end defmethod

@defmethod String charAt (position)
Create a new string that constains the character from position
@var{position} of the the string object.

@c @cartouche
@example
"foobar".charAt (3);
@result{} "b"
@end example
@c @end cartouche
@end defmethod

@defmethod String charCodeAt (position)
Return the code of the character at position @var{position} in the
string object.

@c @cartouche
@example
"foobar".charCodeAt (3);
@result{} 98
@end example
@c @end cartouche
@end defmethod

@defmethod String concat (@var{string}[, @dots{}])
Create a new string by appending the argument strings @var{string},
@dots{} to the end of the string object.

@c @cartouche
@example
"foo".concat ("bar");
@result{} "foobar"
@end example
@c @end cartouche
@end defmethod

@defmethod String crc32 ()

@table @strong
@item Standard
@value{NGS}
@end table

Count a 32-bit CRC of the string.

@c @cartouche
@example
var str = "Hello, world!";
System.print ("CRC32 of \"", str, "\" is ",
              str.crc32 ().toString (16), ".\n");
@print{} CRC32 of "Hello, world!" is e4928064.
@end example
@c @end cartouche
@end defmethod

@defmethod String indexOf (string[, start_index])
Return the index of the first substring of @var{string} within the
string object, or -1 if the string didn't contain the substring.  The
optional argument @var{start_index} can be used to specify the index
from which the searching is started.

@c @cartouche
@example
var str = "foobar foo bar foo";
str.indexOf ("foo");
@result{} 0
str.indexOf (" foo");
@result{} 6
str.indexOf ("foo", 1);
@result{} 7
str.indexOf ("Foo");
@result{} -1
@end example
@c @end cartouche
@end defmethod

@defmethod String lastIndexOf (string[, start_index])
Return the the index of the last substring of @var{string} within the
string object, or -1 if the string didn't contain the substring.  The
optional argument @var{start_index} can be used to specify the index
from which the searching is started.

@c @cartouche
@example
var str = "foobar foo bar foo";
str.lastIndexOf ("foo");
@result{} 15
str.lastIndexOf ("bar");
@result{} 11
str.lastIndexOf ("foo", 14);
@result{} 7
str.lastIndexOf ("Foo");
@result{} -1
@end example
@c @end cartouche
@end defmethod

@defmethod String match (regexp)
@end defmethod

@defmethod String replace (regexp, substitution)
@end defmethod

@defmethod String search (regexp)
@end defmethod

@defmethod String slice (start[, end])
@end defmethod

@defmethod String split (separtor[, limit])
@end defmethod

@defmethod String substr (start[, length])
@end defmethod

@defmethod String substring (start[, end])
@end defmethod

@defmethod String toLowerCase ()
Create a new string which contents is the data of the string object,
converted to the lower case.

@c @cartouche
@example
"FoObAr".toLowerCase ();
@result{} "foobar"
@end example
@c @end cartouche
@end defmethod

@defmethod String toUpperCase ()
Create a new string which contents is the data of the string object,
converted to the upper case.

@c @cartouche
@example
"FoObAr".toUpperCase ();
@result{} "FOOBAR"
@end example
@c @end cartouche
@end defmethod

@defmethod String unpack (format)

@table @strong
@item Standard
@value{NGS}
@end table

@end defmethod


@defcv Property String length
The length of the string.

@c @cartouche
@example
"foobar".length;
@result{} 6
var str = new String ("foo");
str.append ("bar");
str.length;
@result{} 6
@end example
@c @end cartouche
@end defcv


@node System, VM, String, Native Objects
@subsection System

@table @strong
@item Standard
@value{NGS}
@end table


@defop {Static Method} System chdir (directory)
Change the process' current working directory to @var{directory}.  The
function returns a boolean success status.
@end defop

@defop {Static Method} System error (any[, @dots{}])
Convert arguments @var{any}@dots{} to string and print the resulting
string to the standard error stream of the system.
@end defop

@defop {Static Method} System exit (code)
Terminate the program execution and return the value @var{code} to the
operating system as the return value of the running program.
Effectively the method performs C-code @samp{exit (@var{code})}.
@end defop

@defop {Static Method} System getcwd ()
Get the current working directory of the process.  The function returns
a strings presenting the directory or @code{false} if errors were
encountered.
@end defop

@defop {Static Method} System getenv (variable)
Return the value of the environment variable @var{variable}.  The method
returns the value as a string or @samp{undefined} if the variable was
not defined in the environment.
@end defop

@defop {Static Method} System popen (command, mode)
@end defop

@defop {Static Method} System print (any[, @dots{}])
Convert arguments @var{any}@dots{} to string and print the resulting
string to the standard output stream of the system.
@end defop

@defop {Static Method} System sleep (seconds)
Stop the interpreter for @var{seconds} seconds.
@end defop

@defop {Static Method} System strerror (errno)
Return a string that describes the system error code @var{errno}.
@end defop

@defop {Static Method} System system (command)
@end defop

@defop {Static Method} System usleep (micro_seconds)
Stop the interpreter for @var{micro_seconds} micro seconds.
@end defop

@defcv {Static Property} System bits
Return a value that describes the "bitness" of the underlying system.
Possible values might be @samp{16}, @samp{32}, @samp{64}, or even
@samp{128}.  Normally this is the size of a host system pointer in bits.
@end defcv

@defcv {Static Property} System canonicalHost
The canonical host name of the system where the interpreter was
compiled.

@example
System.stdout.writeln (System.canonicalHost);
@print{} powerpc-ibm-aix4.2.1.0
@end example
@end defcv

@defcv {Static Property} System canonicalHostCPU
The CPU part of the canonical host name.

@example
System.stdout.writeln (System.canonicalHostCPU);
@print{} powerpc
@end example
@end defcv

@defcv {Static Property} System canonicalHostVendor
The Vendor part of the canonical host name.

@example
System.stdout.writeln (System.canonicalHostVendor);
@print{} ibm
@end example
@end defcv

@defcv {Static Property} System canonicalHostOS
The OS part of the canonical host name.

@example
System.stdout.writeln (System.canonicalHostOS);
@print{} aix4.2.1.0
@end example
@end defcv

@defcv {Static Property} System errno
The system's error number.  The error number can be converted to a
string with the @code{strerror()} method of the System object.

@example
var fp = new File ("output.txt");
if (!fp.open ("w"))
  System.error ("couldn't create output file `", fp, "': ",
                System.strerror (System.errno), "\n");
@print{} couldn't create output file `output.txt': Permission denied
@end example
@end defcv

@defcv {Static Property} System lineBreakSequence
The line break sequence that is used in the underlying system.  For
example, the outputs from the following lines are identical:

@example
System.stdout.writeln ("Hello!");
@print{} Hello!
System.stdout.write ("Hello!" + System.lineBreakSequence);
@print{} Hello!
@end example

@end defcv

@defcv {Static Property} System stderr
The system's standard error stream.  This is a normal JavaScript file
and all methods of the File object can be called for it.

@example
System.stderr.writeln ("panic: must exit");
System.exit (1);
@print{} panic: must exit
@end example
@end defcv

@defcv {Static Property} System stdin
The system's standard input stream.
@end defcv

@defcv {Static Property} System stdout
The system's standard output stream.
@end defcv


@node VM,  , System, Native Objects
@subsection VM

@table @strong
@item Standard
@value{NGS}
@end table


@defop {Static Method} VM garbageCollect ()
Perform a garbage collection for the virtual machine heap.  Normally,
the garbage collection is triggered automatically, but the
@code{garbageCollect()} method can be used to trigger the collection
explicitly.
@end defop

@defop {Static Method} VM stackTrace ([@var{limit}])
Print the contents of the virtual machine stack.  Optional argument
@var{limit} specifies how many stack frames are printed.  If no
arguments are given, the whole virtual machine stack is printed.

@c @cartouche
@example
function recursive (n)
@{
  if (n > 5)
    VM.stackTrace ();
  else
    recursive (n + 1);
@}

recursive (0);
@print{}VM: stacktrace: stacksize=2048, used=78
@print{}#0   recursive(): builtin 0
@print{}#1   recursive(): null 1 6
@print{}#2   recursive(): null 1 5
@print{}#3   recursive(): null 1 4
@print{}#4   recursive(): null 1 3
@print{}#5   recursive(): null 1 2
@print{}#6   recursive(): null 1 1
@print{}#7   .global(): null 1 0
@end example
@c @end cartouche
@end defop

@defcv {Static Property} VM dispatchMethod
The name of the dispatch method, currently used in the virtual machine.
The method returns a string that describes the method.  The possible
return values are @samp{switch-basic}, @samp{switch}, and @samp{jumps}.
@end defcv

@defcv {Static Property} VM gcCount
How many times the garbage collection has been performed for the heap.
@end defcv

@defcv {Static Property} VM gcTrigger
The garbage collection trigger.  When the virtual machine heap has
allocated more than @code{gcTrigger} number of bytes of memory, the
virtual machine will perform a garbage collection.
@end defcv

@defcv {Static Property} VM heapAllocated
The number of bytes of memory the system has allocated from the heap.
@end defcv

@defcv {Static Property} VM heapFree
The number of bytes of memory the heap freelist contains.
@end defcv

@defcv {Static Property} VM heapSize
The size of the heap in bytes.
@end defcv

@defcv {Static Property} VM numConstants
The number of constants defined in the virtual machine.
@end defcv

@defcv {Static Property} VM numGlobals
The number of global symbols defined in the virtual machine.  This value
equals to the number of global variables and functions, defined in the
system.
@end defcv

@defcv {Static Property} VM stackSize
The size of the virtual machine stack.
@end defcv

@defcv {Static Property} VM stacktraceOnError
A boolean flag that tells whether the virtual machine stack trace is
printed if an error occurs in the program execution.
@end defcv

@defcv {Static Property} VM verbose
The verbosity level of the virtual machine.
@end defcv

@defcv {Static Property} VM verboseStacktrace
A boolean flag that tells whether the virtual machine prints the normal
or verbose stacktrace.
@end defcv

@defcv {Static Property} VM version
The version string of the interpreter virtual machine.
@end defcv

@defcv {Static Property} VM versionMajor
The major version number of the virtual machine.
@end defcv

@defcv {Static Property} VM versionMinor
The minor version number of the virtual machine.
@end defcv

@defcv {Static Property} VM versionPatch
The patch level number of the virtual machine.
@end defcv

@defcv {Static Property} VM warnUndef
A boolean flag that tells whether the virtual machine should print a
warning message if an undefined variable is used.
@end defcv



@node Extensions,  , Native Objects, NGS JavaScript Language
@section Extensions

@menu
* Curses::
* JS::
* MD5::
@end menu

@node Curses, JS, Extensions, Extensions
@subsection Curses


@node JS, MD5, Curses, Extensions
@subsection JS

@deffn Constructor JS ()
@end deffn

@defmethod JS compile (file, asm_file, bc_file)
@end defmethod

@defmethod JS eval (string)
@end defmethod

@defmethod JS evalFile (filename)
@end defmethod

@defmethod JS evalJavaScriptFile (filename)
@end defmethod

@defmethod JS executeByteCodeFile (filename)
@end defmethod

@defmethod JS getVar (name)
@end defmethod

@defmethod JS setVar (name, value)
@end defmethod

@defcv Property JS errorMessage
@end defcv

@c ----------------------------------------------------------------------
@node MD5,  , JS, Extensions
@subsection MD5

@deffn Constructor MD5 ()
Create a new MD5 message digest object.

@c @cartouche
@example
var md5 = new MD5 ();
@end example
@c @end cartouche
@end deffn

@defmethod MD5 final ()
Return the MD5 value of the data, set to the object with the
@code{update()} method.  The method returns a 32 bytes long string that
holds the MD5 value as a hexadecimal number.

@c @cartouche
@example
function print_md5 (str)
@{
  var md5 = new MD5 ();
  md5.update (str);
  System.print ("MD5 of \"", str, "\" is ",
                md5.final (), ".\n");
@}
print_md5 ("Hello, world!");
@print{} MD5 of "Hello, world!" is 6CD3556DEB0DA54BCA060B4C39479839.
@end example
@c @end cartouche
@end defmethod

@defmethod MD5 finalBinary ()
Return the MD5 value of the data.  The method returns a 128 bits long
MD5 value.
@end defmethod

@defmethod MD5 init ()
Initalize the object to the initial state.  The method can be used to
reset the object after some data has been set to it with the
@code{update()} method.
@end defmethod

@defmethod MD5 update (str)
Append data to the object.  The method can be called multiple times, so
that the MD5 message digest can be counted one block at a time.

@c @cartouche
@example
function count_md5_for_file (stream)
@{
  var md5 = new MD5 ();

  while (!stream.eof ())
    @{
      var data = stream.read (1024);
      md5.update (data);
    @}

  return md5.final ();
@}
@end example
@c @end cartouche
@end defmethod


@c ----------------------------------------------------------------------
@node The js Program, The jsas Program, NGS JavaScript Language, Top
@chapter The @file{js} Program

The @samp{js} program is the JavaScript interpreter command.  It can be
used to execute JavaScript and JavaScript byte-code files.  The progam
can also be used to compile JavaScript files into the byte-code files.

@menu
* Invoking The js Program::
* Evaluating and Executing Code::
* Compiling JavaScript Code::
@end menu

@node Invoking The js Program, Evaluating and Executing Code, The js Program, The js Program
@section Invoking The @samp{js} Program

The @code{js} program is invoked as:

@code{js} @var{option}@dots{} @var{file} [@var{argument}@dots{}]

@noindent The @code{js} program processes the command line options and
when the first non-option argument, or the option @samp{--file}, is
encountered, it is assumed to contain JavaScript or byte-code that
should be evaluated.  The interpreter will pass all remaining arguments
to the script throught the @samp{ARGS} array.  The items in the array
are strings containing the arguments @var{argument}@dots{}.  The first
item of the array is always the name of the script @var{file}.

The options can be one or more of the following command line options:

@table @code
@item -a
@itemx --annotate-assembler

Annotate the created assembler listing with the original JavaScript
source code.  The option can be used only with the @samp{--assembler}
option.

@item -c
@itemx --compile

Compile JavaScript files to byte-code.  The generated byte-code is saved
to file which name is created from the name of the input file by
replacing the suffix @samp{.js} with the suffix @samp{.jsc}.  The
compilation can be controlled with options @samp{--debug},
@samp{--optimize}, and @samp{--compiler-option}.

@item -d @var{type}
@itemx --dispatch=@var{type}

Use the byte-code instruction dispatch method @var{type}.  The current
implementation supports the following dispatch methods:

@table @code
@item switch-basic

The basic switch-method using a big switch-case table to dispatch the
instruction.  This method is available only if the interpreter has been
configured with the option @samp{--with-all-dispatchers}.

@item switch

An optimized version of the switch-method.  This method is supported on
all environments.

@item jumps

The fastest dispatch method that uses the `computed goto' statement of
the GNU C-compiler.  This method is available if the interpreter has
been compiler with the GNU C-compiler.
@end table

The default dispatch method, for environments that has the GNU
C-compiler, is @samp{jumps}.  For all other environments, the default
method is @samp{switch}.


@item -e @var{code}
@itemx --eval=@var{code}

Evaluate JavaScript code @var{code}.

@cartouche
@example
$ js --eval='System.print ("Hello, world!\n");'
@print{} Hello, world!
@end example
@end cartouche


@item -E
@itemx --events

Print the interpreter events to the standard error.

@cartouche
@example
$ js -E -c test.js
[js: garbage collect]
[js: garbage collect]
[js: garbage collect]
[js: garbage collect]
@end example
@end cartouche


@item -f
@itemx --file

Stop processing options and use the next argument as the name of the
JavaScript (or byte-code) file.  All the remaining arguments are passed
to the interpreter through the @code{ARGS} array.  The first item of the
array will be the name of the script, i.e. the argument that follows the
option @samp{--file}.

@cartouche
@example
$ cat hello.js
@print{} var i;
@print{} for (i = 0; i < ARGS.length; i++)
@print{}   System.print (i, ": ", ARGS[i], "\n");
$ js --file hello.js a b c d
@print{} 0: hello.js
@print{} 1: a
@print{} 2: b
@print{} 3: c
@print{} 4: d
@end example
@end cartouche

The option can also be used with the option @samp{--load} to indicate
the last file to load.  Also in that case, the remaining arguments will
be passed to the script through the @code{ARGS} array.

@item -g
@itemx --debug

Make the compiler to generate debugging information to the generated
byte-code files.  This option can be used with the option
@samp{--compile}.

@item -h
@itemx --help

Print a short help message that describes the options that can be given
to the @samp{js} program.

@item -l
@itemx --load

Load multiple JavaScript and JavaScript byte-code files to the
interpreter.  Normally, the first non-option argument is evaluated and
all remaining arguments are passed to the script as arguments.  With the
option @code{--load}, multiple files can be loaded the to the
interpreter.  The loading can be stopped with option @code{--file} that
specifies the last file to load.

For example, if we have files @file{a.js}:

@example
function do_a ()
@{
  System.print ("do_a()\n");
@}
@end example

@noindent @file{b.js}:

@example
function do_b ()
@{
  System.print ("do_b()\n");
@}
@end example

@noindent and @file{main.js}:

@example
do_a ();
do_b ();
@end example

@noindent the whole application can be run as:

@cartouche
@example
$ js --load a.js b.js --file main.js @var{arguments}@dots{}
@print{} do_a()
@print{} do_b()
@end example
@end cartouche

@item -N
@itemx --no-compiler

Do not define the compiler to the virtual machine.  This option makes
the interpreter smaller, but the interpreter can only execute
pre-compiled byte-code files.  The option disables the @samp{eval}
global method.

@item -O [@var{level}]
@itemx --optimize[=@var{level}]

Set the compiler optimization level to @var{level}.  The compiler has
three different optimization levels:

@table @code
@item 0
Do not optimize.

@item 1
Perform all cheap optimizations which do not required heavy assembler
instruction analyzing.

@item 2
Perform all optimizations, supported by the compiler.
@end table

The default optimization level is 1.

@item -r @var{option}
@itemx --secure=@var{option}

Turn on virtual machine security option @var{option}.  The following
security options are available:

@table @code
@item file
Disable insecure methods from the buit-in File object.

@item system
Disable insecure methods from the buit-in System object.
@end table


@item -s @var{size}
@itemx --stack-size=@var{size}

Set the size of the virtual machine operand stack to @var{size}.  The
size of the virtual machine operand stack is set at the startup-time and
it can't be enlarged dynamically at the runtime.

@item -S
@itemx --assembler

Compile JavaScript files to JavaScript assembler.  The generated
assembler listing is saved to file which name is created from the name
of the input file by replacing the suffix @samp{.js} with the suffix
@samp{.jas}.  The compilation can be controlled with options
@samp{--optimize}, and @samp{--compiler-option}.

@item -t
@itemx --stacktrace

Print a stack trace on error.  When an error occurs during the
evaluation of a script, the virtual machine will halt and the @samp{js}
program terminates.  If the option @samp{--stacktrace} was given to the
interpreter, the virtual machine will print a stack trace that shows the
call stack at the point of the error.

The following listing showns an program that raises an error at the
specified recursion level.

@example
function recursive (level)
@{
  if (level <= 0)
    error ("recursion limit exceeded");
  else
    recursive (level - 1);
@}

recursive (5);
@end example

@noindent If the program is executed without the @samp{--stacktrace}
option, the following result is shown:

@example
$ js hello.js
js: evaluation of file `hello.js' failed:
hello.js:6: recursion limit exceeded
@end example

@noindent With the @samp{--stacktrace} option, the @samp{js} program
will print the following error message:

@cartouche
@example
$ js --stacktrace hello.js
@print{} VM: error: hello.js:6: recursion limit exceeded
@print{} VM: stacktrace: stacksize=2048, used=44
@print{} #0   recursive(): null 1 "recursion limit exceeded"
@print{} #1   recursive(): null 1 0
@print{} #2   recursive(): null 1 1
@print{} #3   recursive(): null 1 2
@print{} #4   recursive(): null 1 3
@print{} #5   recursive(): null 1 4
@print{} #6   .global(): null 1 5
@print{} js: evaluation of file `hello.js' failed:
@print{} hello.js:6: recursion limit exceeded
@end example
@end cartouche

@item -v
@itemx --verbose

Increase the verbosity of the interpreter.  The option can be given
multiple times to increase the amount of messages the interpreter
prints.

@item -V
@itemx --version

Print the version number of the @code{js} program.

@item -W @var{option}
@itemx --compiler-option=@var{option}

Set JavaScript compiler options according to the option specification
@var{option}.  The specification @var{option} can be given in two forms.
In the normal form, the option specifies a compiler option that should
be set on.  If the specification @var{option} starts with the prefix
`@code{no-}', the specified option will be turn off.  The following
option specifications are currently implemented:

@table @code
@item all
match most of the compile time options

@item pedantic
match all compile time options.  This option generates as much warnings
as possible.  It will also complain about some things that are allowed
by the ECMAScript standard, but which are consired to show bad
programming style, for example, missing semicolons.

@item runtime
match all runtime options

@item shadow
warn if a variable declaration shadows a parameter

@item undefined
runtime check for undefined global variables

@item unused-argument
warn about unused arguments

@item unused-variable
warn about unused local variables

@item with-clobber
warn if the with-lookup of a symbol is clobbered because the symbol is
defined to be a local variable or a function argument

@item missing-semicolon
warn about missing semicolons that are fixed by the missing semicolon
inserting during the compilation

@item strict-ecma
warn about things that are supported by this implementation, but are not
allowed by the ECMAScript standard.  These features are:

@itemize @bullet
@item line terminators in string and regular expression constants
@end itemize


@item deprecated
warn if deprecated features has been used in the source code

@end table

@item -x
@itemx --executable
Add execute permissions to the generated byte-code files.  This option
is useful on Linux environments where JavaScript byte-code files can be
executed natively with the `binfmt_js' module.

@cartouche
@example
$ cat hello.js
@print{} System.stdout.writeln ("Hello, world!");
$ js -cx hello.js
$ ./hello.jsc
@print{} Hello, world!
@end example
@end cartouche

@end table


@node Evaluating and Executing Code, Compiling JavaScript Code, Invoking The js Program, The js Program
@section Evaluating and Executing Code

@node Compiling JavaScript Code,  , Evaluating and Executing Code, The js Program
@section Compiling JavaScript Code

The compilation of JavaScript code is carried out with the following
command:

@code{js} [@var{options}] @code{-c} @var{file}@dots{}

@noindent where @var{file} is a JavaScript source file to compile and
@var{options} specify additional compiler options.

In the simplest form, the compilation goes as follows:

@cartouche
@example
$ js -c hello.js
@end example
@end cartouche

@noindent This example compiles file @file{hello.js} to byte-code file
@file{hello.jsc} with the default compiler options.

@menu
* Warning Messages::
* Optimization::
* Debugging Information::
* Assembler Listings::
@end menu

@node Warning Messages, Optimization, Compiling JavaScript Code, Compiling JavaScript Code
@subsection Warning Messages

It is nice to get as many error messages as possible at the compilation
time.  However, sometimes some error messages are false and it is
annoying to see them every time you compile your project.  The option
@code{--compiler-option} can be used to adjust the level of warning
messages the compiler generates.

Normally we want to get all possible compiler time warnings.  They can
be enable with the @code{-Wall} option.  To set the warnings
individually, the following options can be given for the
@code{--compiler-option} option.  The option names can be prefixed with
string @samp{no-} to turn them off instead of setting them.  For
example, let's assume that we want to get as much warnings as possible,
but we do not care about unused function arguments:

@cartouche
@example
$ js -Wall -Wno-unused-arguments -c hello.js
@end example
@end cartouche

@noindent In this example, we turn on all warnings @samp{-Wall}, but we
turn off warnings about unused arguments @samp{-Wno-unused-arguments}.

The @code{js} program knows the following warning options:

@table @code
@item shadow
Warn if a variable declaration shadows a parameter.  For example, when
compiling file @file{test.js} containing code:

@example
function foo (a, b)
@{
  var a = 1;
  return a + b;
@}
@end example

@noindent the following warning is generated:

@cartouche
@example
$ js -Wshadow -c test.js
@print{} test.js:3: warning: declaration of `a' shadows a parameter
@end example
@end cartouche

@item unused-argument
Warn if an argument is not used in the function body.  For example, when
compiling file @file{test.js} containing code:

@example
function foo (a, b)
@{
  return a + 5;
@}
@end example

@noindent the following warning is generated:

@cartouche
@example
$ js -Wunused-argument -c test.js
@print{} test.js:1: warning: unused argument `b'
@end example
@end cartouche

@item unused-variable
Warn if a local variable is not used in the function body.  For example,
when compiling file @file{test.js} containing code:

@example
function foo (a, b)
@{
  var c;
  return a + b;
@}
@end example

@noindent the following warning is generated:

@cartouche
@example
$ js -Wunused-variable -c test.js
@print{} test.js:3: warning: unused variable `c'
@end example
@end cartouche

@item with-clobber
Warn if the with-lookup of a symbol is clobbered because the symbol is
defined to be a local variable or a function argument.  For example,
when compiling file @file{test.js} containing code:

@example
function foo (PI)
@{
  with (Math)
    System.print ("PI=", PI, "\n");
@}
@end example

@noindent the following warning is generated:

@cartouche
@example
$ js -Wwith-clobber -c test.js
@print{} test.js:4: warning: the with-lookup of symbol `PI' is
@print{} clobbered by the argument definition
@end example
@end cartouche

@item missing-semicolon
Warn if a semicolon is missing from the input.  The missing semicolons
are inserted during the parsing by the automatic semicolon inserting.
However, since the missing semicolons show bad programming style, this
option will warn about them.  For example, when compiling file
@file{test.js} containing code:

@example
function foo ()
@{
  return 1
@}

foo ()
@end example

@noindent the following warnings are generated:

@cartouche
@example
$ js -Wmissing-semicolon -c test.js
test.js:3: warning: missing semicolon
test.js:6: warning: missing semicolon
@end example
@end cartouche

@item strict-ecma
warn about things that are supported by this implementation, but are not
allowed by the ECMAScript standard.  For example, when compiling file
@file{test.js} containing code:

@example
function foo ()
@{
  System.stdout.writeln ("Hello, world!
");
@}
@end example

@noindent the following warning is generated:

@cartouche
@example
$ js -Wstrict-ecma -c test.js
test.js:3: warning: ECMAScript don't allow line terminators in
string constants
@end example
@end cartouche


@item deprecated
warn if deprecated features has been used in the source code.  For
example, when compiling file @file{test.js} containing code:

@example
function foo ()
@{
  for (var i in arguments)
    System.stdout.writeln (i);
@}
@end example

@noindent the following warning is generated:

@cartouche
@example
$ js -Wdeprecated -c test.js
test.js:1: warning: the `arguments' property of Function instance
is deprecated
@end example
@end cartouche

@end table

Besides the compiler time checks, the virtual machine can also perform
some checks at the runtime.  These checks can be set and unset with the
@samp{-Wruntime} option.

The following runtime warnings are supported:

@table @code
@item undefined
Warn if the value of an undefined global variable is used.  For example,
when running file @file{test.js} containing code:

@example
foo = an_undefined_variable;
@end example

@noindent the following warning is generated:

@cartouche
@example
$ js test.js
@print{} VM: warning: using undefined global `an_undefined_variable'
@end example
@end cartouche

@end table


@node Optimization, Debugging Information, Warning Messages, Compiling JavaScript Code
@subsection Optimization

@node Debugging Information, Assembler Listings, Optimization, Compiling JavaScript Code
@subsection Debugging Information

As a default, the JavaScript compiler do not include symbolic debugging
information to the generated byte-code files.  The debugging information
can be generated by giving the compiler @code{-g} option.  The debugging
information is also generated for the internal byte-code files that are
created when the interpreter evaluates plain JavaScript source code.

In the current implementation, the debugging information contains only
the names of the source files, and mappings from the virtual machine
program counter offsets to the source file locations.  In the future, it
will contain information about local variables and function arguments,
so that the symbolic debugger can print their values.

The presence of the debugging information shows in the error messages
the interpreter shows.  For example, let's consider the following
JavaScript source code file @file{test.js}:

@example
function foo (a)
@{
  a += 1;
  if (a > 50)
    error ("a overflow");

  return 1;
@}

foo (50);
@end example

When this file is compiled to the byte-code without debugging
information, the following error message is raised:

@cartouche
@example
$ js -c test.js
$ js test.jsc
@print{} js: evaluation of file `test.jsc' failed:
@print{} a overflow
@end example
@end cartouche

If we recompile the file with the debugging information, we will get a
more precise error message from the interpreter:

@cartouche
@example
$ js -g -c test.js
$ js test.jsc
@print{} js: evaluation of file `test.js' failed:
@print{} test.js:5: a overflow
@end example
@end cartouche

@noindent Now we see the exact source code location where the error
occurred.

The debugging information can be removed from the byte-code files after
the compilation with the @code{jsdas} program.

@cartouche
@example
$ jsdas --strip test.jsc
test.jsc:
jsdas: removing section 3
$ js test.jsc
js: evaluation of file `test.jsc' failed:
a overflow
@end example
@end cartouche

@node Assembler Listings,  , Debugging Information, Compiling JavaScript Code
@subsection Assembler Listings

The JavaScript compiler can generate assembler listings from the
JavaScript source files.  The assembler listings are generated just
before the resulting byte-code data would be generated. So the resulting
assembler listing is exactly the same that will be in the resulting
byte-code data.  The assembler listing is generated with the
@code{--assembler} option.  For example, if we have a source file
@file{hello.js} with the following contents:

@example
function hello ()
@{
  System.stdout.writeln ("Hello, world!");
  return true;
@}

hello ();
@end example

@noindent it can be compiled to assembler with command

@cartouche
@example
$ js -S hello.js
@end example
@end cartouche

@noindent The command will save the assembler listing in file
@file{hello.jas}:

@example
hello:
        load_arg        1
        add_2_i
        min_args        2
        const           "Hello, world!"
        const_i1
        load_global     System
        load_property   stdout
        call_method     writeln
        pop_n           4
        const_true
        return

.global:
        const_i0
        const_null
        jsr             hello
        apop            2
@end example

The option @code{--annotate-assembler} can be used with the
@code{--assembler} option.  It mixes the original source code to the
generated assembler listing.  In this format, it is easy to see how
different JavaScript constructs are compiled in the assembler.  Our
example file can be compiled to the annotated assembler with the
following command:

@cartouche
@example
$ js -a -S hello.js
@end example
@end cartouche

@noindent The result listing is saved to file @file{hello.jas}:

@example
; -*- asm -*-
; function hello ()

hello:
; @{
        load_arg        1
        add_2_i
        min_args        2
;   System.stdout.writeln ("Hello, world!");
        const           "Hello, world!"
        const_i1
        load_global     System
        load_property   stdout
        call_method     writeln
        pop_n           4
;   return true;
        const_true
        return
; @}
;
; hello ();

.global:
        const_i0
        const_null
        jsr             hello
        apop            2
@end example


@c ----------------------------------------------------------------------
@node The jsas Program, The jsdas Program, The js Program, Top
@chapter The @samp{jsas} Program

The @samp{jsas} program is a assembler for the JavaScript assembler.
The program can be used to compile assembler files into byte-code.

@menu
* Invoking The jsas Program::
@end menu

@node Invoking The jsas Program,  , The jsas Program, The jsas Program
@section Invoking The @samp{jsas} Program

The @code{jsas} program is invoked as:

@code{jsas} @var{option}@dots{} @var{file}@dots{}

The program reads the options and processes the assembler files
@var{file}@dots{} according to the options. The options can be one of
more of the following command line options:

@table @code
@item -g
@itemx --debug

Make the assembler to generate debugging information to the generated
byte-code files.

@item -h
@itemx --help

Print a short help message that describes the options that can be given
to the @samp{jsas} program.

@item -O
@itemx --optimize

Optimize the assembler instructions.

@item -v
@itemx --verbose

Turn on verbose diagnostic messages.  When this options is given, the
@code{jsas} program tells what it is doing.

@item -V
@itemx --version

Print the version number of the @code{jsas} program.

@end table

@c ----------------------------------------------------------------------
@node The jsdas Program, The jswrap Program, The jsas Program, Top
@chapter The @samp{jsdas} Program

The @samp{jsdas} program is a disassembler and a manipulator for the
JavaScript byte-code files.  The program can be used to view,
disassemble and manipulate the byte-code files.

@menu
* Invoking The jsdas Program::
* Viewing Byte-Code Files::
* Manipulating Byte-Code Files::
@end menu

@node Invoking The jsdas Program, Viewing Byte-Code Files, The jsdas Program, The jsdas Program
@section Invoking The @samp{jsdas} Program

The @code{jsdas} program is invoked as:

@code{jsdas} @var{option}@dots{} @var{file}@dots{}

The program reads the options and processes the byte-code files
@var{file}@dots{} according to the options.  The options can be one or
more of the following command line options:

@table @code
@item -c
@itemx --code

Print the code section of the byte-code files.  This is the default
action that is preformed if no options are given for the @code{jsdas}
program.

@item -C
@itemx --constants

Print the constants section of the byte-code file.

@item -d
@itemx --debug

Print the debug section of the byte-code file.

@item -h
@itemx --help

Print a short help message that describes the options that can be given
to the @code{jsdas} program.

@item -i
@itemx --info

Print the byte-code file information.

@item -l @var{type} @var{data}
@itemx --link @var{type} @var{data}

Link a new section to the byte-code file.  The section's type is
@var{type} and its contents is read from file @var{data}.

@item -r @var{type}
@itemx --remove @var{type}

Remove section of type @var{type} from the byte-code files.

@item -s
@itemx --symtab

Print the symbol table section of the byte-code file.

@item -S
@itemx --strip

Remove the debug section from the byte-code files.

@item -V
@itemx --version

Print the version number of the @code{jsdas} program.
@end table

@node Viewing Byte-Code Files, Manipulating Byte-Code Files, Invoking The jsdas Program, The jsdas Program
@section Viewing Byte-Code Files

In this section we assume that we have a source file @file{hello.js}
with the following contents:

@c @cartouche
@example
function main ()
@{
  System.print ("Hello, world!\n");
@}

main ();
@end example
@c @end cartouche

The file has been compiled to byte-code file @file{hello.jsc} with the
following command:

@cartouche
@example
$ js -Wall -g -c hello.js
@end example
@end cartouche

The option @samp{--info} is used to view the contents of the byte-code
file.  For example, our example file contains the following information:

@cartouche
@example
$ jsdas --info hello.jsc
hello.jsc:

* byte-code file information

  section 0: type=0 (code), length=34
  section 1: type=1 (constants), length=40
  section 2: type=2 (symtab), length=25
  section 3: type=3 (debug), length=40
@end example
@end cartouche

@noindent We see that the byte-code file has four sections: code,
constants, symtab and debug.  The listing shows also their lengths.  The
sections are:

@table @code
@item code
the byte-code instructions of the file

@item constants
the constant values of the file

@item symtab
the symbol table

@item debug
the debugging information
@end table

Next, we would like to see a assembler listing of the byte-code, defined
in the @code{code} section of the file.  This can be viewed with the
option @samp{--code} that is the @code{jsdas}'s default option (so no
options for the following example).

@cartouche
@example
$ jsdas hello.jsc
hello.jsc:

* section `Code'

main:
  0     load_arg        1
  2     add_2_i
  3     min_args        2
  5     const           "Hello, world!\n"
  10    const_i1
  11    load_global     System
  16    call_method     print
  21    pop_n           4
  23    const_undefined
  24    return

.global:
  25    const_i0
  26    const_null
  27    jsr             main
  32    apop            2
@end example
@end cartouche

The constants section holds the constant data the byte-code instructions
need.  These constants are pushed to the stack with the @code{const}
byte-code operand, or they are used to name a symbol in method
invocation or in subroutine call.

The constant section can be viewed with the @samp{--constants} option.

@cartouche
@example
$ jsdas --constants hello.jsc
hello.jsc:

* section `Constants'

  0:    "Hello, world!\n"
  1:    System
  2:    print
  3:    main
@end example
@end cartouche

Our example file defines four constants.  A string @samp{Hello,
world!\n} and three symbols @samp{System}, @samp{print}, and
@samp{main}.

The debugging information holds line number information about the source
file from which the file was compiled.  The debugging section can be
viewed with the option @samp{--debug}:

@cartouche
@example
$ jsdas --debug hello.jsc
hello.jsc:

* section `Debug'

  2     hello.js:2
  10    hello.js:3
  26    hello.js:6
@end example
@end cartouche

The symbol table hold the information about the global symbols the
byte-code file defines.  For each symbol, the symbol table has an offset
that points to the appropriate location in the byte-code instruction
stream.

The symbol table information can be viewed with the @samp{--symtab}
option:

@cartouche
@example
$ jsdas --symtab hello.jsc
hello.jsc:

* section `Symtab'

  main                                    0
  .global                                 25
@end example
@end cartouche

@node Manipulating Byte-Code Files,  , Viewing Byte-Code Files, The jsdas Program
@section Manipulating Byte-Code Files

@cartouche
@example
$ jsdas --link 7001 hello.js hello.jsc
hello.jsc:
jsdas: linking 67 bytes of data to section 7001
$ jsdas --info hello.jsc
hello.jsc:

* byte-code file information

  section 0: type=0 (code), length=34
  section 1: type=1 (constants), length=40
  section 2: type=2 (symtab), length=25
  section 3: type=3 (debug), length=40
  section 4: type=7001, length=67
@end example
@end cartouche

@cartouche
@example
$ jsdas --remove 3 hello.jsc
hello.jsc:
jsdas: removing section 3
$ jsdas --remove 7001 hello.jsc
hello.jsc:
jsdas: removing section 7001
$ jsdas -i hello.jsc
hello.jsc:

* byte-code file information

  section 0: type=0 (code), length=34
  section 1: type=1 (constants), length=40
  section 2: type=2 (symtab), length=25
@end example
@end cartouche

@c ----------------------------------------------------------------------
@node The jswrap Program, JavaScript API, The jsdas Program, Top
@chapter The `@code{jswrap}' Program

The @code{jswrap} program is a tool that helps implementing C functions
in JavaScript.

@menu
* Invoking The jswrap Program::
* Definition File Format::
* Re-Entrant Functions::
* Calling the Functions from C::
* Sample Project::
@end menu

@node Invoking The jswrap Program, Definition File Format, The jswrap Program, The jswrap Program
@section Invoking The @code{jswrap} Program

The @code{jswrap} program is invoked as:

@code{jswrap} @var{options}@dots{} @var{file}

@noindent The @code{jswrap} program processes the command line options
and according to them and the default values, it converts the input file
@var{file} to the corresponding @file{.h} and @file{.c} files.  The
options can be one of more of the following command line options:

@table @code
@item -g
@itemx --debug

Generate debugging information to the generated JavaScript byte-code.

@item -h @var{file}
@itemx --header @var{file}

Generate the C header file to file @var{file}.  The default C header
file name is constructed from the input file name by replacing the
suffix @file{.jsw} with suffix @file{.h}.

@item -n
@itemx --no-error-handler

Do not generate the default error handler to the generated C files.  If
this option is specified, then the error handler must be defined in your
code.

@item -o
@itemx --output @var{file}

Generate the C output to file @var{file}.  The default output file name
is constructed from the input file name by replacing the suffix
@file{.jsw} with suffix @file{.c}.

@item -r
@itemx --reentrant

Generate re-entrant C functions.  The option adds a `@code{JSInterpPtr}'
argument to all C functions it generates.

@item -V
@itemx --version
Print the version number of the @code{jswrap} program.

@item --help
Print a short help message that describes the options that can be given
to the @code{jswrap} program.
@end table


@node Definition File Format, Re-Entrant Functions, Invoking The jswrap Program, The jswrap Program
@section Definition File Format

The definition file contains the function definitions and their
implementation in JavaScript.  The function definitions are normal
JavaScript function definitions but they are extended with the type
information.  The type information is used to generate the C header
files and the glue code that is used in the function call.  The
definition file can also contain normal JavaScript comments.  The
comments are ignored and they are not copied to the generated C header
and implementation files.

The syntax of the function definition is:

@example
function [@var{return_type}] @var{function_name} @code{(}@var{argument_type}@dots{} @var{argument}[, @dots{}]@code{)}
@{
  @var{JavaScript code implementing the function.}
@}
@end example

@noindent Where:

@table @var
@item return_type

specifies the return type of the function.  If the return type
specification is omitted, the function is a @code{void} function
returning no value.

@item function_name

is the name of the function.  The name must be a valid C identifier
matching regular expression `@code{^[A-Za-z_][A-Za-z_0-9]*}'.

@item argument_type

specifies the type of the argument, its passing type, and the life scope
of the value of the argument.

@item argument

is the name of the argument.  The name must be a valid C identifier.
@end table


@menu
* The Type Specifiers::
* The Pass-Type Specifiers::
* The Life Scope Specifiers::
@end menu

@node The Type Specifiers, The Pass-Type Specifiers, Definition File Format, Definition File Format
@subsection The Type Specifiers

The type specifiers specify the native C and JavaScript type that is
used for the argument or for the return value.  The following type are
supported:

@table @code
@item cstring

A @code{'\0'} terminated C-string.  In the C, this is presented as
`@code{char *}'.  In the JavaScript, this is a normal string.

@item double

A floating point number.  In the C, this is a `@code{double}' floating
point number.

@item int

An integer Number.  In the C, this is a `@code{long}' integer.

@item string

An arbitrary data block.  In the C, this is presented as `@code{unsigned
char *}, @code{unsigned int}' pair.  In the JavaScript, this is a normal
string.  @strong{Note!} Because the type's presentation in C is two
types, this value can't be used as a return value of a function.
@end table

The following example shows how the types are converted to the
corresponding C header file.  The input file @file{types.jsw} is as
follows:

@example
function types (cstring vcstring, double vdouble, int vint,
                string vstring)
@{
@}
@end example

The resulting C header file @file{types.h} contains the following
definitions for the function @code{types}:

@example
void types (
        char *vcstring,
        double vdouble,
        long vint,
        unsigned char *vstring,
        unsigned int vstring_len
        );
@end example


@node The Pass-Type Specifiers, The Life Scope Specifiers, The Type Specifiers, Definition File Format
@subsection The Pass-Type Specifiers

The passing type specifiers specify how the argument is passed to the
function.  The following specifies are supported:

@table @code
@item in

An input argument.  This is the default pass-type for arguments.

@item out

An output argument.  In the JavaScript, the initial value of the
argument is @code{undefined}.  When the control returns from the
implementation of the function, the argument's current value is returned
to the calling C function.

In the C, the output and input-output arguments are presented as
pointers to the variables, containing the values.

@item inout

An input-output argument.
@end table

The following example shows show the output and input-output arguments
are presented in the C header file.  The input file @file{pass.jsw} is
as follows:

@example
function pass (out cstring vcstring, out double vdouble, inout int vint,
               inout string vstring)
@{
@}
@end example

The resulting C header file @file{pass.h} contains the following
definitions for the function @code{pass}:

@example
void pass (
        char **vcstring,
        double *vdouble,
        long *vint,
        unsigned char **vstring,
        unsigned int *vstring_len
        );
@end example


@node The Life Scope Specifiers,  , The Pass-Type Specifiers, Definition File Format
@subsection The Life Scope Specifiers

The life scope specifiers specify the liveness of the value, passed in
an argument.  The following specifiers are supported:

@table @code
@item static

The argument points to static data that can't change while the execution
is in the JavaScript code.  This means that the JavaScript can use the
same data that is given to it; it don't have to make a private copy of
the data.  The specifier can only be used with @code{cstring} and
@code{string} types.

The specifier don't have any affect for the generated C header file.
@end table


@node Re-Entrant Functions, Calling the Functions from C, Definition File Format, The jswrap Program
@section Re-Entrant Functions



@node Calling the Functions from C, Sample Project, Re-Entrant Functions, The jswrap Program
@section Calling the Functions from C


@node Sample Project,  , Calling the Functions from C, The jswrap Program
@section Sample Project

@example
function hello (cstring user)
@{
  System.stdout.writeln ("Hello, " + user + "!");
@}

function int max_sum (int a, int b, int out sum)
@{
  sum = a + b;

  return a > b ? a : b;
@}
@end example

@cartouche
@example
$ jswrap sample.jsw
@end example
@end cartouche

@example
/* This file is automatically generated from `hello.jsw' by jswrap. */

#ifndef HELLO_H
#define HELLO_H

void hello (
        char *user
        );

int max_sum (
        int a,
        int b,
        int *sum
        );

#endif /* not HELLO_H */
@end example

@example
#include <js.h>
#include "hello.h"

JSInterpPtr jswrap_interp;

int
main (int argc, char *argv[])
@{
  int a, b, max, sum;

  jswrap_interp = js_create_interp (NULL);

  hello ("World");

  a = 5;
  b = 7;
  max = max_sum (a, b, &sum);
  printf ("%d + %d = %d, max(%d, %d) = %d\n", a, b, sum, a, b, max);

  return 0;
@}
@end example

@c ----------------------------------------------------------------------
@node JavaScript API, Virtual Machine, The jswrap Program, Top
@chapter JavaScript API

@menu
* Interpreter Handling::
* Evaluation and Compilation::
* Type Handling::
* Defining Global Methods::
* Classes::
* Modules::
@end menu

@node Interpreter Handling, Evaluation and Compilation, JavaScript API, JavaScript API
@section Interpreter Handling

@deftypefun {const char *} js_version ()
Return a string that describes the JavaScript interpreter version
number.  The returned string is in format
@code{"@var{major}.@var{minor}.@var{patch}"}, where @var{major},
@var{minor}, and @var{patch} are integer numbers.
@end deftypefun

@deftypefun void js_init_default_options (JSInterpOptions *@var{options})
Initialize the interpreter options @var{options} to the default values.
These are the same values that are used in the interpreter creation, if
the argument @var{options} of @code{js_create_interp()} is @code{NULL}.
@end deftypefun

@deftypefun JSInterpPtr js_create_interp (JSInterpOptions *@var{options})
Create a new JavaScript interpreter.  The function returns an
interpreter handle that must be passed to all other interpreter API
functions.  The argument @var{options} specify additional options for
the interpreter.  If the argument is NULL, the default values are used.
If the interpreter creation fails -- due insufficient memory resources
-- the function return value @code{NULL}.
@end deftypefun

@deftypefun void js_destroy_interp (JSInterpPtr @var{interp})
Destroy interpreter @var{interp} and free all resources the interpreter
has allocated.  The handle @var{interp} must not be used after this
function.
@end deftypefun

@deftypefun {const char *} js_error_message (JSInterpPtr @var{interp})
Return an error message of the latest error in interpreter @var{interp}.
@end deftypefun

@deftypefun void js_result (JSInterpPtr @var{interp}, JSType *@var{result_return})
Get the result of the latest evaluation or execution in interpreter
@var{interp}.  The result is returned in @var{result_return}.  All data,
returned in @var{result_return}, belongs to the interpreter.  The caller
must not modify or changed it in any ways.
@end deftypefun

@deftypefun void js_set_var (JSInterpPtr @var{interp}, char *@var{name}, JSType *@var{value})
@end deftypefun

@deftypefun void js_get_var (JSInterpPtr @var{interp}, char *@var{name}, JSType *@var{value})
@end deftypefun

@deftypefun void js_get_options (JSInterpPtr @var{interp}, JSInterpOptions *@var{options})
Get the options of interpreter @var{interp} to @var{options}.
@end deftypefun

@deftypefun void js_set_options (JSInterpPtr @var{interp}, JSInterpOptions *@var{options})
Modify the options of interpreter @var{interp} according to
@var{options}.
@end deftypefun



@node Evaluation and Compilation, Type Handling, Interpreter Handling, JavaScript API
@section Evaluation and Compilation

@deftypefun int js_eval (JSInterpPtr @var{interp}, char *@var{code})
Evaluate JavaScript code @var{code} with interpreter @var{interp}.  The
argument @var{code} is NUL-terminated a C-string holding the JavaScript
code.  The function returns 1 if the operation was successful or 0
otherwise.  If the evaluation failed, the error message can be retrieved
with function @code{js_error_message()}.
@end deftypefun

@deftypefun int js_eval_data (JSInterpPtr @var{interp}, char *@var{data}, unsigned int @var{datalen})
Evaluate JavaScript code @var{data}, @var{datalen} with interpreter
@var{interp}.
@end deftypefun

@deftypefun int js_eval_file (JSInterpPtr @var{interp}, char *@var{filename})
Evaluate file @var{filename} with interpreter @var{interp}.  The file
@var{filename} can contain JavaScript or byte-code.
@end deftypefun

@deftypefun int js_eval_javascript_file (JSInterpPtr @var{interp}, char *@var{filename})
Evaluate JavaScript code file @var{filename} with interpreter
@var{interp}.
@end deftypefun

@deftypefun int js_execute_byte_code_file (JSInterpPtr @var{interp}, char *@var{filename})
Execute a byte-code file @var{filename} with interpreter @var{interp}.
@end deftypefun

@deftypefun int js_apply (JSInterpPtr @var{interp}, char *@var{name}, unsigned int @var{argc}, JSType *@var{argv})
Call function @var{name} with arguments @var{argc}, @var{argv}.  The
return value of the function @var{name} can be retrieved with the
@code{js_result()} function.
@end deftypefun

@deftypefun int js_compile (JSInterpPtr @var{interp}, char *@var{input_file}, char *@var{assembler_file}, char *@var{byte_code_file})
Compile JavaScript input file @var{input_file}.  If the argument
@var{assembler_file} is not @code{NULL}, the generated assembler code is
saved to the file, specified by the argument.  If the argument
@var{byte_code_file} is not @code{NULL}, the generated byte-code data is
svaed to the file, specified by the argument.
@end deftypefun

@deftypefun int js_compile_to_byte_code (JSInterpPtr @var{interp}, char *@var{input_file}, unsigned char **@var{bc_return}, unsigned int *@var{bc_len_return});
Compile JavaScript file @var{input_file} to byte-code and return the
resulting byte-code data in @var{bc_return}, @var{bc_len_return}.  The
returned byte-code data @var{bc_return} belongs to the interpreter and
it must be saved by the caller @strong{before} any other JS functions is
called.  If the data is not saved, its contents will be invalidated at
the next garbage collection.
@end deftypefun

@deftypefun int js_compile_data_to_byte_code (JSInterpPtr @var{interp}, char *@var{data}, unsigned int @var{datalen}, unsigned char **@var{bc_return}, unsigned int *@var{bc_len_return});

Compile JavaScript code @var{data}, @var{datalen} to byte-code and
return the resulting byte-code data in @var{bc_return},
@var{bc_len_return}.
@end deftypefun

@deftypefun int js_execute_byte_code (JSInterpPtr @var{interp}, unsigned char *@var{bc}, unsigned int @var{bc_len});

Execute byte-code data @var{bc}, @var{bc_len}.  The byte-code data is
the contents of a byte-code file, or a copy of the data returned by the
@code{js_compile_to_byte_code()} or
@code{js_compile_data_to_byte_code()} functions.

@strong{Note!} You can't use the data from the
@code{js_compile_to_byte_code()}, @code{js_compile_data_to_byte_code()}
functions as an input for this function.  You must take a private copy
of the data and pass that copy to the function:

@example
if (js_compile_to_byte_code (interp, file, &bc, &bclen))
  @{
    char *bc_copy = xmalloc (bclen);
    memcpy (bc_copy, bc, bclen);
    js_execute_byte_code (interp, bc_copy, bclen);
    xfree (bc_copy);
  @}
@end example
@end deftypefun


@node Type Handling, Defining Global Methods, Evaluation and Compilation, JavaScript API
@section Type Handling

@deftypefun void js_type_make_string (JSInterpPtr @var{interp}, JSType *@var{type}, unsigned char *@var{data}, unsigned int @var{length})
Create a new string type from @var{length} bytes of data @var{data}.
The result string is created to @var{type}.
@end deftypefun

@deftypefun void js_type_make_array (JSInterpPtr @var{interp}, JSType *@var{type}, unsigned int @var{length})
Create a new array type of length @var{length}.  The result array is
created to @var{type}.
@end deftypefun



@node Defining Global Methods, Classes, Type Handling, JavaScript API
@section Global Methods

@deftypefun void js_create_global_method (JSInterpPtr @var{interp}, char *@var{name}, JSGlobalMethodProc @var{proc}, void *@var{context}, JSFreeProc @var{context_free_proc})
@end deftypefun



@node Classes, Modules, Defining Global Methods, JavaScript API
@section Classes

@deftypefun JSClassPtr js_class_create (void *@var{class_context}, JSFreeProc @var{class_context_destructor}, int @var{no_auto_destroy}, JSConstructor @var{constructor})

Create a new class with class context data @var{class_context}.  The
context data is destroyed with @var{class_context_destructor}.  If the
argument @var{no_auto_destroy} is not 0, the JavaScript interpreter will
@strong{not} destroy the class when the interpreter is destroyed.  In
that case, it is the caller's responsibility to call
@code{js_class_destroy()} for the returned class handle, after the
interpreter has been destroyed.  If the argument @var{constructor} is
not @code{NULL}, it is used to instantiate the class when a `@code{new
}@var{class}@code{ (}@var{args}[@dots{}]@code{);}' expression is
evaluated in the JavaScript code.
@end deftypefun

@deftypefun void js_class_destroy (JSClassPtr @var{cls})
Destroy class handle @var{cls}.  The class handle must be created by the
@code{js_class_create()} function, so that value @code{1} was given for
the @var{no_auto_destroy} argument.
@end deftypefun

@deftypefun JSVoidPtr js_class_context (JSClassPtr @var{cls})
Return the class context of class @var{cls}.  The returned value is the
same that was given for the @var{class_context} argument in call of
function @code{js_class_create()}.
@end deftypefun

@deftypefun int js_class_define_method (JSClassPtr @var{cls}, char *@var{name}, unsigned int @var{flags}, JSMethodProc @var{method})
Define a new method for the class @var{cls}.  The name of the new method
is @var{name} and its implementation is @var{method}.  The argument
@var{flags} can have the following flags:

@table @code
@item JS_CF_STATIC
The created method is a static method.
@end table
@end deftypefun

@deftypefun int js_class_define_property (JSClassPtr @var{cls}, char *@var{name}, unsigned int @var{flags}, JSPropertyProc @var{property})
Define a new property for the class @var{cls}.  The name of the property
is @var{name} and its setter and getter function is @var{property}.  The
argument @var{flags} can have the following flags:

@table @code
@item JS_CF_STATIC
The property is a static property.

@item JS_CF_IMMUTABLE
The property is immutable.  An error to try to set the property.
@end table
@end deftypefun

@deftypefun int js_define_class (JSInterpPtr @var{interp}, JSClassPtr @var{cls}, char *@var{name})
Define the class @var{cls} to the interpreter @var{interp} with name
@var{name}.  If the value @code{0} was given for the argument
@var{no_auto_destroy} of the function @code{js_class_create()}, the
handle @var{cls} must not be used after this call.
@end deftypefun

@deftypefun int js_instantiate_class (JSInterpPtr @var{interp}, JSClassPtr @var{cls}, void *@var{instance_ctx}, JSFreeProc @var{instance_ctx_destructor}, JSType *@var{result_return})
@end deftypefun

@deftypefun {const JSClassPtr} js_lookup_class (JSInterpPtr @var{interp}, char *@var{name})
Lookup the class context by name from the interpreter @var{interp}.
@end deftypefun

@deftypefun int js_isa (JSInterpPtr @var{interp}, JSType *@var{object}, JSClassPtr @var{cls}, void **@var{instance_context_return})

Check if object @var{object} is an instance of class @var{cls}.  The
function returns a boolean success status.  If the argument
@var{instance_context_return} is not @code{NULL}, it will be set to the
instance context of object @var{object}.
@end deftypefun

@node Modules,  , Classes, JavaScript API
@section Modules

@deftypefun int js_define_module (JSInterpPtr @var{interp}, JSModuleInitProc @var{init_proc})
@end deftypefun

@c ----------------------------------------------------------------------
@node Virtual Machine, JavaScript Compiler, JavaScript API, Top
@chapter Virtual Machine

@menu
* Byte-Code File Format::
* Byte-Code Operands::
* Stack Frame::
@end menu

@node Byte-Code File Format, Byte-Code Operands, Virtual Machine, Virtual Machine
@section Byte-Code File Format

@menu
* File Header::
* Code Section::
* Constants Section::
* Symtab Section::
* Debug Section::
@end menu

@node File Header, Code Section, Byte-Code File Format, Byte-Code File Format
@subsection File Header

@table @code
@item magic
An @code{UInt32} number containing the JavaScript byte-code file magic.
The value of the magic is @code{0xc0014a53}.

@item nsects
An @code{UInt32} number containing the number of sections in this
byte-code file.
@end table

@node Code Section, Constants Section, File Header, Byte-Code File Format
@subsection Code Section

@node Constants Section, Symtab Section, Code Section, Byte-Code File Format
@subsection Constants Section

The constants section contains the constant values of the byte-code.
The different constant types are stored as follows:

@table @r
@item integer

(UInt8)@code{3}, (Int32)@var{value}

@item string

(UInt8)@code{4}, (UInt32)@var{length}, @var{length bytes of data}

@item float

(UInt8)@code{5}, (double)@var{value}

@item symbol

(UInt8)@code{10}, @var{symbol name}, (UInt8)@code{0}

@item NaN

(UInt8)@code{13}

@item regular expression

(UInt8)@code{100}, (UInt8)@var{flags}, (UInt32)@var{length}, @var{length
bytes of regexp source}

The item @var{flags} holds the regular expression flags.  It is a
combination of the following flags:

@table @code
@item 0x01
global match
@item 0x02
ignore case
@end table

@end table

@node Symtab Section, Debug Section, Constants Section, Byte-Code File Format
@subsection Symtab Section

@node Debug Section,  , Symtab Section, Byte-Code File Format
@subsection Debug Section


@node Byte-Code Operands, Stack Frame, Byte-Code File Format, Virtual Machine
@section Byte-Code Operands

The virtual machine knows the following byte-code operands.  Each
operand is identified by a 8 bit long unsigned integer number.  The
first operand @code{halt} has code 0, the next operand @code{done} has
code 1, and so on.  Some operand take arguments that are shown after the
operand name in the following listing.  The meanings of the arguments
are:

@table @code
@item Int8
The code of the operand is followed by a 8 bit long integer number
argument.

@item Int16
The code of the operand is followed by a 16 bit long integer number
argument.

@item Int32
The code of the operand is followed by a 32 bit long integer number
argument.

@item Symbol
The code of the operand is followed by a 32 bit long integer number
argument.  The number is an offset to the constant section and the
specified constant is a symbol that is the argument of the operand.
@end table

The notation

@var{before} @result{} @var{after}

@noindent desribes how the operand modifies the virtual machine stack.
For example, the notation:

--- @result{} @code{undefined}

@noindent means that the operand takes no items from the stack and it
pushes value @code{undefined} to the stack.  The notation:

@var{any} @var{any} @result{} @code{boolean}

@noindent means that the operand takes two items from the stack and it
pushes a boolean result to the stack.

The virtual machine knows the following byte-code operands.

@deffn Operand halt @ @ --- @result{} ---
Halt the virtual machine.  The program execution stops immediately and
the virtual machine starts execute the following C-code:

@example
while (1)
  sleep (5);
@end example

@noindent This "sleep forever" loop is implemented for debugging
purposes.
@end deffn

@deffn Operand done @ @ --- @result{} ---
The execution of the byte-code is finished and the control returns to
the calling C-function.
@end deffn

@deffn Operand nop @ @ --- @result{} ---
Do nothing; no operation.
@end deffn

@deffn Operand dup @ @ any @result{} any any
Duplicate the item at the top of the stack.
@end deffn

@deffn Operand pop @ @ any @result{} ---
Remove one item from the top of the stack.
@end deffn

@deffn Operand pop_n @code{Int8} @ @ any @dots{} any @result{} ---
Remove @var{Int8} items from the top of the stack.
@end deffn

@deffn Operand apop @code{Int8} @ @ any_n @dots{} any_0 @result{} any_0
Remove @var{Int8} items from the top of the stack, leaving the topmost
item on the top of the stack.  This operand is used to remove arguments
of a function call, leaving the function's return value to the top of
the stack.
@end deffn

@deffn Operand swap @ @ any_1 any_2 @result{} any_2 any_1
Swap the two topmost items in the stack.
@end deffn

@deffn Operand roll @code{Int8} @ @ any_n @dots{} any_1 any_0 @result{} any_0 any_n @dots{} any_1
@end deffn

@deffn Operand const @code{Int32} @ @ --- @result{} const
Push a constant from the constant section to the stack.  The constant is
specified by the value @var{Int32}.
@end deffn

@deffn Operand const_null @ @ --- @result{} @code{null}
Push value @code{null} to the stack.
@end deffn

@deffn Operand const_true @ @ --- @result{} @code{true}
Push value @code{true} to the stack.
@end deffn

@deffn Operand const_false @ @ --- @result{} @code{false}
Push value @code{false} to the stack.
@end deffn

@deffn Operand const_undefined @ @ --- @result{} @code{undefined}
Push value @code{undefined} to the stack.
@end deffn

@deffn Operand const_i0 @ @ --- @result{} @code{0}
Push integer number @code{0} to the stack.
@end deffn

@deffn Operand const_i1 @ @ --- @result{} @code{1}
Push integer number @code{1} to the stack.
@end deffn

@deffn Operand const_i2 @ @ --- @result{} @code{2}
Push integer number @code{2} to the stack.
@end deffn

@deffn Operand const_i3 @ @ --- @result{} @code{3}
Push integer number @code{3} to the stack.
@end deffn

@deffn Operand const_i @code{Int32} @ @ --- @result{} @code{Int32}
Push integer number @code{Int32} to the stack.
@end deffn

@deffn Operand load_global @code{Symbol} @ @ --- @result{} value
Push the value of the global variable @var{Symbol} to the stack.  The
operand will @strong{not} lookup the variable @var{Symbol} from the
with-chain.
@end deffn

@deffn Operand store_global @code{Symbol} @ @ value @result{} ---
Store the topmost item of the stack to the global variable @var{Symbol}.
@end deffn

@deffn Operand load_arg @code{Int8} @ @ --- @result{} value
Push the value of the argument @var{Int8} to the stack.
@end deffn

@deffn Operand store_arg @code{Int8} @ @ value @result{} ---
Store the topmost item of the stack to the argument @var{Int8}.
@end deffn

@deffn Operand load_local @code{Int16} @ @ --- @result{} value
Push the value of the local variable @var{Int16} to the stack.
@end deffn

@deffn Operand store_local @code{Int16} @ @ value @result{} ---
Store the topmost item of the stack to the local variable @var{Int16}.
@end deffn

@deffn Operand load_property @code{Symbol} @ @ object @result{} value
Push the value of the property @var{Symbol} of object @var{object} to
the stack.
@end deffn

@deffn Operand store_property @code{Symbol} @ @ object value @result{} ---
Save the value @var{value} to the property @var{Symbol} of object
@var{object}.
@end deffn

@deffn Operand load_array @ @ object index @result{} value
Push the @var{index}:th item of object @var{object} to the stack.
@end deffn

@deffn Operand store_array @ @ value object index @result{} ---
Store the value @var{value} to the @var{index}:th position of object
@var{object}.
@end deffn

@deffn Operand nth @ @ any integer @result{} item boolean
Push the @var{integer}:th item of object @var{any} to the stack.  Push a
boolean success status that tells whether the object @var{any} did
contain @var{integer}:th item.
@end deffn

@deffn Operand cmp_eq @ @ any1 any2 @result{} boolean
Compare the two objects @var{any1}, @var{any2} for equality and push a
boolean result code to the stack.
@end deffn

@deffn Operand cmp_ne @ @ any any @result{} boolean
Compare the two objects @var{any1}, @var{any2} for inequality and push a
boolean result code to the stack.
@end deffn

@deffn Operand cmp_lt @ @ any1 any2 @result{} boolean
Compare whether object @var{any1} is smaller than object @var{any2}.
Push a boolean result code to the stack.
@end deffn

@deffn Operand cmp_gt @ @ any1 any2 @result{} boolean
Compare whether object @var{any1} is greater than object @var{any2}.
Push a boolean result code to the stack.
@end deffn

@deffn Operand cmp_le @ @ any1 any2 @result{} boolean
Compare whether object @var{any1} is smaller than, or equal to object
@var{any2}.  Push a boolean result code to the stack.
@end deffn

@deffn Operand cmp_ge @ @ any1 any2 @result{} boolean
Compare whether object @var{any1} is greater than, or equal to object
@var{any2}.  Push a boolean result code to the stack.
@end deffn

@deffn Operand cmp_seq @ @ any1 any2 @result{} boolean
Compare the two objects @var{any1}, @var{any2} for strict equality and
push a boolean result code to the stack.
@end deffn

@deffn Operand cmp_sne @ @ any any @result{} boolean
Compare the two objects @var{any1}, @var{any2} for strict inequality and
push a boolean result code to the stack.
@end deffn

@deffn Operand sub @ @ any1 any2 @result{} result
Substract object @var{any2} from object @var{any1} and push the
result to the stack.
@end deffn

@deffn Operand add @ @ any1 any2 @result{} result
Add object @var{any2} to object @var{any1} and push the result to
the stack.
@end deffn

@deffn Operand mul @ @ any1 any2 @result{} result
Multiply object @var{any1} with object @var{any2} and push the result to
the stack.
@end deffn

@deffn Operand div @ @ any1 any2 @result{} result
Divide object @var{any1} with object @var{any2} and push the result to
the stack.
@end deffn

@deffn Operand mod @ @ integer1 integer2 @result{} result
Count object @var{integer1} modulo object @var{integer2} and push the
result to the stack.
@end deffn

@deffn Operand neg @ @ any @result{} result
Negate object @var{any} and push the result to the stack.
@end deffn

@deffn Operand and @ @ any1 any2 @result{} result
Perform a bitwise and operation between objects @var{any1} and
@var{any2} and push the result to the stack.
@end deffn

@deffn Operand not @ @ any1 any2 @result{} result
Perform a bitwise not operation between objects @var{any1} and
@var{any2} and push the result to the stack.
@end deffn

@deffn Operand or @ @ any1 any2 @result{} result
Perform a bitwise or operation between objects @var{any1} and @var{any2}
and push the result to the stack.
@end deffn

@deffn Operand xor @ @ any1 any2 @result{} result
Perform a bitwise xor operation between objects @var{any1} and @var{any2}
and push the result to the stack.
@end deffn

@deffn Operand shift_left @ @ integer1 integer2 @result{} integer
Shift integer number @var{integer1} left @var{integer2} bits.  Push the
result value to the stack.
@end deffn

@deffn Operand shift_right @ @ integer1 integer2 @result{} integer
Shift integer number @var{integer1} right @var{integer2} bits.  Push the
result value to the stack.
@end deffn

@deffn Operand shift_rright @ @ integer1 integer2 @result{} integer
@end deffn

@deffn Operand iffalse @code{Int32} @ @ any @result{} ---
If the topmost item in the stack has boolean value `false', adjust the
program counter with relative offset @var{Int32}.
@end deffn

@deffn Operand iftrue @code{Int32} @ @ any @result{} ---
If the topmost item in the stack has boolean value `true', adjust the
program counter with relative offset @var{Int32}.
@end deffn

@deffn Operand call_method @code{Symbol} @ @ object @result{} result
Call method @var{Symbol} in the object @var{object}.  Push the result of
the method call to the stack.
@end deffn

@deffn Operand jmp @code{Int32} @ @ --- @result{} ---
Adjust program counter with relative offset @var{Int32}, e.g. jump to
relative position @var{pc} + @var{Int32}.
@end deffn

@deffn Operand jsr @ @ function @result{} result
Jump to subroutine @var{function} and push the result of the subroutine
call to the stack.  The operand will @strong{not} process the
with-chain.
@end deffn

@deffn Operand return @ @ result @result{} result
Return from a subroutine with value @var{result}.
@end deffn

@deffn Operand typeof @ @ any @result{} string
Push the type name of object @var{any} to the stack.
@end deffn

@deffn Operand new @ @ object @result{} result object
Create an instance of object @var{object} and call its constructor
function.  Push the result from the constructor and the new instance to
the stack.  The return value of the constructor is discarded.
@end deffn

@deffn Operand delete_property @code{Symbol} @ @ object @result{} undefined
Delete property @var{Symbol} from object @var{object}.  Push value
@code{undefined} to the stack.
@end deffn

@deffn Operand delete_array @ @ object index @result{} undefined
Delete the @var{index}:th property of object @var{object}.  Push value
@code{undefined} to the stack.
@end deffn

@deffn Operand locals @code{Int16} @ @ --- @result{} undefined @dots{} undefined
Allocate @var{Int16} local variables from the stack frame.  The operand
@code{locals} must be called in the beginning of the function code.  The
operand will push @var{Int16} @samp{undefined} values to the stack.  The
values will be the place-holders for the local variables.
@end deffn

@deffn Operand min_args @code{Int8} @ @ integer @result{} ---
If the number of the arguments for the function @var{integer} is smaller
than @code{Int8}, expand the stack frame so that the function gets
@code{Int8} arguments.  The created arguments will have value
@code{undefined}.
@end deffn

@deffn Operand load_nth_arg @ @ integer @result{} argument
Push the @var{integer}'th argument of function to the top of the stack.
The index @var{integer} must be an integer number.
@end deffn

@deffn Operand with_push @ @ object @result{} ---
Push object @var{object} to the function's with-lookup chain.
@end deffn

@deffn Operand with_pop @code{Int8} @ @ --- @result{} ---
Pop @var{Int8} objects from the function's with-lookup chain.
@end deffn

@deffn Operand try_push @code{Int32} @ @ --- @result{} ---
Push a try-frame with a catch block offset @var{Int32} to the virtual
machine's try-chain.
@end deffn

@deffn Operand try_pop @code{Int8} @ @ --- @result{} ---
Pop @var{Int8} frames from the virtual machine's try-chain.
@end deffn

@deffn Operand throw @ @ any @result{} ---
Throw an exception with value @var{any}.
@end deffn

@deffn Operand iffalse_b @code{Int32} @ @ boolean @result{} ---
If the topmost item in the stack is @code{false}, adjust the program
counter with relative offset @var{Int32}.  The operand assumes that the
topmost item is a boolean value.
@end deffn

@deffn Operand iftrue_b @code{Int32} @ @ boolean @result{} ---
If the topmost item in the stack is @code{true}, adjust the program
counter with relative offset @var{Int32}.  The operand assumes that the
topmost item is a boolean value.
@end deffn

@deffn Operand add_1_i @ @ integer @result{} integer
Add integer number one to the top most item in the stack.  The operand
assumes that the topmost item is an integer number.
@end deffn

@deffn Operand add_2_i @ @ integer @result{} integer
Add integer number two to the top most item in the stack.  The operand
assumes that the topmost item is an integer number.
@end deffn

@deffn Operand load_global_w @code{Symbol} @ @ --- @result{} value
Push the value of the global variable @var{Symbol} to the stack.  The
operand will lookup the property @var{symbol} from the currently active
with-chain.
@end deffn

@deffn Operand jsr_w @code{Symbol} @ @ function @result{} result
Jump to subroutine @var{function} and push the result of the subroutine
call to the stack.  The operand will lookup the method @var{Symbol} from
the currently active with-chain.  If the method is not found, the
argument @var{function} is used.
@end deffn

@c ----------------------------------------------------------------------
@node Stack Frame,  , Byte-Code Operands, Virtual Machine
@section Stack Frame

@example
JS_SP0  sp @result{}
JS_SP1          local_var_@var{n}
JS_SP2          @dots{}
JS_SP(@var{n})        local_var_1
JS_LOCAL(0)     local_var_0
                return_addr
JS_WITHPTR      with_ptr
JS_ARGS_FIXP    args_fix
        fp @result{}   old_fp
JS_ARG(0)       this
JS_ARG(1)       arg_count
JS_ARG(2)       argument_1
                argument_2
                @dots{}
JS_ARG(@var{n})       argument_@var{n}
                local_var_@var{n}
                @dots{}
                local_var_0
                args_fix
                return_addr
                with_ptr
                old_fp
                this
                @dots{}
@end example

@c ----------------------------------------------------------------------
@node JavaScript Compiler, GNU Library General Public License, Virtual Machine, Top
@chapter JavaScript Compiler

The JavaScript compiler is implemented in the JavaScript language.
Because the JavaScript language does not have namespaces, the compiler
has been coded to a fixed part of the global namespace.  All global
symbols the compiler uses, start with the prefix `@code{JSC$}'.  This
prefix is reserved for the interpreter and users must not define any
symbols or functions starting with that prefix.

The compiler compiles JavaScript source code to byte-code and it returns
a fixed byte-code file as the result.  This result file (or data block)
can be passed to the virtual machine for execution.

The compiler has three stages.  The first stage parse the input stream
and create a syntax tree for the input.  The second stage transforms the
syntax tree to a list of assembler operations.  The third stage converts
the symbolic assembler instructions to byte-code operands.

Depending on the compilation options, the compiler performs different
optimizations during the compilation.  The basic optimizations include
constant folding, peephole optimization, and optimization of jumps to
jump instructions.  During the batch-compilation (when compiling a
JavaScript source file @file{.js} to byte-code file @file{.jsc}) the
compiler performns heavier optimizations to minimize the size of the
generated byte-code file, and to speed up some operations.


@menu
* Public Entry Points::
@end menu

@node Public Entry Points,  , JavaScript Compiler, JavaScript Compiler
@section Public Entry Points

@defun JSC$compile_file (@var{name}, @var{flags}, @var{asm_file}, @var{bc_file})
Compile JavaScript source file @var{name} according to @var{flags}.  If
argument @var{asm_file} is not @code{null}, symbolic assembler output is
saved to that file.  If argument @var{bc_file} is not @code{null}, the
byte-code output is saved to that file.

The function returns a string that holds the byte-code output for the
source file.
@end defun

@defun JSC$compile_string (@var{string}, @var{flags}, @var{asm_file}, @var{bc_file})
Compile JavaScript source code @var{string} according to @var{flags}.  If
argument @var{asm_file} is not @code{null}, symbolic assembler output is
saved to that file.  If argument @var{bc_file} is not @code{null}, the
byte-code output is saved to that file.

The function returns a string that holds the byte-code output for the
source code.
@end defun

In both functions, the argument @var{flags} specify the verbosity,
warning, and optimization levels of the compilation.  The following
values can be given to flags:

@table @code
@item JSC$FLAG_VERBOSE
turns on diagnostic messages

@item JSC$FLAG_ANNOTATE_ASSEMBLER
add original JavaScript source lines to the generated assembler listing

@item JSC$FLAG_GENERATE_DEBUG_INFO
generate debugging information to the byte-code file

@item JSC$FLAG_GENERATE_EXECUTABLE_BC_FILES
add execute permissions to the generated byte-code files

@item JSC$FLAG_OPTIMIZE_PEEPHOLE
perform peephole optimization

@item JSC$FLAG_OPTIMIZE_JUMPS
perform optimization for jumps to jump instructions

@item JSC$FLAG_OPTIMIZE_BC_SIZE
optimize the size of the genated byte-code file

@item JSC$FLAG_OPTIMIZE_HEAVY
perform optimizations which require liveness analyzing of the
variables

@item JSC$FLAG_OPTIMIZE_MASK
mask to turn on all optimizations

@item JSC$FLAG_WARN_UNUSED_ARGUMENT
warn if an argument of a function is unused in the function body

@item JSC$FLAG_WARN_UNUSED_VARIABLE
warn in a variable is defined but it is not used in the function body

@item JSC$FLAG_WARN_SHADOW
warn if a variable declaration shadows a parameter of a function

@item JSC$FLAG_WARN_WITH_CLOBBER
warn if a symbol with-lookup is clobbered because the symbol is defined
to be a local variable or a function argument

@item JSC$FLAG_WARN_MISSING_SEMICOLON
warn if a semicolon is missing from the input.  The missing semicolons
are inserted during the parsing by the automatic semicolon inserting.
However, since the missing semicolons show bad programming style, this
option will warn about them.

@item JSC$FLAG_WARN_STRICT_ECMA
warn about things that are supported by this implementation, but are not
allowed by the ECMAScript standard

@item JSC$FLAG_WARN_DEPRECATED
warn if deprecated features has been used in the source code

@item JSC$FLAG_WARN_MASK
mask to turn on all warnings
@end table

The compiler entry points can be called from JavaScript and C programs.
For example, they are used extensively to implement the JavaScript API,
described in the @file{js.h} file.  The following example shows how a
C-string, containing JavaScript code, can be compiled and executed.
Similar function can be found from the JavaScript API implementing the
@code{js_eval()} function.

@example
int
eval_code (JSInterpPtr interp, char *code);
@{
  JSNode argv[5];
  int i = 0;
  int result;
  ByteCode *bc;

  /* Compile the code. */

  /* Argument count. */
  argv[i].type = JS_INTEGER;
  argv[i].u.vinteger = 4;
  i++;

  /* Source for the compiler. */
  js_make_static_string (interp->vm, &argv[i], code, strlen (code));
  i++;

  /* Flags. */
  argv[i].type = JS_INTEGER;
  argv[i].u.vinteger = JSC_FLAG_VERBOSE;
  argv[i].u.vinteger |= JSC_FLAG_OPTIMIZE_MASK;
  argv[i].u.vinteger |= JSC_FLAG_WARN_MASK;
  i++;

  /* Assembler file. */
  argv[i].type = JS_NULL;
  i++;

  /* Byte-code file. */
  argv[i].type = JS_NULL;
  i++;

  /* Call the compiler entry point. */
  result = js_vm_apply (interp->vm, "JSC$compile_string", i, argv);
  if (result == 0)
    return 0;

  bc = js_bc_read_data (interp->vm->exec_result.u.vstring->data,
                        interp->vm->exec_result.u.vstring->len);

  /* And finally, execute it. */
  result = js_vm_execute (interp->vm, bc);

  /* Free the byte-code. */
  js_bc_free (bc);

  return result;
@}
@end example

The following example shows how the compiler entry point can be called
from JavaScript code.  The example code compiles a JavaScript source
code file @file{input.js} into byte-code and stores the result to file
@file{ouput.jsc}.

@example
try
  @{
    JSC$compile_file ("input.js",
      		JSC$FLAG_OPTIMIZE_MASK | JSC$FLAG_WARN_MASK,
      		null, "output.jsc");
  @}
catch (e)
  @{
    System.stdout.writeln ("compilation failed: " + e);
  @}
@end example

@c ----------------------------------------------------------------------
@node GNU Library General Public License, Index, JavaScript Compiler, Top
@ifinfo
@appendix GNU Library General Public License
@end ifinfo

@set lgpl-appendix 1
@include lgpl.texinfo

@c ----------------------------------------------------------------------
@page
@node Index,  , GNU Library General Public License, Top
@unnumbered Index

@printindex cp

@contents
@bye
