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.
| Question | Page |
|---|---|
| I have a task — which construct do I use | Which construct to use when |
| what does this word mean | Glossary — in Russian |
| I have a list and need a sum without duplicates — what do I write | Operations |
| show me from zero, step by step | Tutorial |
| what does "proved" mean, and how does it differ from "checked" | Why and how |
| the full language contract | Language specification — in Russian |
Glossary: flang words and the usual terms
| In flang | Usual name | Closest analogue |
|---|---|---|
тип with вариантs | enum with data, tagged union | enum in Rust, union in TypeScript |
разбор … случай | pattern matching | match in Rust and Python |
если … то … иначе | if as an expression | the ternary operator |
пусть | constant | const |
отобразить, отфильтровать, свёртка | map, filter, reduce | the same in JavaScript and Python |
объект and запись | a struct with fields and its value | dataclass, interface |
пример | a unit test inside the function | doctest |
требует | precondition: what must hold on input | an assert at the top of a function |
обеспечивает | postcondition: what holds for the result on every input | an 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 response | reducer, 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:
| Code | What it means |
|---|---|
| 0 | parsing, types, termination and examples passed |
| 1 | there is an error; it is named by a FLANG_… code |
| 2 | all 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 |
| 3 | only 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 output | What 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
| Sign | How else it is typed | Where it stands |
|---|---|---|
→ | ->, => | a fold, map, filter, a function type |
"text" | 'text' | a string literal |
: ( , and the other punctuation | full-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
| Line | What 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:
- the directory of the file that has the
usesline; - every directory above it — as long as the directory holds at least one
.flangfile; - the library shipped with the compiler.
| Case | What to do, or what happens |
|---|---|
| the module is in a subdirectory or elsewhere | list 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 found | the error FLANG_IMPORT_AMBIGUOUS with both paths |
| the module is not found | the error FLANG_IMPORT_NOT_FOUND |
| the name of a library module | is not translated: the list module is called «Lists» in a file with Russian keywords too; uses «Списки» is FLANG_IMPORT_NOT_FOUND |
| Russian | English | Esperanto | Chinese |
|---|---|---|---|
модуль | module | module | 模块 |
экспортирует | exports | eksportas | 导出 |
использует | uses | uzas | 使用 |
категория | category | kategorio | 类别 |
объект, структура | object, structure | objekto, strukturo | 对象, 结构 |
запись | record | rikordo | 记录 |
тип | type | tipo | 类型 |
вариант | variant | varianto | 变体 |
это | — | — | — |
вложен объект, вложена структура | nested object, nested structure | — | 嵌套对象, 嵌套结构 |
примечание | note | noto | 注 |
Function
The parts go in this order. The body comes last and is one expression.
| Part | Required | What it means |
|---|---|---|
total | no | the function always terminates; the compiler proves it |
function «Name» | yes | the declaration |
accepts name: type, name: type | no | parameters; types are required |
returns type | yes | the result type |
requires «name» condition | no | precondition; the caller must make it true |
decreases expression | no | a termination measure: a number that goes down on every recursive call |
for all p ensures «name» condition | no | postcondition about result |
example «name» / given / expected | no | a 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.
| Rule | Detail |
|---|---|
ensures must have a name | the 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 examples | a false example is the error FLANG_EXAMPLE, exit code 1 |
flang emit does not run the examples | it says so in its output and generates the code |
requires is checked at run time | a violation at the entry of the program is the error FLANG_PRECONDITION |
| Russian | English | Esperanto | Chinese |
|---|---|---|---|
код символа | character code | kodo de signo | 字符码 |
символ по коду | character by code | signo per kodo | 按码字符 |
убывает | decreases | — | — |
тотальная | total | totala | 完全 |
функция | function | funkcio | 函数 |
принимает | accepts | akceptas | 接受 |
возвращает | returns | redonas | 返回 |
пример | example | ekzemplo | 示例 |
дано | given | donite | 给定 |
ожидается | expected | atendata | 期望 |
история | — | — | — |
хочу | — | — | — |
чтобы | — | — | — |
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 it | When it applies | Run-time check |
|---|---|---|
| «композицией» (by composition) | no recursion | no |
| «структурой» (by structure) | match recurses on a part of the value | no |
| «точным шагом» (by exact step) | a nat parameter goes down by a constant | no |
| «постоянным шагом» (by constant step) | a number parameter goes down by a constant and is bounded below | yes |
| «объявленной мерой» (by declared measure) | the function has decreases | yes |
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 measure must be a non-negative integer; this is checked on every call.
«GCD»of 12 and 18 gives 6; of 1.5 and 0.7 it stops withFLANG_MEASURE; - the kernel does not derive the descent of a declared measure, so the termination of such a function counts as not proved.
flang runruns it only with the key--trust.
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)
| Pattern | What it covers |
|---|---|
case Name | a variant without fields |
case variant Name with field as name | a variant with its fields bound to names |
case empty, case head and tail | a list or a string |
case any | everything 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
| Type | What it is | What to use it for |
|---|---|---|
number | IEEE-754 double | everything else, and any division |
nat | an integer in [0, 2⁵³−1] | a counter, an index, a count, a length |
integer | an integer in [−(2⁵³−1), 2⁵³−1] | a difference, a balance, an offset, a temperature |
weight | non-negative, where +∞ is a value | weight, distance, path cost |
hundredths | an integer count of hundredths | money: 19.99 is written 1999 |
thousandths | an integer count of thousandths | rates, shares, exchange rates |
string | a string | text |
boolean | true / false | a condition |
null | a 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:
| Expression | Result |
|---|---|
(-12) modulo 6, 0 times -5, 0 divided by -5 | 0: arithmetic never produces -0 |
-0 equals 0 | false: a -0 that comes in as a literal or an input differs from 0 |
NaN equals NaN | true: 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.
| Literal | Value |
|---|---|
[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
| What | How it is written |
|---|---|
operations on exact integer | plus, minus, times, modulo, comparisons; no divided by |
operations on exact fraction | plus, minus, times, divided by, comparisons; no modulo |
| fraction → integer | integer part f — the quotient without the remainder |
| integer → fraction | the literal [[n], [1]] |
| Limit | What happens |
|---|---|
an exact number and a number in one operation | FLANG_TYPE: «точное целое и число не смешиваются» (they do not mix) |
a result below zero: [1] minus [2] | FLANG_PROPERTY at run time |
| division by the zero fraction | FLANG_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.
| Form | What it is |
|---|---|
u32 5 | a word of type u32 with value 5 |
u64 "18446744073709551615" | a value above 2⁵³−1: decimal digits in quotes |
word bitwise and 15 | a number next to a word takes the type of the word |
u8 300 | the error FLANG_OVERFLOW at check time: 300 does not fit in u8 |
0xFF | the 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.
| Operation | How it is written | What it gives | |
|---|---|---|---|
| checked arithmetic | a plus b, minus, times, divided by, modulo | the exact result; if it does not fit the type or the divisor is zero, the error FLANG_OVERFLOW at run time | |
| modular arithmetic | a plus b with overflow, likewise minus and times | the result modulo 2^w | |
| bitwise operations | bitwise and, bitwise or, bitwise xor, bitwise not a | the same as &, `\ | , ^, ~` in C |
| shifts | shifted left by n, shifted right by n | n is below the word width; a right shift of a signed word is arithmetic | |
| rotations | rotated left by n, rotated right by n | n is taken modulo the width | |
| comparisons | equals, is less than, is at most and the rest | values are compared with their sign | |
| full product | a times b with double width | a 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).
| Form | What it does |
|---|---|
u32 b with b: u8 | a word of another width with the same value |
u8 n with n: nat | number → word |
to number word | word → number; a u64 value above 2⁵³−1 gives FLANG_OVERFLOW |
to text word | the 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.
| Missing | What to use |
|---|---|
a byte array type (байты is an unknown type) | list u8 |
| a fixed-size array | a list and a postcondition about its length |
| hexadecimal literals | a decimal number; keep the hexadecimal form in the name of an example or in a note line |
division on exact integer | for fields up to 64 bits, u64 and shifted right by |
| proofs of conditions about bits | examples on the function |
List
| Form | What it is |
|---|---|
list Type, list of Type | the type of a homogeneous list |
[1, 2, 3], list of 1 and 2 and 3 | a 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"
| Form | What it means |
|---|---|
object «Line» | a record with fields |
name is type, «name»: type | a field; the two spellings are equivalent |
may be | the field can be absent; the examples may leave it out |
record «Line» with title equal to "bolt" and price equal to 30 | a record value |
entry.price | reading a field |
type «Answer» with variants | a type with variants (an enum with data) |
variant Ok with value equal to 30 | a 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
| Form | Example |
|---|---|
| in words | функция из числа и строки в признак (Russian keywords) |
| with an arrow | number → 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
| What | How it is written |
|---|---|
| function call | «Name» of argument and argument |
| record field | value.field |
| record field by word | field «x» at value, field «x» from value |
| arithmetic | plus, minus, times, divided by, modulo, percent of |
| comparison | equals, is not equal to, is greater than, is less than, is at most, is at least |
| logic | not, and also, or |
| literals | 12, "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.
утверждение «три вызова схлопываются»
для всех а: строка
утверждаем («Приклеить пустое» от
(«Приклеить пустое» от
(«Приклеить пустое» от а))) равен а
| Rule | Detail |
|---|---|
| an error inside such an expression | names 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.
| Rule | What it means |
|---|---|
nothing after the opening """ on its line | the text starts on the next line; another character there is the error FLANG_LEX at its position |
the first """ without a backslash before it closes | the rest of that line is read as usual |
| common indentation | the 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 indentation | a line of only spaces becomes empty; trailing spaces stay |
| closing quotes on their own line | the 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 block | the error FLANG_LEX at the opening quotes |
a bad \uXXXX | an error at the line and column of the backslash itself |
| interpolation | there 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
"""
| Russian | English | Esperanto | Chinese |
|---|---|---|---|
пусть | let | estu | 令 |
если | if | se | 如果 |
то | then | tiam | 那么 |
иначе | else | alie | 否则 |
разбор | match | kongruo | 匹配 |
случай | case | kazo | 情况 |
от | of | de | 的 |
и | and | kaj | 和 |
и притом | and also | kaj ankaŭ | 并且 |
или | or | aŭ | 或者 |
не | not | — | 非 |
с | with | kun | 带有 |
из | from | el | 从 |
только | only | nur | 仅 |
в, к | to, into, in, onto | al | 到 |
по | by | per | 按 |
у | at | ĉe | 在 |
как | as | kiel | 作为 |
где | where | kie | 其中 |
начиная с | starting with | komencante per | 起始于 |
Built-in forms over lists and strings
| Form | What it does |
|---|---|
length X | the length of a list or a string |
head X, tail X, empty | parts of a list and of a string |
item N in X | the N-th element of a list |
char N in X | the N-th character of a string |
add X to Y, prepend X to Y | at the end and at the front of a list |
map X as name → body | map: a new list |
filter X where name → condition | filter: the items that fit |
substring X from A to B | a slice of a string |
split X by Y | string → list of strings |
join X by Y | list of strings → string |
join X with Y | concatenating two strings |
contains, begins with | checks over a string |
to number, to number or failure, to text | conversions |
character code X | character → its code point as a number |
character by code N | code point → a one-character string; an error on a fraction, outside [0, 1114111], and on a lone surrogate |
decompose X into characters | string → list of characters |
hash256 X | the 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
| Russian | English | Esperanto | Chinese |
|---|---|---|---|
отобразить | map | mapi | 映射 |
отфильтровать | filter | filtri | 过滤 |
свёртка, свертка | fold | faldo | 折叠 |
длина | length | longo | 长度 |
целая часть | integer part | entjera parto | 整数部分 |
символ | char | signo | 字符 |
разложить | decompose | malkomponi | 分解 |
на символы | into characters | en signojn | 为字符 |
подстрока | substring | subĉeno | 子串 |
соединить | join | kunigi | 连接 |
разделить | split | dividi | 分割 |
содержит | contains | enhavas | 包含 |
начинается с | begins with | komenciĝas per | 开始于 |
к числу или беда | to number or failure | al nombro aŭ fiasko | 转数字或失败 |
к числу | to number | al nombro | 转数字 |
к строке | to text | al teksto | 转文本 |
хеш256 | hash256 | — | 哈希256 |
голова | head | kapo | 头 |
хвост | tail | vosto | 尾 |
элемент | item | ero | 元素 |
голова и хвост | head and tail | kapo kaj vosto | 头和尾 |
пусто | empty | malplena | 空 |
пустой список | empty list | malplena listo | 空列表 |
список из | list of | listo de | 列表由 |
список | list | listo | 列表 |
добавить | add | aldoni | 添加 |
приписать | prepend | antaŭmeti | 前置 |
любое | any | ajna | 任意 |
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
| Form | What it means |
|---|---|
function «Name» | a function as a value |
function «Name» with a equal to 10 | the same with the parameter a fixed: partial application by parameter name |
f of 5 | applying a value |
number → number | the type |
Limits:
- only a declared function can be a value. There are no anonymous function values;
- an inline body (
x → x plus 1) is accepted only by the built-inmap,filterandfold. It is part of the form and cannot be passed to your own function: the errorFLANG_UNKNOWN_NAME; - the parameters of a partial application go in the order they are declared;
- only a function that the program takes somewhere with the form
function «Name»can be applied; otherwise it is the errorFLANG_APPLY. There is no separate compilation: function values are resolved across the whole program at once.
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.
| Form | What it expands into | Error for a malformed form |
|---|---|---|
| a one-line header | функция, принимает, возвращает on three lines | FLANG_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 it | FLANG_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
в конце прибыль
пусть сегодня равно цена минус минимум
пусть ниже равно если цена меньше минимум то цена иначе минимум
пусть лучше равно если сегодня больше прибыль то сегодня иначе прибыль
дальше: минимум станет ниже, прибыль станет лучше
| Line | What it means |
|---|---|
для каждого х из список | a step for every item |
пока условие | steps while the condition holds; a bound is required |
шагов не больше n, иначе v | a 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:
- the name of a loop becomes the name of a type shared by the whole module. Two loops with the same name in different functions are the error
FLANG_TYPE: «тип объявлен дважды» (the type is declared twice); - the kernel does not prove a postcondition of a function written with a
для каждогоloop: it is checked on the examples only.
класс — an object and functions over it
класс «Счёт»
владелец: строка
остаток: число
всегда «остаток не отрицателен» остаток не меньше 0
метод «Положить» принимает сумма: число
требует «сумма не отрицательна» сумма не меньше 0
остаток станет остаток плюс сумма
метод «Пусто ли» возвращает признак
остаток равен 0
| Form | What it expands into |
|---|---|
класс «Счёт» | объект «Счёт» |
метод «Положить», метод «Пусто ли» | the functions «Счёт: Положить» and «Счёт: Пусто ли» with the first parameter этот: «Счёт» |
| a field name in a method | остаток → этот.остаток |
lines поле станет значение at the end of a method | the 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
"фигура"
класс «Квадрат» есть «Фигура»
сторона: число
метод «Площадь» возвращает число
сторона умножить на сторона
метод «Название» возвращает строка
"квадрат"
| Form | What it expands into |
|---|---|
интерфейс «Фигура» | тип «Фигура» with a variant for every class of the file that есть «Фигура» |
a метод of the interface | the function «Фигура: Площадь» with разбор over the classes |
| a method without a body | required in every class |
| a method with a body | the default implementation |
обеспечивает on a method of the interface | a 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
| Word | Where it goes | Who must make it true | What checks it |
|---|---|---|---|
requires «name» condition | after returns, before the body | the caller | at run time, at the entry of the program |
for all p ensures «name» condition | the same place, after requires | the function | the kernel at check time; if not proved, at run time on every return |
total | before the word function | the compiler | at check time; see "Totality and measures" |
theorem «name» | top level, next to the function | you | the kernel at check time, step by step |
утверждение «name» (statement) | top level, without a function | you | the 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.
| Where | How it works |
|---|---|
| inside the function | the condition is an assumption; a theorem uses it through by hypothesis, without induction too |
| at the entry of the program | a violation is the error FLANG_PRECONDITION |
| on internal calls | no 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 body | Proved |
|---|---|
empty list | yes |
the literal [1, 2] | yes |
filter L where x → C, where C is the condition being proved | yes |
add X to L, prepend X to L | yes, if the condition holds for X and for L |
if C then A else B | yes, if it holds in both branches |
map | no |
The body after the colon is a condition again, so quantifiers nest:
обеспечивает «каждый с каждым положителен» для всех х из результат: для всех м из результат: м больше 0
| Rule | Detail |
|---|---|
| "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 fit | the error FLANG_PROOF_STEP |
| where a quantifier may stand | inside a condition too: under and also and under if … then … else |
| where a quantifier ends | at 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
| Line | What it does |
|---|---|
theorem «name» | the same name as the postcondition it proves |
given name: type | the variables |
claim condition | what is being proved |
induction on name decreases measure | proof by induction; decreases is needed only where a number goes down, not a part of a value |
case … / then justification | one step |
next claim by justification | an intermediate fact; later steps can use it |
therefore proved | the 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.
| Justification | Use it when | Limit |
|---|---|---|
by property «name» | the step contains a call to a function that has a postcondition with that name | the postcondition being proved cannot be named |
by hypothesis | there 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 name | an 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 rules | any 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
следовательно доказано
| Form | What it means |
|---|---|
из строки N | the source line the fact comes from: a precondition or the body |
из K, из K и L | the 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»
| Construction | What 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 examples | a condition on the arrow; checked on the values of the examples |
«b» after «a» | composition; the right one runs first |
chain / first / next | the same composition in reading order |
identity «X» | the identity arrow of an object |
category «C» with a list of arrows | the arrows the module declares as its own |
isomorphism / forward morphism / inverse morphism | a pair of arrows there and back |
functor | carries 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 / morphisms | a functor of two arguments: a pair of objects → an object, a pair of arrows → an arrow |
embedding, intersection | a part of an object and the common part of two objects |
monoid / carrier / operation / identity / inverse element | an 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 output | What 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.
| What | How it is checked | Error |
|---|---|---|
the ends of composed arrows: «b» after «a» | from the declarations, without values | FLANG_COMPOSE_MISMATCH |
an arrow and its function: one input «A», the result «B» | from the declarations | FLANG_MORPHISM_SHAPE |
| the arrows of an isomorphism go between its objects | from the declarations | FLANG_ISO_MISMATCH |
the objects of an isomorphism have an identity | from the declarations | FLANG_ISO_IDENTITY_MISSING |
| there and back gives the identity | on the values of the examples | FLANG_ISO_NOT_INVERSE |
| the object a mapped arrow starts from has an image | from the declarations | FLANG_FUNCTOR_OBJECT_MISSING |
| the square of a functor commutes | on the values of the examples | FLANG_FUNCTOR_SQUARE |
| a natural transformation | on the values of the examples | FLANG_TRANSFORM_NOT_NATURAL |
| the laws of a category: equality is an equivalence, composition respects it and is associative | on 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:
| What | What happens |
|---|---|
| the laws of a category without its own equality | not computed; flang check says so and returns code 2 |
| arrows without a declared category | the same, code 2 |
a functor whose objects have no gives | not 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 category | not 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
| Line | What 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 step | a step that may give no answer |
return expression | the 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)
| Line | What 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 N | the step limit for a handler that is not total |
with mailbox N | the 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 / expected | a test of a concurrent program: messages in, expected state out |
seed of N through M | the 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
| Command | What it does with a run block |
|---|---|
flang check | parses it and checks the types, does not execute it; returns code 2 on the example above |
flang test | executes 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:
| What | Names |
|---|---|
| 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
| Word | Where it belongs | Where it is described |
|---|---|---|
plan | effects (files, network, processes): declared by the same three lines as a process | Categories and functors, section «Эффекты и HTTP» |
date, money | older keywords: date behaves as string, money as number | Glossary |
has — the line given «Object» has «field» equal to value | an older theorem form | below |
utility, rule, nested object, in data, find where, by morphism | older keywords: still parsed, but a program cannot be built from them | Glossary |
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
| Russian | English | Esperanto | Chinese |
|---|---|---|---|
утилита | utility | utilaĵo | 工具 |
правило | rule | regulo | 规则 |
свойство | property | propraĵo | 属性 |
результат | result | rezulto | 结果 |
начинает с | starts with | komencas per | 始于 |
поле, поля | field | kampo | 字段 |
морфизм | morphism | morfismo | 态射 |
после | after | post | 之后 |
цепочка | chain | ĉeno | 链 |
сначала | first | unue | 首先 |
затем | next | poste | 然后 |
единица | identity | identeco | 恒等 |
даёт | gives | donas | 给出 |
закон | law | leĝo | 定律 |
изоморфизм | isomorphism | izomorfio | 同构 |
прямой морфизм | forward morphism | rekta morfismo | 正向态射 |
обратный морфизм | inverse morphism | inversa morfismo | 逆态射 |
вложение | embedding | — | 嵌入 |
пересечение | intersection | komunaĵo | 交集 |
моноид | monoid | monoido | 幺半群 |
носитель | carrier | portanto | 载体 |
операция | operation | operacio | 运算 |
обратный элемент | inverse element | inversa elemento | 逆元 |
монада | monad | monado | 单子 |
возврат | return | redono | 单位 |
соединение | flatten | platigo | 压平 |
в монаде | in monad | en monado | 在单子中 |
теорема | theorem | teoremo | 定理 |
следует | follows | — | — |
функтор, функтора | functor | funktoro | 函子 |
бифунктор | bifunctor | bifunktoro | 双函子 |
объекты | objects | objektoj | 对象对 |
морфизмы | morphisms | morfismoj | 态射对 |
утверждение | proposition, statement | propozicio | 命题 |
имеет | has | havas | 具有 |
в данных | in data | en datumoj | 在数据中 |
найти где | find where | trovi kie | 查找其中 |
по морфизму, затем по морфизму, применить морфизм, затем применить морфизм | by morphism, then by morphism, apply morphism, then apply morphism | per morfismo, poste per morfismo | 按态射, 然后按态射 |
следовательно, получаем | therefore | sekve | 因此 |
по закону | under law | laŭ leĝo | 依定律 |
отображается в, отображаются в | maps to, map to | mapiĝas al | 映射到 |
отображается в поле | maps to field | mapiĝas al kampo | 映射到字段 |
отображается в морфизм, отображаются в морфизм | maps to morphism, map to morphism | mapiĝas al morfismo | 映射到态射 |
требует | requires | — | — |
обеспечивает | ensures | — | — |
для всех | for all | — | — |
таких что | such that | — | — |
есть такой | there is | — | — |
а именно | namely | — | — |
утверждаем | claim | — | — |
индукция по | induction on | — | — |
по свойству | by property | — | — |
по примеру | by example | — | — |
по предположению | by hypothesis | — | — |
следовательно доказано | therefore proved | — | — |
процесс | process | procezo | 进程 |
обрабатывает | handles | traktas | 处理 |
с запасом | with budget | kun buĝeto | 带预算 |
с ящиком | with mailbox | kun leterkesto | 带信箱 |
надзор | supervision | — | 监督 |
стратегия | strategy | strategio | 策略 |
порог отказов | failure threshold | sojlo de fiaskoj | 失败阈值 |
прогон | run | rulo | 运行 |
семя | seed | semo | 种子 |
план | plan | plano | 计划 |
What the language does not have
| Habit | What to use instead |
|---|---|
| a loop with a mutable variable | fold, recursion, or a цикл block that expands into them |
| changing an element in place | building a new value |
| an exception | a Result: a variant of a type with the reason |
null for "not found" | an Optional: a type with variants and a mandatory match |
| a variable | let, which binds once |
| a lambda | a declared function, passed as function «Name» |
| a closure that captures a local variable | partial application by parameter name: function «Name» with a equal to 10 |
bitwise operations on number | machine words u8 … u64, i8 … i64: bitwise and, bitwise or, bitwise xor, shifted left by |
a hexadecimal literal 0xFF | a 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 file | a 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
- Which construct to use when — choosing by task
- Known limits — what the language does not do and will not
- Standard library reference — the standard library modules