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

Language reference

This page answers one question: what each construct of the language means and how it is written. Every construct has its form, an example, what the compiler checks, and its limits.

QuestionPage
I have a task — which construct do I useWhich construct to use when
what does this word meanGlossary — in Russian
I have a list and need a sum without duplicates — what do I writeOperations
show me from zero, step by stepTutorial
what does "proved" mean, and how does it differ from "checked"Why and how
the full language contractLanguage specification — in Russian

Glossary: flang words and the usual terms

In flangUsual nameClosest analogue
тип with вариантsenum with data, tagged unionenum in Rust, union in TypeScript
разбор … случайpattern matchingmatch in Rust and Python
если … то … иначеif as an expressionthe ternary operator
пустьconstantconst
отобразить, отфильтровать, свёрткаmap, filter, reducethe same in JavaScript and Python
объект and записьa struct with fields and its valuedataclass, interface
примерa unit test inside the functiondoctest
требуетprecondition: what must hold on inputan assert at the top of a function
обеспечиваетpostcondition: what holds for the result on every inputan assert at the end, but checked for all inputs
тотальная функцияa function the compiler has proved to terminate—
теоремаa proof you write yourself—
планeffects: the function returns a command ("read the file"), the host executes it and calls the function again with the responsereducer, state machine

The proof kernel ("the kernel" below) is the part of the compiler that proves postconditions for all inputs, not only for the examples.

How to read the examples

Every example with a module line is a whole program, and it passes flang check file.flang. A block without a module line shows one declaration of such a program, or one form.

Exit codes of flang check on the examples of this page:

CodeWhat it means
0parsing, types, termination and examples passed
1there is an error; it is named by a FLANG_… code
2all of the above passed, but the laws of some declarations were not computed; the examples of categories without their own equality and the examples of processes answer this way
3only with --proof: at least one postcondition is not proved

A block without highlighting is compiler output. The compiler prints in Russian whatever language the file is written in. The word at the start of a line (FLANG_TYPE, FLANG_PROOF_STEP) is the error code; the codes are explained in the Diagnostics reference.

Words of the output that appear below:

In the outputWhat it means
«сетка N значений», «посчитано на сетке»the law was checked on N values taken from the examples; it is not proved
«замечаний нет»no errors
«проверено только на тестах»checked on the examples only
«доказано», «не доказано»proved, not proved
«ведомость»the proof report
«на веру»accepted without proof

A keyword has four spellings: Russian, English, Esperanto and Chinese. A file uses one of them. The line // surface: en at the top names the language of the file; without it, the language with most keywords in the file wins. A word of another language in the file is an ordinary name. There are 159 concepts; all spellings are in the Glossary (in Russian).

Names of modules, functions, types, examples and postconditions are written in guillemets «…», whichever spelling the keywords use.

What can be typed more than one way

SignHow else it is typedWhere it stands
→->, =>a fold, map, filter, a function type
"text"'text'a string literal
: ( , and the other punctuationfull-width : ( ,a Chinese layout puts them on the same keys

Words come in more than one spelling too: объект and структура (object, structure), свёртка and свертка (fold), равен, равна, равно, равным, равной, равное (equals, in its grammatical forms). All of them are listed in the Glossary.

Module and imports

LineWhat it does
module «Name»first line of the file, required
exports «A», «B»what is visible outside; without the line, everything is
uses «Module»imports every name of the module
uses «Module» only «A», «B»imports the named ones; the other names of the module are unknown in the file
uses «Module» from "path"the same, but the file is named directly
module «Report»
  exports «Total»
  uses «Lists»

total function «Total»
  accepts items: list number
  returns number
  example «duplicates are not counted twice»
    given items equals [3, 1, 3, 2, 1]
    expected 6
  «Сумма» of («Уникальные» of items)

An import with only — two files side by side:

module «Counting core»

total function «Double»
  accepts n: number
  returns number
  example «two»
    given n equals 2
    expected 4
  n times 2

total function «Triple»
  accepts n: number
  returns number
  example «two»
    given n equals 2
    expected 6
  n times 3
module «Counting»
  uses «Counting core» only «Double»

total function «Four»
  returns number
  example «two doubled»
    expected 4
  «Double» of 2

A call of «Triple» in the second file would be the error FLANG_UNKNOWN_NAME: the name is not on the only list.

A module is found by the name on its module «…» line. The file name and the directory play no part. The search goes in this order:

  1. the directory of the file that has the uses line;
  2. every directory above it — as long as the directory holds at least one .flang file;
  3. the library shipped with the compiler.
CaseWhat to do, or what happens
the module is in a subdirectory or elsewherelist the directories in the variable FLANG_MODULE_DIR, separated by colons, or write from "path"; the path is relative to the importing file and works for a package: from "name.flang-package"
two modules with the same name are foundthe error FLANG_IMPORT_AMBIGUOUS with both paths
the module is not foundthe error FLANG_IMPORT_NOT_FOUND
the name of a library moduleis not translated: the list module is called «Lists» in a file with Russian keywords too; uses «Списки» is FLANG_IMPORT_NOT_FOUND
RussianEnglishEsperantoChinese
модульmodulemodule模块
экспортируетexportseksportas导出
используетusesuzas使用
категорияcategorykategorio类别
объект, структураobject, structureobjekto, strukturo对象, 结构
записьrecordrikordo记录
типtypetipo类型
вариантvariantvarianto变体
это———
вложен объект, вложена структураnested object, nested structure—嵌套对象, 嵌套结构
примечаниеnotenoto注

Function

The parts go in this order. The body comes last and is one expression.

PartRequiredWhat it means
totalnothe function always terminates; the compiler proves it
function «Name»yesthe declaration
accepts name: type, name: typenoparameters; types are required
returns typeyesthe result type
requires «name» conditionnoprecondition; the caller must make it true
decreases expressionnoa termination measure: a number that goes down on every recursive call
for all p ensures «name» conditionnopostcondition about result
example «name» / given / expectednoa test: arguments and the expected result
module «Signature»

total function «Share»
  accepts part: nat, whole: nat
  returns number
  requires «divisor is positive» whole is greater than 0
  for all part ensures «share is non-negative» result is at least 0
  example «half»
    given part equals 1
    given whole equals 2
    expected 0.5
  part divided by whole

A call is «Name» of argument and argument. The word and separates arguments; logical "and" is written and also.

RuleDetail
ensures must have a namethe flang check --proof report lists the postcondition under it, and a theorem refers to it by that name; without a name — FLANG_PARSE
flang check and flang test run the examplesa false example is the error FLANG_EXAMPLE, exit code 1
flang emit does not run the examplesit says so in its output and generates the code
requires is checked at run timea violation at the entry of the program is the error FLANG_PRECONDITION
RussianEnglishEsperantoChinese
код символаcharacter codekodo de signo字符码
символ по кодуcharacter by codesigno per kodo按码字符
убываетdecreases——
тотальнаяtotaltotala完全
функцияfunctionfunkcio函数
принимаетacceptsakceptas接受
возвращаетreturnsredonas返回
примерexampleekzemplo示例
даноgivendonite给定
ожидаетсяexpectedatendata期望
история———
хочу———
чтобы———

Totality and measures

The word total obliges the compiler to prove that the function terminates. There are five ways. flang check file.flang --proof --explain shows which one worked for which function.

Way, as the report names itWhen it appliesRun-time check
«композицией» (by composition)no recursionno
«структурой» (by structure)match recurses on a part of the valueno
«точным шагом» (by exact step)a nat parameter goes down by a constantno
«постоянным шагом» (by constant step)a number parameter goes down by a constant and is bounded belowyes
«объявленной мерой» (by declared measure)the function has decreasesyes

decreases goes between returns and the body. Write it when the recursion goes down by arithmetic, not by taking a part of the value:

module «Measure»

total function «GCD»
  accepts a: number, b: number
  returns number
  decreases b
  example «twelve and eighteen»
    given a equals 12
    given b equals 18
    expected 6
  if b equals 0
    then a
    else «GCD» of b and (a modulo b)

Limits:

The body: four forms

The body of a function is one expression: match, fold, if, or a chain of let lines ending in an expression. A цикл (loop) block is a short form that expands into these.

match — pattern matching over a type with variants

module «Tree»

type «Tree»
  variant Leaf
  variant Node contains value: number, left: «Tree», right: «Tree»

total function «Nodes»
  accepts tree: «Tree»
  returns number
  example «a leaf has no nodes»
    given tree equals variant Leaf
    expected 0
  match tree
    case Leaf
      then 0
    case variant Node with left as l and right as r
      then 1 plus («Nodes» of l) plus («Nodes» of r)
PatternWhat it covers
case Namea variant without fields
case variant Name with field as namea variant with its fields bound to names
case empty, case head and taila list or a string
case anyeverything else

The compiler checks that every variant is handled; a missing one is the error FLANG_MATCH_NOT_EXHAUSTIVE. Recursion on a part of the value is proved to terminate without a measure. Induction in a theorem goes over this form.

fold — reduce: one pass over a list

module «Fold»

total function «Product»
  accepts items: list number
  returns number
  example «three factors»
    given items equals [2, 3, 4]
    expected 24
  fold items starting with 1 as acc and x → acc times x

Termination needs no proof: the list is finite and there is one pass.

Limit: the accumulator type is not refined. The sum of the items of a list nat has the type number, and a nat return type gives FLANG_TYPE.

if — if as an expression

module «Branching»

total function «Sum up to»
  accepts n: nat
  returns number
  example «up to zero is zero»
    given n equals 0
    expected 0
  example «up to three is six»
    given n equals 3
    expected 6
  if n is at most 0
    then 0
    else n plus («Sum up to» of (n minus 1))

Both branches are required: without else it is the error FLANG_PARSE. The condition must be a boolean.

The kernel uses the condition as a fact inside its branch. flang check --proof proves the postcondition of this function:

модуль «If as an expression»

тотальная функция «Положительное»
  принимает н: число
  возвращает число
  для всех н обеспечивает «больше нуля» результат больше 0
  если н больше 0
    то н
    иначе 1

let — a constant

module «Binding»

object «Line»
  price is number
  quantity is number

total function «Line cost»
  accepts entry: «Line»
  returns number
  example «two at three hundred»
    given entry equals record «Line» with price equal to 300 and quantity equal to 2
    expected 660
  let net equals entry.price times entry.quantity
  let tax equals 10 percent of net
  net plus tax

Limits: let binds a name once; there is no reassignment. The name is one word or is written in guillemets: let net amount equals … is the error FLANG_PARSE; write let «net amount» equals ….

Types

Scalars

TypeWhat it isWhat to use it for
numberIEEE-754 doubleeverything else, and any division
natan integer in [0, 2⁵³−1]a counter, an index, a count, a length
integeran integer in [−(2⁵³−1), 2⁵³−1]a difference, a balance, an offset, a temperature
weightnon-negative, where +∞ is a valueweight, distance, path cost
hundredthsan integer count of hundredthsmoney: 19.99 is written 1999
thousandthsan integer count of thousandthsrates, shares, exchange rates
stringa stringtext
booleantrue / falsea condition
nulla type with the single value null"no value" as a result

Nesting: nat ≤ integer ≤ number and nat ≤ weight ≤ number. A value of an exact type fits where a wider one is expected; the reverse does not hold.

An exact type gives the kernel the bounds and the integrality of the value, and gives the termination check a lower and an upper bound. number gives nothing.

module «Exact types»

total function «Order in cents»
  accepts price: hundredths, count: nat
  returns number
  example «three at 19.99»
    given price equals 1999
    given count equals 3
    expected 5997
  price times count

total function «Share»
  accepts part: nat, whole: nat
  returns number
  requires «the divisor is positive» whole is greater than 0
  example «a half»
    given part equals 1
    given whole equals 2
    expected 0.5
  part divided by whole

Arithmetic does not keep the exact type: the sum of two nat values is a number.

$ flang check docs/examples/reference/en/natural-sum.flang
модуль «Sum of naturals»: функций 1, из них с доказанным завершением 1; типов 0
FLANG_TYPE в файле docs/examples/reference/en/natural-sum.flang, строка 6, столбец 5: функция «Sum of nats» объявлена как неотрицательное, а тело даёт число
docs/examples/reference/en/natural-sum.flang: не проверено — замечаний 1
$ echo $?
1

So exact types go on parameters and record fields, and the return type is declared number when the body does arithmetic. divided by always gives number. There is no rounding in the language.

Signed zero:

ExpressionResult
(-12) modulo 6, 0 times -5, 0 divided by -50: arithmetic never produces -0
-0 equals 0false: a -0 that comes in as a literal or an input differs from 0
NaN equals NaNtrue: equals on numbers compares like Object.is

Exact numbers without a ceiling: exact integer and exact fraction

exact integer is a non-negative integer of any length. exact fraction is a non-negative fraction of two such integers. Arithmetic on them loses no digits, and addition is associative.

LiteralValue
[7]seven
[0, 1]4 194 304: digits go lowest first, in base 2²²
[]zero
[[1], [3]]one third: numerator and denominator
[[], [1]]zero as a fraction

The literal has no decimal notation.

module «Exact numbers»

note "The digits of an exact integer go lowest first in base 4194304"

total function «Sum»
  accepts a: exact integer, b: exact integer
  returns exact integer
  example «a carry into the next digit»
    given a equals [4194303]
    given b equals [1]
    expected [0, 1]
  example «two to the fifty-third plus one»
    given a equals [0, 0, 512]
    given b equals [1]
    expected [1, 0, 512]
  a plus b

total function «Sum of fractions»
  accepts a: exact fraction, b: exact fraction
  returns exact fraction
  example «a tenth and a fifth»
    given a equals [[1], [10]]
    given b equals [[1], [5]]
    expected [[3], [10]]
  a plus b

total function «Zero fraction»
  returns exact fraction
  [[], [1]]

total function «Share»
  accepts part: exact fraction, whole: exact fraction
  returns exact fraction
  requires «whole is not zero» whole is greater than «Zero fraction»
  example «a third over two fifths»
    given part equals [[1], [3]]
    given whole equals [[2], [5]]
    expected [[5], [6]]
  part divided by whole

total function «Whole units»
  accepts fraction: exact fraction
  returns exact integer
  example «seven halves are three»
    given fraction equals [[7], [2]]
    expected [3]
  example «a third is zero»
    given fraction equals [[1], [3]]
    expected []
  integer part fraction
WhatHow it is written
operations on exact integerplus, minus, times, modulo, comparisons; no divided by
operations on exact fractionplus, minus, times, divided by, comparisons; no modulo
fraction → integerinteger part f — the quotient without the remainder
integer → fractionthe literal [[n], [1]]
LimitWhat happens
an exact number and a number in one operationFLANG_TYPE: «точное целое и число не смешиваются» (they do not mix)
a result below zero: [1] minus [2]FLANG_PROPERTY at run time
division by the zero fractionFLANG_PROPERTY at run time
an unreduced fraction [[2], [4]]FLANG_TYPE: «дробь не сокращена» (the fraction is not reduced)
a literal in the comparison whole is greater than [[], [1]]stays a list: a literal becomes an exact number only in a parameter, in returns and in an argument. The example moves zero into the function «Zero fraction»

Machine words: u8 … u64, i8 … i64

A machine word is a fixed-width integer, like uint32_t in C or u32 in Rust. There are eight types: unsigned u8, u16, u32, u64 and signed i8, i16, i32, i64. Use them for bit fields, checksums and formats with a fixed field width.

The example takes apart the first 32-bit word of an IPv4 header and puts it back together:

module «Machine words»

note "The first word of an IPv4 header: version, header length, type of service, total length"
note "The word in the examples is 1157627924, which is 0x45000014 in hexadecimal"

total function «Protocol version»
  accepts word: u32
  returns u32
  example «version 4 in the top four bits»
    given word equals u32 1157627924
    expected u32 4
  word shifted right by 28

total function «Header length in words»
  accepts word: u32
  returns u32
  example «five words of 32 bits»
    given word equals u32 1157627924
    expected u32 5
  (word shifted right by 24) bitwise and 15

total function «Total packet length»
  accepts word: u32
  returns u32
  example «twenty bytes, mask 0xFFFF»
    given word equals u32 1157627924
    expected u32 20
  word bitwise and 65535

total function «Build the first word»
  accepts version: u32, header: u32, total: u32
  returns u32
  example «back to 0x45000014»
    given version equals u32 4
    given header equals u32 5
    given total equals u32 20
    expected u32 1157627924
  (version shifted left by 28) bitwise or (header shifted left by 24) bitwise or total

total function «Sum modulo the width»
  accepts a: u32, b: u32
  returns u32
  example «4294967295 plus 2 wraps around zero»
    given a equals u32 4294967295
    given b equals u32 2
    expected u32 1
  a plus b with overflow

total function «Header length in bytes»
  accepts word: u32
  returns number
  ensures «at most sixty bytes» result is at most 60
  example «five words are twenty bytes»
    given word equals u32 1157627924
    expected 20
  4 times (to number («Header length in words» of word))

total function «Byte as a number»
  accepts byte: u8
  returns number
  ensures «fits in a byte» result is at most 255
  example «the largest byte»
    given byte equals u8 255
    expected 255
  to number byte

Literals.

FormWhat it is
u32 5a word of type u32 with value 5
u64 "18446744073709551615"a value above 2⁵³−1: decimal digits in quotes
word bitwise and 15a number next to a word takes the type of the word
u8 300the error FLANG_OVERFLOW at check time: 300 does not fit in u8
0xFFthe error FLANG_PARSE: there is no hexadecimal notation; write 255

Operations. Ordinary arithmetic on words checks for overflow. The result modulo 2^w, familiar from C, is written with the words with overflow.

OperationHow it is writtenWhat it gives
checked arithmetica plus b, minus, times, divided by, modulothe exact result; if it does not fit the type or the divisor is zero, the error FLANG_OVERFLOW at run time
modular arithmetica plus b with overflow, likewise minus and timesthe result modulo 2^w
bitwise operationsbitwise and, bitwise or, bitwise xor, bitwise not athe same as &, `\, ^, ~` in C
shiftsshifted left by n, shifted right by nn is below the word width; a right shift of a signed word is arithmetic
rotationsrotated left by n, rotated right by nn is taken modulo the width
comparisonsequals, is less than, is at most and the restvalues are compared with their sign
full producta times b with double widtha record with the fields «старшая» (high) and «младшая» (low); unsigned words only

Bitwise operations and shifts have the precedence of addition and read left to right. Use parentheses, as the function «Header length in words» does.

Conversions. A word does not mix in one operation with a number or with a word of another width: a plus b with a: u32 and b: u8 is the error FLANG_TYPE with the hint «нужен перевод «u32 …»» (a conversion u32 … is needed).

FormWhat it does
u32 b with b: u8a word of another width with the same value
u8 n with n: natnumber → word
to number wordword → number; a u64 value above 2⁵³−1 gives FLANG_OVERFLOW
to text wordthe decimal form with a sign

A conversion keeps the value. If it does not fit the new type, execution stops with FLANG_OVERFLOW; the high bits are not dropped.

What is checked.

$ flang check docs/examples/reference/en/machine-words.flang
модуль «Machine words»: функций 7, из них с доказанным завершением 7; типов 0
docs/examples/reference/en/machine-words.flang: проверено — доказано 1, проверено только на тестах 1, не доказано 0 (постусловий и утверждений 2); замечаний нет
$ flang check docs/examples/reference/en/machine-words.flang --proof
модуль «Machine words»: функций 7, завершение доказано у 7
постусловие «at most sixty bytes» функции «Header length in bytes» — проверено только на тестах (примеров 1)
постусловие «fits in a byte» функции «Byte as a number» — доказано
итог: постусловий и утверждений 2 — доказано 1, проверено только на тестах 1, не доказано 0
docs/examples/reference/en/machine-words.flang: доказано не всё — доказано 1, проверено только на тестах 1, не доказано 0, ложно 0 (постусловий и утверждений 2); независимая проверка повторила 0 из 1 — код возврата 3
подробный отчёт: flang check docs/examples/reference/en/machine-words.flang --proof --explain
$ echo $?
3

The postcondition «fits in a byte» is proved for every input: the argument is declared u8, and the compiler knows the range of that type. The postcondition «at most sixty bytes» is checked only on the example of the function: the kernel draws no conclusion from the mask bitwise and 15. One postcondition is not proved, so the exit code is 3.

About a word the kernel proves only the range of its type, and only for unsigned arguments of a function. A postcondition about the result of a mask, a shift or an addition is checked on the examples.

Division in a total function. The keyword total promises that the computation ends and that no builtin in the body stops with an error. A quotient of words with a divisor nothing is known about can fail, and flang check does not accept such a function. File docs/examples/reference/en/word-division-total.flang:

module «Word division total»

total function «Packets in the buffer»
  accepts buffer: u64, packet: u64
  returns u64
  example «two packets of 1500 fit in 4096 bytes»
    given buffer equals u64 4096
    given packet equals u64 1500
    expected u64 2
  buffer divided by packet
$ flang check docs/examples/reference/en/word-division-total.flang
модуль «Word division total»: функций 1, из них с доказанным завершением 1; типов 0
FLANG_NOT_TOTAL в файле docs/examples/reference/en/word-division-total.flang, строка 10, столбец 10: функция «Packets in the buffer» объявлена тотальной, а встроенная операция «делить на» может отказать при работе: делитель может оказаться нулём; добавьте «требует» с условием на аргументы, проверку перед вызовом или снимите пометку «тотальная»
docs/examples/reference/en/word-division-total.flang: не проверено — замечаний 1
$ echo $?
1

Without the total mark a function may fail: the check accepts it, and the error happens at run time. File docs/examples/reference/en/word-division.flang:

module «Word division»

function «Packets in the buffer»
  accepts buffer: u64, packet: u64
  returns u64
  example «two packets of 1500 fit in 4096 bytes»
    given buffer equals u64 4096
    given packet equals u64 1500
    expected u64 2
  buffer divided by packet

total function «Packets in the buffer or zero»
  accepts buffer: u64, packet: u64
  returns u64
  example «a packet of zero length gives zero packets»
    given buffer equals u64 4096
    given packet equals u64 0
    expected u64 0
  if packet equals 0
    then u64 0
    else buffer divided by packet
$ flang check docs/examples/reference/en/word-division.flang
модуль «Word division»: функций 2, из них с доказанным завершением 1; типов 0
без доказанного завершения: «Packets in the buffer»
docs/examples/reference/en/word-division.flang: проверено — доказано 0, проверено только на тестах 0, не доказано 0 (постусловий и утверждений 0); замечаний нет

A run of the first function with a divisor of 0 stops with an error:

$ flang run docs/examples/reference/en/word-division.flang --function "Packets in the buffer" --args '{"buffer":4096,"packet":0}'
доказано: утверждений 0
FLANG_OVERFLOW: 4096 «div» 0: деление на ноль
$ echo $?
1

The line «доказано: утверждений 0» says that the file has no unproved postconditions. The next one is the division error: div is the internal name of divided by. Exit code 1. The second function is total: the division stands in an if branch after the divisor is checked. The other way is a precondition requires «the packet is not empty» packet is greater than 0. An addition of words that does not fit the type is not caught by the check in a total function: it stops at run time with the same error FLANG_OVERFLOW.

What machine words do not have.

MissingWhat to use
a byte array type (байты is an unknown type)list u8
a fixed-size arraya list and a postcondition about its length
hexadecimal literalsa decimal number; keep the hexadecimal form in the name of an example or in a note line
division on exact integerfor fields up to 64 bits, u64 and shifted right by
proofs of conditions about bitsexamples on the function

List

FormWhat it is
list Type, list of Typethe type of a homogeneous list
[1, 2, 3], list of 1 and 2 and 3a literal
empty list, []the empty list

A list is covariant: list nat fits where list number is expected.

Record, type with variants, alias

module «Types»

object «Line»
  title is string
  price is number
  discount may be number

type «Invoice» это list «Line»

type «Answer»
  variant Ok contains value: number
  variant Failed contains reason: string

total function «Check price»
  accepts entry: «Line»
  returns «Answer»
  example «price is there»
    given entry equals record «Line» with title equal to "bolt" and price equal to 30
    expected variant Ok with value equal to 30
  example «zero is not a price»
    given entry equals record «Line» with title equal to "nut" and price equal to 0
    expected variant Failed with reason equal to "price is not positive"
  if entry.price is greater than 0
    then variant Ok with value equal to entry.price
    else variant Failed with reason equal to "price is not positive"
FormWhat it means
object «Line»a record with fields
name is type, «name»: typea field; the two spellings are equivalent
may bethe field can be absent; the examples may leave it out
record «Line» with title equal to "bolt" and price equal to 30a record value
entry.pricereading a field
type «Answer» with variantsa type with variants (an enum with data)
variant Ok with value equal to 30a value of a variant; taken apart with match
type «Invoice» is list «Line»an alias; the Russian word это in place of is is accepted in an English file too, as in the example

Values are immutable: a field does not change, a new record is built. Record types are invariant.

This is how Optional and Result are written: "found" and "not found" are different variants, and the caller has to match on them. null is not used for this.

Type parameter (generic)

type «Maybe» of «A»
  variant «Some» contains value: «A»
  variant «None»

Type parameters are introduced by the word of and substituted by it too: «Maybe» of number. At a call they are inferred from the values; there is no syntax to write them explicitly. A whole program with such a type is in the section on the monad.

Function type

FormExample
in wordsфункция из числа и строки в признак (Russian keywords)
with an arrownumber → number

Both give the same type. With English keywords the form in words, function from number to number, is the error FLANG_PARSE: to number is taken by the built-in form of that name. Write the arrow there.

Expressions

WhatHow it is written
function call«Name» of argument and argument
record fieldvalue.field
record field by wordfield «x» at value, field «x» from value
arithmeticplus, minus, times, divided by, modulo, percent of
comparisonequals, is not equal to, is greater than, is less than, is at most, is at least
logicnot, and also, or
literals12, "text", true, false, null, [1, 2]

Precedence, from weakest to strongest:

or  <  and also  <  not  <  comparisons  <  plus minus  <  times divided  <  of  .

Spellings cannot be guessed by analogy; take them from the Glossary.

Line breaks inside parentheses

A line with an unclosed ( continues on the following lines up to the closing ). A line break inside parentheses means a space; the indentation of the continuation plays no part.

утверждение «три вызова схлопываются»
  для всех а: строка
  утверждаем («Приклеить пустое» от
      («Приклеить пустое» от
        («Приклеить пустое» от а))) равен а
RuleDetail
an error inside such an expressionnames its real line
inside […]a line break separates list items, like a comma; a long item goes into parentheses
words made of several words (and also, is at least)are not split over two lines

A string over several lines

A "…" literal may continue on the next line; the line break is part of the value. Single quotes '…' are the same literal.

module «Two spellings»

total function «Through a line break»
  returns string
  example «the same as with \n»
    expected "first\nsecond"
  "first
second"

total function «In single quotes»
  returns string
  example «the same quotes, only different»
    expected "text"
  'text'

The indentation of a continuation line is part of the value: "first⏎ second" equals "first\n second". For text inside an indented body there is the text block.

The text block """

Three double quotes open a block. The text starts on the next line, and the common indentation is removed:

total function «Help»
  returns string
  """
  Commands:
    .help   this text
    .quit   leave
  """

The value is "Commands:\n .help this text\n .quit leave\n". It is the same string as a literal with \n, not a new kind of string.

RuleWhat it means
nothing after the opening """ on its linethe text starts on the next line; another character there is the error FLANG_LEX at its position
the first """ without a backslash before it closesthe rest of that line is read as usual
common indentationthe smallest indentation among the non-blank lines and the line of the closing quotes; a tab counts as one character, like a space
every line loses the common indentationa line of only spaces becomes empty; trailing spaces stay
closing quotes on their own linethe text ends with a line break; on the last text line it does not
backslash sequences are those of "…"\n, \t, \", \\, \uXXXX; the quotes " and ' inside are written as they are
an unclosed blockthe error FLANG_LEX at the opening quotes
a bad \uXXXXan error at the line and column of the backslash itself
interpolationthere is none
total function «No line break at the end»
  returns string
  example «closing quotes on the last text line»
    expected "first\nsecond"
  """
  first
  second"""

total function «Indented inside»
  returns string
  example «closing quotes to the left of the text set the common indentation»
    expected "  first\n"
  """
    first
  """
RussianEnglishEsperantoChinese
пустьletestu令
еслиifse如果
тоthentiam那么
иначеelsealie否则
разборmatchkongruo匹配
случайcasekazo情况
отofde的
иandkaj和
и притомand alsokaj ankaŭ并且
илиoraŭ或者
неnot—非
сwithkun带有
изfromel从
толькоonlynur仅
в, кto, into, in, ontoal到
поbyper按
уatĉe在
какaskiel作为
гдеwherekie其中
начиная сstarting withkomencante per起始于

Built-in forms over lists and strings

FormWhat it does
length Xthe length of a list or a string
head X, tail X, emptyparts of a list and of a string
item N in Xthe N-th element of a list
char N in Xthe N-th character of a string
add X to Y, prepend X to Yat the end and at the front of a list
map X as name → bodymap: a new list
filter X where name → conditionfilter: the items that fit
substring X from A to Ba slice of a string
split X by Ystring → list of strings
join X by Ylist of strings → string
join X with Yconcatenating two strings
contains, begins withchecks over a string
to number, to number or failure, to textconversions
character code Xcharacter → its code point as a number
character by code Ncode point → a one-character string; an error on a fraction, outside [0, 1114111], and on a lone surrogate
decompose X into charactersstring → list of characters
hash256 Xthe SHA-256 of a string as a hexadecimal string

Indexes start at one, and ranges include both ends. An index outside the list stops execution with the error FLANG_BUILTIN_ARGS. Every form has its own prepositions. Everything else is a library function; which one solves which task is on Operations.

module «Built-in forms»

total function «Long words»
  accepts text: string
  returns list string
  example «the short word is dropped»
    given text equals "one twice thrice"
    expected ["twice", "thrice"]
  filter (split text by " ") where word → (length word) is greater than 3

total function «Word lengths»
  accepts words: list string
  returns list number
  example «three words»
    given words equals ["one", "twice", "thrice"]
    expected [3, 5, 6]
  map words as word → length word
module «Strings»

total function «Second word»
  accepts text: string
  returns string
  example «two words»
    given text equals "one twice"
    expected "twice"
  example «one word — no second one»
    given text equals "one"
    expected ""
  let words equals split text by " "
  if (length words) is at least 2 then item 2 in words else ""

total function «First three»
  accepts text: string
  returns string
  example «cut from the head»
    given text equals "abcdef"
    expected "abc"
  example «short text as a whole»
    given text equals "ab"
    expected "ab"
  if (length text) is at least 3 then substring text from 1 to 3 else text

total function «Glued»
  accepts parts: list string
  returns string
  example «joined with a comma»
    given parts equals ["a", "b"]
    expected "a,b"
  join parts by ","

total function «Initial»
  accepts text: string
  returns string
  example «first letter»
    given text equals "abc"
    expected "a"
  example «an empty string has no letter»
    given text equals ""
    expected ""
  if (length text) is at least 1 then char 1 in text else ""
module «Character by character»

total function «Shift a letter»
  accepts letter: string
  returns string
  example «a becomes b»
    given letter equals "a"
    expected "b"
  example «an empty string stays empty»
    given letter equals ""
    expected ""
  if (length letter) is at least 1 then «Character with code» of ((character code letter) plus 1) else ""

total function «Character with code»
  accepts point: nat
  returns string
  example «a code past the end of Unicode is no character»
    given point equals 1114112
    expected ""
  if point is at most 55295
    then character by code point
    else (if (point is at least 57344) and also (point is at most 1114111) then character by code point else "")

total function «Fingerprint»
  accepts text: string
  returns string
  example «fingerprint of the empty string»
    given text equals ""
    expected "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
  hash256 text

total function «Word is usable»
  accepts word: string
  returns flag
  example «a plain word is usable»
    given word equals "house"
    expected yes
  example «an empty one is not»
    given word equals ""
    expected no
  ((length word) is not equal to 0) and also (not (word contains " "))

total function «Words»
  accepts text: string
  returns list of string
  example «two words»
    given text equals "one two"
    expected ["one", "two"]
  split text by " "

total function «Nothing»
  accepts text: string
  returns null
  example «the value of emptiness»
    given text equals "a"
    expected null
  null

A record field by word:

module «Field by word»

object «Point»
  «x»: number
  «y»: number

total function «Abscissa»
  accepts point: «Point»
  returns number
  example «the first coordinate»
    given point equals record «Point» with «x» equal to 3 and «y» equal to 4
    expected 3
  field «x» at point

total function «Ordinate»
  accepts point: «Point»
  returns number
  example «the second coordinate»
    given point equals record «Point» with «x» equal to 3 and «y» equal to 4
    expected 4
  field «y» from point
RussianEnglishEsperantoChinese
отобразитьmapmapi映射
отфильтроватьfilterfiltri过滤
свёртка, сверткаfoldfaldo折叠
длинаlengthlongo长度
целая частьinteger partentjera parto整数部分
символcharsigno字符
разложитьdecomposemalkomponi分解
на символыinto charactersen signojn为字符
подстрокаsubstringsubĉeno子串
соединитьjoinkunigi连接
разделитьsplitdividi分割
содержитcontainsenhavas包含
начинается сbegins withkomenciĝas per开始于
к числу или бедаto number or failureal nombro aŭ fiasko转数字或失败
к числуto numberal nombro转数字
к строкеto textal teksto转文本
хеш256hash256—哈希256
головаheadkapo头
хвостtailvosto尾
элементitemero元素
голова и хвостhead and tailkapo kaj vosto头和尾
пустоemptymalplena空
пустой списокempty listmalplena listo空列表
список изlist oflisto de列表由
списокlistlisto列表
добавитьaddaldoni添加
приписатьprependantaŭmeti前置
любоеanyajna任意

Functions as values

module «Function as a value»

total function «Double»
  accepts x: number
  returns number
  x times 2

total function «Add»
  accepts a: number, b: number
  returns number
  a plus b

total function «Apply twice»
  accepts f: number → number, x: number
  returns number
  f of (f of x)

total function «Trial»
  returns number
  example «five doubled twice»
    expected 20
  «Apply twice» of function «Double» and 5

total function «Trial with capture»
  returns number
  example «ten added twice»
    expected 25
  «Apply twice» of (function «Add» with a equal to 10) and 5
FormWhat it means
function «Name»a function as a value
function «Name» with a equal to 10the same with the parameter a fixed: partial application by parameter name
f of 5applying a value
number → numberthe type

Limits:

Short forms

The compiler expands four forms into ordinary flang before parsing. The proof and the termination of a short form are those of its expanded text. Whole programs with commands and output: Loops, classes, interfaces.

FormWhat it expands intoError for a malformed form
a one-line headerфункция, принимает, возвращает on three linesFLANG_SUGAR_HEADER: возвращает before принимает
цикл (loop)a свёртка (fold) or a function with разбор (match)FLANG_SUGAR_LOOP: no в конце, or a пока without a bound
класс (class)an объект and functions over itFLANG_SUGAR_CLASS: станет changes a field that does not exist
интерфейс (interface)a тип with a variant per class and functions with разборFLANG_SUGAR_INTERFACE: a class lacks a required method

The errors name the line and column of the source text.

One-line header

тотальная функция «Меньшее из двух» принимает первый: число, второй: число возвращает число
  если первый не больше второй то первый иначе второй

цикл — steps with kept values

цикл «Сделка»
  для каждого цена из хвост
  храним минимум: число равным голова, прибыль: число равным 0
  в конце прибыль
  пусть сегодня равно цена минус минимум
  пусть ниже равно если цена меньше минимум то цена иначе минимум
  пусть лучше равно если сегодня больше прибыль то сегодня иначе прибыль
  дальше: минимум станет ниже, прибыль станет лучше
LineWhat it means
для каждого х из списокa step for every item
пока условиеsteps while the condition holds; a bound is required
шагов не больше n, иначе va bound for пока: a step budget and the answer when it runs out
убывает мa bound for пока: a measure
храним имя: тип равным значениеthe values kept between steps
дальше: х станет еthe next step
a branch without дальшеthe answer of the loop: an early exit
в конце выражениеthe answer when the list has ended

A loop over a list without an early exit becomes a свёртка; with an early exit it becomes a function with разбор over the rest of the list; пока becomes a function with a step budget or with a measure.

Limits:

класс — an object and functions over it

класс «Счёт»
  владелец: строка
  остаток: число
  всегда «остаток не отрицателен» остаток не меньше 0

  метод «Положить» принимает сумма: число
    требует «сумма не отрицательна» сумма не меньше 0
    остаток станет остаток плюс сумма

  метод «Пусто ли» возвращает признак
    остаток равен 0
FormWhat it expands into
класс «Счёт»объект «Счёт»
метод «Положить», метод «Пусто ли»the functions «Счёт: Положить» and «Счёт: Пусто ли» with the first parameter этот: «Счёт»
a field name in a methodостаток → этот.остаток
lines поле станет значение at the end of a methodthe method returns a new «Счёт»; the fields not named pass unchanged
всегда «имя» условиетребует on every method and обеспечивает «остаток не отрицателен после» on a method that returns «Счёт»

A call is «Счёт: Положить» от счёт и 30. In this example the kernel proves the postcondition «остаток не отрицателен после».

интерфейс — required methods and laws

интерфейс «Фигура»
  метод «Площадь» возвращает число
  метод «Название» возвращает строка
    обеспечивает «название не пусто» (длина результат) больше 0
    "фигура"

класс «Квадрат» есть «Фигура»
  сторона: число
  метод «Площадь» возвращает число
    сторона умножить на сторона
  метод «Название» возвращает строка
    "квадрат"
FormWhat it expands into
интерфейс «Фигура»тип «Фигура» with a variant for every class of the file that есть «Фигура»
a метод of the interfacethe function «Фигура: Площадь» with разбор over the classes
a method without a bodyrequired in every class
a method with a bodythe default implementation
обеспечивает on a method of the interfacea law: a postcondition on the method of every class and on «Фигура: Название», where the kernel proves it by induction over «Фигура»

A value of the interface is вариант «Квадрат» с значение равным квадрат.

Contracts and proofs

WordWhere it goesWho must make it trueWhat checks it
requires «name» conditionafter returns, before the bodythe callerat run time, at the entry of the program
for all p ensures «name» conditionthe same place, after requiresthe functionthe kernel at check time; if not proved, at run time on every return
totalbefore the word functionthe compilerat check time; see "Totality and measures"
theorem «name»top level, next to the functionyouthe kernel at check time, step by step
утверждение «name» (statement)top level, without a functionyouthe kernel at check time; included in --proof --json

flang check without keys does not report whether postconditions are proved. flang check --proof does: it prints the proof report and returns code 3 if at least one postcondition is not proved. flang run runs a program with an unproved postcondition only with the key --trust.

requires — a precondition

requires «name» condition — what must hold for a call to be valid. The example is the function «Share» in the section Function.

WhereHow it works
inside the functionthe condition is an assumption; a theorem uses it through by hypothesis, without induction too
at the entry of the programa violation is the error FLANG_PRECONDITION
on internal callsno run-time check is generated

ensures — a postcondition

for all p ensures «name» condition — what holds for result on every input. result in the condition is the returned value.

module «Postcondition»

total function «Double all»
  accepts items: list number
  returns list number
  for all items ensures «length is preserved» (length result) equals (length items)
  example «three items»
    given items equals [1, 2, 3]
    expected [2, 4, 6]
  map items as x → x times 2

The kernel first tries to prove the condition. If it is proved, the generated code has no check. If not, the condition is checked on every return, and a violation stops execution with FLANG_PROPERTY.

The name is required. A theorem refers to the postcondition by it, and so does by property in another proof.

для всех … из …: — a condition on every element of a list

The quantifier (for all … from …: in words) is written in the postcondition itself. A colon separates its body.

модуль «For all after a filter»

тотальная функция «Только положительные»
  принимает элементы: список числа
  возвращает список числа
  обеспечивает «все положительны» для всех п из результат: п больше 0
  пример «Смесь»
    дано элементы равно [3, 0, 5]
    ожидается [3, 5]
  отфильтровать элементы где э → э больше 0

The kernel proves such a postcondition from the form of the list the body builds:

Form of the bodyProved
empty listyes
the literal [1, 2]yes
filter L where x → C, where C is the condition being provedyes
add X to L, prepend X to Lyes, if the condition holds for X and for L
if C then A else Byes, if it holds in both branches
mapno

The body after the colon is a condition again, so quantifiers nest:

  обеспечивает «каждый с каждым положителен» для всех х из результат: для всех м из результат: м больше 0
RuleDetail
"there exists"есть такой м, а именно х, что …: you name the value
without а именноthe kernel looks for the value among the subterms of the goal, at most eight; it does not search by values
the named value does not fitthe error FLANG_PROOF_STEP
where a quantifier may standinside a condition too: under and also and under if … then … else
where a quantifier endsat the first top-level colon; everything to the right is the body
for all n ensures …that is the variable of the postcondition, not a quantifier inside the condition

theorem

A theorem is written when the kernel did not prove a postcondition by itself.

module «Theorem»

total function «Sum up to»
  accepts n: nat
  returns number
  for all n ensures «sum up to is non-negative» result is at least 0
  example «no steps left»
    given n equals 0
    expected 0
  if n is at most 0
    then 0
    else n plus («Sum up to» of (n minus 1))

theorem «sum up to is non-negative»
  given n: nat
  claim result is at least 0
  induction on n decreases n
    case 0
      then by example «no steps left»
    case any
      then by hypothesis
  therefore proved
LineWhat it does
theorem «name»the same name as the postcondition it proves
given name: typethe variables
claim conditionwhat is being proved
induction on name decreases measureproof by induction; decreases is needed only where a number goes down, not a part of a value
case … / then justificationone step
next claim by justificationan intermediate fact; later steps can use it
therefore provedthe end

Induction goes over a match on a type with variants and over a decreasing number. It is not required; a short theorem is one justification:

module «Property»

total function «Double all»
  accepts items: list number
  returns list number
  for all items ensures «doubling keeps the length» (length result) equals (length items)
  map items as x → x times 2

total function «Through doubling»
  accepts items: list number
  returns list number
  for all items ensures «through doubling the length is the same» (length result) equals (length items)
  «Double all» of items

theorem «through doubling the length is the same»
  given items: list number
  claim (length result) equals (length items)
  by property «doubling keeps the length»
  therefore proved

How to bring a theorem to «доказано»: Proving by hand.

утверждение — a condition without a function

модуль «Free statements»

утверждение «длина пустого списка нулевая»
  утверждаем (длина пустой список) равен 0

утверждение «ноль нейтрален при сложении»
  для всех н: неотрицательное таких что н больше 0
  утверждаем (н плюс 0) равен н

The kernel checks it exactly like a postcondition, and it appears in flang check --proof --json. The line для всех имя: тип таких что условие gives the variables and an assumption. The assumption н больше 0 is needed here: неотрицательное (nat) admits minus zero at run time, and without the assumption the second condition is false.

An утверждение can also be proved by a theorem with the same name. Limit: an утверждение over a type with a parameter (список «А») is the error FLANG_PARSE.

Induction over a type you declared yourself

индукция по (induction on) works for your own types with variants too: the induction principle comes from the type declaration.

модуль «Own natural»

тип «Нат»
  вариант «Ноль»
  вариант «Следующий» содержит пред: «Нат»

тотальная функция «К числу»
  принимает н: «Нат»
  возвращает число
  разбор н
    случай вариант «Ноль»
      то 0
    случай вариант «Следующий» с пред как п
      то («К числу» от п) плюс 1

утверждение «шаг растит счёт на один»
  для всех н: «Нат»
  утверждаем («К числу» от (вариант «Следующий» с пред равным н)) равно ((«К числу» от н) плюс 1)

теорема «шаг растит счёт на один»
  дано н: «Нат»
  утверждаем («К числу» от (вариант «Следующий» с пред равным н)) равно ((«К числу» от н) плюс 1)
  индукция по н
    случай вариант «Следующий» с пред как п
      то по предположению
  следовательно доказано

The report says «доказано индукцией» (proved by induction). decreases is not needed: a part of the value gets smaller, not a number.

Justifications for a step

Every step must have a justification, or it does not parse.

JustificationUse it whenLimit
by property «name»the step contains a call to a function that has a postcondition with that namethe postcondition being proved cannot be named
by hypothesisthere is an assumption: the induction hypothesis (induction on) or the function's precondition (requires)the hypothesis has no name; there is one per case
by example «name»the case has one value, and the function has an example with that namean example does not prove a pattern with bound names
under law «name»the name is a monoid, monad or isomorphism of this module, or one of the six inference rulesany other name is an error

by property

Uses the postcondition of another function. The kernel finds the calls of that function in the step and substitutes its postcondition: the parameters become the arguments of the call, and result becomes the call itself. The example is the theorem «through doubling the length is the same» above.

Some function of the module must have a postcondition with that name. A reference to the postcondition that is being proved is an error:

$ flang check docs/examples/reference/refused/circular-property.flang
модуль «Circle»: функций 1, из них с доказанным завершением 1; типов 0
FLANG_PROOF_STEP в файле docs/examples/reference/refused/circular-property.flang, строка 12, столбец 3: шаг 1, теорема «длина сохраняется»: «по свойству «длина сохраняется»» ссылается на то самое постусловие, которое сейчас доказывается — это круг. Часть значения обосновывает «по предположению», а не ссылка на саму цель. к этому месту не известно ничего, кроме гипотез «дано»
docs/examples/reference/refused/circular-property.flang: не проверено — замечаний 1
$ echo $?
1

by hypothesis

Uses an assumption: the induction hypothesis (the same condition for a smaller part of the value) or the function's precondition. The theorem «sum up to is non-negative» above uses the induction hypothesis. The hypothesis of another case cannot be used.

With neither a hypothesis nor a precondition, the message says what is missing:

$ flang check docs/examples/reference/refused/missing-hypothesis.flang
модуль «Without a hypothesis»: функций 1, из них с доказанным завершением 1; типов 0
FLANG_PROOF_INDUCTION_STEP в файле docs/examples/reference/refused/missing-hypothesis.flang, строка 12, столбец 3: шаг 1, теорема «половина неотрицательна»: «по предположению» стоит вне индукции, а допущений у этой цели нет ни одного: ни посылки индукции (её даёт `индукция по`), ни предусловия функции (его даёт `требует`). Предполагать не о чем. к этому месту не известно ничего, кроме гипотез «дано»
docs/examples/reference/refused/missing-hypothesis.flang: не проверено — замечаний 1
$ echo $?
1

by example

Proves a case by running an example. An example is one value, so it fits only a case with one value: case 0, case Leaf, case empty.

case variant Node with left as l covers infinitely many values; use by hypothesis there.

The example is looked up by name on the function whose postcondition is being proved. If there is no example with that name, the message gives both names.

under law

Refers to a monoid, monad or isomorphism declared in the module, or to an inference rule by name. Another name is an error:

$ flang check docs/examples/reference/refused/unknown-law.flang
модуль «Without a law»: функций 1, из них с доказанным завершением 1; типов 0
FLANG_PROOF_STEP в файле docs/examples/reference/refused/unknown-law.flang, строка 12, столбец 3: теорема «то же»: шаг 1 (чего не бывает, без основания): правило «чего не бывает» ведомости ядро пока не проверяет; проверяет шесть: Н1, Н3, Н5, О1, О10, Разв2
docs/examples/reference/refused/unknown-law.flang: не проверено — замечаний 1
$ echo $?
1

The message says: the kernel does not check such a rule; by name it checks six rules — Н1, Н3, Н5, О1, О10 and Разв2.

A step that names its rule

A step can name the inference rule and the facts it rests on. The kernel then checks that application of the rule instead of searching for a proof itself.

теорема «результат не больше десяти»
  дано а: число
  дано б: число
  утверждаем результат не больше 10
  затем а не больше б по закону «О1» из строки 5
  затем б не больше 10 по закону «О1» из строки 6
  затем а не больше 10 по закону «О10» из 1 и 2
  по закону «Разв2» из 3 и строки 9
  следовательно доказано
FormWhat it means
из строки Nthe source line the fact comes from: a precondition or the body
из K, из K и Lthe numbers of earlier steps of this theorem
«Н1», «Н3», «Н5»rules of non-negativity by construction
«О1», «О10»rules of order by construction
«Разв2»unfolding the definition of a function

The independent proof check (the program checker) repeats a step that names its rule. A step without a name it accepts without re-checking.

The full list of the kernel's rules: Kernel specification (in Russian).

Categories: a pipeline declared as data

Objects, arrows (morphisms) between them and their composition are declared, not called. In detail, with the output of every check: The categorical surface.

module «Order pipeline»

object «Order»
  amount is number

object «Shipment»
  code is number

object «Invoice»
  total is number

total function «Ship order»
  accepts order: «Order»
  returns «Shipment»
  record «Shipment» with code equal to order.amount

total function «Bill shipment»
  accepts shipment: «Shipment»
  returns «Invoice»
  record «Invoice» with total equal to shipment.code

morphism «ship» from «Order» to «Shipment»
  gives «Ship order»
  law «the shipment code comes from the order amount»
    example «an ordinary order»
      given order equals record «Order» with amount equal to 500
      expected record «Shipment» with code equal to 500

morphism «bill» from «Shipment» to «Invoice»
  gives «Bill shipment»

morphism «process» это «bill» after «ship»

chain «process an order»
  first «ship»
  next «bill»
ConstructionWhat it does
object «X»a kind of data; fields as in a record
morphism «m» from «A» to «B»an arrow with declared ends
gives «F»the function the arrow is
law «name» with examplesa condition on the arrow; checked on the values of the examples
«b» after «a»composition; the right one runs first
chain / first / nextthe same composition in reading order
identity «X»the identity arrow of an object
category «C» with a list of arrowsthe arrows the module declares as its own
isomorphism / forward morphism / inverse morphisma pair of arrows there and back
functorcarries the objects and arrows of one category into another
field «a» maps to field «b»under an object line of a functor: which field of the image a field goes to
bifunctor / objects / morphismsa functor of two arguments: a pair of objects → an object, a pair of arrows → an arrow
embedding, intersectiona part of an object and the common part of two objects
monoid / carrier / operation / identity / inverse elementan operation with its own laws
property «name»a law of one operation; the names are Russian in every file: коммутативность (commutativity), идемпотентность (idempotence), дистрибутивность (distributivity), монотонность (monotonicity), частичный порядок (partial order)

Declarations from the whole programs in docs/examples/reference/en/:

isomorphism «Payment and receipt» from «Payment» to «Receipt»
  forward morphism «issue»
  inverse morphism «by receipt»
functor «Order to payment» from «Orders» to «Payments»
  object «Order» maps to «Payment» gives «Payment for order»
    field «amount» maps to field «cents»
    field «cancelled» maps to field «refunded»
  morphism «cancel order» maps to morphism «refund payment»
bifunctor «Pair» from «Orders» and «Orders» to «Orders»
  objects «Order» and «Order» map to «Order pair»
  morphisms «cancel order» and «cancel order» map to morphism «cancel both»
embedding «Urgent among orders» from «Urgent» to «Order» gives «Urgent order»
intersection «Urgent and paid» from «Urgent» and «Paid» to «Order»

Monoids and folding in parts

module «Monoids»

total function «Add exact»
  accepts a: exact integer, b: exact integer
  returns exact integer
  example «a carry into the next digit»
    given a equals [4194303]
    given b equals [1]
    expected [0, 1]
  a plus b

total function «Exact zero»
  returns exact integer
  []

monoid «Exact sum»
  carrier exact integer
  operation «Add exact»
  identity []

total function «Total»
  accepts sums: list exact integer
  returns exact integer
  example «three terms»
    given sums equals [[1], [2], [3]]
    expected [6]
  fold sums starting with «Exact zero» as acc and x → «Add exact» of acc and x

total function «Add numbers»
  accepts a: number, b: number
  returns number
  example «two and three»
    given a equals 2
    given b equals 3
    expected 5
  a plus b

total function «Opposite»
  accepts a: number
  returns number
  example «three»
    given a equals 3
    expected -3
  0 minus a

monoid «Number sum»
  carrier number
  operation «Add numbers»
  identity 0
  inverse element «Opposite»

property «коммутативность»
  carrier number
  operation «Add numbers»

total function «Squares»
  accepts numbers: list number
  returns list number
  example «three numbers»
    given numbers equals [1, 2, 3]
    expected [1, 4, 9]
  map numbers as x → x times x

A monoid names its carrier, its operation and the identity of the operation. The kernel tries to prove associativity and both identities:

$ flang check docs/examples/reference/en/monoids.flang
моноид «Number sum»: сетка 5 значений, троек 125, нарушений 0 — ПОСЧИТАНО НА СЕТКЕ, не доказано
свойство «коммутативность» у «Add numbers»: сетка 3 значений, пар 9, нарушений 0 — ПОСЧИТАНО НА СЕТКЕ, не доказано
модуль «Monoids»: функций 6, из них с доказанным завершением 6; типов 0
моноид «Exact sum»: сочетательность и единица доказаны ядром — свёртка операцией «Add exact» считается кусками на всех потоках
моноид «Number sum»: сочетательность и единица ядром НЕ доказаны — свёртка операцией «Add numbers» идёт по порядку на одном потоке
docs/examples/reference/en/monoids.flang: проверено — доказано 0, проверено только на тестах 0, не доказано 0 (постусловий и утверждений 0); замечаний нет
Line of the outputWhat it means
«сочетательность и единица доказаны ядром»associativity and identity are proved: a fold whose body is a call of the operation on the accumulator and the item is computed in parts on several threads in the generated code
«ядром НЕ доказаны»not proved: over number associativity is false, and the fold runs in order on one thread
«ПОСЧИТАНО НА СЕТКЕ, не доказано»the law was checked on the values of the examples: 5 values, 125 triples, no violations

A map whose body calls only functions with proved termination is generated the same way. Which targets compute in parts: Parallel map and the monoid fold (in Russian).

inverse element «F» declares a monoid with an inverse. A property whose name is not one of the five listed — an English name such as «commutativity» included — is the error FLANG_UNKNOWN_PROPERTY. A property of an operation that has no examples is the error FLANG_PROPERTY_NOT_JUDGED: there is nothing to compute it on.

What the compiler checks

Laws are checked on a finite set of values taken from the examples. That is not a proof, and the output gives the size of the set:

$ flang check flang/ct/order-shipment.flang
категория «Отгрузки»: сетка 5 значений на 3 объектах, троек стрелок 7, нарушений 0 — ПОСЧИТАНО НА СЕТКЕ, не доказано
изоморфизм «Отгрузка и накладная»: сетка 2 значений, нарушений 0 — ПОСЧИТАНО НА СЕТКЕ, не доказано
модуль «Order shipment»: функций 6, из них с доказанным завершением 6; типов 3
flang/ct/order-shipment.flang: проверено — доказано 0, проверено только на тестах 0, не доказано 0 (постусловий и утверждений 0); замечаний нет

That is: 5 values on 3 objects, 7 triples of arrows, no violations.

WhatHow it is checkedError
the ends of composed arrows: «b» after «a»from the declarations, without valuesFLANG_COMPOSE_MISMATCH
an arrow and its function: one input «A», the result «B»from the declarationsFLANG_MORPHISM_SHAPE
the arrows of an isomorphism go between its objectsfrom the declarationsFLANG_ISO_MISMATCH
the objects of an isomorphism have an identityfrom the declarationsFLANG_ISO_IDENTITY_MISSING
there and back gives the identityon the values of the examplesFLANG_ISO_NOT_INVERSE
the object a mapped arrow starts from has an imagefrom the declarationsFLANG_FUNCTOR_OBJECT_MISSING
the square of a functor commuteson the values of the examplesFLANG_FUNCTOR_SQUARE
a natural transformationon the values of the examplesFLANG_TRANSFORM_NOT_NATURAL
the laws of a category: equality is an equivalence, composition respects it and is associativeon the values of the examples, if the category declares its own equality: object «X» gives «X are equal»exit code 1 and the values on which the law is violated

What the compiler does not check:

WhatWhat happens
the laws of a category without its own equalitynot computed; flang check says so and returns code 2
arrows without a declared categorythe same, code 2
a functor whose objects have no givesnot computed, code 2
the lines field «a» maps to field «b»parsed, but not compared with the fields of the objects
whether an object belongs to a categorynot checked

Ordinary composition written as a function call is checked by the type check anyway. Arrows are for pipelines that are declared.

Monad and in monad

A chain of steps, each of which may give no answer.

module «Discount»

type «Maybe» of «A»
  variant «Some» contains value: «A»
  variant «None»

monad «Maybe» of «A»
  return «Wrap»
  flatten «Flatten»

total function «Wrap» of «A»
  accepts value: «A»
  returns «Maybe» of «A»
  variant «Some» with value equal to value

total function «Flatten» of «A»
  accepts nested: «Maybe» of («Maybe» of «A»)
  returns «Maybe» of «A»
  match nested
    case variant «Some» with value as inner
      then inner
    case «None»
      then variant «None»

total function «Price of item»
  accepts code: number
  returns «Maybe» of number
  if code equals 1
    then variant «Some» with value equal to 500
    else variant «None»

total function «Discount for price»
  accepts price: number
  returns «Maybe» of number
  if price is at least 400
    then variant «Some» with value equal to (price divided by 10)
    else variant «None»

total function «Discounted total»
  accepts code: number
  returns «Maybe» of number
  example «the first item has a discount»
    given code equals 1
    expected variant «Some» with value equal to 450
  example «the second item is not in the catalogue»
    given code equals 2
    expected variant «None»
  in monad «Maybe»
    let price equals «Price of item» of code
    let discount equals «Discount for price» of price
    return price minus discount
LineWhat it does
monad «T» of «A»declared on a type with a parameter
return «F»the function that wraps a value
flatten «F»the function that removes one layer
in monad «T»the binding block
let name equals stepa step that may give no answer
return expressionthe last line of the block

The compiler expands the block into nested matches over the variants of the type. You do not write the chain "if none, return none" at every step — as with ? in Rust or do in Haskell.

Limits: return must be the last line of the block. The mapping (fmap) is not declared — the compiler derives it from the type. The monad laws are checked on the values of the examples, not proved.

Processes and supervision

A process owns its state, like an actor in Erlang. The handler is an ordinary function: it takes the state and a message and returns the new state and a list of actions. Sending a message is an action in that list.

module «Counter»

object «Count»
  «total»: number

object «Reply»
  «состояние»: «Count»
  «действия»: list «Действие»

type «Command»
  variant «add» contains «amount»: number

process «Counter»
  state «Count»
  starts with «empty count»
  accepts «Command»
  handles «counter step»

supervision «Bookkeeping»
  process «Counter» strategy «перезапустить»
  failure threshold 3 within 5000 milliseconds else «передать выше»

total function «empty count»
  returns «Count»
  record «Count» with «total» equal to 0

total function «counter step»
  accepts current: «Count», message: «Command»
  returns «Reply»
  example «adding changes the state and sends nothing»
    given current equals (record «Count» with «total» equal to 1)
    given message equals (variant «add» with «amount» equal to 2)
    expected (record «Reply» with «состояние» equal to (record «Count» with «total» equal to 3) and «действия» equal to [])
  match message
    case variant «add» with «amount» as amount
      let updated equals (record «Count» with «total» equal to (current.«total» plus amount))
      record «Reply» with «состояние» equal to updated and «действия» equal to []

run «two additions»
  seed 1
  given «Counter» accepts (variant «add» with «amount» equal to 2)
  given «Counter» accepts (variant «add» with «amount» equal to 3)
  expected «Counter» equals (record «Count» with «total» equal to 5)
LineWhat it does
process «P»the declaration
state «T»the type of the state
starts with «F»the function giving the initial state
accepts «T»the type of messages
handles «F»the handler
with budget Nthe step limit for a handler that is not total
with mailbox Nthe size of the message queue
supervision «S»a supervisor: what to do on failures
process «P» strategy «…»what to do when the process fails
failure threshold N within M … else «…»the window and the fallback strategy
run «name» / seed / given / expecteda test of a concurrent program: messages in, expected state out
seed of N through Mthe same test over a range of message orderings

A handler without the word total must name a step budget, and a process with such a handler must stand under supervision. The budget and the queue size:

process «Counter»
  state «Count»
  starts with «empty count»
  accepts «Command» with mailbox 4 messages
  handles «counter step» with budget 2000 steps
CommandWhat it does with a run block
flang checkparses it and checks the types, does not execute it; returns code 2 on the example above
flang testexecutes it and compares the expectations; the block counts as one example, and a false expectation is exit code 1

The scheduler is generated together with the code of the c, elixir, js and ts targets — see Processes.

The fixed names of the process model are spelled in Russian in every file:

WhatNames
the fields of the handler's replyсостояние (state), действия (actions)
the type of actions«Действие»
strategiesперезапустить (restart), остановить (stop), передать выше (escalate)
the normal stop reasonнорма

The full model: Processes and fault tolerance (in Russian).

Other words

WordWhere it belongsWhere it is described
planeffects (files, network, processes): declared by the same three lines as a processCategories and functors, section «Эффекты и HTTP»
date, moneyolder keywords: date behaves as string, money as numberGlossary
has — the line given «Object» has «field» equal to valuean older theorem formbelow
utility, rule, nested object, in data, find where, by morphismolder keywords: still parsed, but a program cannot be built from themGlossary

The older theorem form cannot be mixed with the current one: the line given «Object» has «field» next to claim is an error. in data, by morphism and therefore «conclusion» behave the same way.

$ flang check docs/examples/reference/refused/mixed-theorem-forms.flang
FLANG_PARSE в файле docs/examples/reference/refused/mixed-theorem-forms.flang, строка 11, столбец 1: теорема «цена та же» смешала две формы: дано «Объект» имеет «поле» — из старой, а рядом стоят слова доказательства. Выберите одну форму
docs/examples/reference/refused/mixed-theorem-forms.flang: не проверено — замечаний 1
$ echo $?
1
RussianEnglishEsperantoChinese
утилитаutilityutilaĵo工具
правилоruleregulo规则
свойствоpropertypropraĵo属性
результатresultrezulto结果
начинает сstarts withkomencas per始于
поле, поляfieldkampo字段
морфизмmorphismmorfismo态射
послеafterpost之后
цепочкаchainĉeno链
сначалаfirstunue首先
затемnextposte然后
единицаidentityidenteco恒等
даётgivesdonas给出
законlawleĝo定律
изоморфизмisomorphismizomorfio同构
прямой морфизмforward morphismrekta morfismo正向态射
обратный морфизмinverse morphisminversa morfismo逆态射
вложениеembedding—嵌入
пересечениеintersectionkomunaĵo交集
моноидmonoidmonoido幺半群
носительcarrierportanto载体
операцияoperationoperacio运算
обратный элементinverse elementinversa elemento逆元
монадаmonadmonado单子
возвратreturnredono单位
соединениеflattenplatigo压平
в монадеin monaden monado在单子中
теоремаtheoremteoremo定理
следуетfollows——
функтор, функтораfunctorfunktoro函子
бифункторbifunctorbifunktoro双函子
объектыobjectsobjektoj对象对
морфизмыmorphismsmorfismoj态射对
утверждениеproposition, statementpropozicio命题
имеетhashavas具有
в данныхin dataen datumoj在数据中
найти гдеfind wheretrovi kie查找其中
по морфизму, затем по морфизму, применить морфизм, затем применить морфизмby morphism, then by morphism, apply morphism, then apply morphismper morfismo, poste per morfismo按态射, 然后按态射
следовательно, получаемthereforesekve因此
по законуunder lawlaŭ leĝo依定律
отображается в, отображаются вmaps to, map tomapiĝas al映射到
отображается в полеmaps to fieldmapiĝas al kampo映射到字段
отображается в морфизм, отображаются в морфизмmaps to morphism, map to morphismmapiĝas al morfismo映射到态射
требуетrequires——
обеспечиваетensures——
для всехfor all——
таких чтоsuch that——
есть такойthere is——
а именноnamely——
утверждаемclaim——
индукция поinduction on——
по свойствуby property——
по примеруby example——
по предположениюby hypothesis——
следовательно доказаноtherefore proved——
процессprocessprocezo进程
обрабатываетhandlestraktas处理
с запасомwith budgetkun buĝeto带预算
с ящикомwith mailboxkun leterkesto带信箱
надзорsupervision—监督
стратегияstrategystrategio策略
порог отказовfailure thresholdsojlo de fiaskoj失败阈值
прогонrunrulo运行
семяseedsemo种子
планplanplano计划

What the language does not have

HabitWhat to use instead
a loop with a mutable variablefold, recursion, or a цикл block that expands into them
changing an element in placebuilding a new value
an exceptiona Result: a variant of a type with the reason
null for "not found"an Optional: a type with variants and a mandatory match
a variablelet, which binds once
a lambdaa declared function, passed as function «Name»
a closure that captures a local variablepartial application by parameter name: function «Name» with a equal to 10
bitwise operations on numbermachine words u8 … u64, i8 … i64: bitwise and, bitwise or, bitwise xor, shifted left by
a hexadecimal literal 0xFFa decimal number: 255
writing into a list by index (x[i] = v)map builds a new list
a dependent type (list of length n)ensures about the length, and a theorem about it
your own operator, a macro, your own notation inside a filea function whose name is a phrase in guillemets; a type with variants and an interpreter function; for your own syntax, parsing a string with the module «Parsing». Step by step: Your own language in 30 minutes

Next