The language / Foreign files
Start here01
The language02
- 01The basics
- 02Values and numbers
- 03Variables
- 04Calls and expressions
- 05Conditions and loops
- 06Strings
- 07Arrays and hashes
- 08Classes and records
- 09Traits and enums
- 10Blocks
- 11Methods
- 12Imports and exports
- 13Foreign files
- 14Failures
Programs and the world03
- 01Files, input and output
- 02JSON, time, URLs and random numbers
- 03Html and forms
- 04Templates: Ochre
- 05Built-in methods
Kiln04
02 The language / 13
Foreign files
Talking to a library written in C, so the rest of the program never has to.
Some of the work a program needs is already done, in a library written in C. A foreign file is the one place a program talks to such a library: it declares the C functions it needs, wraps them in ordinary methods, and exports those. The rest of the program never sees C, only plain Hematite.
This page starts with a first foreign file and how values cross between Hematite and C. It then moves on to C's memory (structs, arrays and views of what C keeps), to C calling back into the program, and last to wrapping a whole library: handles given back when they're done with, and foreign files that share their C.
A first foreign file
A foreign file's first line names the library, and its extern defs declare the library's functions with C's types. What it exports is ordinary Hematite:
foreign "c"
extern def toupper(letter: Int32): Int32
extern def strlen(text: CString): UInt64
export def shout(letter: Int): Int
return toupper(letter)
end
export def bytes(text: String): Int
return strlen(text)
endAny other file imports it like any other file, and calls shout and bytes without knowing C is behind them:
import "letters"
print(shout(97)) # prints 65
print(bytes("blåbær")) # prints 8Naming the library
foreign "name" is the file's first line, before its imports. "c" is the C library every program has. Another name is a library on the system: foreign "sqlite3" is libsqlite3. hem run opens it when the program first calls into C, and hem build links it into the executable.
An extern def is found in the file's library, or in a library it uses itself: foreign "cairo" also has the C library's memfd_create.
Declaring C's functions
extern def name(parameters): Type declares the library's function name. It has no body, and is only in a foreign file. Ordinary code calls a method that calls it, as shout calls toupper above.
To see all the C a program talks to, run hem foreign app.hem. It lists the program's foreign files, each with its library and its extern defs.
C's types
C's types are written only in extern def lines. Code uses Hematite's, converted at the call:
| C's type | Code gives and gets |
|---|---|
Int8 Int16 Int32 Int64 UInt8 UInt16 UInt32 UInt64 | Int |
Float32 Float64 | Float |
CString | String |
Bytes | Bytes (see Bytes); only as a parameter |
Pointer | an address in C, only kept and given back |
Out[Int32] Out[Int64] Out[Float64] Out[Pointer] Out[Bytes] Out[CString] | room for C to put a value, as a parameter |
one of the file's extern structs, like Tm | the struct, by its address, as a parameter |
CArray[Tm] CArray[Pointer] | the array, by its first element's address, as a parameter |
nil is C's NULL, both ways. A Pointer, CString or Out parameter takes nil, and a Pointer or CString that C gives is a Pointer? or String?, which code checks before it uses it.
Whole numbers and bytes are never quietly changed on the way. An Int that doesn't fit C's type is an error at the call, rather than a different number. Text with a zero byte in it can't go to C.
foreign "c"
extern def abs(n: Int32): Int32
print(abs(-3)) # prints 3
print(abs(3_000_000_000)) # error: 3000000000 doesn't fit in C's Int32, which holds -2147483648 to 2147483647Room for C's answer: Out
Some C functions give a second value by writing it where a parameter points. new Out[Int32]() makes that room, and .value reads what C put there:
foreign "c"
extern def frexp(x: Float64, exponent: Out[Int32]): Float64
const exponent = new Out[Int32]()
print(frexp(48.0, exponent: exponent)) # prints 0.75
print(exponent.value) # prints 6Room for bytes or text says how big it is, and C fills it. An Out[Bytes]'s .value is every byte, as Bytes; an Out[CString]'s is the text before the first zero byte:
foreign "c"
extern def memcpy(to: Out[Bytes], from: Bytes, count: UInt64): Pointer
extern def strncpy(to: Out[CString], from: CString, count: UInt64): Pointer
const copy = new Out[Bytes](size: 4)
memcpy(copy, from: Bytes([9, 8, 7, 6]), count: 4)
print(copy.value == Bytes([9, 8, 7, 6])) # prints true
const text = new Out[CString](size: 16)
strncpy(text, from: "blåbær", count: 15)
print(text.value) # prints blåbær
const nothing = new Out[Bytes]() # error: an Out[Bytes] needs its room's size in bytes: new Out[Bytes](size: 256)A size is 1 to 1073741824 bytes. Out[Int32], Out[Int64], Out[Float64] and Out[Pointer] hold one value, and take no size. The .value of an Out[Pointer] is a Pointer?: nil when C put NULL there.
C's constant addresses: Pointer(...)
Some C libraries name special addresses, like SQLite's SQLITE_TRANSIENT, which is -1 as an address. In a foreign file, Pointer(address) is one:
foreign "c"
static COPY_TEXT = Pointer(-1)
print(COPY_TEXT == Pointer(-1)) # prints true
print(Pointer(0)) # error: Pointer(0) is C's NULL, which is nil: write nilC's memory
Many C functions work on memory: a struct to fill in or to read, an array of them, or memory C keeps for itself. A foreign file declares the struct, and Hematite lays it out as C does. The program can then make that memory itself, make arrays of it, or look at memory C keeps where it is.
A struct: extern struct
A struct is declared with its fields' C types: extern struct Name, a field per line, then end. Here gmtime_r fills in a Tm from a number of seconds:
foreign "c"
extern struct Tm
second: Int32
minute: Int32
hour: Int32
day: Int32
month: Int32
year: Int32
weekday: Int32
yearday: Int32
dst: Int32
offset: Int64
zone: CString
end
extern struct Seconds
value: Int64
end
extern def gmtime_r(time: Seconds, into: Tm): Pointer
const time = new Tm()
gmtime_r(new Seconds(value: 1_700_000_000), into: time)
print(time.year + 1900) # prints 2023
print(time.zone) # prints GMT
time.write(hour: 23)
print(time.hour) # prints 23A field is a number, a Pointer or a CString, and reads as an Int, a Float, a Pointer? or a String? (nil for NULL). extern union Name is written the same way, with every field at its start.
new Tm(...)is C's memory, of the program's own: zeroed, with the fields it names written, and freed when its last copy goes. Copies share it..write(field: value, ...)writes the fields it names, in that memory. A value that doesn't fit its field's C type is a mistake there.- A struct goes to C by its address.
.addressis that address, as aPointer: good while the struct is kept, so keep it in aconst. - Only foreign files have structs.
C's arrays: CArray[...]
new CArray[Seconds](count: 2) is that many structs (or Pointers), next to each other, zeroed. It goes to C by its first element's address.
foreign "c"
extern struct Seconds
value: Int64
end
const times = new CArray[Seconds](count: 2)
times[1].write(value: 5)
print(times[1].value) # prints 5
print(times.length) # prints 2
const pointers = new CArray[Pointer](count: 2)
pointers.write(0, to: times.address)
print(pointers[1]) # prints nil
print(times[2]) # error: index 2 is out of bounds for a CArray of 2 (the last index is 1)An element struct shares the array's memory, so writing it writes the array. A Pointer element is written with .write(index, to: pointer), and reads as a Pointer?.
Views of C's own memory: .at(...)
C also gives the address of memory it keeps: a struct, or an array of them. .at reads (and writes) it where it is:
foreign "c"
extern struct Seconds
value: Int64
end
const kept = new Seconds(value: 42)
const view = Seconds.at(kept.address)
print(view.value) # prints 42Seconds.at(pointer) is a view of the struct there, and Seconds.at(pointer, index: 2) of the third one from there. CArray[Seconds].at(pointer, count: 3) is a view of an array of 3.
A view is good only as long as C keeps that memory, so it's used where it's made: never kept in a field, nor given to or by a method. No type can be written for it. C takes one where it takes the struct.
C's data: extern static
extern static name is the address of C's data by that name, as a static Pointer. A view reads what's there:
foreign "c"
extern static environ
const variables = CArray[Pointer].at(environ, count: 1)
print(variables[0] != nil) # prints trueWhen C calls back
Callbacks: C calling a method
Some C functions call back: qsort asks how two elements compare, an event library tells what happened. extern callback Name(parameters): Type declares the type of function C calls, with C's types, as an extern def does, and a method of the file's is one:
foreign "c"
extern struct Seconds
value: Int64
end
extern callback Compare(a: Pointer, b: Pointer): Int32
extern def qsort(items: CArray[Seconds], count: UInt64, size: UInt64, compare: Compare)
class Sorter
readable var comparisons: Int = 0
def sort(items: CArray[Seconds])
qsort(items, count: items.length, size: 8, compare: Sorter.compare)
end
private def compare(a: Pointer?, b: Pointer?): Int
self.comparisons = self.comparisons + 1
if a == nil or b == nil
return 0
end
return Seconds.at(a).value - Seconds.at(b).value
end
end
const items = new CArray[Seconds](count: 3)
items[0].write(value: 30)
items[1].write(value: 10)
items[2].write(value: 20)
var sorter = new Sorter()
sorter.sort(items)
print(items[0].value) # prints 10
print(sorter.comparisons > 0) # prints true
const kept = Sorter.compare # error: Sorter.compare is a method itself, without parentheses: it goes where C takes a callback; to call it, write Sorter.compare(...) on an objectClass.method, without parentheses, is that method itself, where C takes a callback: an argument, or a struct's field. It takes what C gives (nil for NULL) and gives what C takes back. It can't fail.
C calls it on a lent object. While a method of an object of that class calls C, the object is lent to the callbacks C makes, which change it as a changing method does. So that method changes its object, and is called on a var. Above, sort calls qsort, so the sorter is lent to each compare, which counts on it; and sorter is a var.
A callback with no object lent (made at another time, or from another thread) stops the program, and so does a mistake in one, after what it printed: C has nowhere to put it.
Wrapping a library
Handles: a class holding a Pointer
A C library often gives a handle: a Pointer to something it keeps, until it's given back. A foreign file keeps each handle in a class, which says how it's given back with def release():
foreign "c"
extern def malloc(size: UInt64): Pointer
extern def free(memory: Pointer)
export class Buffer
readable const size: Int
const memory: Pointer
static def make(size: Int): Buffer!
const memory = malloc(size)
if memory == nil
return failure("there's no memory for #{size} bytes")
end
return new Buffer(size: size, memory: memory)
end
def release()
free(self.memory)
end
endCode that uses it sees an ordinary class, made by a method that can fail:
import "buffers"
const buffer = try Buffer.make(64)
const copy = buffer
print(copy.size) # prints 64A class holding a Pointer must define def release(): it takes nothing, gives nothing and can't fail. Hematite calls release itself, exactly once, when the object's last copy goes, and for what's left when the program ends. Copies share the handle, so its fields never change: they're all const. A record is copied freely, so it can't hold a Pointer.
- Only foreign files read a
Pointerfield, even areadableone. newgives every private field of a class holding aPointer, since only its foreign file has aPointerto give. That's how aStatementholds theDatabaseit came from, made byStatement.prepare(database, sql: ...).- An object holding another is released first: a statement holding its database is given back before the database.
Foreign files together
A library's foreign file can grow long. Foreign files can share C between them, so one library's C can be split up: what one exports, other foreign files use as they use their own, C's types and all.
foreign "c"
export extern struct Point
x: Int32
y: Int32
end
export extern def abs(n: Int32): Int32
export def point(x: Int, y: Int): Point
return new Point(x: x, y: y)
enddistances.hem is foreign too, so it uses point, the Points it gives and C's abs from points.hem as if they were its own:
foreign "c"
import "points"
export def distance(from: Int, to: Int): Int
const start = point(from, y: 0)
const end_at = point(to, y: 0)
return abs(end_at.x - start.x)
endAn ordinary file gets only what's ordinary. It can call distance, but not abs:
import "distances"
import "points"
print(distance(9, to: 2)) # prints 7
print(abs(-7)) # error: 'abs' (from points.hem) is C's own function, and only a foreign file (whose first line is foreign "library") calls it; use what that file gives ordinary code- A foreign file may export anything it has:
export extern struct,export extern union,export extern callback,export extern def,export extern static, and methods and classes that take and give C's types. - Only foreign files use them. In a file that isn't foreign, a value of C's type is an error where it's used, and so is a call to a method that takes or gives one, or to an
extern def. The error names the foreign file it's from. - A class's callbacks can be its own file's or another foreign file's
extern callback.