Pre-AlphaMetaScript is in early design phase. The compiler is not yet available.Join Discord for updates
MetaScript

Language Reference

Complete reference for MetaScript syntax and semantics.

Lexical Structure

Comments

// Single line comment

/*
  Multi-line
  comment
*/

/// Documentation comment (generates docs)
/// @param name - The user's name
function greet(name: string): void {}

Identifiers

// Valid identifiers
myVariable
_private
$special
camelCase
PascalCase
SCREAMING_CASE

// Unicode allowed
π = 3.14159
こんにちは = "hello"

Keywords

Reserved words that cannot be used as identifiers:

abstract  as        async     await     break
case      catch     class     const     continue
debugger  default   delete    do        else
enum      export    extends   false     finally
for       from      function  if        implements
import    in        instanceof interface let
new       null      of        package   private
protected public    return    static    super
switch    this      throw     true      try
type      typeof    undefined var       void
while     with      yield

MetaScript-specific keywords:

comptime  derive    macro     trait     where

Types

Primitive Types

// Numbers
const int: number = 42
const float: number = 3.14
const hex: number = 0xFF
const binary: number = 0b1010
const scientific: number = 1e10

// Sized integers
const i: i32 = 42
const u: u64 = 100
const byte: u8 = 255

// Strings
const str: string = "hello"
const template: string = `Hello, ${name}!`
const multiline: string = `
  Multiple
  lines
`

// Booleans
const yes: boolean = true
const no: boolean = false

// Null and undefined
const nothing: null = null
const notDefined: undefined = undefined

// Void (no return value)
function log(msg: string): void {
  console.log(msg)
}

// Never (never returns)
function fail(msg: string): never {
  throw new Error(msg)
}

Composite Types

// Arrays
const numbers: number[] = [1, 2, 3]
const matrix: number[][] = [[1, 2], [3, 4]]

// Tuples
const pair: [string, number] = ["age", 42]
const triple: [string, number, boolean] = ["x", 1, true]

// Objects
const point: { x: number, y: number } = { x: 1, y: 2 }

// Maps
const map: Map<string, number> = new Map()
map.set("one", 1)

// Sets
const set: Set<number> = new Set([1, 2, 3])

Union Types

type StringOrNumber = string | number

function process(value: StringOrNumber): void {
  if (typeof value === "string") {
    console.log(value.toUpperCase())
  } else {
    console.log(value.toFixed(2))
  }
}

Intersection Types

type Named = { name: string }
type Aged = { age: number }
type Person = Named & Aged

const person: Person = { name: "Alice", age: 30 }

Type Aliases

type UserId = string
type Point = { x: number, y: number }
type Handler<T> = (value: T) => void

Generics

// Generic function
function identity<T>(value: T): T {
  return value
}

// Generic class
class Box<T> {
  constructor(public value: T) {}

  map<U>(fn: (value: T) => U): Box<U> {
    return new Box(fn(this.value))
  }
}

// Constrained generics
function getLength<T: { length: number }>(item: T): number {
  return item.length
}

Declarations

Variables

// Immutable (preferred)
const name = "Alice"

// Mutable
let count = 0
count += 1

// Destructuring
const { x, y } = point
const [first, ...rest] = array

Functions

// Named function
function add(a: number, b: number): number {
  return a + b
}

// Arrow function
const multiply = (a: number, b: number): number => a * b

// Async function
async function fetch(url: string): Promise<Response> {
  return await http.get(url)
}

// Generator
function* range(start: number, end: number): Generator<number> {
  for (let i = start; i < end; i++) {
    yield i
  }
}

// Default parameters
function greet(name: string, greeting: string = "Hello"): string {
  return `${greeting}, ${name}!`
}

// Rest parameters
function sum(...numbers: number[]): number {
  return numbers.reduce((a, b) => a + b, 0)
}

Classes

class Animal {
  // Properties
  name: string
  private age: number
  protected species: string

  // Constructor
  constructor(name: string, age: number) {
    this.name = name
    this.age = age
  }

  // Methods
  speak(): void {
    console.log(`${this.name} makes a sound`)
  }

  // Static members
  static kingdom: string = "Animalia"

  static create(name: string): Animal {
    return new Animal(name, 0)
  }

  // Getters/Setters
  get displayName(): string {
    return this.name.toUpperCase()
  }

  set displayName(value: string) {
    this.name = value.toLowerCase()
  }
}

// Inheritance
class Dog extends Animal {
  breed: string

  constructor(name: string, age: number, breed: string) {
    super(name, age)
    this.breed = breed
  }

  override speak(): void {
    console.log(`${this.name} barks`)
  }
}

Traits (Interfaces)

trait Printable {
  print(): void
}

trait Serializable {
  toJSON(): string
  static fromJSON(json: string): Self
}

// Implementing traits
class Document implements Printable, Serializable {
  content: string

  print(): void {
    console.log(this.content)
  }

  toJSON(): string {
    return JSON.stringify({ content: this.content })
  }

  static fromJSON(json: string): Document {
    const data = JSON.parse(json)
    return new Document(data.content)
  }
}

Enums

// Union type (preferred)
type Color = "red" | "green" | "blue"

// Const enum for numeric values
const enum Status {
  Pending = 0,
  Active = 1,
  Completed = 2,
}

Expressions

Operators

// Arithmetic
+ - * / % **

// Comparison
== != < > <= >=
=== !== // Strict equality

// Logical
&& || !

// Bitwise
& | ^ ~ << >> >>>

// Assignment
= += -= *= /= %= **=
&= |= ^= <<= >>= >>>=

// Nullish
?? // Nullish coalescing
?. // Optional chaining

Control Flow

// If/else
if (condition) {
  // ...
} else if (other) {
  // ...
} else {
  // ...
}

// Ternary
const result = condition ? "yes" : "no"

// Switch
switch (value) {
  case 1:
    // ...
    break
  case 2:
  case 3:
    // ...
    break
  default:
    // ...
}

// Pattern matching (MetaScript extension)
match (result) {
  { ok: true, value } => console.log(value),
  { ok: false, error } => console.error(error),
}

Loops

// For
for (let i = 0; i < 10; i++) {
  // ...
}

// For...of
for (const item of items) {
  // ...
}

// For...in
for (const key in object) {
  // ...
}

// While
while (condition) {
  // ...
}

// Do...while
do {
  // ...
} while (condition)

Error Handling

try {
  riskyOperation()
} catch (error) {
  console.error(error)
} finally {
  cleanup()
}

// Throw
throw new Error("Something went wrong")

Modules

Exports

// Named exports
export const PI = 3.14159
export function add(a: number, b: number): number {
  return a + b
}
export class Calculator {}

// Default export
export default class App {}

// Re-exports
export { foo, bar } from "./other"
export * from "./utils"
export * as utils from "./utils"

Imports

// Named imports
import { foo, bar } from "./module"

// Default import
import App from "./app"

// Namespace import
import * as utils from "./utils"

// Combined
import App, { helper } from "./app"

// Type-only import
import type { User } from "./types"

// Dynamic import
const module = await import("./dynamic")

Macros

Built-in Macros

// @derive - Generate trait implementations
@derive(Eq, Clone, Debug, Serialize)
class User {
  name: string
  email: string
}

// @comptime - Compile-time execution
@comptime {
  const config = JSON.parse(fs.readFileSync("config.json"))
}

// @test - Mark test function
@test
function additionWorks(): void {
  assert(add(1, 2) === 3)
}

// @macro - Define custom macro
@macro
function logged(fn: FunctionDecl): FunctionDecl {
  // Transform AST
  return fn
}

Next Steps