GorillaScript Language Specification

Version: 1.1 (Bytecode Version: 0x00010001)

Last Updated: December 2025

Copyright: 2017-2025 Eric Berger, gorilla3d.de Gorilla3D Framework


Table of Contents

  1. Overview
  2. Architecture
  3. Syntax Specification
  4. Type System
  5. Control Flow Structures
  6. Functions and Procedures
  7. Classes and Interfaces
  8. Native Interoperability
  9. Bytecode Execution Model
  10. Performance Characteristics
  11. Known Limitations
  12. Example Scripts

1. Overview

1.1 What is GorillaScript?

GorillaScript is a scripting language designed for the Gorilla3D Framework that provides a Pascal/Delphi-based syntax with native Delphi interoperability. It is a compiled, bytecode-interpreted language that allows embedding scripting capabilities into Delphi applications.

1.2 Key Features

  • Pascal/Delphi Syntax: Familiar syntax for Delphi developers
  • Bytecode Compilation: Source code is compiled to bytecode for execution
  • Native Interop: Direct access to Delphi classes, interfaces, records, and enums
  • Stack-Based VM: Bytecode executes on a stack-based virtual machine
  • Type Safety: Strong typing with compile-time type checking
  • RTTI Integration: Deep integration with Delphi's Runtime Type Information system

1.3 Design Philosophy

GorillaScript is designed to provide a balance between performance and flexibility for scripting scenarios within the Gorilla3D Framework.

It prioritizes:

  • Ease of integration with existing Delphi codebases
  • Familiar syntax for Delphi developers
  • Type safety and compile-time error detection
  • Runtime extensibility through native class registration

2. Architecture

2.1 Component Overview

GorillaScript consists of three main components:

  1. Parser (TGorillaScriptParserDelphi)

    • Parses source code into an Abstract Syntax Tree (AST)
    • Supports Delphi/Pascal syntax
    • Uses either Castalia or SimpleParser lexer backend
    • Location: Gorilla.Script.Parser.Delphi.pas
  2. Compiler (TGorillaScriptCompiler)

    • Transforms AST into bytecode
    • Generates optimized instruction sequences
    • Produces portable bytecode streams
    • Location: Gorilla.Script.Compiler.pas
  3. Executor (TGorillaScriptExecutor)

    • Interprets and executes bytecode
    • Manages stack and heap memory
    • Handles native method calls
    • Location: Gorilla.Script.Executor.pas

2.2 Execution Pipeline

Source Code (.pas)
    ↓
Parser (Lexer + Syntax Analysis)
    ↓
Abstract Syntax Tree (AST)
    ↓
Compiler (Code Generation)
    ↓
Bytecode Stream
    ↓
Executor (VM Interpretation)
    ↓
Execution Result

2.3 Engine Architecture

The TGorillaScriptEngine component orchestrates all scripting activities:

  • Script Management: Collection of scripts with source code
  • Type Registry: Registered native enums, sets, structs, interfaces, and classes
  • Search Paths: Directories for unit resolution
  • Compiler Directives: Conditional compilation support
  • Library Binding: Extensible library system via TGorillaScriptLibraryBinder

2.4 Memory Model

Stack:

  • Maximum size: 512 values (configurable via GORILLA_SCRIPT_MAX_STACKSIZE)
  • Stores local variables, parameters, and temporary computation results
  • Each stack entry is a TGorillaScriptStackValue containing a reference and TValue

Call Stack:

  • Maximum depth: 128 calls (configurable via GORILLA_SCRIPT_MAX_CALLSTACK)
  • Tracks function/procedure call hierarchy
  • Each entry contains reference and address information

Heap:

  • Maximum size: 32 MB (configurable via GORILLA_SCRIPT_MAX_HEAPSIZE)
  • Stores dynamically allocated objects and data structures
  • Memory management integrated with Delphi's reference counting

3. Syntax Specification

3.1 Language Basics

GorillaScript uses Pascal/Delphi syntax:

Case Sensitivity: Case-insensitive for keywords and identifiers Comments:

  • Single-line: // comment
  • Multi-line: { comment } or (* comment *)
  • Compiler directives: {$DEFINE SYMBOL}

Statement Terminator: Semicolon (;)

3.2 Program Structure

A GorillaScript program follows standard Delphi unit structure:

program Gorilla3DTest;

uses
    System.SysUtils, FMX.UI, Gorilla3DTest.App;

    procedure Main();
    var LApp : TGorillaApp;
    begin
        // this script is used in keep-alive mode
        // the created script object will be destroyed automatically
        // when the executor will be destroyed.
        LApp := TGorillaApp.Create();
    end;

begin
    Main();
end.

WARNING: Currently it is necessary to declare at least one global function that needs to be called. At this stage of development the program itself does not have an stack context. Therefor we need to call a global function first.

The included Gorill3DTest.App unit looks like this:

unit Gorilla3DTest.App;

interface

uses
    System.SysUtils, System.Math,
    FMX.OS, FMX.UI, FMX.Types, FMX.Forms, FMX.StdCtrls, FMX.Objects3D, Gorilla.DefTypes,
    Gorilla.Viewport, Gorilla.Camera, Gorilla.Light, Gorilla.Model, Gorilla.Controller.Input,
    Gorilla.Material.Lambert, Gorilla.Material.Bumpmap;

const 
    GORILLA_CAPTION : String = 'Gorilla3D Scripting 3D Demo';

type
    TMyClass = class(TObject)
        public
            Tag : String;
    end;

    TGorillaApp = class
        protected
            FWindow    : TForm;
            FViewport  : TGorillaViewport;
            FCenter    : TControl3D;
            FCamera    : TGorillaCamera;
            FLight     : TGorillaLight;
            FCube      : TGorillaCube;
            FSphere    : TGorillaSphere;
            FPlane     : TGorillaPlane;
            FModel     : TGorillaModel;
            FMaterial1 : TGorillaLambertMaterialSource;
            FMaterial2 : TGorillaBumpMapMaterialSource;
            FTimer     : TTimer;
            FInput     : TGorillaInputController;

            FSinCurve  : Double;

            procedure DoOnKeyUp(ASender : TObject; AKeyCode : Integer);
            procedure DoOnTimer(ASender : TObject);

        public
            property Viewport : TGorillaViewport read FViewport;
            property Camera : TGorillaCamera read FCamera;
            property Light : TGorillaLight read FLight;

            property Cube : TGorillaCube read FCube;
            property Sphere : TGorillaSphere read FSphere;
            property Plane : TGorillaPlane read FPlane;

            property Timer : TTimer read FTimer;

            constructor Create(); override;
    end;

implementation

constructor TGorillaApp.Create();
var LForm  : TForm;
    LTexPath : String;
    LTest  : TMyClass;
    LTest2 : TObject;
    LOpts  : TGorillaLoadOptions;
begin
    inherited Create();

    LTest  := TMyClass.Create() as TObject;
    LTest.Tag := 'MyTestClass';
    LTest2 := (LTest as TObject);
    System.WriteLn(LTest.Tag);

    LForm := TUI.GetMainForm();
    Self.FSinCurve := 0.0;

    Self.FWindow := LForm;
    Self.FWindow.Caption := GORILLA_CAPTION;

    // create viewport
    Self.FViewport := TGorillaViewport.Create(LForm);
    Self.FViewport.Parent := LForm;

    // create dummy and camera
    Self.FCenter := TDummy.Create(Self.FViewport) as TControl3D;
    Self.FCenter.Parent := Self.FViewport;

    Self.FCamera := TGorillaCamera.Create(Self.FCenter);
    Self.FCamera.Parent := Self.FCenter;
    Self.FCamera.Target := Self.FCenter;
    Self.FCamera.Position.Point := TPoint3D.Create(0, -10, -50);

    Self.FViewport.Camera := Self.FCamera;
    Self.FViewport.UsingDesignCamera := false;

    /// Overloaded native methods are not detectable for the RTTI, therefore we
    /// use LoadNewModelFromOptions instead of LoadNewModelFromFile in this
    /// demo here.
{ $DEFINE TEST_STRUCT_CALL}
{$IFDEF TEST_STRUCT_CALL}
    LOpts := TGorillaLoadOptions.Create('\delphi\projects\wax\lib\gorilla\source\demos\assets\models\suzanne.gltf', nil, nil);
    Self.FModel := TGorillaModel.LoadNewModelFromOptions(Self.FViewport, LOpts);
{$ELSE}
    // create and load a model from file
    Self.FModel := TGorillaModel.LoadNewModelFromFile(Self.FViewport, nil,
        '\delphi\projects\wax\lib\gorilla\source\demos\assets\models\suzanne.gltf', []);
{$ENDIF}
    Self.FModel.Parent := Self.FViewport;
    Self.FModel.Position.Point := TPoint3D.Create(5, -2, 0);
    Self.FModel.RotationAngle.X := 180;
    Self.FModel.Scale.Point := TPoint3D.Create(2, 2, 2);

    // create light source
    Self.FLight := TGorillaLight.Create(Self.FViewport);
    Self.FLight.Parent := Self.FViewport;
    Self.FLight.Position.Point := TPoint3D.Create(0, -20, 0);
    Self.FLight.LightType := TLightType.Spot;
    Self.FLight.RotationAngle.X := -90;
    Self.FLight.SpotExponent := 0.25;
    Self.FLight.SpotCutOff := 60;

    // create cube and sphere
    Self.FCube := TGorillaCube.Create(Self.FViewport);
    Self.FCube.Parent := Self.FViewport;
    Self.FCube.Scale.Point := TPoint3D.Create(5, 5, 5);
    Self.FMaterial1 := TGorillaLambertMaterialSource.Create(Self.FCube);
    Self.FMaterial1.Parent := Self.FCube;
{$IFDEF MSWINDOWS}
    LTexPath := '..\assets\textures\';
{$ELSE}
    LTexPath := TOS.GetDocumentsPath();
{$ENDIF}    
    Self.FMaterial1.Texture.LoadFromFile(LTexPath + 'crate1_diffuse.jpg');
    Self.FCube.MaterialSource := Self.FMaterial1;

    Self.FSphere := TGorillaSphere.Create(Self.FCube);
    Self.FSphere.Parent := Self.FCube;  
    Self.FSphere.Position.Point := TPoint3D.Create(-3, -1, 0);
    Self.FMaterial2 := TGorillaBumpMapMaterialSource.Create(Self.FSphere);
    Self.FMaterial2.Parent := Self.FSphere;
{$IFDEF MSWINDOWS}
    LTexPath := LTexPath + 'bump\';
{$ENDIF}
    Self.FSphere.MaterialSource := Self.FMaterial2;

    Self.FPlane := TGorillaPlane.Create(Self.FViewport);
    Self.FPlane.Parent := Self.FViewport;
    Self.FPlane.RotationAngle.X := -90;
    Self.FPlane.SetSize(100, 100, 1);
    Self.FPlane.MaterialSource := Self.FMaterial1;

    // create a timer for animation
    Self.FTimer := TTimer.Create(Self.FViewport);
    Self.FTimer.Parent := Self.FViewport;
    Self.FTimer.Interval := 16;
    Self.FTimer.OnTimer := @Self.DoOnTimer;
end;

procedure TGorillaApp.DoOnKeyUp(ASender : TObject; AKeyCode : Integer);
begin
    TUI.ShowInfo('Taste gedrückt = ' + AKeyCode.ToChar());
end;

procedure TGorillaApp.DoOnTimer(ASender : TObject);
var LY, LX : Double;
begin
    // update window caption with FPS for checking performance
    Self.FWindow.Caption := GORILLA_CAPTION + ' ' + Self.FViewport.FPS.ToString() + ' FPS';

    // animate 3D elements
    Self.FViewport.BeginUpdate();
    try
        Self.FSinCurve := Self.FSinCurve + 0.1;
        LY := TMath.Sin(Self.FSinCurve);
        LX := TMath.Cos(Self.FSinCurve);

        Self.FCube.Position.Point := TPoint3D.Create(0, LY * 2, 0);
        Self.FCube.RotationAngle.Y := Self.FCube.RotationAngle.Y + 1;
        Self.FSphere.RotationAngle.Y := Self.FSphere.RotationAngle.Y - 1;

        Self.FLight.Position.Point := TPoint3D.Create(LX * 5, -10, LY * 3);

        Self.FModel.RotationAngle.Y := Self.FModel.RotationAngle.Y + 1;
    finally
        Self.FViewport.EndUpdate();
    end;
end;

end.

3.3 Variable Declarations

var
  MyInteger: Integer;
  MyString: String;
  MyBoolean: Boolean;
  MyObject: TMyClass;
  MyArray: TArray;

3.4 Constant Declarations

const
  MAX_VALUE = 100;
  APP_NAME = 'MyApp';
  PI_VALUE = 3.14159;

3.5 Operators

Arithmetic Operators:

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • div (Integer division)
  • mod (Modulo)

Comparison Operators:

  • = (Equality)
  • <> (Inequality)
  • < (Less than)
  • <= (Less than or equal)
  • > (Greater than)
  • >= (Greater than or equal)

Logical Operators:

  • and (Boolean AND)
  • or (Boolean OR)
  • xor (Boolean XOR)
  • not (Boolean NOT)

Bitwise Operators:

  • and (Bitwise AND)
  • or (Bitwise OR)
  • xor (Bitwise XOR)
  • shl (Shift left)
  • shr (Shift right)

Special Operators:

  • @ (Address of)
  • in (Set membership)
  • as (Type cast)
  • is (Type check)

4. Type System

4.1 Primitive Types

GorillaScript supports standard Delphi primitive types:

Integer Types:

  • ShortInt / Int8: 8-bit signed integer
  • Byte / UInt8: 8-bit unsigned integer
  • SmallInt / Int16: 16-bit signed integer
  • Word / UInt16: 16-bit unsigned integer
  • Integer / LongInt / Int32: 32-bit signed integer
  • Cardinal / LongWord / UInt32: 32-bit unsigned integer
  • Int64: 64-bit signed integer
  • UInt64: 64-bit unsigned integer

Floating-Point Types:

  • Single: 32-bit floating-point
  • Double: 64-bit floating-point

Boolean Types:

  • Boolean: Standard boolean type

String Types:

  • String: Unicode string (UnicodeString)

String Helper Methods:

  • str.ToInteger() - Convert string to integer
  • str.ToInt64() - Convert string to 64-bit integer
  • str.ToSingle() - Convert string to single precision float
  • str.ToDouble() - Convert string to double precision float
  • str.ToBoolean() - Convert string to boolean
  • str.ToValue() - Convert string to TValue

Numeric Type Helpers:

All numeric types (Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double) provide:

  • .ToString() - Convert to string representation
  • .ToChar() - Convert to character representation
  • Boolean provides .ToString() for "True"/"False" representation

Special Types:

  • Pointer: Generic pointer type
  • TValue: Variant-like type for dynamic typing
  • TMethod: Method pointer type

4.2 Structured Types

Arrays:

GorillaScript provides a powerful TArray type with rich helper methods. Arrays can hold mixed types (strings, numbers, booleans) in the same array.

var LArr1 : TArray;
begin
  // Create array with size
  LArr1 := TArray.Create(5);

  // Mixed-type storage
  LArr1[0] := 'abc';      // String
  LArr1[1] := 123.25;     // Double
  LArr1[2] := true;       // Boolean
  LArr1[4] := LArr1[0];   // Copy element

  // Display array
  System.WriteLn(LArr1.ToString()); // [abc, 123.25, True, (empty), abc]
end;

TArray Helper Methods:

  • Construction & Info:

    • TArray.Create(size) - Create array with specified size
    • arr.Length() - Get array length
    • arr.IsEmpty() - Check if array is empty
    • arr.High() - Get highest index
    • arr.Low() - Get lowest index (always 0)
  • Element Access:

    • arr[index] - Read/write element at index
    • arr.First() - Get first element
    • arr.Peek() - Get last element
  • Modification:

    • arr.SetLength(newSize) - Resize array
    • arr.Push(item) - Add item to end
    • arr.Pop() - Remove last item
    • arr.Delete(index, count) - Delete elements
  • Slicing & Copying:

    • arr.Slice(count) - Get slice from start
    • arr.Reduce(count) - Reduce array size
    • arr.Copy(start, count) - Copy range
  • Conversion:

    • arr.ToString() - Convert to string representation
    • arr.ToValue() - Convert to TValue

Records (Structs):

type
  TMyRecord = record
    Field1: Integer;
    Field2: String;
  end;

Sets:

type
  TMyEnum = (meOne, meTwo, meThree);
  TMySet = set of TMyEnum;

var
  MySet: TMySet;
begin
  MySet := [meOne, meThree];
  if meTwo in MySet then
    // ...
end;

Enumerations:

type
  TColor = (clRed, clGreen, clBlue);

var
  MyColor: TColor;
begin
  MyColor := clRed;
end;

4.3 Class Types

Classes follow standard Delphi object-oriented syntax:

type
  TMyClass = class(TObject)
  private
    FValue: Integer;
  protected
    procedure DoProtectedWork;
  public
    constructor Create;
    destructor Destroy; override;
    procedure PublicMethod;
    property Value: Integer read FValue write FValue;
  end;

Visibility Specifiers:

  • private: Accessible only within the class
  • protected: Accessible within the class and descendants
  • public: Accessible everywhere
  • published: Public with RTTI (for native classes)

4.4 Interface Types

type
  IMyInterface = interface
    ['{GUID}']
    procedure DoSomething;
    function GetValue: Integer;
  end;

  TMyClass = class(TInterfacedObject, IMyInterface)
  public
    procedure DoSomething;
    function GetValue: Integer;
  end;

4.5 Type Aliases

type
  TComponentName = String;
  TCallback = procedure(ASender: TObject) of object;

5. Control Flow Structures

5.1 If-Then-Else Statement

if Condition then
  Statement
else if AnotherCondition then
  AnotherStatement
else
  DefaultStatement;

// Block form
if Condition then
begin
  Statement1;
  Statement2;
end
else
begin
  Statement3;
  Statement4;
end;

5.2 Case Statement

GorillaScript supports advanced case statements with integers, floats, and strings. Ranges are supported for all types.

Integer Case:

case Value of
  0: Statement1;
  1, 2, 3: Statement2;         // Multiple values
  4..10: Statement3;            // Range
  11..20, 25, 30..35: Statement4;  // Mixed ranges and values
else
  DefaultStatement;
end;

String Case:

case StringValue of
  'Hello': Statement1;
  'Hallo'..'Hulu': Statement2;  // String range (alphabetical)
  'World': Statement3;
else
  DefaultStatement;
end;

Float Case:

case FloatValue of
  1225.70: Statement1;
  1225.749..1225.7501: Statement2;  // Float range
else
  DefaultStatement;
end;

Block Form:

case Value of
  0:
    begin
      Statement1;
      Statement2;
    end;
  1:
    begin
      Statement3;
    end;
end;

5.3 For Loop

Standard For Loop:

// For-to loop
for i := 0 to 10 do
  Statement;

// For-downto loop
for i := 10 downto 0 do
  Statement;

// Block form
for i := 0 to Count - 1 do
begin
  Statement1;
  Statement2;
end;

Performance Note: For loops are currently slow due to bytecode interpretation overhead on each iteration. See Section 10.1 for details.

5.4 While Loop

Status: Fully Implemented

While loops are implemented using general bytecode operations (JUMP, JUMP_ON_ZERO):

while Condition do
  Statement;

// Block form
while Condition do
begin
  Statement1;
  Statement2;
end;

// With break and continue
while Condition do
begin
  if ShouldSkip then
    Continue;
  if ShouldStop then
    Break;
  ProcessItem;
end;

Implementation: The compiler generates a condition check followed by a conditional jump. The loop body is executed, then an unconditional jump returns to the condition check.

5.5 Repeat-Until Loop

Status: Fully Implemented

Repeat-until loops are implemented using general bytecode operations:

repeat
  Statement1;
  Statement2;
until Condition;

// With break and continue
repeat
  if ShouldSkip then
    Continue;
  if ShouldStop then
    Break;
  ProcessItem;
until Condition;

Implementation: The loop body is executed first, then the condition is checked. A conditional jump returns to the start if the condition is false. This ensures the body executes at least once.

5.6 Try-Except-Finally

// Try-Except
try
  RiskyOperation;
except
  on E: Exception do
    HandleException(E);
end;

// Try-Finally
try
  AllocateResource;
  UseResource;
finally
  FreeResource;
end;

// Try-Except-Finally
try
  RiskyOperation;
except
  on E: ESpecificException do
    HandleSpecific(E);
  on E: Exception do
    HandleGeneral(E);
end;

5.7 Break and Continue

for i := 0 to 100 do
begin
  if ShouldSkip(i) then
    Continue;

  if ShouldStop(i) then
    Break;

  ProcessItem(i);
end;

6. Functions and Procedures

6.1 Procedure Declaration

procedure MyProcedure(Param1: Integer; Param2: String);
begin
  // Implementation
end;

6.2 Function Declaration

function MyFunction(Param1: Integer): String;
begin
  Result := IntToStr(Param1);
end;

6.3 Parameter Modifiers

Value Parameters (default):

procedure Process(Value: Integer);

Var Parameters (by reference):

procedure Modify(var Value: Integer);
begin
  Value := Value + 1;
end;

Out Parameters:

procedure GetValues(out Value1: Integer; out Value2: String);
begin
  Value1 := 42;
  Value2 := 'Hello';
end;

Const Parameters:

procedure Display(const Value: String);
begin
  // Value cannot be modified
  WriteLn(Value);
end;

6.4 Function Overloading

function Calculate(A, B: Integer): Integer; overload;
begin
  Result := A + B;
end;

function Calculate(A, B: Double): Double; overload;
begin
  Result := A + B;
end;

6.5 Method Directives

Virtual Methods:

type
  TBaseClass = class
    procedure DoWork; virtual;
  end;

  TDerivedClass = class(TBaseClass)
    procedure DoWork; override;
  end;

Abstract Methods:

type
  TAbstractClass = class
    procedure DoWork; virtual; abstract;
  end;

Static Methods:

type
  TMyClass = class
    class procedure StaticMethod; static;
  end;

7. Classes and Interfaces

7.1 Class Definition

type
  TMyClass = class(TObject)
  private
    FField: Integer;
    procedure PrivateMethod;
  protected
    procedure ProtectedMethod;
  public
    constructor Create; overload;
    constructor Create(AValue: Integer); overload;
    destructor Destroy; override;

    procedure PublicMethod;
    function GetValue: Integer;

    property Field: Integer read FField write FField;
  end;

7.2 Constructors and Destructors

constructor TMyClass.Create;
begin
  inherited Create;
  FField := 0;
end;

constructor TMyClass.Create(AValue: Integer);
begin
  inherited Create;
  FField := AValue;
end;

destructor TMyClass.Destroy;
begin
  // Cleanup
  inherited;
end;

7.3 Properties

Read/Write Properties:

type
  TMyClass = class
  private
    FValue: Integer;
  public
    property Value: Integer read FValue write FValue;
  end;

Getter/Setter Methods:

type
  TMyClass = class
  private
    FValue: Integer;
    function GetValue: Integer;
    procedure SetValue(AValue: Integer);
  public
    property Value: Integer read GetValue write SetValue;
  end;

7.4 Inheritance

type
  TBaseClass = class(TObject)
  public
    procedure BaseMethod;
  end;

  TDerivedClass = class(TBaseClass)
  public
    procedure DerivedMethod;
    procedure BaseMethod; override;
  end;

7.5 Interface Implementation

type
  IMyInterface = interface
    ['{GUID-HERE}']
    procedure InterfaceMethod;
  end;

  TMyClass = class(TInterfacedObject, IMyInterface)
  public
    procedure InterfaceMethod;
  end;

implementation

procedure TMyClass.InterfaceMethod;
begin
  // Implementation
end;

7.6 Object Lifetime

var
  MyObject: TMyClass;
begin
  // Create object
  MyObject := TMyClass.Create;
  try
    MyObject.DoWork;
  finally
    // Destroy object
    MyObject.Free;
  end;
end;

8. Native Interoperability

8.1 Overview

GorillaScript provides seamless integration with native Delphi code through the RTTI system. Native classes, interfaces, records, enums, and sets can be registered and used directly in scripts.

8.2 Registering Native Classes

Native classes are registered with the engine and become available in scripts:

// In Delphi host code
Engine.RegisteredClasses.Add(TMyNativeClass);

After registration, the class is available in scripts:

// In script
var
  MyObject: TMyNativeClass;
begin
  MyObject := TMyNativeClass.Create;
  MyObject.NativeMethod;
  MyObject.Free;
end;

8.3 Registering Enumerations

// In Delphi host code
Engine.RegisteredEnums.Add(
  TGorillaScriptRegisteredType.From(
    'MyUnit.TMyEnum',
    TypeInfo(TMyEnum)
  )
);

8.4 Registering Records

// In Delphi host code
Engine.RegisteredStructs.Add(
  TGorillaScriptRegisteredType.From(
    'MyUnit.TMyRecord',
    TypeInfo(TMyRecord)
  )
);

8.5 Registering Interfaces

// In Delphi host code
Engine.RegisteredInterfaces.Add('MyUnit.IMyInterface');

8.6 Native Method Calls

Native methods are called through RTTI with automatic type conversion:

  • Script values are converted to native Delphi types
  • Native return values are converted back to script values
  • Method overloading is resolved at compile time
  • Property access is translated to getter/setter calls

8.7 Event Handling

Native events can be assigned to script methods:

// In script
procedure TMyForm.ButtonClick(Sender: TObject);
begin
  ShowMessage('Button clicked!');
end;

procedure TMyForm.FormCreate(Sender: TObject);
begin
  Button1.OnClick := @Self.ButtonClick;
end;

Event handlers are wrapped by TGorillaScriptObjectEventHandler which dispatches calls from native code to script methods.

8.8 Default Native Types

The following types are automatically available in all scripts:

Primitive Types: String, Int8, ShortInt, UInt8, Byte, Int16, SmallInt, UInt16, Word, Integer, LongInt, Cardinal, LongWord, Int32, UInt32, Int64, UInt64, Single, Double, Boolean, Pointer, TValue, TMethod

Base Classes: TObject, TInterfacedObject, IInterface, TComponentName

Special Types: TShader, TVertexShader, TPixelShader, System, TCustomAttribute, NATIVE, GLSL, UNIFORM, ATTRIBUTE, VARYING

8.9 Default Native Units

Pre-registered units available without explicit "uses" clause:

  • System: Core system functions
  • System.SysUtils: String and utility functions
  • System.Math: Mathematical functions
  • System.Math.Vectors: Vector operations
  • System.Types: Standard types
  • System.Classes: Component streaming
  • System.UITypes: UI-related types

9. Bytecode Execution Model

9.1 Bytecode Structure

File Format:

  • Magic Number: 0xDEADBABE
  • Version: 0x00010001 (Major: 1, Minor: 1)
  • Bytecode stream
  • Symbol tables

Instruction Format:

OPERATION [OPERANDS...] DELIMITER

9.2 Bytecode Operations

The VM supports the following operation categories:

Control Flow:

  • GS_BC_NONE: No operation
  • GS_BC_DELIM: Command delimiter
  • GS_BC_HALT: Stop execution
  • GS_BC_RETURN: Return from function
  • GS_BC_JUMP: Unconditional jump
  • GS_BC_JUMP_ON_ZERO: Jump if top of stack is zero
  • GS_BC_JUMP_ON_NOTZERO: Jump if top of stack is non-zero

Stack Operations:

  • GS_BC_GET_STACKVALUE: Pop value from stack
  • GS_BC_SET_STACKVALUE: Push value to stack
  • GS_BC_COPY: Duplicate top stack value
  • GS_BC_COPYTOP: Copy stack top
  • GS_BC_PUSH: Push value
  • GS_BC_POP: Pop value

Arithmetic Operations:

  • GS_BC_ADD: Addition
  • GS_BC_SUB: Subtraction
  • GS_BC_MUL: Multiplication
  • GS_BC_DIV: Division
  • GS_BC_MOD: Modulo
  • GS_BC_POW: Power
  • GS_BC_INC: Increment
  • GS_BC_DEC: Decrement

Comparison Operations:

  • GS_BC_LT: Less than
  • GS_BC_LEQ: Less than or equal
  • GS_BC_GT: Greater than
  • GS_BC_GEQ: Greater than or equal
  • GS_BC_EQ: Equal
  • GS_BC_NEQ: Not equal

Logical Operations:

  • GS_BC_NOT: Boolean NOT
  • GS_BC_AND: Boolean AND
  • GS_BC_OR: Boolean OR
  • GS_BC_XOR: Boolean XOR

Bitwise Operations:

  • GS_BC_BITAND: Bitwise AND
  • GS_BC_BITOR: Bitwise OR
  • GS_BC_BITXOR: Bitwise XOR
  • GS_BC_SHL: Shift left
  • GS_BC_SHR: Shift right

Object Operations:

  • GS_BC_GET_TYPE: Get type information
  • GS_BC_GET_METHOD: Get method pointer
  • GS_BC_GET_FIELD: Get field value
  • GS_BC_SET_FIELD: Set field value
  • GS_BC_GET_CONST: Get constant value
  • GS_BC_GET_NATIVE_PROPERTY: Get native property
  • GS_BC_SET_NATIVE_PROPERTY: Set native property
  • GS_BC_CALL: Call method
  • GS_BC_READ_ACC_ARR: Array read access
  • GS_BC_WRITE_ACC_ARR: Array write access
  • GS_BC_ISTYPE: Type check
  • GS_BC_AS: Type cast
  • GS_BC_ADDRESSOF: Get address
  • GS_BC_IN: Set membership test
  • GS_BC_NEWSET: Create new set

Control Structures:

  • GS_BC_FOR_LOOP: For loop (has dedicated handler)
  • GS_BC_WHILE_LOOP: While loop marker (implemented via JUMP/JUMP_ON_ZERO)
  • GS_BC_REPEAT_LOOP: Repeat loop marker (implemented via JUMP/JUMP_ON_ZERO)
  • GS_BC_CASE: Case statement
  • GS_BC_TRY: Try block
  • GS_BC_EXCEPT: Except block
  • GS_BC_FINALLY: Finally block
  • GS_BC_RANGECHECK: Range check

9.3 Execution Model

Interpreter Loop:

  1. Read bytecode instruction
  2. Decode operation
  3. Execute operation via lookup table
  4. Update instruction pointer
  5. Repeat until HALT or RETURN

Method Dispatch:

  • Native methods: Direct invocation via RTTI
  • Script methods: Jump to bytecode address
  • Virtual methods: Table lookup then dispatch

Stack Frame: Each function call creates a stack frame containing:

  • Local variables
  • Parameters
  • Return address
  • Stack offset
  • Call stack offset

9.4 Lookup Table Optimization

The executor uses a lookup table (FByteCodes) to map bytecode operations to handler procedures, avoiding case statement overhead:

// Faster than case statement
LProc := FByteCodes[ABC];
LProc(AContext, AByteCode);

10. Performance Characteristics

10.1 Loop Performance

Critical Performance Issue: For Loops

For loops currently exhibit significant performance degradation compared to native Delphi code. This is due to the execution model where each loop iteration interprets bytecode through the __DoExecByteCode() function.

Benchmark Data:

  • 1 million iterations with 2 sub-calls: ~3.5 seconds (on 3.5 GHz CPU)
  • Safe-Mode enabled: +1 second overhead (try-except on each operation)
  • Thread-Safe mode enabled: +600ms overhead (TMonitor locking)

Root Cause Analysis:

From Gorilla.Script.Executor.pas (lines 638-797):

procedure TGorillaScriptExecutor.DoForLoop(...);
begin
  // Comment on line 720-721:
  // "The following code was just an experiment for optimizing loops in
  // scripting, but did not result in the expected performance yet."
  Exit;  // Loop optimization disabled

  // Experimental optimization code follows but is never executed
  ...

  while LLoopRunning do
  begin
    repeat
      AByteCode.Read(LBC, SizeOf(LBC));
      if LBC = GS_BC_JUMP then
        // Handle jump
      else
        __DoExecByteCode(LBC);  // ← Performance bottleneck
    until LLoopBreak;
  end;
end;

Performance Impact: Each loop iteration requires:

  1. Reading bytecode instruction (I/O operation)
  2. Looking up handler in table
  3. Function call overhead
  4. Stack frame creation
  5. Optional locking (thread-safe mode)
  6. Optional try-except (safe mode)

Workarounds:

  1. Minimize loop iterations where possible
  2. Move computation-heavy work to native methods
  3. Consider using native code for performance-critical loops
  4. Disable safe-mode and thread-safe mode if not needed

10.2 General Performance Guidelines

Execution Speed:

  • Native method calls: Fast (direct RTTI invocation)
  • Arithmetic operations: Moderate (bytecode interpretation)
  • Control flow: Moderate to slow (jump operations)
  • For loops: Slow (see section 10.1)
  • While/Repeat loops: Moderate (implemented via jump operations)

Memory Usage:

  • Stack: 512 values max (each ~16-24 bytes)
  • Call Stack: 128 calls max
  • Heap: 32 MB max
  • Bytecode: Proportional to source code size

Optimization Tips:

  1. Use native methods for heavy computation
  2. Minimize loop iterations
  3. Cache method lookups when possible
  4. Use local variables instead of fields when possible
  5. Avoid deep call hierarchies
  6. Consider compilation overhead for short-lived scripts

11. Known Limitations

11.1 Critical Limitations

11.1.1 Self Context Issue

Severity: High Status: Known issue, workaround required

When writing code inside a class method, you must explicitly qualify member access with Self. even when already in the self context:

Incorrect (will not work):

type
  TMyClass = class
  private
    FValue: Integer;
  public
    procedure SetValue(AValue: Integer);
  end;

procedure TMyClass.SetValue(AValue: Integer);
begin
  FValue := AValue;  // ← ERROR: FValue not resolved
end;

Correct (required workaround):

procedure TMyClass.SetValue(AValue: Integer);
begin
  Self.FValue := AValue;  // ← Must use "Self."
end;

Impact: Affects all field, property, and method access within class methods.

Workaround: Always prefix member access with Self. in class methods.

11.1.2 For Loop Performance

Severity: High Status: Known issue, optimization attempt failed

For loops are significantly slower than native Delphi code due to bytecode interpretation overhead. See Section 10.1 for details.

11.2 Language Limitations

11.2.1 Limited Generic Support

Generic types are supported only for pre-defined native types like TArray<T>. User-defined generic types are not supported.

11.2.2 No Inline Assembly

Inline assembly (asm blocks) is not supported and will cause compilation errors.

11.2.3 Limited Preprocessor

Compiler directives support is limited:

  • {$DEFINE}, {$IFDEF}, {$ENDIF} are supported
  • Advanced directives may not work as expected
  • Conditional compilation is basic

11.2.4 No Advanced RTTI Attributes

Custom attributes beyond basic system attributes may not be accessible in scripts.

11.2.5 Limited Variant Support

The Variant type has limited support. Use TValue for dynamic typing instead.

11.3 Implementation Limitations

11.3.1 Thread Safety

Thread-safe mode adds significant performance overhead (~600ms per million iterations). For single-threaded scenarios, disable with:

// In source code, remove {$DEFINE THREADSAFE}

11.3.2 Memory Limits

Hard-coded memory limits:

  • Stack: 512 values
  • Call Stack: 128 calls
  • Heap: 32 MB

These limits require recompilation to change.

11.3.3 Error Reporting

Error messages may not always provide accurate line numbers or context, especially for complex expressions.

11.3.4 Debugging Support

Limited debugging capabilities:

  • No breakpoints in script code
  • No step debugging
  • Debug output available only in DEBUG_VERBOSE mode

11.4 Interoperability Limitations

11.4.1 Pointer Arithmetic

Pointer arithmetic is not supported. Pointers can be stored and passed but not manipulated.

11.4.2 Raw Memory Access

Direct memory access functions (like Move, FillChar) may have limited or no support.

11.4.3 External Library Calls

No support for calling external DLLs directly. Must be wrapped in native Delphi code first.


Appendix A: Bytecode Reference

Complete Bytecode Operation List

Opcode Name Description
0 GS_BC_NONE No operation
1 GS_BC_DELIM Statement delimiter
2 GS_BC_HALT Stop execution
3 GS_BC_RETURN Return from function
5 GS_BC_JUMP Unconditional jump
6 GS_BC_JUMP_ON_ZERO Conditional jump (zero)
7 GS_BC_JUMP_ON_NOTZERO Conditional jump (non-zero)
8 GS_BC_GET_STACKVALUE Pop stack value
9 GS_BC_SET_STACKVALUE Push stack value
10 GS_BC_ADD Addition
11 GS_BC_SUB Subtraction
12 GS_BC_MUL Multiplication
13 GS_BC_DIV Division
14 GS_BC_MOD Modulo
15 GS_BC_POW Power
16 GS_BC_LT Less than
17 GS_BC_LEQ Less than or equal
18 GS_BC_GT Greater than
19 GS_BC_GEQ Greater than or equal
20 GS_BC_EQ Equal
21 GS_BC_NEQ Not equal
22 GS_BC_NOT Boolean NOT
23 GS_BC_AND Boolean AND
24 GS_BC_OR Boolean OR
25 GS_BC_XOR Boolean XOR
26 GS_BC_BITAND Bitwise AND
27 GS_BC_BITOR Bitwise OR
28 GS_BC_BITXOR Bitwise XOR
29 GS_BC_SHL Shift left
30 GS_BC_SHR Shift right
31 GS_BC_INC Increment
32 GS_BC_DEC Decrement
33 GS_BC_ADDRESSOF Get address
34 GS_BC_IN Set membership
35 GS_BC_AS Type cast
40 GS_BC_COPY Copy stack value
41 GS_BC_COPYTOP Copy top of stack
42 GS_BC_RANGECHECK Range check
43 GS_BC_TRY Try block
44 GS_BC_EXCEPT Except block
45 GS_BC_FINALLY Finally block
46 GS_BC_FOR_LOOP For loop (dedicated handler)
47 GS_BC_WHILE_LOOP While loop marker (uses JUMP ops)
48 GS_BC_REPEAT_LOOP Repeat loop marker (uses JUMP ops)
49 GS_BC_CASE Case statement
50 GS_BC_GET_TYPE Get type information
51 GS_BC_GET_METHOD Get method pointer
52 GS_BC_GET_FIELD Get field value
53 GS_BC_SET_FIELD Set field value
54 GS_BC_GET_CONST Get constant value
55 GS_BC_GET_NATIVE_PROPERTY Get native property
56 GS_BC_SET_NATIVE_PROPERTY Set native property
64 GS_BC_CALL Call method
65 GS_BC_READ_ACC_ARR Array read
66 GS_BC_WRITE_ACC_ARR Array write
67 GS_BC_ISTYPE Type check
68 GS_BC_NEWSET Create set

Appendix B: Troubleshooting

Common Issues and Solutions

Issue: "Field not found in class method"

  • Cause: Self context issue
  • Solution: Always prefix member access with Self.

Issue: "Script runs slowly with loops"

  • Cause: Bytecode interpretation overhead
  • Solution: Move computation to native methods or reduce iterations

Issue: "Stack overflow error"

  • Cause: Call stack depth exceeded (max 128)
  • Solution: Reduce recursion depth or refactor algorithm

Issue: "Out of stack space"

  • Cause: Stack size exceeded (max 512 values)
  • Solution: Reduce local variable count or refactor

Issue: "Cannot access native class member"

  • Cause: Class not registered with engine
  • Solution: Register class using Engine.RegisteredClasses.Add(TMyClass)

Appendix C: Version History

Version 1.1 (Current)

  • Bytecode version: 0x00010001
  • Native interop support
  • RTTI integration
  • Event handling support

Known Issues in Current Version

  • For loop performance issues (bytecode interpretation overhead)
  • Self context issue in class methods (must use Self. prefix)
  • For loop optimization disabled (experimental code not working)

Appendix D: References

Source Files

Core Files:

  • Gorilla.Script.pas: Main engine component
  • Gorilla.Script.Parser.Delphi.pas: Delphi syntax parser
  • Gorilla.Script.Compiler.pas: Bytecode compiler
  • Gorilla.Script.Executor.pas: Bytecode interpreter
  • Gorilla.Script.ByteCode.pas: Bytecode definitions
  • Gorilla.Script.Types.pas: Type system
  • Gorilla.Script.Entities.pas: AST entities

Library Files:

  • Gorilla.Script.Libraries.pas: Library system
  • Gorilla.Script.Lib.*.pas: Standard library modules

External Dependencies

  • SimpleParser or Castalia (lexer backend)
  • Delphi RTL (System, System.SysUtils, System.Classes, System.Rtti)

End of Specification