Neutron Language Reference

This document provides a comprehensive reference for the Neutron programming language. It covers syntax, data types, operators, control flow, functions, built-in functions, modules, classes, and all other features of the language.

Comments

Comments in Neutron start with //. Everything from // to the end of the line is ignored by the interpreter.

// This is a comment
var x = 10; // This is also a comment

Data Types

Neutron is a dynamically typed language. It has the following built-in data types:

Number

Represents floating-point numbers (doubles).

var x = 10;      // An integer
var y = 3.14;    // A floating-point number
var z = -42;     // A negative number

Boolean

Represents true or false.

var is_active = true;
var is_admin = false;

String

Represents a sequence of characters.

var name = "Neutron";
var message = "Hello, world!";
var multiline = "Line 1\nLine 2\tTabbed";

Nil

Represents the absence of a value.

var x = nil;

Object

Represents collections of key-value pairs.

Array

Represents collections of values (via JSON arrays).

Function

Represents callable functions.

Module

Represents imported modules.

Object Literals

Object literals are collections of key-value pairs enclosed in curly braces ({}). Keys must be string literals, and values can be any valid expression.

var person = {
  "name": "John Doe",
  "age": 30,
  "city": "New York"
};

// Access object properties
say(person["name"]); // John Doe

// Objects can be nested
var config = {
  "database": {
    "host": "localhost",
    "port": 5432
  },
  "api": {
    "version": "v1",
    "timeout": 30
  }
};

Object literals work seamlessly with the JSON module:

use json;

var data = {
  "name": "John Doe",
  "age": 30,
  "city": "New York"
};

// Convert object to JSON string
var jsonString = json.stringify(data);
say(jsonString); // {"name":"John Doe","age":30,"city":"New York"}

// Parse JSON string back to object
var parsed = json.parse(jsonString);
say(parsed["name"]); // John Doe

Variables

Variables are declared using the var keyword. They can be assigned a value when they are declared, or they can be assigned a value later.

var x;          // Declare a variable without a value (it will be nil)
var y = 10;     // Declare a variable with a value
x = 20;         // Assign a new value to x

// Variables are dynamically typed
var value = 42;    // Number
value = "hello";   // Now a string
value = true;      // Now a boolean

Operators

Neutron supports a variety of operators for arithmetic, comparison, logical operations, and string manipulation.

Arithmetic Operators

  • + Addition (also string concatenation)
  • - Subtraction
  • * Multiplication
  • / Division

Comparison Operators

  • == Equal
  • != Not equal
  • < Less than
  • <= Less than or equal to
  • > Greater than
  • >= Greater than or equal to

Logical Operators

  • and Logical AND
  • or Logical OR
  • ! Logical NOT
var x = 10 + 5;  // 15
var y = 20 - 10; // 10
var z = 5 * 2;   // 10
var w = 10 / 2;  // 5

// String concatenation
var greeting = "Hello, " + "world!"; // "Hello, world!"
var message = "Value: " + 42;        // "Value: 42"

// Comparison
say(10 == 10); // true
say(10 != 5);  // true
say(5 < 10);   // true

// Logical operations
say(true and false); // false
say(true or false);  // true
say(!true);          // false

Control Flow

Neutron provides several control flow statements.

If-Else Statements

The if statement executes a block of code if a condition is true. The else statement can be used to execute a block of code if the condition is false.

if (x > 10) {
    say("x is greater than 10");
} else {
    say("x is not greater than 10");
}

While Loops

The while loop executes a block of code as long as a condition is true.

var i = 0;
while (i < 5) {
    say(i);
    i = i + 1;
}

For Loops

The for loop is a more convenient way to write loops with a clear initializer, condition, and increment.

for (var i = 0; i < 5; i = i + 1) {
    say(i);
}

Functions

Functions are defined using the fun keyword.

Defining Functions

fun greet(name) {
    say("Hello, " + name + "!");
}

Calling Functions

greet("Neutron"); // Prints "Hello, Neutron!"

Return Statement

The return statement is used to return a value from a function. If no value is specified, the function returns nil.

fun add(a, b) {
    return a + b;
}

var result = add(5, 10);
say(result); // 15

Built-in Functions

Neutron provides several built-in functions that are available in the global scope without needing to import any modules.

Output Functions

say(value)

Prints a value to the console followed by a newline.

Type Conversion

str(number)

Converts a number to a string.

int(string)

Converts a string to an integer.

Binary Conversion

int_to_bin(number)

Converts an integer to a binary string.

bin_to_int(string)

Converts a binary string to an integer.

Character/ASCII

char_to_int(string)

Converts a single-character string to its ASCII value.

int_to_char(number)

Converts a number (ASCII value) to a single-character string.

say("Hello, world!");           // Output: Hello, world!
say(42);                       // Output: 42
say(true);                     // Output: true
say(nil);                      // Output: 

var num = 42;
var text = str(num);           // "42"
say("Number as string: " + text);

var numberText = "123";
var number = int(numberText);  // 123
say("String as number: " + number);

var decimal = 10;
var binary = int_to_bin(decimal);    // "1010"
say("10 in binary: " + binary);

var character = "A";
var ascii = char_to_int(character);   // 65
say("ASCII value of A: " + ascii);

Modules

Neutron supports modules, which allow you to organize your code into separate files and provide additional functionality. Modules can be written in Neutron (.nt files) or as native C++ extensions (.so files).

Using Modules

The use statement is used to import a module.

use math;
use sys;
use json;

Core Modules

Neutron provides several built-in modules that extend the language's capabilities:

math Module

Provides basic mathematical functions.

  • add(a, b) - Addition
  • subtract(a, b) - Subtraction
  • multiply(a, b) - Multiplication
  • divide(a, b) - Division
  • pow(base, exp) - Power
  • sqrt(n) - Square root
  • abs(n) - Absolute value

sys Module

Provides system-level operations including file I/O, directory operations, environment access, and process control.

  • read(path) - Read file contents
  • write(path, content) - Write to file
  • exists(path) - Check if file exists
  • mkdir(path) - Create directory
  • cwd() - Get current directory
  • env(name) - Get environment variable

json Module

Provides JSON parsing and serialization capabilities.

  • stringify(value, pretty?) - Convert to JSON
  • parse(jsonString) - Parse JSON string
  • get(object, key) - Get property value

http Module

Provides HTTP client functionality for making web requests.

  • get(url, headers?) - HTTP GET
  • post(url, data?, headers?) - HTTP POST
  • put(url, data?, headers?) - HTTP PUT
  • delete(url, headers?) - HTTP DELETE

time Module

Provides time-related functions for timestamps, formatting, and delays.

  • now() - Get current timestamp
  • format(timestamp, format?) - Format time
  • sleep(milliseconds) - Sleep/pause

convert Module

Provides advanced string and binary conversion utilities.

  • char_to_int(string) - Char to ASCII
  • int_to_char(number) - ASCII to char
  • string_length(string) - String length
  • int_to_bin(number) - Integer to binary
use sys;
use json;
use math;

// File operations
sys.write("hello.txt", "Hello, world!");
var content = sys.read("hello.txt");
say(content); // "Hello, world!"

// JSON operations
var data = {
  "name": "Alice",
  "age": 30,
  "active": true
};
var jsonStr = json.stringify(data);
say(jsonStr); // {"name":"Alice","age":30,"active":true}

// Math operations
var sum = math.add(5, 3);           // 8
var power = math.pow(2, 3);         // 8
var root = math.sqrt(16);           // 4

Classes

Neutron supports object-oriented programming with classes, methods, and the this keyword.

Defining Classes

Classes are defined using the class keyword. Classes can contain methods and properties.

class Person {
    var name;
    var age;
    
    fun initialize(name, age) {
        this.name = name;
        this.age = age;
    }
    
    fun greet() {
        say("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
    }
    
    fun setAge(newAge) {
        this.age = newAge;
    }
    
    fun getAge() {
        return this.age;
    }
}

Creating Instances

To create an instance of a class, you call the class like a function.

var person = Person();
person.initialize("Alice", 30);
person.greet(); // "Hello, my name is Alice and I am 30 years old."

// Update properties
person.setAge(31);
say("Age: " + person.getAge()); // "Age: 31"

The 'this' Keyword

The this keyword refers to the current instance of the class and is used to access instance properties and methods.

class Counter {
    var count;
    
    fun initialize() {
        this.count = 0;
    }
    
    fun increment() {
        this.count = this.count + 1;
        return this.count;
    }
    
    fun decrement() {
        this.count = this.count - 1;
        return this.count;
    }
    
    fun getValue() {
        return this.count;
    }
}

var counter = Counter();
counter.initialize();
say(counter.increment()); // 1
say(counter.increment()); // 2
say(counter.getValue());  // 2

Binary Compilation

Neutron scripts can be compiled to standalone executables using the -b flag. This provides several advantages:

  • Standalone Distribution: No need for users to install the Neutron interpreter
  • Performance: Compiled binaries may offer improved performance
  • Code Protection: Source code is embedded and not easily readable
  • Simplified Deployment: Single executable file for easy distribution

Basic Compilation

# Compile with default output name
./neutron -b hello.nt
# Creates: hello.nt.out

# Compile with custom output name  
./neutron -b hello.nt hello_app
# Creates: hello_app

# Run the compiled binary
./hello.nt.out

Supported Features

Binary compilation supports all core Neutron language features:

Core Language

  • ✓ Variables and Data Types
  • ✓ Operators (arithmetic, comparison, logical)
  • ✓ Control Flow (if/else, while, for)
  • ✓ Functions and Classes

Built-in Features

  • ✓ Built-in Functions
  • ✓ All Core Modules (sys, json, math, http, time, convert)
  • ✓ Neutron Modules (.nt files)
  • ⚠ Native Box Modules (requires .so files)

Module Creation

Neutron supports two types of modules that you can create:

Neutron Modules (.nt files)

Written in Neutron language itself and stored as .nt files.

// utils.nt - A utility module
fun double_value(x) {
    return x * 2;
}

fun greet_user(name) {
    return "Welcome, " + name + "!";
}

// Module can have initialization code
say("Utils module loaded");

Native Box Modules (C++)

High-performance modules written in C++ and compiled to shared libraries.

box/
└── my_module/
    └── native.cpp
# Build the module
./neutron --build-box my_module

Using Custom Modules

use utils;
use my_module;

var doubled = utils.double_value(21);    // 42
var greeting = utils.greet_user("Alice"); // "Welcome, Alice!"

// Use native module functions
var result = my_module.fast_calculation(1000);

Known Issues

This section lists known issues and limitations in the Neutron interpreter and language.

Recently Fixed Issues ✅

✅ Logical OR and AND Operators

Status: FIXED

The or and and operators (lowercase keywords) work correctly in all contexts.

Note: Use and and or (lowercase), not && or || which are not implemented.

// This works:
if (x < 1 or x > 10) {
    x = 1;
}

// This also works:
if (x > 0 and x < 100) {
    say("Valid range");
}

✅ Empty String to Integer Conversion

Status: FIXED

Converting an empty string to an integer with convert.int() now returns 0 instead of throwing an error.

use convert;

var empty = "";
var num = convert.int(empty);  // Returns 0
say(num);  // Output: 0

✅ While Loop Stack Overflow

Status: FIXED

While loops with many iterations previously caused stack overflow errors. This has been fixed in the latest version.

// This now works with any number of iterations:
var i = 0;
while (i < 1000000) {
    i = i + 1;
}
say("Success!");

✅ Break and Continue Statements

Status: FIXED (October 4, 2025)

break and continue statements are now fully implemented.

for (var i = 0; i < 10; i = i + 1) {
    if (i == 5) {
        break;  // Exit loop
    }
    say(i);
}

✅ String Interpolation

Status: IMPLEMENTED (October 4, 2025)

String interpolation with ${...} syntax is now fully implemented.

var name = "World";
var count = 42;
say("Hello, ${name}! Count: ${count}");

✅ Enhanced Array Operations

Status: IMPLEMENTED (October 4, 2025)

Comprehensive array methods including map, filter, and find are now available.

var arr = [1, 2, 3, 4, 5];
fun double(x) { return x * 2; }
var doubled = arr.map(double);

Current Known Issues

ℹ️ Symbol Operators Not Implemented

Status: By Design

C-style operators &&, ||, ++, -- are not implemented.

Workaround: Use keyword equivalents:

  • Use and instead of &&
  • Use or instead of ||
  • Use x = x + 1 instead of x++

⚠️ Else-If Chain Complexity

Status: Under Investigation

Extremely complex else-if chains (10+ levels) may cause performance issues.

Workaround: Keep else-if chains reasonable or use nested if-else.

⚠️ Array Indexing with Variables

Status: Limited Support

Complex expressions as array indices may not work in all contexts.

Workaround: Use simple variables or pre-calculated indices.

ℹ️ Square Bracket Property Access

Status: By Design

JsonObject properties must be accessed using dot notation, not square brackets.

Example:

use sys;
var info = sys.info();
say(info.platform);  // Works
// say(info["platform"]); // Error

Best Practices

  • Always import required modules at the top of your file
  • Use and and or keywords for logical operations
  • Use dot notation for object property access
  • Keep else-if chains reasonable (<10 levels)
  • Test complex array indexing thoroughly

Exception Handling

Neutron supports exception handling with try-catch-finally blocks for robust error handling.

Try-Catch Statement

try {
    // code that might throw an exception
    riskyOperation();
} catch (error) {
    // code to handle the exception
    say("Exception caught: " + error);
}

Try-Finally Statement

try {
    // code that might throw an exception
    doSomething();
} finally {
    // code that always executes (cleanup, etc.)
    cleanup();
}

Try-Catch-Finally Statement

try {
    // code that might throw an exception
    riskyOperation();
} catch (error) {
    // code to handle the exception
    say("Exception caught: " + error);
} finally {
    // code that always executes
    cleanup();
}

Throw Statement

You can throw any value as an exception.

throw "An error occurred";
throw someValue;  // Can throw any value

try {
    if (x < 0) {
        throw "Negative value not allowed";
    }
} catch (error) {
    say("Error: " + error);
}

Type System

Neutron uses a dynamically typed system with runtime type checking. Variables can hold values of any type and can be reassigned to different types.

All Value Types

Primitive Types

  • NIL: Absence of value (nil)
  • BOOLEAN: True or false
  • NUMBER: 64-bit floating point
  • STRING: UTF-8 text

Complex Types

  • ARRAY: Dynamic ordered collection
  • OBJECT: Key-value pairs
  • FUNCTION: Callable functions
  • CLASS: Class definitions
  • INSTANCE: Class instances
  • MODULE: Imported modules

Type Conversions

Use the fmt module for explicit type conversions.

use fmt;

var str = fmt.to_str(42);         // "42"
var num = fmt.to_float("3.14");   // 3.14
var int_val = fmt.to_int("123");  // 123

// Type checking
var type = fmt.type(value);       // Returns type as string

Truthiness Rules

Type Truthy Falsy
NIL-nil
BOOLEANtruefalse
NUMBERAll except 00, 0.0
STRINGNon-empty""
ARRAY/OBJECT/etcAll (even empty)-

Memory Management

Neutron uses automatic garbage collection for memory management. Objects are collected when no longer reachable.

  • Stack-allocated: NIL, BOOLEAN, NUMBER (no heap overhead)
  • Heap-allocated: STRING, ARRAY, OBJECT, FUNCTION, CLASS, INSTANCE, MODULE
  • GC Algorithm: Mark-and-sweep garbage collection
  • Trigger: Automatic when heap exceeds threshold

Advanced Modules

Arrays Module

The arrays module provides comprehensive array manipulation functions.

use arrays;

var arr = arrays.new();           // Create new array
arrays.push(arr, 1);               // Add element
arrays.push(arr, 2);
arrays.push(arr, 3);

var len = arrays.length(arr);      // Get length
var item = arrays.at(arr, 0);      // Get element at index
arrays.set(arr, 0, 10);            // Set element at index

var slice = arrays.slice(arr, 0, 2);  // Create subarray
var str = arrays.join(arr, ", ");     // Join to string
arrays.reverse(arr);                  // Reverse in place
var idx = arrays.index_of(arr, 2);    // Find index

// Advanced operations
var clone = arrays.clone(arr);        // Shallow copy
var flat = arrays.flat(nested);       // Flatten nested arrays
arrays.shuffle(arr);                  // Randomly shuffle

Async Module

The async module provides basic asynchronous operations.

use async;
use time;

// Simulate async operation
fun fetchData() {
    time.sleep(1000);  // Simulate delay
    return "Data fetched!";
}

var result = fetchData();
say(result);

Build & Deployment

Quick Start

# Clone the repository
git clone https://github.com/yasakei/neutron.git
cd neutron

# Build the interpreter
make

# Run a Neutron program
./neutron examples/hello.nt

# Run the REPL
./neutron

Cross-Platform Support

Neutron supports multiple platforms with consistent behavior.

Linux

  • ✓ GCC 7+ or Clang 6+
  • ✓ CMake 3.15+
  • ✓ Full support

macOS

  • ✓ Apple Clang 11+
  • ✓ CMake 3.15+
  • ✓ Full support

Windows

  • ✓ MSVC 2019+
  • ✓ MINGW64
  • ✓ Full support

Testing

Neutron includes a comprehensive test suite to verify functionality.

# Run all tests
make test

# Run specific test file
./neutron tests/test_arrays.nt

# Run test suite script
./run_tests.sh    # Linux/macOS
./run_tests.ps1   # Windows

Learning Resources