nuxScript

🏷️ Sistema de Tipos Avançado

Refinements, Brands, Newtypes, Opaque Types

Refinements

// Tipo com predicate
type Positive = Int | x > 0
type NonEmpty = String | len(x) > 0
type ValidEmail = String | x ~/r "^\w+@\w+\.\w+$"

// Validação automática
let n: Positive = 5    // OK
let m: Positive = -1   // Error!

Brands (Marker Types)

// Marcar tipos existentes
brand UserId = Int
brand SessionToken = String

// Não podem ser usados diretamente
let uid: UserId = 5          // OK
let tid: SessionToken = "abc"   // OK

// Un branded
let raw: Int = unbrand(uid)

Newtypes

// Wrapper com overhead zero
newtype Money as Float
newtype Meter as Float

let m: Money = Money(100.50)
let v: Float = unwrap(m)

// Operations
fn add(a: Money, b: Money): Money 
    = Money(unwrap(a) + unwrap(b))

Opaque Types

// Tipo opaco (interno oculto)
opaque Handle

fn create(): Handle = ...
fn use(h: Handle): Void = ...

// Não pode ser criado fora do módulo
let h: Handle = create()
use(h)

Type Guards

// Guard check
let is_positive(x: Int): Bool = is_type(x, Positive)
let is_email(x: String): Bool = is_type(x, ValidEmail)

// Smart cast
if is_type(email, ValidEmail)
    print(email)  // Já inferido como ValidEmail
end