Table of Contents
< All Topics
Print

Gnosis Script Syntax

The Gnosis Script syntax is quite simple. A Gnosis Script or Gnosis Expression consists of one or more statements separated by a semicolon (;).

A statement may consist of several substatements separated by a comma (,).

The result of the Expression is the result of the last statement. For example, the result of the following Expression is ‘Last substatement’:

'1st statement'; '2nd statement 1st substatement', 'Last substatement'

Gnosis Script statements comprise Values, Operators, Expressions, Keywords, and Comments.

Gnosis Script ignores multiple spaces. You can add white space to your script to make it more readable. For best readability, programmers often avoid code lines longer than 80 characters. If a Gnosis Script statement does not fit on one line, the best place to break it is after an operator.

Gnosis Script statements can be grouped in code blocks inside parenthesis (…). Code blocks define statements to be executed together.

Values, Variables, and Assignment Operators

The Gnosis Script syntax defines two types of values: Fixed and Variable. Fixed values are called Literals. Variable values are called Variables.

The two most essential syntax rules for fixed values are:

  1. Numbers are written with or without decimals.
  2. Strings are text written within double or single quotes.

The result of the last statement in the Expression can be assigned to a variable with the equal sign operator.

varName = 'value';

When first assigned within the Expression, a local variable is automatically created. Local variables are valid and visible only within the Expression’s scope and can be reused in other parts of the Expression.

However, if an existing global variable with the same name exists, its value is updated. To force the creation of a local variable, the special (var) keyword is used to ensure the creation of a local variable.

var varName = 'value'

It is best practice always to use the var keyword unless you knowingly intend to update a global variable.

The conditional assignment operator (?=) initializes a variable only if it doesn’t exist yet or has a value of null or missing. Otherwise, the assignment is skipped. For example, the following Expression assigns 5 to the variable arg only if it doesn’t exist or the value is null or missing.

arg ?= 5

Chain the variable assignments using equal signs as delimiters to assign multiple variables the same value.

var1 = var2 = var3 = 'value'

The assignment operator has the lowest priority within the substatement.

Identifiers

Identifiers are used to name local variables, object properties, and functions. Identifiers may contain any number of English letters, digits, underscore (_), dollar signs ($), or at (@) symbols and cannot start from a digit.

var1,
_internalVar,
$Item.$ItemType;

Reserved words

Four reserved words cannot be used as identifiers:

  • null – Nothing, null value.
  • missing – Missing value for arguments.
  • true – Boolean constant true.
  • false – Boolean constant false.

The following language lexemes also cannot be used as identifiers:

  • or
  • and
  • not
  • if
  • else
  • var
  • return
  • break
  • tail

Integer numbers

Integer numbers can be specified both in decimal and in hexadecimal number systems. An underscore symbol for readability can separate thousands.

-1000,
10_000,
0xF0

Floating point numbers

Floating point numbers are specified in a standard way; the dot symbol separates the integral part from the fractional part. The exponent part may be added using the letter e.

-1000.01,
1. ,
.5 ,
1e5

Decimal numbers

Decimal numbers are specified as integral parts, followed by the dot symbol and the fractional part, and have a ‘d’ suffix at the end.

-1000.01d,
.5d,
100d

Currency numbers

Currency numbers are specified as integral parts, followed by the dot symbol and fractional parts, and have ‘$’ suffixes at the end.

Examples:

1000.01$,
.5$,
100$

Strings

Literal strings are enclosed to single-quote symbols. A backslash should precede any quote symbol inside a literal string to prevent it from being treated as the end of the string. Literal string lasts until the end marker and can sit on several lines of code – line end markers and spaces are left as is in the string.

'Valid string example',
'Another valid \'string\'',
'Multi-line
            string'

Here are all the supported escape sequences:

  • \’ – Represents a single quote symbol.
  • \” – Represents double quote symbol.
  • \{ – Represents opening brace symbol.
  • \} – Represents closing brace symbol.
  • \\ – Represents backslash symbol.
  • \r – Represents carriage return symbol.
  • \n – Represents line feed symbol.
  • \t – Represents tabulation symbol.
  • \uXXXX – Represents any Unicode symbol where XXXX is a hexadecimal code.

Strings can be easily concatenated using the (+) operator. During concatenation, all non-string values are automatically converted to strings.

'Text' + 1 + ' = ' + (2 + 2)

Raw Strings

Raw literal strings are enclosed to triple single-quote symbols (”’). The raw string can contain any sequence of characters except the end marker. No detection of any escape sequence was performed, and all characters were left as is.

'''All the following symbols and sequences are valid inside raw string:
- single quote ',
- double single quote '',
- double quote ",
- double double quote "",
- triple double quote """,
- no escape for \n
'''

Template strings

Template strings are enclosed to double-quote symbols. A backslash should precede any double quote symbol inside a template string to prevent it from being treated as the end of the string.

Template strings can contain substitutions. Each substitution in the template string is an expression enclosed to { and } symbols or {: and :} Markers.

The value of a template string is a string with all substitutions evaluated and placed in the original template as strings (using the ToString function). However, suppose the template string consists of only one substitution without any textual prefix or suffix. In that case, the value of the template string is the value of the evaluated substitution expression without type conversion.

So, the following template string evaluates to the string Five is greater than two.

"Five is {5 > 2 ? 'greater' : 'less'} than two"

The following template string evaluates to the number 5.

"{5}"

Substituion expressions may easily contain nested template strings.

"Five is {5 > 2 ? 'greater' : "never {'less'} "} than two"

It is possible to provide a custom string format (see ToString function for more details) for substitution using the arrow (->):

"{15 -> X}"; // to get hexadecimal value representation
"{Date() -> D}" // to get full human readable date of today

Raw Template Strings

Raw template strings are enclosed in triple double-quote symbols (“). They can contain any sequence of characters except the end marker. No detection of any escape sequence was performed, and all characters were left as is.

Raw template strings can contain substitutions, the same as regular Template Strings. Substituion expressions may easily contain nested raw template strings.

"""Five is {5 > 2 ? 'greater' : """never {'less'} """} than two"""

Arrays

To define an array of values, square brackets are used:

[1, 2, 3, 3 + 1],
[1],
[]

Arrays can be easily concatenated using the + operator. All non-array values are automatically converted to 1-element arrays during concatenation.

[1, 2] + [3, 4] + 5

Comparison of arrays

Two arrays are treated as equal when they have an equal number of elements and all corresponding elements are equal.

Array Map Query

???

Dictionaries

To define a dictionary of key-value pairs, curly braces are used:

{ Key1 = Identifier1, Key2 = 2, Key3 = 'Text', Key4 = 2 + 2 }

If an identifier cannot represent a key, the colon symbol should be a separator between the key and value instead of an equal sign. In this case, the key can be an expression.

{ 'Some Key' : Identifier1, 1 : 'Text', (2 + 2) : 'Four' }

Dictionaries can be easily concatenated using the + operator. If the first dictionary contains the same duplicate keys as the second one, all matching keys from the left dictionary are overwritten by corresponding values from the first one.

For example, the following Expression leads to the result { Key1 = 3, Key2 = 2, Key3 = 1 }.

{ Key1 = 1, Key2 = 2 } + { Key1 = 3, Key3 = 1 }

Comparison of dictionaries

Two dictionaries are treated as equal when there is a corresponding key-value pair in the second dictionary and vice versa for every key-value pair from the first dictionary.

Dictionary Map Query

???

Functions

Gnosis Scripts execute functions to perform business logic. The function name is used to call the function, followed by the arguments list enclosed in parentheses.

Skip(array, 3);
Count(array);
IsEmpty(array);
Random()

Dot Operator

If the dot operator joins an identifier with a function call, the Identifier is treated as the first function argument. For example, the following two expressions are equivalent:

Count(array);
array.Count()

Argument Missing Keyword

Some of the arguments may be omitted if they are not required. To omit non-required arguments in the middle of the arguments list, the reserved (missing) keyword is used.

Round(4.5, missing, true)

Custom Functions

It is possible to define custom functions for the cases when built-in functions are insufficient. To specify a custom function that is visible to the rest of the script, the following syntax should be used:

functionName(args) => bodyExpression

Where args is a comma-separated list of argument names.

IsOdd(n) => n % 2 != 0;
// Usage: IsOdd(2); someNumberVar.IsOdd();

Add(a, b) => a + b;

Inc() => GlobalVar = GlobalVar + 1;

IsNextOdd() => (
	GlobalCounter = GlobalCounter + 1;
	GlobalCounter % 2 != 0;
);

If a function has only one single argument, then parentheses can be omitted:

Increment value => value + 1;
Increment(1);
// result is 2

Anonymous Functions

A function name is not required. Functions defined without a name are called anonymous functions. Anonymous functions are often used as predicate arguments for other functions:

array.Count(item => item != 0)

If an anonymous function is assigned to a variable, the variable’s name automatically becomes the function’s name. So, the following two definitions are equivalent:

Increment value => value + 1;
Increment = value => value + 1

Application Functions

You can create custom functions that are Gnosis Scripts saved in the Gnosis Files /functions folder.

Boolean true conformance

A condition value is treated as (true) when it is:

  • Boolean and equals to true
  • Number and does not equal to 0
  • Array, Dictionary, String, or Url and is not empty.
  • DateTime and does not equal to January 1, 0001 (00:00:00.000)
  • Date and does not equal to January 1, 0001
  • Time and does not equal to 00:00:00.000
  • Any other non-null object

Comments

The Gnosis Script supports comments in the code. Comments serve the same purpose as in most programming languages: to make notes for a human reading the code. They are not calculated or run in any way.

Single-line comments start with // and last till the end of the line:

// This is a single line comment

Multi-line comments start with /* and end with */:

/* This is a multiline comment,
   it occupies several lines. */

Documenting Gnosis Scripts

Custom Gnosis Script Functions, Task Commands, and Web API Views can be commented with @directives to generate documentation automatically.

Documentation Directives

To document a function, add a comment block with a description of the purpose of the function. Include @ directives to document the function parameters, result, example, and group name.

@group

The @group directive assigned the function to a function group like a category. This can be used to get only functions that belong to a group.

@param

The @param directive describes a function parameter, its data type, specify if optional, its default value if missing, and a description for the parameter. When documenting functions and commands, the default is applied for the parameter.

@param {paramName}[?] : {dataType} [= {defaultValue}] // description text

@result

The @result directive specifies the data type of the function result.

@example

The @example directive is used to show an example of how to use the function.

The following is an example of documenting a custom function:

/**
 * Get a random number.
 * @group GroupName
 * @param min : integer // The minimum number.
 * @param max : integer = 100 // The maximum number, optional, defaults to 100.
 * @param operator? : bool // If true, return positive number, otherwise return a negative number.
 * @result integer 
 * @example RandomNumber(1, missing, false);
 */
RandomNumber(min, max, operator) => (
	var r = Random(min,max);
	operator or operator == missing ? r : - r;
);
// Return a negative number between -1 and -100.
RandomNumber(1, missing, false)

Get Custom Gnosis Script Documentation

The documentation can be returned in JSON format with the following Gnosis v1 Web API endpoints:

/api/Runtime/Types
/api/Runtime/Functions
/api/View/CodeInfo
/documentation/API.json"