README.md

AdderScript

What is it

Adder is a lightweight python-like language, implemented on top of JavaScript and designed to be safe to execute untrusted code.

Why?

The main purpose of Adder is to let you execute untrusted code on other users's browsers and even on your Node.js server, without worrying about security complications.

Adder will not let the untrusted code access anything you don't want it to access, will not allow it to get stuck or hog resources, and will make sure it can't do any harm or go outside its boundaries.

The main reason Adder is secured is that no JavaScript code is ever executed using plain eval().
Instead, everything is parsed and interpreted by the Adder interpreter, that is built and designed to be limited and safe.

Advantages

Here are the key features of Adder:

Beautiful Pythonic syntax - if you know Python, you know Adder.

Secured by design (Adder is designed to run untrusted code).

Works on both Node.js and Browsers.

No need for any sub-processes.

Simple & accessible interface.

Easy to extend, and easy to remove builtins and limit.

Agnostic to JavaScript changes and versions.

Easy to limit memory usage, commands per run, execution time, etc..

Caching and Optimizations makes it pretty fast for multiple executions.

Via npm

Via bower

Via git (clone)

Tests & Examples

Tests

To run Adder tests, you can open the html file tests/test.html in the browser of your choice.

To test in Node.js, run the following command (requires Node.js and qunit-cli installed):

qunit-cli tests/test.js

Performance Tests

To run performance tests, open the html file tests/performance.html in the browser of your choice.
To test performance in Node.js, execute file tests/performance-node.js in Node.

Note that results may vary from run to run, so its recommended to execute several times and do an average.

Interactive Shell

To get an interactive shell and play with the language, you can open examples/shell.html in the browser of your choice.

Sandbox

To get a rich Adder sandbox with code examples and minimal editor, you can open examples/sandbox.html in the browser of your choice.

Performance

In overall, Adder appears to be 3-5 times slower than executing plain JavaScript, on multiple executions. On FireFox it appears to be much faster, due to caching of expressions.

The following is a summary of performance tests I conducted on multiple browsers (with windows 8). In bars below less is better:

These tests execute the same logic with Adder and JavaScript couple thousands of times, and measure the time it took to execute each code.

Please note:

The tests above don't include compile time (Adder scripts are compiled prior the tests).

Adder programs that execute multiple times have internal caching which makes them faster. If your project run each Adder program only once, performance would be slightly worse.

For more info check out tests/performance.html.

Executing Adder - Host application side

This part of the docs explain how to setup and execute Adder from the host application side, eg the client JavaScript or your Node.js server.

Later in these docs we'll learn the language itself and how to write Adder scripts.

Quick Example

Before diving into the APIs, lets start with a simple example:

// init Adder environment (connect output to alerts)AdderScript.init({
outputFunc:function(text) {alert("output from script: "+ text);},
});
// create a simple script and compile it
compiledCode =AdderScript.compile('print("Hello World!")');
// spawn a program and execute it// the result will be an alert with the text "Hello World!".var program =AdderScript.newProgram(compiledCode);
program.execute();

Pretty simple right? Now lets dive in a little deeper.

Init Environment

To run Adder scripts you first need to init environment:

// if you don't provide any params output will go to console.log and default flags will applyAdderScript.init();

Compile Code

Once the environment is ready, you can compile Adder codes using the compile function:

var compiled =AdderScript.compile(someCodeString);

Save / Load pre-compiled code

If you want to save the compiled code for later usage, you can simply JSON.stringify() it into a file:

Create & Execute Programs

An Adder Program can be think of as a process executing a single Adder script one or more times.
However, the Adder program is not a real process but an object living on the same memory space as the host application.

To spawn a new program from a compiled code, use newProgram():

var program =AdderScript.newProgram(compiledCode);

The program will now live in memory and you can execute it as many times as needed and access its internal memory and variables.

Executing the same program multiple times is much faster than spawning a new program every time, due to caching and internal optimizations.
In addition, global scope variables will stay alive between different executions of the same program.

To execute the program code once, use execute:

program.execute();

If you want to clear your program's context (eg remove all user defined variables from global scope), use resetContext():

program.resetContext();

Get values and execution errors

You can easily access the last evaluated result and get it as a native JavaScript object, using getLastValue():

var lastVal =program.getLastValue();

In addition, you can read any variable in the program's global scope using getGlobalVar():

flags

The following are all the flags you can set when you init Adder environment (as the 'flags' option):

var flags = {
stackLimit:256, // Stack depth limit. If exceeded will throw 'StackOverflow' exception.
maxStatementsPerRun:2048, // Maximum statements that can be executed in a single run. If exceeded will throw 'ExceededStatementsLimit' exception.
maxStringLen:5000, // Maximum allowed string lengths. If exceeded will throw 'ExceedMemoryLimit' exception.
maxContainersLen:1000, // Maximum values allowed in lists, sets and dictionaries. If exceeded will throw 'ExceedMemoryLimit' exception.
maxVarsInScope:100, // Limit number of variables allowed per scope. If exceeded will throw 'ExceedMemoryLimit' exception.
executionTimeLimit:1000, // Time limit for a single execution (in milliseconds). If exceeded will throw 'ExceededTimeLimit' exception.
memoryAllocationLimit:10000, // Memory limit, very roughly estimated, in bytes (per execution). If exceeded will throw 'ExceedMemoryLimit' exception.
removeBuiltins: [], // An optional list of builtin function and const names you want to remove from the language.
throwErrors:false, // If true, will throw exceptions from Adder execution if occur. If false, you need to check errors with getLastError().
}

modules

Modules are objects with functions and consts you can access from Adder scripts.
For example, there's the built-in Math module that provide all the Math-related functionality and consts.

You can choose which modules are included in your environment to have fine control over which APIs Adder scripts can access.

Note that you cannot import modules from inside Adder script, Adder code can only access what the host application allows it (this is by design).

To include all modules you can set modules to ["ALL"].
However, that's not recommended in production, as it will include modules that can pop alerts and write to console (something you normally wouldn't want).

To load only the "safe for production" modules, use ["SAFE"].

All available modules will be described later in the chapter about writing Adder scripts.

outputFunc

An optional function to handle script output when print is called. For example, if you want to send all print output directly to console:

functionoutputFunc() {
console.log(Array.from(arguments).join(""));
}

Note that this is the default behavior; If no outputFunc is provided, all output will go to console.log by default.

showDebugConsole

If set to true, Adder will show some useful debug data in console.

Register Functions

The most simple way to extend Adder's API and create an interface to the host application, is via builtin functions.

Define a built-in object type

A module acts like a singleton. But what if you need an object you can instantiate, like Adder's list, dict or set?

To define a new built-in object type use defineBuiltinObject():

// init AdderScript environmentAdderScript.init();
// define a new object type "Person" and return a function to instantiate it
createPerson =AdderScript.defineBuiltinObject("Person", {
"say_hello": {
func:function() {alert("Hello World!")},
requiredParams:0,
optionalParams:0
},
"race":"human",
});
// now you can use 'createPerson' to create a new 'Person' instances.// however, you still need to provide an API for Adder to create it.// lets register a new built-in function, "create_person", that will use 'createPerson' to create a new 'Person' instance:AdderScript.addBuiltinFunction({name:"create_person", // function namefunc:function(x) {returncreateFunc(this)}, // the function itself to create Person.
requiredParams:0, // number of required params
optionalParams:0}); // number of additional optional params

Note that 'createPerson' function expect to get 'this' as param, where 'this' is any built-in function or module.

Now you can create and use the new 'Person' objects from Adder scripts (the following is an Adder script code):

# will create a new person and call its function 'say_hello()'
a = create_person()
a.say_hello()

Writing Adder Scripts

Previously we learned how to execute adder scripts and interact with them from the host application side.
In this part of the tutorial we'll learn how to actually write Adder scripts.

Basic Syntax

Adder syntax is the same as Python, so if you know Python you know Adder and can skip this part.

If you are not familiar with Python, here's a quick summary (after this you will also be able to use Python!).

Indentation

Adder is indent-sensitive; indentation is used to open and close blocks (instead of curly brackets in other languages).

Lets take a look at an example with if and else blocks:

if a ==5:
print("this is the if block")
else:
print("this is the else block")

Indents must be multiply of 4 spaces. Wrong indentation will throw syntax errors.

Comments

Comments in Adder begin with the hash character ("#") and are terminated by the end of line:

# this is a comment line
a =5# this part is also a comment; after 'a = 5' is executed this part will be ignored.

Variables

To create a new variable you just need to assign a value to it:

a =5

Variables in Adder are loosely typed, meaning you can change the type on the fly:

a =5# 'a' is a number.
a ="foo"# now 'a' is a string.
a =True# and now 'a' is a boolean.

Variables & Scopes

If 'a' is defined in a parent's block, setting its value will override it. For example:

# define variable 'a' in parent block
a =5# override the variable 'a' from inside the 'if' blockifTrue:
a =6# print 'a', which should now be '6'print(a)

In addition, if you assign a variable inside a function that also exist in global scope, you will override it:

# define global variable 'a'
a =5# define a function that override global variable 'a' with another valuedeftest():
a =6# call the function that will change the value of 'a'
test()
# print 'a' that should now be '6'print(a)

If you are familiar with Python you will notice this behavior is slightly different;
In Python, you need to use the global statement to override global variables from inside a function. In Adder, all variable assignment is global by default.

Builtin Consts

False

The false value of the bool type. Assignments to False are illegal and will raise a SyntaxError.

True

The true value of the bool type. Assignments to True are illegal and will raise a SyntaxError.

None

None is frequently used to represent the absence of a value, as when default arguments are not passed to a function.
Assignments to None are illegal and will raise a SyntaxError.

NaN

NaN (Not a Number) is a special constant that represent an illegal expressions involving numbers and non-number values.
For example, 5 * "a" will return NaN (note however that 5 * "2" will be evaluated as '5 * 2' and return 10).

VERSION

String, the current Adder Script version.

Operators

This chapter describe all the language arithmetic and comparison operators.

Basic Arithmetic Operators

In adder all the basic arithmetic operators are supported - add, subtract, multiply, divide and modulate:

a =5+2
b =4-2
c =6/3
d =2*15
e =5%2

In addition, there's a built-in operator for power, represented by **:

a =2**3# equals to '2 * 2 * 2'

In-place operators

In-place operators are syntactic sugar to change the value of a variable:

a +=1# the same as "a = a + 1"
b -=1# the same as "b = b - 1"
c /=2# the same as "c = c / 2"
d *=2# the same as "d = d * 2"

Most arithmetic operators have their own in-place version.

Comparison operators

Adder support all the basic comparison operators: >, <, >=, <=, !=, ==.
They work the same as in most programming language:

Bitwise operators

not

The not operator invert a boolean value, eg turn true into false and vice-versa:

ifnotTrue:
print("hello!")

or

To create a conditional 'or', use the or operator:

a =5if a ==1or a ==5:
print("a is either 1 or 5")

Note that or doesn't necessarily return a boolean (true / false), it returns the first value that when cast to boolean will return true.
This means you can also use or to assign the first value option.

For example:

# this will print "yay!", the first value considered as 'true' when casted as boolean
a =FalseorNoneor"yay!"orTrueprint(a)

and

To create a conditional 'and', use the and operator:

a =1
b =2if a ==1and b ==2:
print("a is 1 and b is 2")

With and operator the condition is met only if all parts are true.

in

In General, in is used to check if a value is contained in an object.

For example, with lists in will return true if the list contain the given value:

lst =list(1,2,3)
if1in lst:
print("'1' is in the list!")

With dictionaries, in will return true if value is a key inside the dictionary.

insert (val, position)

pop ([position])

Remove and return the last value from list, or from a given position (if provided position argument).

For example:

# using pop without position param
a =list("foo", "bar", "hello")
a.pop() # <-- will remove and return "hello", which is the last value in the list.# using pop with position param
a =list("foo", "bar", "hello")
a.pop(1) # <-- will remove and return "bar", which is the value with index 1 in the list.

shift ()

Remove and return the first value from the list.

For example:

a =list("foo", "bar", "foobar")
a.shift() # <-- will remove and return "foo", the first value in the list.

remove (val)

Remove a given value from list (if found).

For example:

a =list("foo", "bar", "hello")
a.remove("bar") # <-- will remove "bar" from the list.

at (position)

Iterating lists

To iterate over the values in a List, use for-in loop:

a =list("foo", "bar", "foobar")
for val in a:
print(val)

Set

A Set is like a list, but in a set each value may only appear once. In addition, a Set may only contain simple types and not objects.
Sets are much faster when you need to check if values exist or not.

To create a new set:

# create an empty set
a =set()
# create a set with starting values: "Apple", "Banana", "Orange"
a =set("Apple", "Banana", "Orange")

The set API is slightly different than Python's set.

A set instance have the following functions:

clone ()

Create a shallow copy of the set.

For example:

a =set(1,2,3)
b = a.clone() # <-- 'b' will now be equal to 'a', but not the same object.

empty ()

Return true if set is empty, false otherwise.

For example:

a =set()
if a.empty():
print("Set 'a' is empty!")

to_list ()

Convert the set to a List object.

For example:

a =set(1, 2, 3)
b = a.to_list() # <-- 'b' is now a new list with values 1, 2, 3.

len ()

Return set length.

For example:

a =set(1,2)
print(a.len()) # <-- will print '2'.

add (val)

Add a value to the end of the set. If value already exist in set, will not do anything (as sets may only contain each value once).

For example:

a =set("foo", "bar")
a.add("foobar") # <-- set will now contain: "foo", "bar", "foobar".

has (val)

Return if the set contains a given value.

For example:

# create a set
a =set("foo", "bar")
# check if contains a valueif a.has("foo"):
print("'foo' is in set")

float (val)

int (val)

len (val)

Return the length of an object (depends on object type).
This is equivalent to val.len().

For example:

a =list(1,2,3)
print(len(a)) # <-- will print 3

ord (chr)

Return the ASCII value of a character.

For example:

print(ord('a')) # <-- will print 97

range ([start], end, [step])

Return a list containing the values between a given starting point, ending point, and with an optional step size.

This method is extremely useful with for loops.

For example:

# will print numbers 0 to 9 (including). total of 10 iterations.for i inrange(10):
print(i)
# will print numbers 5 to 7 (including). total of 3 iterations.for i inrange(5, 8):
print(i)
# will print numbers 0 to 9 (including), with steps of 2. total of 5 iterations.for i inrange(0, 10, 2):
print(i)
# will create a list with values 0-9 (including).
a =range(10)

equal (a, b)

Return True if both values are equal, False otherwise.
This is equivalent to a == b, but usable as a function, so you can do things like compare_func = equal and later use 'compare_func' or override it.

For example:

a =list(1,2,3)
b =list(1,2,3)
if equal(a, b):
print("Lists are equal!")

dir ([obj])

Return all the keys in current scope or in object's API.

This function should not be used for production purposes, its mostly useful to examine objects in shell.

For example:

# will print everything in global scopeprint(dir())
# will print the API functions and vars of the 'Math' moduleprint(dir(Math))

delete (obj)

Remove a variable.

For example:

a =5
delete(a) # <-- 'a' will no longer exist after this.

exist (obj)

Return True if variable name exists in current scope or globals.

For example:

if exist("a"):
print("'a' exists: "+ a)

Modules

Modules are objects with built-in functions and constants that Adder scripts can access and use.

When setting up the environment (on your host application), you can choose which modules to import and can even register your own modules (this described in details in previous chapters).

You use modules with the dot notation:

a = Math.abs(-5)

All modules act like a global singleton class.

In this chapter we'll go over the basic built-in modules and describe their APIs.

Math

Provide basic math-related functionality and constants.

The Math module provide the following API:

abs (val)

Convert a number to its absolute value.

For example:

Math.abs(-5) # <-- will return 5.

min (...)

Get a list of numeric arguments (or a single list argument) and return the smallest value.

rand ()

rand_int ([min,] max)

print(Random.rand_int(2, 10)) # print a random number between 2 to 10 (inclusive)print(Random.rand_int(5)) # print a random number between 0 to 5 (inclusive)

rand_float ([min,] max)

Return a random float number between min and max.

For example:

print(Random.rand_float(2, 10)) # print a random number between 2.0 to 10.0 (inclusive)print(Random.rand_float(5)) # print a random number between 0.0 to 5.0 (inclusive)

select (iterable)

Return a random value from a list or a set (doesn't work with dictionaries).

For example:

print(Random.select(list(1,2,3,4,5))) # get a random value from list optionsprint(Random.select(set(1,2,3,4,5))) # get a random value from set options

boolean ()

Return either True or False.

For example:

print("And the answer is: "+ Random.boolean())

binary ()

Return either 0 or 1.

For example:

print("0 or 1: "+ Random.binary())

Alert

Provide functionality to show alerts to user (in browser). Use it for debug purposes, not recommended for production.

The Alert module provide the following API:

alert (msg)

Show a standard browser alert box with msg string.

Input

Provide functionality to get input from user (in browser). Use it for debug purposes, not recommended for production.

The Input module provide the following API:

rawInput (msg, [default])

Show a standard browser prompt box with msg string, and a default value (if provided).

What Next

If you want to start using Adder Scripts it is recommended you get familiar with the language.
Check out the Adder Sandbox and the examples there, or take a look at the following Cool Game made with Adder.

If you find any bugs, problems or security breaches in Adder, please report in the git repository, or drop me an email at ronenness@gmail.com.