flang the compiler proves your program cannot hang 0.9.0 GitHub Try in the browserTry it Русский

Embedding flang in someone else's program

How do you call a function written in flang from a program in another language? The flang emit command generates source code in your language: a static library in C, a module in JavaScript, a module in Python. That code goes into your project as an ordinary file. The flang compiler is not needed while it runs.

There are ten emit targets: c, cpp, csharp, elixir, go, java, js, python, rust, ts.

One command

flang emit <file> --target <target> --out <directory>
flagwhat it does
--out directorywhere to write the files; a missing directory is created
--no-clido not generate the runner flang_cli; keep the module and the runtime
--max-steps N, --max-depth Nlimits on steps and call depth, written into the code as defaults
--index-base 0 or --index-base 1the number the program counts list items from; written into FL_INDEX_BASE
--runtime pathwhere to take the target's runtime sources from

With --max-steps 500 --max-depth 200 the JavaScript module has the lines const $DEFAULT_MAX_STEPS = 500 and const $DEFAULT_MAX_DEPTH = 200. With --index-base 0 the top of flang_runtime.h has #define FL_INDEX_BASE 0.

Before generating, emit runs the same checks as check. If the program fails them, no file is written. The file broken.flang:

модуль «Broken»

тотальная функция «Удвоить»
  принимает х: число
  возвращает строка
  х умножить на 2
$ flang emit broken.flang --target js --out ./out
FLANG_TYPE в файле broken.flang, строка 6, столбец 5: функция «Удвоить» объявлена как строка, а тело даёт число
flang emit: печать отменена — программа не проходит проверку, замечаний 1.
…
$ ls ./out
ls: cannot access './out': No such file or directory

The first line is a type error: the function must return a string (строка) and returns a number (число). The second says that generation is cancelled because the program does not pass the check. The exit code is 1 and the directory is not created.

Which files you get

One program, docs/examples/rosetta/factorial-english.flang, generated for every target:

targetfiles
cflang_runtime.h flang_runtime.c factorial.h factorial.c flang_cli.c Makefile
cppflang_runtime.hpp flang_runtime.cpp flang_cpp.hpp factorial.hpp factorial.cpp flang_cli.cpp Makefile
csharpValue.cs Field.cs FlangError.cs Ctx.cs Flang.cs Factorial.cs FlangCli.cs flang.csproj Makefile
elixirflang_runtime.ex factorial.ex flang_cli.ex Makefile
gogo.mod flangrt/flang_runtime.go flang/factorial.go cli/main.go Makefile
javaValue.java Field.java FlangError.java Ctx.java Flang.java Factorial.java FlangCli.java Makefile
jsfactorial.js flang_cli.js package.json
pythonflang_runtime.py factorial.py flang_cli.py Makefile
rustCargo.toml src/runtime.rs src/factorial.rs src/lib.rs src/cli.rs src/main.rs Makefile
tsfactorial.ts flang_runtime.js flang_cli.js package.json tsconfig.json

Every target has the same parts: a runtime (values, arithmetic, error messages), the program's module (one function per flang function), the runner flang_cli and a build file. With --no-cli there is no runner: js keeps factorial.js and package.json, c keeps five files of six.

A program with процесс (process) and надзор (supervision) declarations is generated by c, elixir, js and ts. The other six exit with code 1 and a message that the target has no concurrency scheduler.

$ flang emit docs/examples/rosetta/factorial-english.flang --target c --out ./out-c
напечатано файлов 6, байт …, в ./out-c
…
$ ls ./out-c
Makefile  factorial.c  factorial.h  flang_cli.c  flang_runtime.c  flang_runtime.h

The first output line says that 6 files were generated. make in that directory builds a static library and the runner:

$ cd out-c && make -j4
cc -std=c99 -Wall -Wextra -Werror -pedantic -O2 -flto   -c -o flang_runtime.o flang_runtime.c
cc -std=c99 -Wall -Wextra -Werror -pedantic -O2 -flto   -c -o factorial.o factorial.c
cc -std=c99 -Wall -Wextra -Werror -pedantic -O2 -flto   -c -o flang_cli.o flang_cli.c
ar rcs libfactorial.a flang_runtime.o factorial.o
cc -std=c99 -Wall -Wextra -Werror -pedantic -O2 -flto -o flang_cli flang_cli.o flang_runtime.o factorial.o -lm -lpthread

The library is named lib<module>.a. The module name is written in lower-case Latin letters: module «Factorial» gave libfactorial.a. If the module name is in Russian, the files and the library are called program: program.c, libprogram.a. Linking needs -lm and -lpthread.

The library has no main. Each flang function becomes one C function. The header says how to call it:

/*
 * Контракт вызова: функция кладёт результат в *result и возвращает FL_OK
 * либо НЕ трогает *result и возвращает FL_ERROR, заполнив *error (его можно
 * передать NULL). Результат живёт в арене контекста — до ближайшего
 * fl_arena_reset; чтобы сохранить его надолго, скопируйте в свою память.
 */
fl_status factorial_factorial(fl_ctx *ctx, fl_value n, fl_value *result, fl_error *error);
fl_status factorial_product(fl_ctx *ctx, fl_value items, fl_value *result, fl_error *error);

The comment says: the function puts the result into *result and returns FL_OK, or leaves *result alone, returns FL_ERROR and fills *error (which may be NULL). The result is kept in the context's arena until the next fl_arena_reset; copy it to your own memory to keep it longer.

A C function is named <module>_<function> in Latin letters: «Factorial» → factorial_factorial, «Приписать в начало» of module «Factorial» → factorial_pripisat_v_nachalo. The header declares three more functions:

The host is your C program. It includes the header and links with the library:

#include <stdio.h>
#include "factorial.h"

int main(void) {
  fl_arena arena;
  fl_ctx ctx;
  fl_error error = {0};
  fl_value result;

  fl_arena_init(&arena);
  fl_ctx_init(&ctx, &arena);

  if (factorial_factorial(&ctx, fl_number(10), &result, &error) != FL_OK) {
    printf("error: %s — %s\n", error.code, error.message);
    fl_arena_release(&arena);
    return 1;
  }
  printf("factorial(10) = %.0f\n", result.as.number);

  fl_value items[4] = { fl_number(1), fl_number(2), fl_number(3), fl_number(4) };
  if (factorial_product(&ctx, fl_list(items, 4), &result, &error) != FL_OK) { /* … */ }
  printf("product([1,2,3,4]) = %.0f\n", result.as.number);

  /* An error: a string where a number is expected. */
  if (factorial_factorial(&ctx, fl_text_borrow("x", 1, 1), &result, &error) != FL_OK) {
    printf("error: %s — %s\n", error.code, error.message);
  }

  fl_arena_release(&arena);
  return 0;
}
$ cc -std=c99 -Wall -Wextra -Werror -pedantic -O2 -o host host.c libfactorial.a -lm -lpthread
$ ./host
factorial(10) = 3628800
product([1,2,3,4]) = 24
error: FLANG_TYPE — сравнения порядка допустимы только для чисел

The third line is the type error FLANG_TYPE: the function was given a string. Its text says that order comparisons are allowed only for numbers.

Three rules:

  1. Memory is allocated in an arena, and the host owns the arena: fl_arena_init at the start, fl_arena_release at the end. Results of the functions are in the arena and are gone with it. Copy a result you need longer into your own memory.
  2. An error is returned as a value. There are no exceptions: the function returns FL_ERROR and fills an fl_error with fields code and message.
  3. fl_ctx holds the limits: call depth, step count and a check of the remaining stack. One context can serve many calls, as here.

A direct call of factorial_factorial does not check argument types. That is why the string reached a comparison inside the function and the error arose there. Pass values that come from outside through factorial_enter.

The generated C also builds into WebAssembly. An example is in the repository directory docs/examples/web/wasm/.

The value at the boundary

Each target has its own representation of flang values. The host passes arguments and reads results through it.

C

fl_value is a tag and a union (flang_runtime.h):

flangtaghow to read it
numbers: число, целое, неотрицательноеFL_NUMBERv.as.number, a double
machine word u8…u64FL_WORDbuilt with fl_word(width, sign, bits)
flagFL_FLAGv.as.flag
stringFL_STRINGv.as.string.utf8, .bytes, .points
listFL_LISTv.as.list.items, .count
recordFL_RECORDfl_field_get(ctx, v, "field name", &out, &err)
variantFL_VARIANTfl_variant_is(v, "Name"), fl_variant_field(ctx, v, "field", …)
nothingFL_NOTHINGno data

A string may lack a terminating zero: a substring points into shared memory. Print it with its length, not with %s. There are two lengths: bytes is UTF-8 bytes, points is code points. длина (length) in the language counts code points.

Two functions make a string in C. fl_text_borrow(utf8, bytes, points) does not copy the bytes, and the caller counts the code points. fl_text(ctx, utf8, bytes, &out, &err) copies the string into the arena and counts the points itself; it is the safer one.

Only function and module names are written in Latin letters. Field and variant names stay as written: a field «адрес» is read with fl_field_get(&ctx, v, "адрес", …).

If a function returns an error as an ordinary value, the host gets a value, not FL_ERROR. In docs/examples/errors/number-parsing.flang the function «Разобрать число» returns the variant «Вышло» (succeeded) or «Не вышло» (failed):

42 → Вышло, значение = 42
abc → Не вышло, сообщение = «к числу»: строка "abc" не является числом

FL_ERROR means the computation did not complete: a wrong type, no steps left or no depth left. A variant is an ordinary result; test it with fl_variant_is.

JavaScript

A number is a number, a string a string, a flag a boolean, "nothing" is null. A list is an Array. A record is a plain object with the original field names. A variant is an object with fields variant and fields. An error is thrown as a FlangError exception with fields code, message and diagnostics.

Python

In Python values are boxed in a Value with fields tag and data. Functions take the context as their first argument. The runtime does not accept a plain Python number; wrap it:

import factorial, flang_runtime as rt

ctx = factorial.new_context()
r = factorial.fn_factorial(ctx, rt.number(10))      # not 10, but rt.number(10)
print("factorial(10) =", r.tag, r.data)             # → 1 3628800.0
p = factorial.fn_product(ctx, rt.list_of([rt.number(x) for x in (1, 2, 3, 4)]))
print("product([1,2,3,4]) =", p.data)               # → 24.0
try:
    factorial.fn_factorial(ctx, rt.text("x"))
except rt.FlangError as e:
    print("error:", e.code, "|", e.message)         # → FLANG_TYPE | сравнения порядка допустимы только для чисел

All targets

The parameter types, the calling rules and the тотальная (total) mark of every function are written in the generated header or module.

Error codes (FLANG_TYPE, FLANG_RECURSION_LIMIT, …) are the same on every target. Message texts are Russian on every target, even when the program is written with the English keywords. In your program test the code, not the text.

JavaScript: embedding into your own project

The module has no import and no require at the top level. The only import is inside the function $callDeep and runs when that function is called.

$ flang emit docs/examples/rosetta/factorial-english.flang --target js --no-cli --out ./out-js
напечатано файлов 2, байт …, в ./out-js
…
$ ls ./out-js
factorial.js  package.json
import { factorial, product, $newContext } from "./factorial.js"

console.log(factorial(10))          // 3628800
console.log(product([1, 2, 3, 4]))  // 24

A function name is the flang name in camelCase: «Factorial» → factorial, «Numbers from and to» → numbersFromAndTo. Russian names are written in Latin letters: function «Разобрать число» of module «Number parsing» becomes razobratChislo in the file number_parsing.js. Field names and the value of the variant field stay as written:

import { razobratChislo, Vyshlo } from "./number_parsing.js"

for (const текст of ["42", "abc"]) {
  const итог = razobratChislo(текст)
  console.log(JSON.stringify(текст), "→", итог.variant, JSON.stringify(итог.fields))
}
console.log("built by the host:", JSON.stringify(Vyshlo({ значение: 7 })))
"42" → Вышло {"значение":42}
"abc" → Не вышло {"сообщение":"«к числу»: строка \"abc\" не является числом"}
built by the host: {"variant":"Вышло","fields":{"значение":7}}

The .js extension and your package's "type"

The file has the extension .js and is written as ECMAScript modules. A package.json with "type": "module" is generated next to it. If you move the file alone into a project whose package.json declares "type": "commonjs" or declares no "type", Node reads it as CommonJS and the import fails:

SyntaxError: Named export '$newContext' not found. The requested module './factorial.js'
is a CommonJS module, which may not support all module.exports as named exports.

There are two fixes: rename the file to .mjs, or declare "type": "module" in the directory where it lies.

Limits and depth

$newContext({ maxSteps, maxDepth }) sets the limits anew. A limit you do not pass takes its default; it is not left over from the previous call. Exceeding a limit throws a FlangError with code FLANG_RECURSION_LIMIT:

FlangError | FLANG_RECURSION_LIMIT | функция «Numbers from and to» исчерпала лимит шагов (50) на глубине вызовов 50

A direct call computes on the JavaScript stack. Deep recursion can exhaust it before reaching the declared depth limit. The module answers with the same FLANG_RECURSION_LIMIT error and a different text:

прямой вызов 9000: FLANG_RECURSION_LIMIT | функция «Numbers from and to» исчерпала стек хозяина
на глубине 6950, не дойдя до предела глубины вызовов (10000)
$callDeep 9000: длина 9000

The message says that the function exhausted the host's stack at depth 6950 without reaching the call-depth limit of 10000. The number 6950 depends on the machine and the Node version. The last line shows the fix: await $callDeep(function, [arguments], limits) runs the computation in a separate thread with a set stack size, and the declared limit becomes reachable. In a browser, and where the thread could not be created, the computation runs on the ordinary stack.

Any language: the runner and JSON

If there is no target for your language, use the runner flang_cli. It is generated next to the module. It reads JSON requests from standard input, one per line, and writes one answer line for each. One process serves the whole stream of requests. The format is the same on every target.

$ printf '%s\n' '{"fn":"Factorial","args":[{"n":"10"}]}' \
                '{"fn":"Product","args":[{"l":[{"n":"1"},{"n":"2"},{"n":"3"},{"n":"4"}]}]}' \
                '{"fn":"Factorial","args":[{"s":"x"}]}' | node flang_cli.js ./factorial.js
{"ok":true,"value":{"n":"3628800"}}
{"ok":true,"value":{"n":"24"}}
{"ok":false,"code":"FLANG_TYPE","message":"вызов функции «Factorial»: аргумент «n» не соответствует типу неотрицательное"}

The first two lines are results, the third is a type error. The same input fed to ./flang_cli built from the c target gives the same three lines. A function is called by its flang name, not by its C or JavaScript name. Every value carries a mark of its kind, because JSON has fewer kinds of values than the language:

notationvalue
{"n":"1.5"}a number written as a string: otherwise NaN, Infinity and −0 would be lost
{"s":"…"}a string
{"l":[…]}a list
{"r":[["field", …]]}a record
{"v":"Name","f":[…]}a variant
null, true/false"nothing", a flag

Before the call the runner compares the arguments with the declared parameter types. So to {"s":"x"} it answers that argument «n» does not match the type. A direct call factorial("x") reaches the function body and gets the error about order comparisons shown above. The type table is written next to the functions: factorial_entry in C, $PROGRAM.entry in JavaScript.

What is not promised

Next