Repository navigation
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.
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 use
@[...]:@[nogc],@[repr(C)]. -
Instance fields inside
structorclassmethods use@followed immediately by a lowercase identifier:@x,@score.
-
#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-
Voidfunction, method, ormatcharm is returned automatically. Explicit early exit usesreturn(orreturn 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-
Integers: Decimal (
42,1_000_000) and hexadecimal (0xFF,0x10_20). Unannotated integer literals default toI64, 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 toF64and adapt toF32when expected. -
Characters: Single-quoted ASCII byte literals (
'a','\n','\0','\\','\'') producingU8. -
Strings:
- Plain literals (
"hello\n") contain no#{...}interpolation, live in.rodata, are valid inside@[nogc], and coerce implicitly toPtr[U8]for C APIs. - Interpolated strings (
"x=#{x}, ok=#{flag}") evaluate embedded expressions and allocate a GC-managedString. Supported escape sequences:\n,\t,\r,\\,\",\',\0,\#.
- Plain literals (
| 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
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 = 3Assigning to _ explicitly discards an expression result (_ = fs.remove(path)).
Top-level globals require an explicit type annotation and initializer:
g_counter: I64 = 0| 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) |
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
endif, elsif, unless, and while conditions must have non-nullable type Bool.
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
endWhen 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).
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
endComparing a non-nullable value to nil is a compile-time error, as is accessing .field or .method directly on T? without unwrapping or using &..
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 trueBoolean 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")
endrecv&.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"The compiler automatically narrows local variables from T? to T across:
-
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
-
Negation &
unless:unless x == nilnarrowsxtoT. -
Compound
and/orconditions: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
-
while x != nilloops:xis narrowed toTinside the loop body. -
Post-early-exit narrowing: When one branch of an
ifterminates (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
@[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 astructdirectly from its fields in declaration order.Player.new("Lin", 100)allocates on the GC heap and runsinitialize(...)if defined (otherwise initializes fields positionally). -
@fieldshorthand ininitialize: Parameters prefixed with@(such as@name: String) automatically assign directly to the corresponding instance field before the constructor body executes. -
Mutation rules:
structmethods cannot assign to@fieldunless declaredmut def.classmethods receive a GC reference pointer and may mutate fields directly. See Memory Model for ABI details.
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"] # 99Functions, 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"Any expression recv.name(args...) resolves in strict precedence order:
- Built-in members on primitives,
String,Array,Slice,StaticArray,Ptr, andArena. - Direct fields and member methods on
recv'sstructorclass(member methods always shadow free functions). - Top-level free functions
def name(first: T, ...)(concrete or generic) visible in the current module or its imports. If multiple imported modules definename, the call is an ambiguity error and must be qualified asalias.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)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.
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| ... endon integers;xs.each do |v| ... endandxs.each_with_index do |v, i| ... endonArray[T],Slice[T], andStaticArray[T, N]. -
User-defined
yieldfunctions: Any function or method whose body containsyield(...)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
endFunctions using yield cannot be referenced with &fn_name.
# 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
endStateless 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).
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)
endConstruct 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
endmatch rules:
-
Enum exhaustiveness: Matching on an
enumwithout anelsebranch requires every variant to be covered exactly once. Missing or duplicate variants are compile-time errors. -
Shorthand & destructuring: Use
.variantorEnumName.variant, destructure payloads with.variant(a, b), and ignore individual payload slots with_(e.g.,when .err(_)). -
Multiple patterns: A single
whenarm accepts comma-separated patterns (when .red, .blueorwhen '+', '-'). -
Primitive &
Stringmatching:matchalso matches integers,U8character literals, andStringvalues (using byte-wisehl_str_eq_len).
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)
enddefer 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.
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.hlFor import target, the compiler appends .hl if omitted and searches in strict order:
- Explicit
[dependencies]declared inh.toml(<dep_dir>/lib.hl-><dep_dir>/<name>.hl-><dep_dir>/main.hl, or<dep_dir>/<subpath>.hl) - Relative to the importing file's directory (
<parent_dir>/<target>.hl) - Relative to the current working directory or absolute path (
<target>.hl) - Extra include directories supplied via
-I <dir> - Local standard library directory (
std/<target>.hl) - Installed
$H_HOMEstandard library directory ($H_HOME/std/<target>.hland$H_HOME/<target>.hl, auto-detected from/proc/self/exeor$H_HOME)
Cyclic imports are detected during module loading and rejected at compile time.
- 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