Skip to content

Reflection Tutorial

Paul Squires edited this page Nov 30, 2026 · 1 revision

Home › Reflection Tutorial

Reflection Tutorial

tiko's reflection happens at compile time. You do not ask a type about itself while the program runs. Instead the compiler, which knows every field of every type and every constant of every enum, writes the code that would otherwise be kept in step by hand: comparisons, hashes, debug text, enum names and the walk over a type's fields. There are four tools:

  • derive: a line in a type that gives it = and <> (equal), < > <= >= (order), a hash (hash) and a ToText( ) member (text), all written from its fields.
  • hashvalue( k ): the hash Map and Set use, for any built-in type, any type with derive hash and any containers.Hashable, so your own generic code can hash a key too.
  • enumname, enumcount and enumvalue: an enum value's name, the number of constants, and the i-th constant, so an enum can be printed, walked and parsed without a select case that lists its names a second time.
  • derive fields, visitfields and visitvalue: a call on a visitor of your own for each field of a type, with the field's name and value, so a serialiser or a decoder is written once for every type.

Who this is for: a tiko programmer who has written a type and used a Map or Set. No knowledge of hashing is assumed.

What you need: a tiko toolchain. Every program in this tutorial was compiled and run on windows-x86_64, and the output shown is the real output.

The running example is a warehouse's stock list. Part by part, we ask more of it:

  1. Serialising a type: an encoder and a decoder with visitfields.
  2. A key type for a Map, written by hand and then with derive.
  3. Debug text with derive text.
  4. Sorting with derive order.
  5. Hashing in your own generic code with hashvalue.
  6. Enum names, counts and values.
  7. All of it together: a stock report.
  8. derive in a generic type.
  9. What the compiler says when a field cannot take part.
  10. When to write it by hand.

Every listing is a complete program. Copy it into a .tiko file and compile it with tiko file.tiko.


Part 1 — Serialising a type

A type's ToText( ) (Part 3) is for reading by a person; nothing reads it back. To save an item to a file and load it again, something has to name every field, once to write it and once to read it, and be kept in step with the type by hand. derive fields hands that job to the compiler:

  • derive fields on a type writes nothing. It gives permission to walk the type's fields.
  • visitfields( x, v ) is a statement. For each field of x, base first, it writes a call on v, a visitor: a type of your own with a Visit overload per kind of field. The call carries the field's name, as declared, and the field itself.

What the call is depends on the field:

The field is The call
a type with derive fields v.Enter( "name" ), then its fields, then v.Leave( )
a containers.Array( of U ) v.VisitList( "name", x.field )
anything else v.Visit( "name", x.field )

The encoder

The visitor below writes a stock item as key = value lines. Enter and Leave keep a prefix, so the location's fields come out as loc.aisle and loc.bin:

#import "std/containers"

type Location
    derive fields
    as int32 aisle, bin
end type

type Item
    derive fields
    as ustring name
    as int32 qty
    as float64 price
    as Location loc
    as containers.Array( of ustring ) tags
end type

'' Writes one "key = value" line per field. A nested type's fields get its name as a prefix.
type KeyWriter
    as ustring prefix                                   '' "" at the top, "loc." inside loc
    declare sub Visit( byval nm as ustring, byref x as const int32 )
    declare sub Visit( byval nm as ustring, byref x as const float64 )
    declare sub Visit( byval nm as ustring, byref x as const ustring )
    declare sub Enter( byval nm as ustring )
    declare sub Leave( )
    declare sub VisitList( of U )( byval nm as ustring, byref a as containers.Array( of U ) )
end type

sub KeyWriter.Visit( byval nm as ustring, byref x as const int32 )
    print prefix & nm & " = " & x
end sub
sub KeyWriter.Visit( byval nm as ustring, byref x as const float64 )
    print prefix & nm & " = " & str( x )
end sub
sub KeyWriter.Visit( byval nm as ustring, byref x as const ustring )
    print prefix & nm & " = """ & x & """"
end sub
sub KeyWriter.Enter( byval nm as ustring )
    prefix &= nm & "."
end sub
sub KeyWriter.Leave( )
    '' drop the last "name." from the prefix
    dim as integer i = instrrev( prefix, ".", len( prefix ) - 1 )
    prefix = left( prefix, i )
end sub
sub KeyWriter.VisitList( of U )( byval nm as ustring, byref a as containers.Array( of U ) )
    for i as integer = 0 to a.Count( ) - 1
        visitvalue( nm & "[" & i & "]", a[ i ], this )     '' Visit, Enter/Leave or VisitList, per U
    next
end sub

dim as Item it
it.name = "Bolt M6"
it.qty = 250
it.price = 0.12
it.loc.aisle = 4
it.loc.bin = 17
it.tags.Push( "metal" )
it.tags.Push( "small" )

dim as KeyWriter w
visitfields( it, w )
name = "Bolt M6"
qty = 250
price = 0.12
loc.aisle = 4
loc.bin = 17
tags[0] = "metal"
tags[1] = "small"

Three things to notice:

  • One Visit per field type. Each call is an ordinary call, and a byref parameter takes no widening: an int32 overload does not take an int16 field. A field type with no overload is an error at the visitfields line (below).
  • VisitList is the one generic. A generic body cannot tell what U is, so it hands each element to visitvalue( name, a[ i ], this ), which applies the table above to that one value. An Array( of Location ) would go through Enter and Leave; an Array( of Array( of int32 ) ) through VisitList again. Keep the generic under its own name: tiko allows one generic procedure per name, and does not rank it against ordinary overloads of the same name.
  • Nothing in KeyWriter names Item. Another type with derive fields and the same kinds of fields is written by the same visitor, and a field added to Item is written with no other change.

The decoder

Reading is the same walk in the other direction. visitfields( it, r ) over a variable passes each field by reference, so the decoder's overloads take byref without const and assign. A key that is not in the input leaves its field as it was, which for a fresh value is its initializer:

#import "std/containers"

type Location
    derive fields
    as int32 aisle, bin
end type

type Item
    derive fields
    as ustring name
    as int32 qty
    as float64 price
    as Location loc
    as containers.Array( of ustring ) tags
end type

'' Reads the fields back from "key = value" lines. A key that is missing leaves its field alone.
type KeyReader
    as containers.Map( of ustring, ustring ) values     '' key -> the text after " = "
    as ustring prefix
    declare function Has( byval nm as ustring ) as boolean
    declare sub Visit( byval nm as ustring, byref x as int32 )
    declare sub Visit( byval nm as ustring, byref x as float64 )
    declare sub Visit( byval nm as ustring, byref x as ustring )
    declare sub Enter( byval nm as ustring )
    declare sub Leave( )
    declare sub VisitList( of U )( byval nm as ustring, byref a as containers.Array( of U ) )
end type

function KeyReader.Has( byval nm as ustring ) as boolean
    return values.Contains( prefix & nm )
end function
sub KeyReader.Visit( byval nm as ustring, byref x as int32 )
    if Has( nm ) then x = valint( values[ prefix & nm ] )
end sub
sub KeyReader.Visit( byval nm as ustring, byref x as float64 )
    if Has( nm ) then x = val( values[ prefix & nm ] )
end sub
sub KeyReader.Visit( byval nm as ustring, byref x as ustring )
    if Has( nm ) then
        dim as ustring s = values[ prefix & nm ]
        x = mid( s, 2, len( s ) - 2 )                     '' drop the quotes
    end if
end sub
sub KeyReader.Enter( byval nm as ustring )
    prefix &= nm & "."
end sub
sub KeyReader.Leave( )
    prefix = left( prefix, instrrev( prefix, ".", len( prefix ) - 1 ) )
end sub
sub KeyReader.VisitList( of U )( byval nm as ustring, byref a as containers.Array( of U ) )
    '' One element per "nm[i]" key, read until the first that is missing.
    dim as integer i = 0
    while Has( nm & "[" & i & "]" )
        dim as U elem                                     '' a default element: all a generic can make
        a.Push( elem )
        visitvalue( nm & "[" & i & "]", a[ i ], this )
        i += 1
    wend
end sub

dim as ustring lines( 0 to 5 ) = { "name = ""Bolt M6""", "qty = 250", "price = 0.12", _
                                   "loc.aisle = 4", "tags[0] = ""metal""", "tags[1] = ""small""" }
dim as KeyReader r
for i as integer = 0 to ubound( lines )
    dim as integer eq = instr( lines( i ), " = " )
    r.values[ left( lines( i ), eq - 1 ) ] = mid( lines( i ), eq + 3 )
next

dim as Item it
it.loc.bin = 99                                           '' no "loc.bin" line: it stays 99
visitfields( it, r )
print it.name & " | qty " & it.qty & " | price " & it.price
print "aisle " & it.loc.aisle & " | bin " & it.loc.bin
print it.tags.Count( ) & " tags: " & it.tags[ 0 ] & ", " & it.tags[ 1 ]
Bolt M6 | qty 250 | price 0.12
aisle 4 | bin 99
2 tags: metal, small

The decoder's VisitList cannot build an element of its own, because all it knows of U is that it has a default. So it pushes a default element and lets visitvalue fill it in, once for each tags[i] key it finds.

A real format, such as TOML or JSON, puts the same calls to a library: Enter opens a table, Leave closes it under its key, and VisitList opens an array. The visitor is written once, for the format; each type adds only derive fields.

When it does not compile

Forgetting derive fields is an error at the walk, naming the type:

type Location
    as int32 aisle, bin
end type

type Printer
    as integer lines
    declare sub Visit( byval nm as ustring, byref x as const int32 )
end type
sub Printer.Visit( byval nm as ustring, byref x as const int32 )
    print nm; " ="; x
end sub

dim as Location l
dim as Printer p
visitfields( l, p )
shop.tiko(15,1): error TKO1280: visitfields( ) walks a type with 'derive fields', and 'location' has none
     |
  15 | visitfields( l, p )
     | ^

A field that no Visit takes is the ordinary overload error, at the visitfields line. Here qty is an int16, and the only number overload takes byref as const int32:

type Item
    derive fields
    as ustring name
    as int16 qty
end type

type Printer
    as integer lines
    declare sub Visit( byval nm as ustring, byref x as const int32 )
    declare sub Visit( byval nm as ustring, byref x as const ustring )
end type
sub Printer.Visit( byval nm as ustring, byref x as const int32 )
    print nm; " ="; x
end sub
sub Printer.Visit( byval nm as ustring, byref x as const ustring )
    print nm; " = "; x
end sub

dim as Item it
dim as Printer p
visitfields( it, p )
shop.tiko(21,1): error TKO0698: this argument does not convert to the parameter's type
     |
  21 | visitfields( it, p )
     | ^

Add an int16 overload, or take numbers byval x as int32, which widens. A nested derive fields field and a visitor with no Enter is the ordinary missing-member error, TKO0739. Every message is listed on the VisitFields page.


Part 2 — A key type

A stock location is an aisle and a bin. To count stock per location, the location has to be a Map key, and a Map key needs two things: an = that says when two keys are the same, and a hash that gives equal keys equal numbers.

By hand

Without derive, the key extends containers.Hashable, overrides HashOf( ) and writes its own operator =:

#import "std/containers"

type Sku extends containers.Hashable
    as int32 aisle, bin
    declare constructor( byval aisle as int32 = 0, byval bin as int32 = 0 )
    declare function HashOf( ) as ulongint override
end type

constructor Sku( byval aisle as int32 = 0, byval bin as int32 = 0 )
    this.aisle = aisle
    this.bin = bin
end constructor

function Sku.HashOf( ) as ulongint
    return containers.HashInt( hashvalue( aisle ) ) xor hashvalue( bin )
end function

operator = ( byref a as Sku, byref b as Sku ) as boolean
    return a.aisle = b.aisle andalso a.bin = b.bin
end operator

dim as containers.Map( of Sku, int32 ) stock
stock[ Sku( 1, 3 ) ] = 12
stock[ Sku( 3, 1 ) ] = 40

dim as Sku wanted = Sku( 1, 3 )
print stock.Contains( wanted ), stock[ wanted ]
print stock.Contains( Sku( 1, 4 ) )
true            12
false

It works, but the field list is now written three times: in the type, in HashOf( ) and in operator =. Add a field to the type and forget one of the other two, and nothing tells you. If = compares a field the hash leaves out, the Map still works, only slower. If the hash covers a field = leaves out, two keys that are equal can hash differently, and the Map loses entries. Extending Hashable also gives every key a hidden pointer to a table of methods (the type now extends object), and a type that extends object is not filled field by field, so type<Sku>( 1, 3 ) no longer builds one; that is why this version needs a constructor.

With derive

#import "std/containers"

type Sku
    derive equal, hash
    as int32 aisle, bin
end type

dim as containers.Map( of Sku, int32 ) stock
stock[ type<Sku>( 1, 3 ) ] = 12
stock[ type<Sku>( 3, 1 ) ] = 40

dim as Sku wanted = ( 1, 3 )
print stock.Contains( wanted ), stock[ wanted ]
print stock.Contains( type<Sku>( 1, 4 ) )
print wanted = type<Sku>( 1, 3 ), wanted <> type<Sku>( 3, 1 )
print cbool( hashvalue( wanted ) = hashvalue( type<Sku>( 1, 3 ) ) )
true            12
false
true          true
true

One line replaces the base type, the constructor, HashOf( ) and operator =. derive equal writes = and <>, comparing each field in declaration order. derive hash writes a hash from exactly the fields equal compares, so equal values always hash equal: the rule the hand-written version left to you now holds by construction. Add a field to Sku and both follow it.

Sku is a plain type again, so type<Sku>( 1, 3 ) and ( 1, 3 ) build one, and no hidden pointer is added to it.


Part 3 — Debug text

Printing a value while you debug means writing out its fields one by one. derive text adds a member, ToText( ), that does it for you:

enum Unit
    Each, Pack, Kg
end enum

type Sku
    derive equal, hash, text
    as int32 aisle, bin
end type

type Item
    derive text
    as Sku sku
    as ustring name
    as Unit unit
    as float64 price
    as int32 lastCounts( 0 to 2 )
    as Item ptr substitute
end type

dim as Item tea
tea.sku = type<Sku>( 1, 3 )
tea.name = "Tea, ""Breakfast"" blend"
tea.unit = Pack
tea.price = 4.25
tea.lastCounts( 0 ) = 12 : tea.lastCounts( 1 ) = 9 : tea.lastCounts( 2 ) = 15

print tea.sku.ToText( )
print tea.ToText( )
Sku(aisle=1, bin=3)
Item(sku=Sku(aisle=1, bin=3), name="Tea, ""Breakfast"" blend", unit=Pack, price=4.25, lastCounts=[12, 9, 15], substitute=&h0)

Each kind of field is written its own way:

  • A field of a type of your own uses that type's ToText( ), so sku nests.
  • A string is quoted, with each " inside it doubled.
  • An enum field is written as its constant's name, Pack, not as 1.
  • An array is written in brackets; a pointer as &h and its address, &h0 when it is null.

A base type comes first, as a field named base:

type Stamp
    derive text
    as int32 day
end type

type Delivery extends Stamp
    derive text
    as boolean signed
end type

dim as Delivery d
d.day = 14
d.signed = true
print d.ToText( )
Delivery(base=Stamp(day=14), signed=true)

ToText( ) is a member, not a conversion, so print does not call it on its own. Leave it out, and the compiler says what to write:

type Sku
    derive equal, hash, text
    as int32 aisle, bin
end type
dim as Sku s = ( 1, 3 )
print s
shop.tiko(6,7): error TKO0871: a 'sku' has no printable form; 'print' cannot take it
     |
   6 | print s
     |       ^
shop.tiko(2,5): note: 'derive text' gives it a ToText( ) member, which print does not call: write .ToText( )
     |
   2 |     derive equal, hash, text
     |     ^

The text is for debugging, logs and test messages. It is not a file format: nothing reads it back.


Part 4 — Sorting

A picker walks the warehouse aisle by aisle, and within an aisle bin by bin. That is an order on Sku, and derive order writes it: <, >, <= and >=, comparing the fields in the order they are declared. The first field that differs decides. order needs equal beside it.

#import "std/containers"
using containers

type Sku
    derive equal, order, hash, text
    as int32 aisle, bin
end type

dim as Array( of Sku ) picks
picks.Push( type<Sku>( 3, 1 ) )
picks.Push( type<Sku>( 1, 12 ) )
picks.Push( type<Sku>( 1, 3 ) )
picks.Push( type<Sku>( 2, 7 ) )

Sort( picks )                         '' aisle first, then bin
for i as integer = 0 to picks.Count( ) - 1
    print picks[ i ].ToText( )
next

print type<Sku>( 1, 12 ) < type<Sku>( 2, 1 )     '' aisle decides
print type<Sku>( 1, 3 ) <= type<Sku>( 1, 3 )

dim as OrderedMap( of Sku, int32 ) stock
stock.Put( type<Sku>( 2, 7 ), 5 )
stock.Put( type<Sku>( 1, 3 ), 12 )
stock.Put( type<Sku>( 3, 1 ), 40 )
for each kv in stock
    print kv.key.ToText( ), kv.value
next
Sku(aisle=1, bin=3)
Sku(aisle=1, bin=12)
Sku(aisle=2, bin=7)
Sku(aisle=3, bin=1)
true
true
Sku(aisle=1, bin=3)          12
Sku(aisle=2, bin=7)          5
Sku(aisle=3, bin=1)          40

containers.Sort and the ordered containers, OrderedMap and OrderedSet, need only <, so a type with derive order works with all of them.

Declaration order is the sort order. Declare bin first and the same values sort by bin:

#import "std/containers"
using containers

type ByBin
    derive equal, order, text
    as int32 bin, aisle                '' bin is declared first now
end type

dim as Array( of ByBin ) picks
picks.Push( type<ByBin>( 1, 3 ) )
picks.Push( type<ByBin>( 12, 1 ) )
picks.Push( type<ByBin>( 3, 1 ) )
Sort( picks )
for i as integer = 0 to picks.Count( ) - 1
    print picks[ i ].ToText( )
next
ByBin(bin=1, aisle=3)
ByBin(bin=3, aisle=1)
ByBin(bin=12, aisle=1)

A boolean has no order, so a type with a boolean field cannot derive order:

type Flagged
    derive equal, order
    as int32 id
    as boolean urgent
end type
shop.tiko(2,5): error TKO1267: 'derive order' on 'flagged' needs '<', '>', '<=' and '>=' on every field, and field 'urgent' is 'boolean', which has none
     |
   2 |     derive equal, order
     |     ^

Part 5 — Hashing in your own code

hashvalue( k ) is the hash Map and Set use. It is built into the compiler, so it needs no #import, and it takes any key Map would take: an integer, a float, a string, a pointer, an enum, a type with derive hash, or a type that extends containers.Hashable.

That makes it useful in generic code of your own. Here is a function that sends each key to one of n shards (files, worker threads, locks), the same key always to the same shard, whatever the key's type:

type Sku
    derive equal, hash
    as int32 aisle, bin
end type

'' Which of n shards (files, workers, locks) a key belongs to.
'' The same key always lands on the same shard, whatever its type.
function ShardOf( of K )( byref k as K, byval n as int32 ) as int32
    return hashvalue( k ) mod n
end function

dim as ustring code = "TEA-01"
dim as Sku a = ( 1, 3 ), b = ( 1, 3 ), c = ( 3, 1 )

print ShardOf( 42, 4 ), ShardOf( code, 4 )
print ShardOf( a, 4 ), ShardOf( b, 4 ), ShardOf( c, 4 )
 2              1
 2             2             1

a and b are equal, so they land on the same shard. The values are the same on every target, so a shard chosen on Windows is the same shard on Linux.

A type with no hash is an error where hashvalue meets it, with a note naming the generic instance that asked:

type Note
    as int32 id
end type

function ShardOf( of K )( byref k as K, byval n as int32 ) as int32
    return hashvalue( k ) mod n
end function

dim as Note x
print ShardOf( x, 4 )
shop.tiko(6,23): error TKO1266: hashvalue( ) cannot hash 'note': it is not a built-in type, has no 'derive hash' and no HashOf( ) method
     |
   6 |     return hashvalue( k ) mod n
     |                       ^
shop.tiko(10,14): note: in instantiation of 'shardof( of note )'
     |
  10 | print ShardOf( x, 4 )
     |              ^

hashvalue is for lookups: Maps, Sets, shards, caches. For checksums and passwords, which need a hash that is hard to forge, see Hash.


Part 6 — Enum names, counts and values

The warehouse has zones. Three intrinsics turn an enum into something a program can print, size a table with, and read back from text:

  • enumname( v ): the name of the constant whose value is v, as spelled in the declaration.
  • enumcount( E ): how many constants E declares. It is a compile-time constant, so it can size an array.
  • enumvalue( E, i ): the i-th constant of E, counting from 0 in declaration order.
enum Zone
    Dry, Chilled, Frozen
end enum

'' Name -> value: walk the constants and compare names.
function ParseZone( byref s as ustring, byref z as Zone ) as boolean
    for i as int32 = 0 to enumcount( Zone ) - 1
        if lcase( enumname( enumvalue( Zone, i ) ) ) = lcase( s ) then
            z = enumvalue( Zone, i )
            return true
        end if
    next
    return false
end function

dim as int32 pallets( 0 to enumcount( Zone ) - 1 )    '' one slot per zone
dim as ustring lines( 0 to 4 ) = { "dry", "frozen", "FROZEN", "chilled", "attic" }

for i as int32 = 0 to ubound( lines )
    dim as Zone z
    if ParseZone( lines( i ), z ) then
        pallets( z ) += 1
    else
        print "unknown zone: "; lines( i )
    end if
next

for i as int32 = 0 to enumcount( Zone ) - 1
    dim as Zone z = enumvalue( Zone, i )
    print enumname( z ), pallets( z )
next
unknown zone: attic
Dry            1
Chilled        1
Frozen         2

Add a zone to the enum, and the table, the parser and the report all follow it. Before these intrinsics, the names lived in a select case (or a macro) beside the enum and had to be kept in step by hand.

enumvalue walks the constants as they are declared, so it also works when the values are not 0, 1, 2. When two constants share a value, each is counted, and enumname gives the first one declared. A value no constant has is named "":

enum HttpStatus
    Ok = 200
    Created = 201
    NotFound = 404
    Missing = 404
end enum

for i as int32 = 0 to enumcount( HttpStatus ) - 1
    print enumvalue( HttpStatus, i ), enumname( enumvalue( HttpStatus, i ) )
next
print "["; enumname( cast( HttpStatus, 500 ) ); "]"
 200           Ok
 201          Created
 404          NotFound
 404          NotFound
[]

enumname needs a value of a named enum. A plain integer is an error, because the compiler cannot know which enum is meant: write enumname( cast( HttpStatus, 404 ) ). enumcount and enumvalue take the enum type itself, not one of its values.


Part 7 — The stock report

All of it together. A scan records a zone, an aisle and a bin. The program counts scans per location in a Map, prints the locations in order, and totals each zone:

#import "std/containers"
using containers

enum Zone
    Dry, Chilled, Frozen
end enum

type Sku
    derive equal, order, hash, text
    as Zone zone
    as int32 aisle, bin
end type

'' Count every scan, one Map entry per distinct Sku.
dim as Map( of Sku, int32 ) counts
dim as Sku scans( 0 to 5 ) = { ( Frozen, 2, 1 ), ( Dry, 1, 3 ), ( Frozen, 2, 1 ), _
                              ( Chilled, 4, 2 ), ( Dry, 1, 3 ), ( Frozen, 2, 1 ) }
for i as int32 = 0 to ubound( scans )
    counts[ scans( i ) ] += 1                 '' inserts 0 on the first scan
next

'' The report, in Sku order: zone, then aisle, then bin.
dim as Array( of Sku ) keys = counts.Keys( )
Sort( keys )
for i as integer = 0 to keys.Count( ) - 1
    print keys[ i ].ToText( ), counts[ keys[ i ] ]
next

'' Totals per zone, in a table enumcount sizes.
dim as int32 perZone( 0 to enumcount( Zone ) - 1 )
for each kv in counts
    perZone( kv.key.zone ) += kv.value
next
for i as int32 = 0 to enumcount( Zone ) - 1
    print enumname( enumvalue( Zone, i ) ); ": "; perZone( i )
next
Sku(zone=Dry, aisle=1, bin=3)               2
Sku(zone=Chilled, aisle=4, bin=2)          1
Sku(zone=Frozen, aisle=2, bin=1)           3
Dry:  2
Chilled:  1
Frozen:  3

Every piece the compiler wrote follows the type: zone is declared first, so it sorts first; it is an enum, so the text names it; and it takes part in = and the hash, so a Frozen bin and a Dry bin at the same aisle and bin are different keys. No line of the program repeats the field list or the zone names.


Part 8 — derive in a generic type

A generic type can derive too. The members are written for each instance, so Pair( of int32, float64 ) gets an = that compares an int32 and a float64:

#import "std/containers"

type Pair( of A, B )
    derive equal, hash, text
    as A first
    as B second
end type

dim as containers.Set( of Pair( of int32, float64 ) ) seen
dim as Pair( of int32, float64 ) p = ( 7, 2.5 ), q = ( 7, 2.5 )
seen.Add( p )
print seen.Contains( q )
print p.ToText( )
true
Pair(of int32, float64)(first=7, second=2.5)

The checks are made per instance, and only where a member is used. A Box( of Opaque ), where Opaque has no =, compiles; it is an error only where two of them are compared:

type Opaque
    as int32 x
end type

type Box( of T )
    derive equal
    as T value
end type

dim as Box( of int32 ) i1, i2
dim as Box( of Opaque ) o1, o2       '' compiles: nothing compares them yet
print i1 = i2
print o1 = o2
shop.tiko(13,10): error TKO1261: 'derive equal' on 'box( of opaque )' needs '=' on every field, and field 'value' is 'opaque', which has none
     |
  13 | print o1 = o2
     |          ^
shop.tiko(6,5): note: declared here
     |
   6 |     derive equal
     |     ^

So a generic container can derive everything, and an instance pays only for what it uses.


Part 9 — What the compiler says

derive is checked when the type is declared. Each mistake has its own message, naming the type and, where it is a field's fault, the field.

hash without equal. A hash only means something beside the = it agrees with:

type Sku
    derive hash
    as int32 aisle, bin
end type
shop.tiko(2,5): error TKO1264: 'derive hash' on 'sku' needs 'derive equal' too: a hash must cover exactly the fields '=' compares
     |
   2 |     derive hash
     |     ^

A field that cannot take part. Every field takes part, private fields too, and a field of a type of your own takes part through that type's own members:

type Label
    as int32 colour, size
end type

type Shelf
    derive equal, hash
    as int32 id
    as Label tag
end type
shop.tiko(6,5): error TKO1261: 'derive equal' on 'shelf' needs '=' on every field, and field 'tag' is 'label', which has none
     |
   6 |     derive equal, hash
     |     ^
shop.tiko(6,5): error TKO1262: 'derive hash' on 'shelf' needs a hash for every field, and field 'tag' is 'label', which has none
     |
   6 |     derive equal, hash
     |     ^

The fix is to derive on the inner type as well. Then the outer type compares and hashes through it:

type Label
    derive equal, hash
    as int32 colour, size
end type

type Shelf
    derive equal, hash
    as int32 id
    as Label tag
end type

dim as Shelf a, b
a.tag.colour = 2
print a = b, cbool( hashvalue( a ) = hashvalue( b ) )
b.tag.colour = 2
print a = b, cbool( hashvalue( a ) = hashvalue( b ) )
false          false
true          true

A derived member and a hand-written one. Two = operators for one type would disagree sooner or later, so the compiler asks you to keep one:

type Sku
    derive equal
    as int32 aisle, bin
end type
operator = ( byref a as Sku, byref b as Sku ) as boolean
    return a.aisle = b.aisle
end operator
shop.tiko(2,5): error TKO1263: 'sku' has 'derive equal' and a hand-written 'operator ='; keep one of them
     |
   2 |     derive equal
     |     ^
shop.tiko(5,1): note: declared here
     |
   5 | operator = ( byref a as Sku, byref b as Sku ) as boolean
     | ^

A word that is not one of the five:

type Sku
    derive equal, sort
    as int32 aisle, bin
end type
shop.tiko(2,19): error TKO1258: unknown derive 'sort': the words are equal, order, hash, text and fields
     |
   2 |     derive equal, sort
     |                   ^

The full list is on the Derive page, and every message is in Compiler Error Messages.


Part 10 — When to write it by hand

derive compares field by field. When a key's = is something else, write the key by hand, as in Part 2. A user name that ignores case is one: "Ada" and "ADA" are the same user, so the hash must ignore case too.

#import "std/containers"

'' A user name that compares without regard to case: "Ada" = "ADA".
'' Its '=' is not field by field, so derive cannot write it.
type UserName extends containers.Hashable
    as ustring text
    declare function HashOf( ) as ulongint override
end type

function UserName.HashOf( ) as ulongint
    return hashvalue( lcase( text ) )          '' hash what '=' compares
end function

operator = ( byref a as UserName, byref b as UserName ) as boolean
    return lcase( a.text ) = lcase( b.text )
end operator

dim as containers.Set( of UserName ) users
dim as UserName u
u.text = "Ada"
users.Add( u )

dim as UserName probe
probe.text = "ADA"
print users.Contains( probe )
true

The rule is the one derive hash keeps for you: hash exactly what = compares. Here = compares the lower-cased text, so HashOf( ) hashes the lower-cased text. hashvalue calls HashOf( ) for a Hashable, so Map, Set and Part 5's ShardOf all take a UserName as they take a derived key.


Cheat sheet

type T
    derive equal, order, hash, text    '' any of the four, in any order; hash and order need equal
                                       '' (and fields, for visitfields)
    ...fields...
end type

a = b   a <> b                         '' derive equal: each field, in declaration order
a < b   a <= b   a > b   a >= b        '' derive order: the first field that differs decides
hashvalue( a )                         '' derive hash: from the fields equal compares
a.ToText( )                            '' derive text: "T(field=value, ...)"

hashvalue( k )                         '' any built-in, derive hash or Hashable key
enumname( v )                          '' "Name" of the first constant with value v, or ""
enumcount( E )                         '' number of constants: a compile-time constant
enumvalue( E, i )                      '' the i-th constant, from 0, in declaration order

visitfields( x, v )                    '' derive fields: per field, base first, private too:
                                       ''   v.Enter( "f" ) ... v.Leave( )  a derive fields type
                                       ''   v.VisitList( "f", x.f )        a containers.Array
                                       ''   v.Visit( "f", x.f )            anything else
visitvalue( name, e, v )               '' the same rule for one value: VisitList's loop body

Things to know

  • Nothing happens at run time that you did not write. The members derive gives are ordinary code, written by the compiler when the program is compiled. There is no run-time type information and no cost for a word you do not use.
  • None of these names is reserved. derive is recognised only at the start of a line in a type body, so a field called derive still works. A procedure or variable of your own named hashvalue, enumname, enumcount, enumvalue, visitfields or visitvalue wins in your own code.
  • An enum takes no derive line. It already has = and <, and a hash; use the enum intrinsics for its names.
  • print does not call ToText( ). Write print x.ToText( ).
  • ToText( ) is not a file format. For reading and writing records, write a visitor once and walk each type with visitfields (Part 1).
  • Not yet supported: derive in a partial type, a bitfield field, and a type with an anonymous union. Each is refused with a message rather than compiled wrongly. A union cannot derive at all.
  • These are tiko additions. fbc has nothing like them, so code that must also build with fbc cannot use them.

See also: Derive, HashValue, EnumName, EnumCount, EnumValue, VisitFields, VisitValue, Enum, Map, Set, OrderedMap and OrderedSet, Sorting, Generics.


Home · Keyword Index

Clone this wiki locally