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

Back to README · Documentation index · Русский

Print a program into C and JavaScript

flang emit prints a checked program as source text in another language: the module, a runtime, a driver and a build file. Below, one program — the position where a value belongs in a sorted list — is printed into C and JavaScript, built and run.

The program

модуль «Search insert position»

тотальная функция «Шаг места вставки»
  принимает акк: число, эл: число, цель: число
  возвращает число
  обеспечивает «меньший элемент двигает место» если эл меньше цель то (результат равен (акк плюс 1)) иначе да
  обеспечивает «иначе место стоит на прежнем» если не (эл меньше цель) то (результат равен акк) иначе да
  пример «Элемент меньше цели — шаг вперёд»
    дано акк равно 2
    дано эл равно 3
    дано цель равно 5
    ожидается 3
  пример «Элемент не меньше цели — место не двигается»
    дано акк равно 2
    дано эл равно 7
    дано цель равно 5
    ожидается 2
  если эл меньше цель то акк плюс 1 иначе акк

тотальная функция «Место вставки»
  принимает элементы: список числа, цель: число
  возвращает число
  пример «Пример 1 из условия»
    дано элементы равно [1, 3, 5, 6]
    дано цель равно 5
    ожидается 2
  пример «Пример 2 из условия»
    дано элементы равно [1, 3, 5, 6]
    дано цель равно 2
    ожидается 1
  пример «Пример 3 из условия»
    дано элементы равно [1, 3, 5, 6]
    дано цель равно 7
    ожидается 4
  свёртка элементы начиная с 0 как акк и эл → «Шаг места вставки» от акк и эл и цель

Printing

Save the program to a file and name the target and the output directory:

$ flang emit insert.flang --target c --out out-c
проверок при работе снято 2: постусловие доказано ядром обо всех входах и
проверено примерами функции — в напечатанный код оно не едет.
напечатано файлов 6, байт 612850, в out-c
…
$ flang emit insert.flang --target js --out out-js
…
напечатано файлов 3, байт 54552, в out-js

Before printing, emit checks the program: parsing, types, termination and the proof kernel. It does not run the examples — flang test insert.flang does. A postcondition proved for all inputs is left out of the printed code; an unproved one is printed as a run-time check.

What is in the directory

$ ls out-c
Makefile  flang_cli.c  flang_runtime.c  flang_runtime.h  search_insert_position.c  search_insert_position.h
$ ls out-js
flang_cli.js  package.json  search_insert_position.js
partin Cin JavaScript
program module: one function per flang functiona .c and .h pair named after the moduleone .js with the runtime inside
runtime: values, arithmetic, diagnosticsflang_runtime.c, flang_runtime.h—
driver: JSON in, JSON outflang_cli.cflang_cli.js
buildMakefilepackage.json

The module file is named after the module: «Search insert position» gave search_insert_position. --no-cli prints without the driver; --file <name> writes one file to standard output.

The second function of the program as printed:

fl_status search_insert_position_mesto_vstavki(fl_ctx *ctx, fl_value elementy,
                                               fl_value cel, fl_value *result,
                                               fl_error *error) {
  fl_value fl_t2 = fl_nothing();
  FL_TRY(fl_require_list(ctx, elementy, "свёртка", &fl_t2, error));
  fl_value akk = fl_number(0.0);
  const fl_mark fl_t4 = fl_region_open(ctx);
  for (size_t fl_t3 = 0; fl_t3 < fl_t2.as.list.count; fl_t3 += 1) {
    const fl_value el = fl_t2.as.list.items[fl_t3];
    fl_value fl_t5 = fl_nothing();
    FL_TRY(search_insert_position_shag_mesta_vstavki(ctx, akk, el, cel, &fl_t5,
                                                     error));
    akk = fl_t5;
    FL_TRY(fl_region_recycle(ctx, fl_t4, &akk, error));
  }
  FL_TRY(fl_region_close(ctx, fl_t4, FL_OK, &akk, error));
  *result = akk;
  return FL_OK;
}
export function mestoVstavki(elementy, cel) {
  const $t1 = $requireList(elementy, "свёртка");
  let akk = 0;
  for (const el of $t1) {
    akk = shagMestaVstavki(akk, el, cel);
  }
  return akk;
}

The fold became an ordinary loop. Names are transliterated; the original name sits in the comment above the function. Printed code is not edited by hand: edit the flang source and print again.

Build and run

The driver reads one call per line from standard input and answers one line per call. A function is called by its original flang name, and values are tagged (n is a number, l a list; the full table is in Embedding flang in another program):

$ cat in.json
{"fn":"Место вставки","args":[{"l":[{"n":"1"},{"n":"3"},{"n":"5"},{"n":"6"}]},{"n":"5"}]}
$ cd out-c && make
$ ./flang_cli < ../in.json
{"ok":true,"value":{"n":"2"}}
$ cd ../out-js && node flang_cli.js ./search_insert_position.js < ../in.json
{"ok":true,"value":{"n":"2"}}

Besides the driver, make in the C directory builds the static library libsearch_insert_position.a, which you link into your own program. The JavaScript module is loaded with a plain import, in Node and in the browser.

The other targets

There are ten targets. The same program and the same input gave {"ok":true,"value":{"n":"2"}} on each:

targetfilesbuild and runchecked with
c6make, then ./flang_cligcc 15.2
cpp7make, then ./flang_clig++ 15.2
csharp9dotnet run -- SearchInsertPosition.NET 10.0
elixir4make runElixir 1.20, OTP 29
go5make flang_cli, then ./flang_cliGo 1.26
java8make runOpenJDK 26
js3node flang_cli.js ./search_insert_position.jsNode 26.7
python4python3 flang_cli.py search_insert_positionPython 3.14
rust7make build, then ./target/debug/flang_cli search_insert_positionRust 1.97
ts5node flang_cli.js ./search_insert_position.tsNode 26.7

A program with процесс and надзор declarations is printed by c, elixir, js and ts; a program with a план declaration by c, go, js, python, rust and ts; the other targets refuse. Other differences between targets are in Known limits.