Builtin Functions

BearVM provides a small set of builtin functions. They are called with the same call syntax as user-defined functions.

I/O

puts(<arg>)

Prints the argument to stdout followed by a newline. Accepts int or string values:

call puts("Hello, world!")
call puts(%n)
putf(<arg>)

Prints a float or double value to stdout followed by a newline:

call putf(%f_result)
flush()

Flushes stdout:

call flush()

Call this at the end of programs that produce output, particularly when output may be buffered.

File I/O

open(<path>, <mode>)

Opens a file and returns a file handle. mode is one of the named constants READ or WRITE:

%f = call open("test.txt", READ)
%f = call open("out.txt", WRITE)
read(<fd>, <buf>, <size>)

Reads up to size bytes from the file handle into buf. Returns a string containing the data read:

%buf = alloc 1024
%n   = call read(%f, %buf, 1024)
call puts(%buf)
write(<fd>, <data>, <size>)

Writes size bytes of data to the file handle:

call write(%f, "Hello, world.", 13)
close(<fd>)

Closes a file handle:

call close(%f)

File I/O Example

Reading a file:

@main(): int {
    %f   = call open("test.txt", READ)
    %buf = alloc 1024
    %n   = call read(%f, %buf, 1024)
    call puts(%buf)
    call close(%f)
    ret 0
}

Writing a file:

@main(): int {
    %f = call open("out.txt", WRITE)
    call write(%f, "Hello, world.", 13)
    call close(%f)
    ret 0
}