HTTP server integration, routes, requests and responses.
Documentation home / Language Syntax
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.
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
| Escape | Meaning |
|---|---|
\\n | Line feed |
\\r | Carriage return |
\\t | Tab |
\\\\ | 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.
| Type | Literal / example | Notes |
|---|---|---|
null | null | Absence of a value; also used for implicit function returns and missing parameters. |
number | 42, 3.14, .5 | Stored as a C double. |
bool | true, false | Boolean 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. |
function | func(x) { return x; } | Can be stored, passed and returned. |
iterator | Created 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.
| Group | Operators |
|---|---|
| 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;
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.
| Function | Purpose | Typical 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
.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.
HTML document, element, escaping and template construction.
Numerical helpers and numerical operations.
Formatted tables.
Compute-oriented utilities.
Math functions and constants.
String transformations and checks.
JSON serialization helpers.
CSV parsing and serialization.
Path joining and path-part helpers.
Time and date utilities.
General-purpose random values; not cryptographic.
UUID generation helpers.
Validation utilities.
Environment variable access.
Non-cryptographic hash helpers.
Base64 encoding and decoding.
URL and query-string encoding.
Filesystem helpers using process permissions.
Cryptographic utility module.
Database integration helpers.
HTTP-related helpers.
Logging helpers.
Form-related helpers.
Object utilities.
Plotting utilities.
Regular-expression utilities.
Statistical functions.
Testing helpers.
AI workspace and neural/optimizer/autograd facilities.
XML module source; verify its build and install before importing.
YAML module source; verify its build and install before importing.
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.
| Construct | Accepted form | Notes |
|---|---|---|
| Declaration | define name = expression; | Introduces a binding in the current environment. |
| Named function | func name(a, b) { ... } | Parameters are positional. |
| Anonymous function | func(a, b) { ... } | Can be assigned, passed or returned. |
| Conditional | if (condition) { ... } else { ... } | else if is supported through nested conditional branches. |
| Loop | while (condition) { ... } | Condition is evaluated before each iteration. |
| Iteration | for (item in iterable) { ... } | Iterates arrays, object keys and string characters. |
| Import | import module; | Loads a module namespace. |
| Selected import | from module import name, other; | Copies named exports into the current lexical environment. |
| Assignment | name = 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 family | Instructions | Role |
|---|---|---|
| Constants and names | NOP, LOAD_CONST, LOAD_NAME, STORE_NAME, POP_TOP | Load constants and lexical bindings, store values, and discard expression results. |
| Arithmetic | ADD, SUB, MUL, DIV, MOD, NEG | Numeric operations and addition (which also supports string concatenation through the value layer). |
| Comparisons and logic | NOT, EQ, NE, LT, LE, GT, GE, AND, OR | Unary truthiness negation, equality, ordering and logical operations. |
| Control flow | JUMP, JUMP_IF_FALSE, JUMP_IF_TRUE | Implement branches, loops, break/continue targets and short-circuit evaluation. |
| Calls and functions | CALL, RETURN, MAKE_FUNCTION | Invoke native/user functions, return from frames and create closures. |
| Collections | BUILD_ARRAY, BUILD_OBJECT, GET_INDEX, SET_INDEX, GET_MEMBER, SET_MEMBER | Construct arrays/objects and read or update indexed/member values. |
| Modules | IMPORT, FROM_IMPORT | Load a module object or selected exports. |
| Iteration and termination | ITER_INIT, ITER_NEXT, HALT | Create 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
- Value representation: the VM's tagged
GSValueunion representsnull, double-precision numbers, booleans, strings, arrays, objects, user functions, native functions and iterators. - Lexical environments: each environment stores named bindings and may point to a parent environment. Name lookup and assignment walk this parent chain.
- Closures: creating a function captures the current environment. Calling it creates a child environment, binds positional parameters, and executes the function's code object in a new VM frame.
- Frames and stack: a frame tracks its code object, instruction pointer, operand-stack base and lexical environment. Calls to native functions use the native function pointer; user functions push VM frames.
- Missing values: omitted positional arguments are bound to
null. A function body receives an implicitnullreturn if control reaches its end. - Iteration: array iterators yield values in index order, object iterators yield property names, and string iterators yield one character at a time.
- Object access: a missing object property or out-of-range array/string index produces
nullin the current value access implementation. - Class model: class descriptors and instances are objects marked with runtime metadata. Inherited default fields are cloned for instances; methods remain ordinary function values and receive
selfexplicitly.
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 name | Build source | Documentation |
|---|---|---|
server | server.c | Server API |
construct | construct.c | Construct API |
gsnum | gsnum.c | gsnum |
gs_table | table.c | Tables |
gs_compute | gs_compute.c | Compute |
gs_math | gs_math.c | Math |
gs_string | gs_string.c | Strings |
gs_json | gs_json.c | JSON |
gs_csv | gs_csv.c | CSV |
gs_path | gs_path.c | Paths |
gs_time | gs_time.c | Time |
gs_random | gs_random.c | Random |
gs_uuid | gs_uuid.c | UUID |
gs_validate | gs_validate.c | Validation |
gs_env | gs_env.c | Environment |
gs_hash | gs_hash.c | Hashing |
gs_base64 | gs_base64.c | Base64 |
gs_url | gs_url.c | URL |
gs_file | gs_file.c | Files |
gs_crypto | gs_crypto.c | Cryptography |
gs_db | gs_db.c | Database |
gs_http | gs_http.c | HTTP utilities |
gs_log | gs_log.c | Logging |
gs_form | gs_form.c | Forms |
gs_object | gs_object.c | Objects |
gs_plot | gs_plot.c | Plotting |
gs_regex | gs_regex.c | Regular expressions |
gs_statistics | gs_statistics.c | Statistics |
gs_test | gs_test.c | Testing |
gs_brain | ai-modules/gs_brain.c | AI workspace |
gs_xml | gs_xml.c | XML module source |
gs_yaml | gs_yaml.c | YAML module source |
gs_compat | gs_compat.c | Compatibility source; check its build workflow before importing |
.so files.19. Diagnostics and command-line modes
| Command | Behavior |
|---|---|
greenServeFE file.gsve | Compile and execute a GSVE program. |
greenServeFE --version | Print runtime version. |
greenServeFE --dump file.gsve | Disassemble compiled bytecode. |
greenServeFE --trace file.gsve | Run with VM execution tracing enabled. |
greenServeFE --profile file.gsve | Collect 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
- The accepted source extension is
.gsve. - The language is dynamically typed; numbers are represented as doubles.
- Declarations use
define; functions usefunc; blocks use braces. - Function parameters are positional. Missing arguments become
null; there is no documented default-parameter or variadic-parameter syntax. - Class support is a lightweight descriptor/instance model. Methods receive
selfexplicitly; do not assume automatic method binding. - Native modules are external shared objects using ABI version 1, not keywords built into the language.
- HTTP, HTML, database, numerical and AI capabilities depend on the corresponding module being available in the runtime's module path.
- The current core VM and module APIs should be treated according to the implementation and module-specific documentation; do not infer unsupported syntax from another language.
Core language introduction.
Execution frames and runtime architecture.
Instruction-level details.
Core VM functions.
Module installation and API references.
