Types
Basics
Section titled “Basics”Amethyst is statically typed with inference. Types are checked at compile time and compile to native .NET types.
Nullability
Section titled “Nullability”Null-safety is on by default. Types are non-nullable unless explicitly marked with ?:
name: String # cannot be nullname: String? # can be nullDisabling Null-Safety
Section titled “Disabling Null-Safety”Null-safety can be disabled at the project level or per-file. This is useful when interoperating with C# libraries that predate nullable reference type annotations.
Per-file, place the directive at the top of the file before any declarations:
null_safety off
namespace MyApp::LegacyInteropWhen null-safety is off, all reference types implicitly allow null — matching C#’s
pre-nullable behaviour. String? syntax remains valid but is redundant.
Project-level configuration is [TBD] and will be part of the Project System.
Safe Navigation (&.)
Section titled “Safe Navigation (&.)”&. short-circuits to nil when the receiver is nil; otherwise it calls the method
normally. The result type is the nullable form of the method’s return type:
user&.name # String? — nil if user is nil, otherwise user.nameuser&.address&.city # String? — nil if user or address is nil&. can also appear between an expression and a binary operator, making the
operation nil-safe:
count&.+ 1 # Int? — nil if count is nil, otherwise count + 1score&.* multiplier # Float?And with subscripts:
array&.[0] # T? — nil if array is nil, otherwise array[0]hash&.[:key] # V? — nil if hash is nilReturn type rule: the result is always the nullable form of the called method’s
return type. If the method already returns T?, the result is still T? — not
T??:
user&.nickname # String? — whether nickname returns String or String?Generics
Section titled “Generics”Generic types use bracket syntax:
Array[String]Hash[String, Int]IDictionary[Symbol, Any]Type Inference for Generics
Section titled “Type Inference for Generics”Type parameters are inferred from the arguments passed at the call site:
def identity[T](x: T): T xend
identity(42) # T inferred as Intidentity("hello") # T inferred as StringMultiple type parameters are each inferred independently:
def zip[T, U](a: Array[T], b: Array[U]): Array[Tuple[T, U]]
zip([1, 2], ["a", "b"]) # T = Int, U = StringWhen inference is unambiguous, the explicit form is optional but accepted:
identity[Int](42) # explicit — same resultWhen a type parameter appears only in the return type and cannot be inferred from arguments, it must be provided explicitly:
def default_value[T]: T # T not in any parameter — cannot be inferreddefault_value[Int] # must be explicitType parameters on generic classes are inferred from constructor arguments:
stack = Stack.new(42) # Stack[Int] inferred from the argumentstack = Stack[Int].new # explicit form — required when no argument provides TBuilt-in Types
Section titled “Built-in Types”Built-in types are the standard .NET types under Amethyst names. Only Symbol and
Range come from the Amethyst runtime.
| Amethyst | .NET |
|---|---|
Byte |
System.Byte |
SByte |
System.SByte |
Int |
System.Int32 |
UInt |
System.UInt32 |
Long |
System.Int64 |
ULong |
System.UInt64 |
Single |
System.Single |
Float |
System.Double |
Decimal |
System.Decimal |
String |
System.String |
Char |
System.Char |
Bool |
System.Boolean |
Symbol |
Amethyst.Runtime.Symbol |
Nil |
null |
Void |
void |
Never |
[DoesNotReturn] / unreachable |
Any |
System.Object |
Array[T] |
System.Collections.Generic.List<T> |
Hash[K, V] |
System.Collections.Generic.Dictionary<K, V> |
Tuple[T1, T2, ...] |
System.ValueTuple<T1, T2, ...> |
Range |
Amethyst.Runtime.Range (see Range Literals) |
Regex |
System.Text.RegularExpressions.Regex |
Type |
System.Type |
Pointer[T] |
T* (see Pointers) |
Numeric Coercions
Section titled “Numeric Coercions”Amethyst follows C#’s numeric coercion rules. Widening conversions are implicit; narrowing conversions require an explicit call.
Implicit Widening
Section titled “Implicit Widening”Numeric types widen automatically in this order:
Byte → Int → Long → FloatIn mixed arithmetic, both operands are promoted to the wider type before the operation:
| Expression | Result type |
|---|---|
Int + Int |
Int |
Int + Long |
Long |
Int + Float |
Float |
Long + Long |
Long |
Long + Float |
Float |
Float + Float |
Float |
x: Int = 10y: Float = 3.14z = x + y # z: Float — Int widened to Float before additionExplicit Narrowing
Section titled “Explicit Narrowing”Narrowing conversions (e.g. Float → Int) are never implicit. Use the
appropriate conversion method:
f: Float = 3.99i = f.to_int # 3 — truncates toward zero, like C# (int)fl = f.to_long # 3Ln = i.to_float # 3.0Conversion methods available on all numeric types: to_int, to_long, to_float,
to_byte.
Other Numeric Types
Section titled “Other Numeric Types”SByte, UInt, ULong, Single and Decimal follow C#’s implicit numeric
conversions exactly. In particular:
- Mixing signed and unsigned types requires an explicit conversion, except where a
wider type holds every value (
UInt + LongisLong) - Every integer type widens to
Single,FloatandDecimal;Singlewidens toFloat Decimalnever mixes implicitly withSingleorFloat
Nil, Void, and Never
Section titled “Nil, Void, and Never”These three types are distinct — each models a different concept around absence of value.
Nil is the type of the nil literal. It is the null value, not the absence of a
return. A method returning Nil always returns nil:
def nothing: Nil # returns nil nilendSince a Nil return carries no information, a method declared as returning Nil —
including one whose return type is omitted — compiles to void in IL. C# callers see
a void method; Amethyst callers get nil. Nullable returns such as String? are
ordinary return values and are not affected.
Nil is the second half of nullable types — String? is shorthand for String | Nil.
Void means the method produces no return value. Use it for methods with side effects
whose result is never meaningful to the caller. Maps to void in .NET IL:
def log(message: String): Void puts messageendA Void return value cannot be used in an expression — doing so is a compile error:
result = log("hello") # compile error — Void cannot be assignedNever is the bottom type — a method declared as returning Never never completes
normally. It either always raises an exception or runs forever. The compiler treats
any code after a Never-returning call as unreachable:
def fail(message: String): Never raise RuntimeException, messageend
def loop_forever: Never loop do process_next endendNever is a subtype of every type, so it can appear anywhere a type is expected:
value = if condition compute_valueelse fail("unreachable") # Never — branch is typed as the other branch's typeendIn .NET IL, Never-returning methods are marked with [DoesNotReturn].
Pointers
Section titled “Pointers”Pointer[T] is an unsafe pointer to a T. It compiles to C#’s T*, so methods that
take or return pointers are called from C# exactly as if they were written in C#:
def clear(values: Pointer[Int], count: Int): Void Native.clear(values, count)end// as C# sees itvoid Clear(int* values, int count)Amethyst code can pass pointers through, but not use them. A Pointer[T] value can be
received as a parameter, stored in a local, field or property, passed to another method
(Amethyst or .NET), and returned. Amethyst has no syntax for taking an address,
dereferencing, pointer arithmetic or pinning. Code that needs any of these belongs in C#,
and Amethyst calls it:
def clear_buffer(buffer: NativeBuffer): Void values = buffer.data # Pointer[Int], from C# Native.clear(values, buffer.length) # C# does the unsafe workendBecause Amethyst code never touches the memory behind a pointer, there is no unsafe
marker and no project setting to opt in.
Open Questions [TBD]
Section titled “Open Questions [TBD]”- Which types
Tmay be (C# allows unmanaged types only) - Whether a pointer can be compared with
nil, and whether a null pointer is falsy in conditions
Self Type
Section titled “Self Type”self in a type position refers to the type in which the method is declared — not
the type of the caller or any subclass.
class Animal def clone: self # return type is Animal, always endend
class Dog < Animal # inherits clone — still typed as Animal # override to return Dog: def clone: self # self here = Dog, because this is declared in Dog endendself resolves at the declaration site, not the call site. A method declared in
Animal always has self = Animal, regardless of what type it is called on.
In Protocols
Section titled “In Protocols”Protocols should use a generic type parameter rather than self when the intent is
“the implementing type must accept its own type”. This is the idiomatic pattern:
protocol Comparable[T] def <=>(other: T): Intend
class Temperature implements Comparable[Temperature]
getter value: Float
def <=>(other: Temperature): Int @value <=> other.value endendself in a protocol method still refers to the protocol type itself — useful when a
method genuinely returns or accepts the protocol as a type:
protocol Serializable def serialize: String def self.deserialize(data: String): self # returns the protocol typeendNullable Self
Section titled “Nullable Self”self? is valid — a nullable reference to the declaring type:
class Node def next: self? @next_node endendOverrides and super as a Type
Section titled “Overrides and super as a Type”When overriding a method in a subclass, super can be used as a type to refer to
the parent class’s type — see super as a Type.
Restrictions
Section titled “Restrictions”selfas a type is only valid in method parameter and return type positions.- It cannot appear in local variable annotations — use the concrete type name there.
- It cannot appear in generic type arguments:
Array[self]is a compile error. Use a type parameter instead (mixin Searchable[T],extend Searchable[User]).
Structural Typing
Section titled “Structural Typing”Amethyst supports structural typing through omitted parameter types. When a method parameter has no type annotation, the compiler traces all usages of that parameter within the method body to determine what the argument must provide. The argument is checked against those requirements at the call site — at compile time, not runtime.
def greet(person) name: String = person.name # person must have .name: String "Hello, #{name}!"endThe compiler infers that person must have a name method returning String.
Any type that satisfies this requirement can be passed:
greet(User.new("Alice")) # ok — User has .name: Stringgreet(Contact.new("Bob")) # ok — Contact also has .name: Stringgreet(42) # compile error — Int has no .nameType Annotations Drive Requirements
Section titled “Type Annotations Drive Requirements”Explicit annotations on values derived from the structural parameter constrain the required return types. Without an annotation, the return type is inferred from context:
def describe(item) name: String = item.name # item.name must return String age: Int = item.age # item.age must return Int "#{name}, age #{age}"endChained Access
Section titled “Chained Access”Structural requirements propagate through chains:
def city_of(entity) city: String = entity.address.city # entity must have .address, # and address must have .city: StringendStructural typing is permitted only in private methods. public, protected,
and internal methods must have explicit type annotations on all parameters —
the same rule that applies to return types. This keeps public APIs explicit and
stable:
private def process(item) # ok — private, structural typing allowed item.nameend
def display(item) # compile error — public method, parameter type required item.nameend
def display(item: Displayable) # ok — explicit protocol type item.nameendComplexity Limit
Section titled “Complexity Limit”Structural type inference has a bounded complexity budget. If the compiler cannot determine the structural requirements within that budget — due to deep chains, circular dependencies, or ambiguous usage — it emits a compile error and requires an explicit type annotation:
private def resolve(thing) # compile error: structural type of `thing` is too complex to infer — # add an explicit type annotation or extract to a protocolendThe exact budget is an implementation detail. When inference fails, the fix is to
either annotate the parameter with a concrete type or define a protocol that
captures the required interface.
Other Limitations
Section titled “Other Limitations”- Structural requirements are anonymous — there is no way to name or reuse them.
For a reusable contract, define a
protocolinstead. - Structural parameters cannot be stored in typed fields or returned from methods with an explicit return type without first narrowing to a concrete or protocol type.