greenServeFE logogreenServeFELanguage, VM and Native Module Reference

Documentation home / Language Syntax

Complete language reference · GSVE

greenServeFE Language Syntax

A practical, implementation-aligned reference to the GSVE language accepted by the greenServeFE lexer, parser, compiler and bytecode virtual machine. It covers source syntax, runtime values, control flow, functions, classes, imports, built-ins and the native module boundary.

Version and scope. This reference describes the source currently present in greenServeFE-build (runtime identifies itself as 1.0.6). Native modules are independently compiled shared libraries. An API appearing in a module page is available only when its matching module is built and installed.

1. Quick start

Save source in a file ending in .gsve. The runtime reads the file, tokenizes it, parses an AST, compiles bytecode and executes that bytecode in the VM.

# hello.gsve
define language = "greenServeFE";
print("Hello from " + language);

func square(value) {
    return value * value;
}

print(square(9));
greenServeFE hello.gsve
greenServeFE --version
greenServeFE --dump hello.gsve
greenServeFE --trace hello.gsve
greenServeFE --profile hello.gsve

Statements may be separated by newlines or semicolons. Blocks use braces. The language uses define for declarations and func for function declarations; it does not use JavaScript's let, const or function declaration keywords.

2. Lexical rules

Identifiers

Identifiers begin with an ASCII letter or underscore and continue with letters, digits or underscores. Examples: name, _cache, item2, total_price. Keywords are case-sensitive.

Comments and whitespace

# This is a comment. It continues to the end of this line.
define total = 10; # inline comment

Spaces, tabs, carriage returns and line breaks separate tokens. A # begins a comment outside a quoted string. The lexer accepts both single-quoted and double-quoted strings.

String escapes

EscapeMeaning
\\nLine feed
\\rCarriage return
\\tTab
\\\\Backslash
\\"Double quote
\\'Single quote
define message = "first line\nsecond line";
define label = 'Dominex\'s program';
print(message);
print(label);

3. Values and literals

The runtime value model includes null, number, boolean, string, array, object, user function, native function and iterator.

TypeLiteral / exampleNotes
nullnullAbsence of a value; also used for implicit function returns and missing parameters.
number42, 3.14, .5Stored as a C double.
booltrue, falseBoolean literals are lowercase.
string"hello", 'hello'Quoted text with supported backslash escapes.
array[1, 2, 3]Ordered, zero-indexed, mutable collection.
object{name: "Ada"}String-keyed property collection.
functionfunc(x) { return x; }Can be stored, passed and returned.
iteratorCreated by for (x in value)Used internally for iteration.

Numbers support integer-looking and decimal notation. There is no separate integer type in the runtime representation.

4. Expressions and operators

Arithmetic

define a = 17;
define b = 5;
print(a + b);  # 22
print(a - b);  # 12
print(a * b);  # 85
print(a / b);  # 3.4
print(a % b);  # remainder

Comparison and equality

print(5 == 5);
print(5 != 3);
print(3 < 8);
print(3 <= 3);
print(9 > 4);
print(9 >= 9);

Logical and unary operators

define enabled = true;
define ready = enabled && (4 > 2);
define blocked = false || !ready;
define negative = -12;
define positive = +12;

&& and || short-circuit: the right-hand expression is skipped when the left side already determines the result. Logical results are booleans. Unary ! negates truthiness; unary - negates a number. Unary + is parsed as a unary operator and leaves its operand unchanged.

GroupOperators
Grouping / postfix( ), function call (), index [], member .
Unary!, -, +
Multiplicative*, /, %
Additive+, -
Relational<, <=, >, >=
Equality==, !=
Logical AND&&
Logical OR||
Assignment= (statement/expression assignment form)

Parentheses can make grouping explicit. Addition also supports string concatenation through the runtime's value operation.

5. Declarations and assignment

define username = "Ada";
define score = 100;
define active = true;

score = score + 5;
username = "Grace";
print(username);
print(score);

define name = expression; declares a binding in the current lexical environment. Assignment updates a variable binding or a nested collection target.

define profile = {name: "Ada", stats: {visits: 1}};
profile.name = "Grace";
profile.stats.visits = 2;

define values = [10, 20, 30];
values[1] = 99;
Use define when introducing a variable. Use = to assign a new value to an existing binding, object member or array index.

6. Arrays and objects

Arrays

define colors = ["green", "blue", "gold"];
print(colors[0]);
print(len(colors));
push(colors, "silver");
define last = pop(colors);
print(last);

Array indexes are zero-based. Index expressions may be computed. Arrays can contain mixed values and nested arrays/objects.

Objects

define account = {
    name: "Ada",
    active: true,
    balance: 125.50
};
print(account.name);
print(account["balance"]);
account.active = false;

define key = "name";
print(account[key]);

Object keys may be identifiers or quoted strings. Values are arbitrary expressions. Dot access uses a literal member name; bracket access uses a computed key.

Nested values and iteration

define orders = [
    {id: 101, items: ["book", "pen"]},
    {id: 102, items: ["laptop"]}
];

for (order in orders) {
    print(order.id);
    for (item in order.items) {
        print(item);
    }
}

Arrays, objects and strings are iterable. Array iteration yields elements; object iteration yields keys; string iteration yields characters.

7. Control flow

if / else if / else

define score = 82;
if (score >= 90) {
    print("excellent");
} else if (score >= 70) {
    print("pass");
} else {
    print("retry");
}

while

define count = 0;
while (count < 3) {
    print(count);
    count = count + 1;
}

for / in

for (number in [10, 20, 30]) {
    print(number);
}

for (key in {host: "localhost", port: 8080}) {
    print(key);
}

break and continue

for (number in [1, 2, 3, 4, 5]) {
    if (number == 2) {
        continue;
    }
    if (number == 5) {
        break;
    }
    print(number);
}

break exits the nearest loop. continue advances the nearest loop to its next iteration.

8. Functions, return values and closures

Named function declaration

func add(a, b) {
    return a + b;
}
print(add(12, 8));

Function expressions and values

define multiply = func(a, b) {
    return a * b;
};
define operation = multiply;
print(operation(6, 7));

Return and omitted arguments

func greet(name) {
    if (name == null) {
        return "Hello";
    }
    return "Hello " + name;
}
print(greet());
print(greet("Ada"));

A function that reaches its closing brace returns null. A missing positional argument is supplied as null. Validate arguments when a function requires them.

Closures

func make_counter() {
    define count = 0;
    func next() {
        count = count + 1;
        return count;
    }
    return next;
}
define counter = make_counter();
print(counter());
print(counter());

Nested functions capture the lexical environment where they are created. Captured bindings can be read and updated after the outer function has returned.

Recursion

func factorial(n) {
    if (n <= 1) {
        return 1;
    }
    return n * factorial(n - 1);
}
print(factorial(5));

9. Class descriptors and instances

The runtime includes lightweight class descriptors, default fields, methods, inheritance, instance creation and instanceof. Methods are ordinary functions: pass the instance explicitly as the first parameter (commonly named self). This is not an automatic receiver-binding or constructor-dispatch system.

define Animal = class({
    fields: {name: "unknown"},
    methods: {
        describe: func(self) {
            return "Animal: " + self.name;
        }
    }
});

define Dog = class({
    extends: Animal,
    fields: {kind: "dog"},
    methods: {
        speak: func(self) {
            return self.name + " says woof";
        }
    }
});

define pet = new Dog();
pet.name = "Rex";
print(pet.describe());
print(pet.speak());
print(pet instanceof Dog);

Class construction is provided by core built-ins rather than a separate class-declaration keyword. Consult the current runtime examples before relying on advanced inheritance behavior.

10. Core built-in functions

These functions are registered by the VM and do not require importing a native module.

FunctionPurposeTypical use
print(...values)Print values separated by spaces and finish with a newline.print("total", total)
show(...values)Core output alias in the VM.show(profile)
interact(prompt?)Print optional prompt, read one stdin line, return string or null at EOF.define name = interact("Name: ")
len(value)Length/count of string, array or object; otherwise 0.len(items)
str(value)Convert value to its string representation.str(42)
num(value)Convert using the runtime numeric conversion.num("12")
type(value)Return runtime type name.type(data)
range(stop)Generate values from 0 up to (excluding) stop.range(5)
range(start, stop, step?)Generate a stepped numeric array; step defaults to 1.range(2, 10, 2)
push(array, value)Append to array and return its new count.push(items, "new")
pop(array)Remove and return final array item.pop(items)
keys(object)Return object keys as an array.keys(profile)
values(object)Return object values as an array.values(profile)
contains(container, value)Test membership in supported string/collection values.contains(names, "Ada")
clone(value)Recursively clone nested data.define copy = clone(data)
merge(a, b)Merge object data.define config = merge(base, overrides)
has(object, key)Check whether an object owns a key.has(user, "email")
class(options)Create a lightweight class descriptor.define T = class({...})
new(Class)Create an instance from a class descriptor.define item = new(T)
instanceof(value, Class)Test instance/class relationship.instanceof(item, T)
range() refuses a zero step and caps generated output at 100,000 items. interact() reads from process standard input; it is not a browser prompt.

11. Imports and native modules

Import a module namespace

import gs_math;
print(gs_math.sqrt(81));

Import selected names

from gs_math import sqrt, clamp;
print(sqrt(144));
print(clamp(120, 0, 100));

Import statements are compiled to module-loading operations. The VM dynamically loads a shared object, resolves the initializer symbol greenServeFE_module_init, and exposes the returned object under the module name. Imported members are then accessed through normal member lookup.

Module search path

export GREENSERVE_MODULE_PATH=/usr/local/lib/modules
export LD_LIBRARY_PATH=/usr/local/lib/modules:$LD_LIBRARY_PATH

A typical Linux installation places shared objects such as /usr/local/lib/modules/gs_math.so and /usr/local/lib/modules/server.so in the module search directory. Local module paths are also recognized by the loader. Ensure the shared object matches the runtime's native ABI.

Native module ABI

GSValue greenServeFE_module_init(const GSNativeAPI *api);

A module initializer receives the versioned GSNativeAPI table and returns a GSVE object containing exported native functions. The API provides value constructors, retain/release and copy operations, array/object access, conversions, truthiness, printing and a callback bridge for calling GSVE functions. Current ABI version is 1. Modules should use the public API rather than private VM structures.

Server and HTML construction

import server;

func home(req, res) {
    res.html("

Hello from greenServeFE

"); } server.get("/", home); server.serve(".", 8080, {host: "0.0.0.0", static: false});

The server and construct APIs are native modules with their own references. Check Server and Construct for exact exported methods and current build status. The server module's availability depends on its corresponding native build and installation; the VM core alone is not a full HTTP server.

12. How source becomes executable

Execution pipeline
.gsve source
  → lexer (tokens with source locations)
  → parser (AST)
  → compiler (GSCode)
  → bytecode instruction stream
  → VM frames + operand stack + environments
  → runtime values and native calls

Lexer and parser

The lexer recognizes identifiers, numeric and string literals, keywords, punctuation, arithmetic/comparison/logical operators and source line/column positions. The parser builds expression and statement nodes for declarations, assignments, blocks, conditionals, loops, functions, calls, arrays, objects, indexing, members and imports.

Compiler and code objects

The compiler translates AST expressions and statements into instructions. A GSCode stores instructions, constants, name references, child function code objects and parameter metadata. Function bodies are compiled into child code objects; function creation captures the current lexical environment.

Virtual machine

The VM executes instructions using an instruction pointer, operand stack and call frames. Frames refer to a code object and lexical environment. Environments link to parent environments for lexical lookup and closure capture. Runtime values include reference-counted strings, arrays, objects, functions and iterators.

Bytecode operations

The instruction set includes loading constants/names, storing names, stack operations, arithmetic, comparisons, unary operations, jumps, conditional jumps, calls, returns, array/object construction, member/index get/set, function creation, imports, iterator initialization/advance and halt.

Use --dump to inspect compiled instructions, --trace to observe execution and --profile to collect runtime profiling data.

13. Native module catalog

These are module families represented in the build repository and documentation. Each module is separate from the core syntax and must be built/installed before its import can succeed. The linked module pages document the currently published API surface.

server

HTTP server integration, routes, requests and responses.

construct

HTML document, element, escaping and template construction.

gsnum

Numerical helpers and numerical operations.

gs_math

Math functions and constants.

gs_csv

CSV parsing and serialization.

gs_path

Path joining and path-part helpers.

gs_random

General-purpose random values; not cryptographic.

gs_env

Environment variable access.

gs_hash

Non-cryptographic hash helpers.

gs_url

URL and query-string encoding.

gs_file

Filesystem helpers using process permissions.

gs_db

Database integration helpers.

gs_brain

AI workspace and neural/optimizer/autograd facilities.

gs_xml

XML module source; verify its build and install before importing.

gs_yaml

YAML module source; verify its build and install before importing.

Security and trust: gs_file performs filesystem operations with the permissions of the running process; it is not a sandbox. gs_random and non-cryptographic hashes are not substitutes for cryptographic primitives. Only load native modules you trust.

14. Grammar and compiler-supported forms

This section describes the forms represented by the current lexer, parser and compiler. It is intentionally narrower than JavaScript, Python or C: syntax from those languages is not automatically accepted by GSVE.

ConstructAccepted formNotes
Declarationdefine name = expression;Introduces a binding in the current environment.
Named functionfunc name(a, b) { ... }Parameters are positional.
Anonymous functionfunc(a, b) { ... }Can be assigned, passed or returned.
Conditionalif (condition) { ... } else { ... }else if is supported through nested conditional branches.
Loopwhile (condition) { ... }Condition is evaluated before each iteration.
Iterationfor (item in iterable) { ... }Iterates arrays, object keys and string characters.
Importimport module;Loads a module namespace.
Selected importfrom module import name, other;Copies named exports into the current lexical environment.
Assignmentname = value;, obj.key = value;, arr[index] = value;Assignment targets must be identifiers, member expressions or index expressions.
Object literal{key: value, "other-key": value}Keys are identifiers or quoted strings.

Statement separators and blocks

Newlines and semicolons separate statements. Braces delimit blocks and object literals. Parentheses group expressions and surround conditions, loop headers and function arguments. Commas separate function parameters, call arguments, array items and object entries.

Current syntax exclusions

The current token and AST definitions do not define dedicated syntax for let, const, var, function, arrow functions, classes declared with a class keyword, ternary expressions, switch, try/catch, exceptions, async/await, generators, template literals, increment/decrement operators, compound assignment operators, or type annotations. Use the documented GSVE forms instead of assuming these constructs work.

15. Bytecode instruction reference

The compiler emits GSInstr records. Each instruction stores an 8-bit opcode, a signed 32-bit argument and the source line. A GSCode object owns its instruction array, constants, name table, child function code objects and parameter count.

Opcode familyInstructionsRole
Constants and namesNOP, LOAD_CONST, LOAD_NAME, STORE_NAME, POP_TOPLoad constants and lexical bindings, store values, and discard expression results.
ArithmeticADD, SUB, MUL, DIV, MOD, NEGNumeric operations and addition (which also supports string concatenation through the value layer).
Comparisons and logicNOT, EQ, NE, LT, LE, GT, GE, AND, ORUnary truthiness negation, equality, ordering and logical operations.
Control flowJUMP, JUMP_IF_FALSE, JUMP_IF_TRUEImplement branches, loops, break/continue targets and short-circuit evaluation.
Calls and functionsCALL, RETURN, MAKE_FUNCTIONInvoke native/user functions, return from frames and create closures.
CollectionsBUILD_ARRAY, BUILD_OBJECT, GET_INDEX, SET_INDEX, GET_MEMBER, SET_MEMBERConstruct arrays/objects and read or update indexed/member values.
ModulesIMPORT, FROM_IMPORTLoad a module object or selected exports.
Iteration and terminationITER_INIT, ITER_NEXT, HALTCreate an iterator, advance it or stop execution.

Logical && and || are compiled as conditional jumps so the right-hand expression is skipped when its result is unnecessary. The VM also has logical opcode handlers, but the compiler's short-circuit path uses jumps and boolean normalization. Use greenServeFE --dump program.gsve to inspect the actual instruction stream generated for a program.

16. Runtime values, environments and calls

GSVE is dynamically typed. The VM does not provide static type checking, a garbage-collected heap, process isolation or a security sandbox. Treat scripts and native modules as trusted executable code.

17. Native module ABI and loader

Export contract

#include "module.h"

GSValue greenServeFE_module_init(const GSNativeAPI *api) {
    GSValue exports = api->object();
    /* Create native functions with api->native(...),
       then add them to exports with api->object_set(...). */
    return exports;
}

The initializer symbol is greenServeFE_module_init; the current ABI version is GSFE_MODULE_ABI_VERSION 1. The initializer receives a GSNativeAPI function table. It returns one GSVE object whose properties form the module's public namespace. A module that returns a non-object or omits the initializer cannot be imported successfully.

Native API services

The ABI exposes constructors for null, number, boolean, string, object, array and native-function values; value copy/retain/release; array and object access; C-string, truthiness and numeric conversions; value printing; and a callback bridge for invoking GSVE functions from native code. Use the ABI table instead of depending on private VM structures.

Module lookup order

For a simple import such as import gs_math;, the loader tries the current-directory path ./gs_math.so, then ./modules/gs_math.so, then gs_math.so through the platform loader, followed by each colon-separated directory in GREENSERVE_MODULE_PATH. If the import string contains a slash or already ends in .so, it is treated as a direct path. Loaded modules are cached by import name for the lifetime of the VM.

export GREENSERVE_MODULE_PATH=/usr/local/lib/modules
export LD_LIBRARY_PATH=/usr/local/lib/modules:$LD_LIBRARY_PATH

# Example source file
import gs_math;
print(gs_math.sqrt(81));

The loader opens modules with dlopen, resolves the initializer with dlsym, and keeps the shared-library handle alive until VM teardown. A missing library, missing initializer or invalid return value is reported as a runtime module-loading error.

18. Build-source module inventory

The following names are represented by C module sources in the build repository. The presence of a source file does not by itself guarantee that a matching shared object is installed on a particular machine. Consult the module's own page and release/build workflow for its exact exports and availability.

Import nameBuild sourceDocumentation
serverserver.cServer API
constructconstruct.cConstruct API
gsnumgsnum.cgsnum
gs_tabletable.cTables
gs_computegs_compute.cCompute
gs_mathgs_math.cMath
gs_stringgs_string.cStrings
gs_jsongs_json.cJSON
gs_csvgs_csv.cCSV
gs_pathgs_path.cPaths
gs_timegs_time.cTime
gs_randomgs_random.cRandom
gs_uuidgs_uuid.cUUID
gs_validategs_validate.cValidation
gs_envgs_env.cEnvironment
gs_hashgs_hash.cHashing
gs_base64gs_base64.cBase64
gs_urlgs_url.cURL
gs_filegs_file.cFiles
gs_cryptogs_crypto.cCryptography
gs_dbgs_db.cDatabase
gs_httpgs_http.cHTTP utilities
gs_loggs_log.cLogging
gs_formgs_form.cForms
gs_objectgs_object.cObjects
gs_plotgs_plot.cPlotting
gs_regexgs_regex.cRegular expressions
gs_statisticsgs_statistics.cStatistics
gs_testgs_test.cTesting
gs_brainai-modules/gs_brain.cAI workspace
gs_xmlgs_xml.cXML module source
gs_yamlgs_yaml.cYAML module source
gs_compatgs_compat.cCompatibility source; check its build workflow before importing
Module safety: native modules execute inside the same process as the VM and are not sandboxed. Filesystem and network modules operate with the process's operating-system permissions. Never load untrusted .so files.

19. Diagnostics and command-line modes

CommandBehavior
greenServeFE file.gsveCompile and execute a GSVE program.
greenServeFE --versionPrint runtime version.
greenServeFE --dump file.gsveDisassemble compiled bytecode.
greenServeFE --trace file.gsveRun with VM execution tracing enabled.
greenServeFE --profile file.gsveCollect VM profiling information.

Source diagnostics identify lexer, parser, compiler or runtime stages and include line/column positions where available. The CLI prints the relevant source line and a caret under the reported location.

20. Current implementation boundaries

Continue learning
Language overview

Core language introduction.

Virtual machine

Execution frames and runtime architecture.

Bytecode reference

Instruction-level details.

Built-in functions

Core VM functions.

Native module catalog

Module installation and API references.