Skip to content

Language Guide

Buntos edited this page Dec 5, 2026 · 1 revision

Language Guide

H combines Ruby-style block syntax (def ... end, do |x| ... end) and dot-chaining with static typing, compile-time nil safety, range/collection for .. in loops, operator overloading, default parameter values, and AOT compilation to native code via LLVM.


1. Lexical Structure & Casing Rules

Mandatory Identifier Casing

H enforces a strict lexical distinction between types and values:

  • Types (struct, class, enum, interface, built-ins, and generic type parameters) must begin with an ASCII uppercase letter ([A-Z][A-Za-z0-9_]*): I64, String, Vec2, Result, T.
  • Functions, methods, variables, constants, parameters, enum variants, and fields must begin with an ASCII lowercase letter or underscore ([a-z_][A-Za-z0-9_]*): main, max_items, dot, @x, _unused.

Because no value or constant ever starts with an uppercase letter, [...] is unambiguous with single-token lookahead:

Context Example Meaning
Type position (after :, ->, or TypeIdent) Array[I64], StaticArray[U8, 32], Ptr[Void] Generic type-argument list
Postfix expression followed by [TypeIdent...] arena.alloc[Packet](), identity[I64](42) Generic call type arguments (must be followed by (...))
Postfix expression followed by lowercase/literal arr[0], arr[i], tbl["key"] Element or overloaded index expression
Primary expression [1, 2, 3] Array literal (Array[T], or StaticArray[T, N] when typed)

Attributes vs. Instance Fields

  • Attributes use @[...]: @[nogc], @[repr(C)].
  • Instance fields inside struct or class methods use @ followed immediately by a lowercase identifier: @x, @score.

Comments, Blocks & Line Continuation

  • # starts a single-line comment.
  • Compound blocks terminate with end: def ... end, mut def ... end, struct ... end, class ... end, enum ... end, interface ... end, if ... elsif ... else ... end, unless ... end, while ... end, for ... in ... end, match ... when ... else ... end, do |...| ... end.
  • Implicit return: The final expression in a non-Void function, method, or match arm is returned automatically. Explicit early exit uses return (or return expr).
  • Multi-line chaining: If the next non-blank, non-comment line begins with . (not ..) or &.: the lexer elides the newline so method/UFCS chains span multiple lines cleanly.
  • Explicit line continuation: A trailing \ joins non-dot lines:
is_valid = score > high_score \
  and lives_left > 0

Literals

  • Integers: Decimal (42, 1_000_000) and hexadecimal (0xFF, 0x10_20). Unannotated integer literals default to I64, and adapt automatically to the expected integer type in typed bindings, parameters, returns, ranges, and comparisons.
  • Floats: Decimal with fractional part (3.14, 1_000.5). Default to F64 and adapt to F32 when expected.
  • Characters: Single-quoted ASCII byte literals ('a', '\n', '\0', '\\', '\'') producing U8.
  • Strings:
    • Plain literals ("hello\n") contain no #{...} interpolation, live in .rodata, are valid inside @[nogc], and coerce implicitly to Ptr[U8] for C APIs.
    • Interpolated strings ("x=#{x}, ok=#{flag}") evaluate embedded expressions and allocate a GC-managed String. Supported escape sequences: \n, \t, \r, \\, \", \', \0, \#.

2. Built-in Types & Numeric Conversions

Category Types Notes
Signed integers I8, I16, I32, I64 Two's complement
Unsigned integers U8, U16, U32, U64, Usize Usize is pointer-width (64-bit on x86-64 / AArch64)
Floating point F32, F64 IEEE-754 single and double precision
Boolean & Void Bool, Void true, false
Text String Immutable 16-byte { ptr, len } NUL-terminated view
Collections Array[T], Slice[T], StaticArray[T, N] Array[T] is GC-backed; Slice[T] is { ptr, len }; StaticArray[T, N] is inline unboxed
Pointers & Allocators Ptr[T], Arena Non-nullable by default (Ptr[T]? for nullable pointers)
Function types Fn(A, B) -> R, @[nogc] Fn(A, B) -> R Fat closure { fn_ptr, env_ptr } vs raw C function pointer
Nullable T? Wraps any type T; only T? accepts nil

H does not perform silent lossy numeric conversions. Use explicit cast methods on any numeric value:

  • Signed: .to_i8, .to_i16, .to_i32, .to_i64
  • Unsigned: .to_u8, .to_u16, .to_u32, .to_u64, .to_usize
  • Floating-point: .to_f32, .to_f64

3. Bindings, Globals & Operators

Local Variables & Constants

Local variables are mutable by default; const creates an immutable binding that rejects reassignment and mut def method calls:

count = 0          # inferred I64, mutable
count += 1

limit: Usize = 64  # explicit type annotation
const max_retries = 3

Assigning to _ explicitly discards an expression result (_ = fs.remove(path)).

Module-Level Globals

Top-level globals require an explicit type annotation and initializer:

g_counter: I64 = 0

Operators

Group Operators
Arithmetic +, -, *, /, %, unary -
Compound assignment +=, -=, *=, /=
Bitwise &, `
Comparison ==, !=, <, <=, >, >=
Logical (short-circuiting, strict Bool) and / &&, or / `
Ranges (in for ... in) .. (exclusive upper bound), ..= (inclusive upper bound)
Nil handling & propagation ?? (nil-coalescing), &. (safe navigation), ? (postfix try/unwrap)
Pointer dereference & function ref .* (explicit deref), &fn_name (function value)

4. Control Flow, for ... in Loops & Ranges

Conditionals & while

if score >= 90
  puts("A")
elsif score >= 80
  puts("B")
else
  puts("C")
end

unless ready
  return 1
end

i = 0
while i < 10
  i += 1
  if i == 3
    next
  elsif i == 7
    break
  end
end

if, elsif, unless, and while conditions must have non-nullable type Bool.

for ... in Ranges & Collections

for ... in lowers directly to an indexed loop with zero heap allocation (@[nogc]-safe) and supports break, next, defer, and _ when the loop variable is unused:

# Exclusive range: 0, 1, 2, 3, 4
for i in 0..5
  puts("#{i}")
end

# Inclusive range: 1, 2, 4, 5 (plain literal 0/1 adapts to the opposite bound's integer type)
for i in 1..=5
  if i == 3
    next
  end
  total += i
end

# Discard loop counter
for _ in 0..steps
  step()
end

# Iterate collections directly (Array[T], Slice[T], StaticArray[T, N] -> T; String -> U8)
for item in [2, 4, 6, 8]
  sum += item
end

for ch in "hello"
  if ch == 'l'
    count += 1
  end
end

When one bound of a range is a plain integer literal (e.g., for i in 0..arr.len), it adapts automatically to the other bound's integer type (Usize in this example).


5. Nil Safety, Bool? Rule & Flow Narrowing

Non-Nullable by Default

A plain type T can never hold nil. To permit absence, write T?:

def find_even_above(limit: I64) -> I64?
  for i in 1..=limit
    if i % 2 == 0 and i > 6
      return i
    end
  end
  nil
end

Comparing a non-nullable value to nil is a compile-time error, as is accessing .field or .method directly on T? without unwrapping or using &..

Nil-Coalescing (??) & the Bool? Rule

expr ?? fallback unwraps expr: T? to T strictly when expr != nil. Only nil evaluates fallback (short-circuiting):

flag: Bool? = false
resolved = flag ?? true        # evaluates to false (flag is not nil)
missing: Bool? = nil
defaulted = missing ?? true    # evaluates to true

Boolean operators (and, &&, or, ||, !, not) and branch conditions (if, unless, while) reject Bool? at compile time. Explicitly resolve the nullability instead:

if flag == true
  puts("explicitly true")
end

if (flag ?? false) or fallback_ready
  puts("active")
end

Safe Navigation (&.)

recv&.member evaluates member (field read, method call, or UFCS chain) only when recv != nil, returning U? (or Void for Void methods) and nil otherwise:

active&.add_score(15)
mentor_name = active
  &.mentor
  &.name ?? "no-mentor"

Flow-Sensitive Narrowing

The compiler automatically narrows local variables from T? to T across:

  1. Positive/negative branches:
    if user != nil
      puts(user.name)   # user narrowed to User
    end
    
    if user == nil
      puts("missing")
    else
      puts(user.name)   # user narrowed to User in else branch
    end
  2. Negation & unless: unless x == nil narrows x to T.
  3. Compound and / or conditions:
    if a != nil and b != nil
      sum = a + b       # both a and b narrowed to I64
    end
    
    if a != nil and a.len > 0
      puts(a)           # RHS of `and` sees a narrowed to String
    end
    
    if a == nil or a.len == 0
      return
    end
  4. while x != nil loops: x is narrowed to T inside the loop body.
  5. Post-early-exit narrowing: When one branch of an if terminates (return, break, next), the opposite narrowing persists for the remainder of the enclosing block:
    def narrow_early(a: I64?, b: I64?) -> I64
      if a == nil or b == nil
        return -1
      end
      a + b   # both a and b are narrowed to I64 here
    end

6. Structs, Classes, Operator Overloading & Default Parameters

Structs & Classes

@[repr(C)]
struct Vec2
  x: F64
  y: F64

  @[nogc]
  def dot(other: Vec2) -> F64
    @x * other.x + @y * other.y
  end

  @[nogc]
  mut def scale(factor: F64) -> Void
    @x *= factor
    @y *= factor
  end
end

class Player
  name: String
  score: I64
  mentor: Player?

  def initialize(@name: String, @score: I64)
    @mentor = nil
  end

  def add_score(points: I64) -> Void
    @score += points
  end
end
  • Construction: Vec2.new(3.0, 4.0) constructs a struct directly from its fields in declaration order. Player.new("Lin", 100) allocates on the GC heap and runs initialize(...) if defined (otherwise initializes fields positionally).
  • @field shorthand in initialize: Parameters prefixed with @ (such as @name: String) automatically assign directly to the corresponding instance field before the constructor body executes.
  • Mutation rules: struct methods cannot assign to @field unless declared mut def. class methods receive a GC reference pointer and may mutate fields directly. See Memory Model for ABI details.

Operator Overloading

Both struct and class types can overload arithmetic, comparison, and indexing operators as regular methods (and annotate them @[nogc] for zero-allocation math):

Syntax Overloadable Operators
Binary arithmetic def +(rhs), def -(rhs), def *(rhs), def /(rhs), def %(rhs)
Equality def ==(rhs) -> Bool (!= is derived automatically by negating ==, or may be defined explicitly as def !=(rhs) -> Bool)
Ordering def <(rhs) -> Bool, def <=(rhs) -> Bool, def >(rhs) -> Bool, def >=(rhs) -> Bool
Indexing def [](key) -> V, mut def []=(key, val) -> Void (or def []=(key, val) on class)

Example with an unboxed @[nogc] vector and a string-indexed class:

@[repr(C)]
struct Vec3
  x: F64
  y: F64
  z: F64

  @[nogc]
  def +(o: Vec3) -> Vec3
    Vec3.new(@x + o.x, @y + o.y, @z + o.z)
  end

  @[nogc]
  def *(s: F64) -> Vec3
    Vec3.new(@x * s, @y * s, @z * s)
  end

  @[nogc]
  def ==(o: Vec3) -> Bool
    @x == o.x and @y == o.y and @z == o.z
  end
end

class Table
  keys: Array[String]
  vals: Array[I64]

  def initialize(seed_k: String = "k0", seed_v: I64 = 7)
    @keys = [seed_k]
    @vals = [seed_v]
  end

  def [](key: String) -> I64
    for i in 0..@keys.len
      if @keys[i] == key
        return @vals[i]
      end
    end
    -1
  end

  def []=(key: String, val: I64) -> Void
    for i in 0..@keys.len
      if @keys[i] == key
        @vals[i] = val
        return
      end
    end
    @keys.push(key)
    @vals.push(val)
  end
end

t = Table.new()
t["x"] = 99
v = t["x"]         # 99

Default Parameter Values

Functions, methods, and initialize constructors accept default expressions on trailing parameters. Omitted trailing arguments are filled in at call sites during type checking and code generation:

def connect(host: String = "127.0.0.1", port: U16 = 8080) -> String
  "#{host}:#{port}"
end

a = connect()                        # "127.0.0.1:8080"
b = connect("example.com")           # "example.com:8080"
c = connect("example.com", 9000)     # "example.com:9000"

7. UFCS Dot-Chaining, &fn, do Blocks & Closures

Uniform Function Call Syntax (UFCS)

Any expression recv.name(args...) resolves in strict precedence order:

  1. Built-in members on primitives, String, Array, Slice, StaticArray, Ptr, and Arena.
  2. Direct fields and member methods on recv's struct or class (member methods always shadow free functions).
  3. Top-level free functions def name(first: T, ...) (concrete or generic) visible in the current module or its imports. If multiple imported modules define name, the call is an ambiguity error and must be qualified as alias.name(recv, ...).

Chained calls with zero extra arguments may omit parentheses:

def double(n: I64) -> I64
  n * 2
end

def add_offset(n: I64, offset: I64) -> I64
  n + offset
end

total = 10
  .double
  .add_offset(5)

Function Values (&fn)

Prefix & produces a first-class function value without invoking the function (&double or &mod_alias.fn_name). Local Fn variables always require (...) to call, so referencing op by name never triggers an accidental call:

def apply_twice(n: I64, op: Fn(I64) -> I64) -> I64
  op(op(n))
end

res = apply_twice(10, &double)

Taking & of a @[nogc] function produces type @[nogc] Fn(...) -> R (a raw C-ABI function pointer), which coerces automatically to a general Fn(...) -> R when passed to a higher-order function.

Zero-Overhead do Blocks & yield

Non-escaping do |...| ... end blocks are inlined at compile time with zero heap allocation and work inside @[nogc] functions:

  • Built-in iterators: n.times do |i| ... end on integers; xs.each do |v| ... end and xs.each_with_index do |v, i| ... end on Array[T], Slice[T], and StaticArray[T, N].
  • User-defined yield functions: Any function or method whose body contains yield(...) is compile-time inlined into each call site:
@[nogc]
def repeat_scaled(base: I64) -> Void
  yield(base)
  yield(base * 2)
  yield(base * 3)
end

sum = 0
repeat_scaled(10) do |x|
  sum += x
end

Functions using yield cannot be referenced with &fn_name.

First-Class Closures (fn(...) -> R do ... end)

# Stateless closure: compiles to a raw function pointer, legal in @[nogc]
sq = fn(x: I64) -> I64 do x * x end

# Capturing closure: captures `offset` by value into a GC-allocated environment
def make_adder(offset: I64) -> Fn(I64) -> I64
  fn(x: I64) -> I64 do
    x + offset
  end
end

Stateless closures whose body performs no GC operations automatically have type @[nogc] Fn(...) -> R and require zero heap allocation. Capturing closures allocate their captured environment on the Boehm GC heap and are rejected inside @[nogc] functions (and @[nogc] fn(...) closures reject any variable capture).


8. Payload enums & Exhaustive match

Enums support both simple C-style discriminants and algebraic sum types with per-variant typed payloads:

enum Color
  red
  green
  blue
end

enum Token
  eof
  ident(String)
  int_lit(I64)
  op(U8)
end

Construct variants with EnumName.variant or EnumName.variant(args...).

match works as either a statement or a value-producing expression:

def describe_token(tok: Token) -> String
  match tok
  when .eof
    "eof"
  when .ident(name)
    "id(#{name})"
  when .int_lit(val)
    "int(#{val})"
  when .op(ch)
    match ch
    when '+', '-'
      "op(addsub)"
    else
      "op(other)"
    end
  end
end

match rules:

  • Enum exhaustiveness: Matching on an enum without an else branch requires every variant to be covered exactly once. Missing or duplicate variants are compile-time errors.
  • Shorthand & destructuring: Use .variant or EnumName.variant, destructure payloads with .variant(a, b), and ignore individual payload slots with _ (e.g., when .err(_)).
  • Multiple patterns: A single when arm accepts comma-separated patterns (when .red, .blue or when '+', '-').
  • Primitive & String matching: match also matches integers, U8 character literals, and String values (using byte-wise hl_str_eq_len).

9. Scoped Cleanup (defer)

defer <expr> registers an expression to run automatically when the enclosing lexical scope exits — in LIFO (reverse registration) order — regardless of whether exit occurs via fall-through, return, break, next, or postfix ? propagation:

@[nogc]
def work() -> Void
  ctx = llvm_context_create()
  defer llvm_context_dispose(ctx)

  mod = llvm_module_create("demo", ctx)
  defer llvm_dispose_module(mod)
  # On return: llvm_dispose_module(mod) runs first, then llvm_context_dispose(ctx)
end

defer shares the compiler's scoped cleanup stack with with_arena, so interleaved defer statements and with_arena blocks tear down in strict reverse lexical order.


10. Modules & import

Every .hl file is a module. Import other modules at the top of a file:

import math_a                  # alias defaults to "math_a"
import math_b as mb            # explicit alias "mb"
import "std/str" as str        # path import with alias
import http                    # resolves automatically from std/http.hl or $H_HOME/std/http.hl

Resolution Order

For import target, the compiler appends .hl if omitted and searches in strict order:

  1. Explicit [dependencies] declared in h.toml (<dep_dir>/lib.hl -> <dep_dir>/<name>.hl -> <dep_dir>/main.hl, or <dep_dir>/<subpath>.hl)
  2. Relative to the importing file's directory (<parent_dir>/<target>.hl)
  3. Relative to the current working directory or absolute path (<target>.hl)
  4. Extra include directories supplied via -I <dir>
  5. Local standard library directory (std/<target>.hl)
  6. Installed $H_HOME standard library directory ($H_HOME/std/<target>.hl and $H_HOME/<target>.hl, auto-detected from /proc/self/exe or $H_HOME)

Cyclic imports are detected during module loading and rejected at compile time.

Visibility & Symbol Mangling

  • Types (struct, class, enum, interface) and functions from directly imported modules are visible unqualified unless ambiguous.
  • Qualified calls use alias.fn_name(...) and qualified function references use &alias.fn_name.
  • Non-entry module symbols are mangled as <module_name>__<symbol> in LLVM IR so identically named functions or types in different modules never collide at link time.

Next: Memory Model

Clone this wiki locally