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

flang for Rust and TypeScript users

How is flang like the languages you know, what does it lack and what does it add? Below are a table of equivalents, one example in three languages and two lists of differences. Every construct is covered step by step in the language tour.

Table of equivalents

What you needRustTypeScriptflang
a functionfn f(x: f64) -> f64function f(x: number): numberфункция «Ф» with the lines принимает х: число and возвращает число
an immutable namelet x = 1;const x = 1;пусть х равно 1
a structurestructinterface, typeобъект
a sum typeenum with dataa union with a tag fieldтип with вариант lines
pattern matchingmatchswitch on the tagразбор with случай lines
"may be missing"Option<T>`T \undefined`your own type with two variants
an error as a valueResult<T, E>a union or throwyour own type: a variant with the result and a variant with the reason
a generic typeenum Maybe<T>type Maybe<T>тип «Возможно» от «А»
a trait, an interfacetrait and implinterface and classинтерфейс and класс … есть «…»
map, filter, folditerator methodsarray methodsотобразить, отфильтровать, свёртка
a test#[test] in a tests moduleJest, Vitestпример inside the function
running testscargo testnpm testflang test file.flang
checking without runningcargo checktsc --noEmitflang check file.flang
an importuseimportиспользует «Module»
a packagea crate, Cargo.tomlan npm packageone .flang-package file, the command flang package
a new projectcargo newnpm initflang new name
a comment//////
a compiler error codeE0308TS2322FLANG_TYPE and others with the FLANG_ prefix

A compiler error consists of a code, a file, a line, a column and a text in Russian. Every code is described in the code reference.

One example in three languages

The cost of delivery: pickup is free, a courier costs 200 plus 20 per kilometre. The file delivery-cost.flang:

модуль «Comparison»

тип «Способ»
  вариант «Самовывоз»
  вариант «Курьером» содержит километров: неотрицательное

тотальная функция «Стоимость доставки»
  принимает способ: «Способ»
  возвращает число
  обеспечивает «стоимость не отрицательна» результат не меньше 0
  пример «курьером за пять километров»
    дано способ равно вариант «Курьером» с километров равным 5
    ожидается 300
  разбор способ
    случай вариант «Самовывоз»
      то 0
    случай вариант «Курьером» с километров как километров
      то 200 плюс километров умножить на 20
$ flang check docs/examples/tour/compare/delivery-cost.flang
модуль «Comparison»: функций 1, из них с доказанным завершением 1; типов 1
docs/examples/tour/compare/delivery-cost.flang: проверено — разбор, типы, завершаемость, ядро и примеры; замечаний нет

The same in Rust:

enum Method {
    Pickup,
    Courier { km: u32 },
}

fn delivery_cost(method: &Method) -> u32 {
    match method {
        Method::Pickup => 0,
        Method::Courier { km } => 200 + km * 20,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn courier_five_km() {
        assert_eq!(delivery_cost(&Method::Courier { km: 5 }), 300);
    }
}

And in TypeScript:

type Method =
  | { kind: "pickup" }
  | { kind: "courier"; km: number };

function deliveryCost(method: Method): number {
  switch (method.kind) {
    case "pickup":
      return 0;
    case "courier":
      return 200 + method.km * 20;
  }
}

console.assert(deliveryCost({ kind: "courier", km: 5 }) === 300);

Three differences show at once:

The compiler proved the postcondition on its own:

$ flang check docs/examples/tour/compare/delivery-cost.flang --proof 2>&1 | grep "постусловие"
  постусловие «стоимость не отрицательна» функции «Стоимость доставки» — доказано индукцией по «Способ»: база 2 случая, шаг при допущении на частях (0 случаев), правила сведения: неотрицательность по построению — утверждение обо ВСЕХ входах типа «Способ», а не о написанных

«доказано индукцией по „Способ“» means that both variants of the type were examined and the result is non-negative in each. The statement covers all values; the test with five kilometres is one particular case.

What flang does not have

Every row was checked by running the compiler.

FamiliarWhat the compiler answersWhat to write
a mutable variable, let mut, x = x + 1FLANG_PARSEпусть with a new name, свёртка, or цикл with a храним line
exceptions, throw, panic!there is no word for ita type with a variant for the error, and разбор at the caller
null, undefinedFLANG_TYPE when the result type is differenta type with the variants "present" and "absent"
a lambda as a value: `let f = \x\x * 2`FLANG_UNKNOWN_NAMEa declared function passed as функция «Name»
class inheritanceFLANG_PARSEинтерфейс and several classes
the signs +, *, ==FLANG_PARSEthe words плюс, умножить на, равен
string interpolation: ` Hello, ${name} `the string stays as writtenсоединить ["Hello, ", name] по ""
a loop without a bound: while (true)FLANG_SUGAR_LOOPпока with a шагов не больше or убывает line

A body after the arrow in отобразить, отфильтровать and свёртка is fine: отобразить цены как цена → цена умножить на 2. You cannot store such a body in a name or pass it to your own function.

A function does not touch files, the network or the clock by itself. It returns a description of the action, and the command flang io performs it. Details are on the page The boundary between flang and the host.

What flang adds

FeatureWhat it givesWhere to read
тотальнаяthe compiler proves that the function terminates on any argumentsFunctions that always terminate
требует and обеспечиваетa precondition and a postcondition; the compiler looks for a counterexample and tries to proveYour first proof
теоремаa step-by-step proof for when the compiler did not manage on its ownYour first proof
the types неотрицательное, целое, сотыхa value outside the type is rejected at the callYour own types
flang emitone program becomes code in C, JavaScript and other languagesGenerating code

What surprises on the first day

Next