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

Playground

The playground needs JavaScript and a browser with WebAssembly. Without them the
compiler in a terminal does the same checks: flang check file.flang --proof.

The playground runs flang in this tab: the editor is on the left, the compiler's answer on the right. Nothing to install. The text in the editor is not sent to a server.

The tiles above the editor are setups. A setup is a workplace for one activity: a starter text, a main button and the tabs on the right. Each setup has its own section below.

SetupWhat it doesAddress
First programcomputes a function and runs its tests#setup=first
Proofsshows which postconditions and statements are proved#setup=proof
Testsshows a table of tests: input, expected, actual#setup=tests
Code generationtranslates the program to C, Go, Rust and seven more languages#setup=emit
Reasoning in Russianchecks whether the conclusion follows from the premises#setup=reasoning
Formulatranslates a formula with ∀ and ∃ to flang and checks it#setup=formula
Your own textreads a Russian text and looks for mistakes in its reasoning#setup=prose
Your own language (DSL)leads from a language of three commands to the three languages of the page Your own language in 30 minutes#setup=dsl
C → flangtranslates a C function and checks the translation#setup=c
Python → flangtranslates a Python function and checks the translation#setup=python

The address is appended to the page address: playground.html#setup=prose opens "Your own text".

Common to all setups

An error is shown on the right as one message. The word with the error is underlined in the editor, and the "line N" button puts the cursor on it. The error code (FLANG_…) leads to the code reference.

Editor keys: Tab inserts two spaces or shifts the selected lines, Shift+Tab removes the indent. Enter keeps the indent and deepens it after a line that opens a block. << becomes «», >> becomes ».

Library modules have English names: использует «Lists». If there is no such module, the playground suggests similar names. A program with использует is checked only by the button: with a library the check takes about ten seconds.

Editor

The editor can work in the manner of vim: with modes and keyboard commands. By default vim mode is off, and the editor behaves as a plain text field.

The "Vim" button in the line under the editor turns the mode on, and so does the address #vim=on. The same button or the command :set novim turns it off. The choice is saved in the browser. A phone without a keyboard does not show the button.

The line under the editor shows the mode, the typed part of a command, a message and the place of the cursor: line and column. If the cursor line has a compiler error, its text is shown there too.

ModeHow to enterWhat the keys do
normalEsccommands: moving, editing, searching
inserti a I A o Otype text
visualv, by lines — Vmotions stretch the selection
command:type a command; Enter runs it, Esc cancels

Normal mode reads a key by its place on the keyboard, not by its letter. In the Russian layout в works as d, ш as i, Ж as :. In insert mode, in a search and after f, t, r the character is taken as typed.

What is supportedKeys
Movingh j k l and the arrows; w b e W B E; 0 ^ $; gg G; f t F T and ; ,; % on brackets and guillemets; { } by empty lines; Ctrl+D, Ctrl+U
A number before a command3w, 2dd, 5j, 10G
Operatorsd c y > < gu gU g~ with any motion; dd cc yy >> <<; D C x X s S Y
Editingp P, r, J, ~; . repeats the last edit
Undou undoes an edit, Ctrl+R brings it back
Text objectsiw aw, i" a", i( a(, i[ i{, i« a«, ip ap — after an operator and in a selection
Registers"a…"z; "0 — the last yank; "+ — the system clipboard; "_ — nowhere
Search and replace/ ? n N; * # search for the word under the cursor; :s/what/with/g, :%s/what/with/g; :noh removes the highlight
Compiler errors]d [d — the next and the previous one; :copen — the list, Enter in it puts the cursor on the error
Namesgd — to the declaration of a name; K — the header of the function under the cursor
Completion in insert modeCtrl+P and Ctrl+Space cycle through the words of the language and the names in the text; Ctrl+N where the browser passes it on
Tabs on the rightgt gT, :tab with the name of a tab

Commands after : do what the buttons of the page do. Tab completes a command and its names.

CommandWhat it does
:wsaves the draft in the browser
:check, :proofchecks the text; :proof opens the "Check" tab
:testruns the tests
:run, :run Удвоить {"н": 2}computes a function; the name and the arguments may follow
:emit gogenerates code in the named language
:setup proof, :example helloopens a setup or a step of a ladder by its name
:set nu, :set nonu, :set rnuline numbers: plain, none, counted from the cursor line
:set ic, :set noica search that ignores letter case, and one that does not
:helpopens this section
:qcloses nothing and says so

Ctrl+Enter presses the main button in every mode. Tab in normal mode moves the focus out of the editor; in insert mode it indents.

A search pattern is a JavaScript regular expression; \< and \> mean word edges. gd and K look for the declaration in the text of the editor. They do not find library names.

What is missing: macros (q), marks (m), folding, replace mode (R), block selection (Ctrl+V), several windows, plugins and a settings file. The editor holds one text: the commands :e and :b say so.

First program

"Run" computes a function and runs the tests. The function name and the arguments are in the fields above the editor; the arguments are a JSON object, for example {"н": 21}. If the fields are empty, the first function of the text and the arguments of its first test are used.

flang run does not run a program that is not fully proved. The button "Run without the proof (--trust)" appears then.

The ladder of examples, from simple to complex:

  1. One function and one test
  2. A choice: if, then, else
  3. A list: head and tail
  4. Your own type with variants
  5. A loop that keeps values
  6. A class, a method and an interface

Proofs

"Check" shows one row for every postcondition (обеспечивает) and statement. A click on a row leads to its place in the text. The statuses:

A separate program, checker, goes through what is proved once more: the independent check. Its answer is shown with the verdict. For programs with использует the playground has no independent check.

The "Formulas" tab shows the statements written with ∀ and ∃. The "Pictures" tab draws a proof tree, the arrows of a category, monoid laws and circles for sets.

The ladder of examples, from simple to complex:

  1. A postcondition proved for all numbers
  2. A false postcondition and a counterexample
  3. A condition on the input: «требует»
  4. A list: a postcondition for every length
  5. A theorem by induction on your own type
  6. A monad and its laws

Tests

A test in flang is an пример inside a function: дано names the arguments, ожидается the result. The table shows the input, the expected and the actual value of every test. A failed test marks its line in the editor.

The ladder of examples, from simple to complex:

  1. One test: given and expected
  2. Three tests: a usual case and two edge cases
  3. A test that fails
  4. Tests with lists
  5. The answer is a variant of your own type

Code generation

"Generate" shows the same program in another language; the command flang emit generates it. There are ten languages: C, C++, Go, Rust, Java, JavaScript, TypeScript, Elixir, Python and C#. Buttons above the code choose the language and the file.

Code is generated only for a program that passes the check. Runtime library files are not shown; only their names are listed.

The ladder of examples, from simple to complex:

  1. One function in C
  2. A branch in Go
  3. A list and recursion in Python
  4. Your own type in Rust
  5. A condition on the input in TypeScript

Reasoning in Russian

The text consists of a dictionary (Понятие:, Свойство:, Имя:), premises and a conclusion after the word «Следовательно». The answer is "Follows" or "does not follow" with a counterexample. A text without a dictionary is checked by the "Your own text" setup.

The ladder of examples, from simple to complex:

  1. All, all, therefore all
  2. A name instead of «все» (all)
  3. A denial: «ни один» (no one)
  4. A part: «некоторые» (some)
  5. A conclusion that does not follow

Formula

The first line starts with ∀, ∃, \forall, \exists, forall or exists. A translator turns the formula into a flang statement, and the kernel checks it. If the formula cannot be read, the reason is named, for example "there is no ℝ in flang".

The ladder of examples, from simple to complex:

  1. An equality for any two integers
  2. LaTeX notation and three numbers
  3. A condition: if, then
  4. The sign ∃: «there is such a number»
  5. A formula about a list
  6. A false formula and a counterexample

Your own text

Paste a text in Russian: up to 6000 characters and up to 40 sentences. "Check the reasoning" reads every sentence and checks two things:

A conclusion is a sentence that starts with «следовательно», «значит», «поэтому» or «итак» (therefore, so, hence, thus). Its premises are the sentences starting from the previous conclusion.

The "Example…" list puts one of the ten texts of the ladder into the editor: from a correct chain to a text where some lines are not read. The line under the buttons says what to look at in the chosen example.

Every sentence in the answer gets a coloured mark:

Under the mark you see how the meaning of the sentence is written down, or why it did not take part in the check. The reasons are: an unknown word; too many ways to read the sentence; a word like «он» or «это» (he, this) that points to another sentence; a construction the grammar does not know.

Write a sentence that is not understood more simply: one statement, plain word order, full nouns instead of «он» and «это». The rest of the text is checked without it.

The frame of the answer is green when no mistakes are found and red when there are some. A grey frame means that not a single sentence was understood. The mistakes are listed under "What is found": a conclusion that does not follow, a contradiction, circular reasoning, a term that changes its meaning, a conclusion without premises.

The text is read with a dictionary and the rules of Russian grammar, so in an ordinary text only some of the sentences are understood. The dictionary is OpenCorpora, under CC BY-SA 3.0; the playground downloads only the dictionary files that the words of the text need. A longer text is checked by the command flang run-script argue:article; see the page Check the reasoning in a text.

The ladder of examples, from simple to complex:

  1. A correct chain
  2. An everyday argument
  3. A conclusion that does not follow
  4. A contradiction
  5. Two mistakes in one text
  6. A textbook definition
  7. A request among statements
  8. Sentences that are not understood
  9. A text with a list of references
  10. A nominal and an over-long sentence

Your own language (DSL)

The ladder starts with a language of three commands and reaches the three languages of the page Your own language in 30 minutes: discount rules, an expression calculator and an order automaton. "Check" shows what is proved, "Run" computes a function, "Tests" runs the tests.

The ladder of examples, from simple to complex:

  1. A language of three commands
  2. Words that read as a phrase
  3. A rule inside a rule and a property of every rule
  4. Its own notation: the program comes as text
  5. A description that checks itself

C → flang

"Translate and check" turns a C function into a flang program and checks it right away. An int overflow and a division by zero become conditions that have to be proved.

The translator understands int, struct of int fields, bool as the result of a function, if/else, while, for, return, arithmetic, comparisons, && and ||. It skips #include lines for stdbool.h, stdint.h, limits.h and stddef.h. There are no pointers, arrays, strings, fractions or library functions: the translator names the line it did not take.

If flang did not prove that a loop ends, the answer says so. What is proved then holds on the condition that the loop ends.

The ladder of examples, from simple to complex:

  1. One function with one branch
  2. Three branches
  3. Division: a zero is found
  4. An int overflow
  5. One function calls another
  6. A loop and a mistake inside it

Python → flang

The translator understands functions with int and bool, if/elif/else, while, for over range(…) or over a list, return, assignments, arithmetic, comparisons, and, or, not and calls of your own functions. A parameter without a type is read as int. Whole numbers in Python have no limit, so the translation adds no bounds. A division by zero becomes a condition that the kernel checks.

The ladder of examples, from simple to complex:

  1. One function with one branch
  2. A loop over a list
  3. Lists in one line
  4. Division: a zero is found
  5. Recursion on the tail of a list
  6. Recursion whose end the translator does not see

Examples

Every block below is in the "Example…" list, in the group "Examples on this page".

Programs and proofs

A function with a postcondition: the condition after обеспечивает is proved for every input.

модуль «Привет»

тотальная функция «Удвоить»
  принимает н: неотрицательное
  возвращает число
  обеспечивает «удвоенное не меньше исходного» результат не меньше н
  пример «дважды два»
    дано н равно 2
    ожидается 4
  н плюс н

A false statement: for н = 0 the doubled value is not greater than the original. The answer is "refuted on the input н = 0".

модуль «Ложное»

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

A failed test: the mean of 1 and 2 is 1.5, and the test expects 2. Open the example in the "Tests" setup.

модуль «Среднее»

тотальная функция «Среднее двух»
  принимает а: число, б: число
  возвращает число
  пример «два и четыре»
    дано а равно 2
    дано б равно 4
    ожидается 3
  пример «один и два»
    дано а равно 1
    дано б равно 2
    ожидается 2
  (а плюс б) делить на 2

A theorem about lists: three statements about the sum and the length, proved for every list.

модуль «Списки»

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

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

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

утверждение «приписанный элемент удлиняет список на один»
  для всех л: список число
  для всех э: число
  утверждаем (длина (приписать э к л)) равна ((длина л) плюс 1)

Induction on your own type. The "Pictures" tab shows the proof tree: the base and the step.

модуль «Своё натуральное»

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

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

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

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

A monoid: joining strings, with the empty string as the unit. The laws are checked on the values from the tests; the picture shows the associativity square and the unit triangles.

модуль «Склейка строк»

тотальная функция «Склеить»
  принимает а: строка, б: строка
  возвращает строка
  пример «два слова»
    дано а равно "мир"
    дано б равно "ок"
    ожидается "мирок"
  пример «с пустой строкой»
    дано а равно ""
    дано б равно "ум"
    ожидается "ум"
  соединить [а, б] по ""

моноид «Склейка»
  носитель строка
  операция «Склеить»
  единица ""

A category and a functor: roubles are turned into kopecks. The square "issue the invoice, then convert" and "convert, then issue" has to commute.

модуль «Заказы и счета»

объект «Заказ»
  рубли является числом

объект «Счёт»
  рубли является числом

объект «Заказ в копейках»
  копейки является числом

объект «Счёт в копейках»
  копейки является числом

тотальная функция «Выставить»
  принимает заказ: «Заказ»
  возвращает «Счёт»
  пример «три рубля — счёт на тринадцать»
    дано заказ равно запись «Заказ» с рубли равным 3
    ожидается запись «Счёт» с рубли равным 13
  запись «Счёт» с рубли равным (заказ.рубли плюс 10)

тотальная функция «Выставить в копейках»
  принимает заказ: «Заказ в копейках»
  возвращает «Счёт в копейках»
  пример «триста копеек — счёт на тысячу триста»
    дано заказ равно запись «Заказ в копейках» с копейки равным 300
    ожидается запись «Счёт в копейках» с копейки равным 1300
  запись «Счёт в копейках» с копейки равным (заказ.копейки плюс 1000)

тотальная функция «Заказы равны»
  принимает а: «Заказ», б: «Заказ»
  возвращает признак
  а.рубли равен б.рубли

тотальная функция «Счета равны»
  принимает а: «Счёт», б: «Счёт»
  возвращает признак
  а.рубли равен б.рубли

тотальная функция «Заказы в копейках равны»
  принимает а: «Заказ в копейках», б: «Заказ в копейках»
  возвращает признак
  а.копейки равен б.копейки

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

тотальная функция «Заказ в копейки»
  принимает заказ: «Заказ»
  возвращает «Заказ в копейках»
  пример «три рубля — триста копеек»
    дано заказ равно запись «Заказ» с рубли равным 3
    ожидается запись «Заказ в копейках» с копейки равным 300
  запись «Заказ в копейках» с копейки равным (заказ.рубли умножить на 100)

тотальная функция «Счёт в копейки»
  принимает счёт: «Счёт»
  возвращает «Счёт в копейках»
  пример «тринадцать рублей — тысяча триста копеек»
    дано счёт равно запись «Счёт» с рубли равным 13
    ожидается запись «Счёт в копейках» с копейки равным 1300
  запись «Счёт в копейках» с копейки равным (счёт.рубли умножить на 100)

морфизм «выставить» из «Заказ» в «Счёт»
  даёт «Выставить»

морфизм «выставить в копейках» из «Заказ в копейках» в «Счёт в копейках»
  даёт «Выставить в копейках»

единица «Заказ»
единица «Счёт»
единица «Заказ в копейках»
единица «Счёт в копейках»

категория «Рубли»
  морфизм «выставить»
  объект «Заказ» даёт «Заказы равны»
  объект «Счёт» даёт «Счета равны»

категория «Копейки»
  морфизм «выставить в копейках»
  объект «Заказ в копейках» даёт «Заказы в копейках равны»
  объект «Счёт в копейках» даёт «Счета в копейках равны»

функтор «В копейки» из «Рубли» в «Копейки»
  объект «Заказ» отображается в «Заказ в копейках» даёт «Заказ в копейки»
  объект «Счёт» отображается в «Счёт в копейках» даёт «Счёт в копейки»
  морфизм «выставить» отображается в морфизм «выставить в копейках»

Sets: the letters of words, their intersection and inclusion. The picture shows circles with the letters.

модуль «Буквы»

тотальная функция «Гласные»
  возвращает список строки
  ["а", "е", "и", "о", "у"]

тотальная функция «Буквы слова мир»
  возвращает список строки
  ["м", "и", "р"]

тотальная функция «Буквы слова ум»
  возвращает список строки
  ["у", "м"]

тотальная функция «Пересечение»
  принимает первое: список строки, второе: список строки
  возвращает список строки
  отфильтровать первое где э → второе содержит э

тотальная функция «Вложение»
  принимает меньшее: список строки, большее: список строки
  возвращает признак
  (длина (отфильтровать меньшее где э → не (большее содержит э))) равна 0

утверждение «общие буквы мира и гласных — гласные»
  утверждаем «Вложение» от («Пересечение» от («Буквы слова мир») и («Гласные»)) и («Гласные»)

утверждение «у слов мир и ум общая только м»
  утверждаем («Пересечение» от («Буквы слова мир») и («Буквы слова ум»)) равно ["м"]

Reasoning in Russian

The conclusion follows from the premises.

Понятие: человек, люди.
Понятие: грек, греки.
Свойство: смертен, смертны.

Все люди смертны. Все греки — люди. Следовательно, все греки смертны.

From "all people are mortal" and "Socrates is mortal" it does not follow that Socrates is a person. The answer shows a counterexample.

Понятие: человек, люди.
Свойство: смертен, смертны.
Имя: Сократ.

Все люди смертны. Сократ смертен. Следовательно, Сократ — человек.

Formula

Addition of integers commutes, in LaTeX notation.

\forall x \in \mathbb{Z},\ \forall y \in \mathbb{Z},\ x + y = y + x

Multiplication of integers commutes, in Unicode notation.

∀ x ∈ ℤ, ∀ y ∈ ℤ, x * y = y * x

A false formula: the square of an integer is not always greater than the number. The kernel finds an input where it is false: x = 0.

∀ x ∈ ℤ, x * x > x

C → flang

The function clamp is proved completely. In midpoint the sum lo + hi goes past the bound of int for lo = 1, hi = 2147483647: the answer shows this input.

int clamp(int x, int lo, int hi)
{
    if (x < lo)
        return lo;
    if (x > hi)
        return hi;
    return x;
}

int midpoint(int lo, int hi)
{
    return (lo + hi) / 2;
}

A palindrome number with bool and a while loop. flang did not prove that the loop ends, and the answer says so.

#include <stdbool.h>

bool isPalindrome(int x) {
    if (x < 0 || (x % 10 == 0 && x != 0)) {
        return false;
    }
    int reversed = 0;
    while (x > reversed) {
        reversed = reversed * 10 + x % 10;
        x /= 10;
    }
    return x == reversed || x == reversed / 10;
}

Python → flang

The larger of two numbers is proved completely.

def max_of_two(a: int, b: int) -> int:
    if a > b:
        return a
    return b

A palindrome number: the end of the while loop is not proved, and the answer is "not everything is proved".

def is_palindrome(x: int) -> bool:
    if x < 0 or (x % 10 == 0 and x != 0):
        return False
    rev = 0
    while x > rev:
        rev = rev * 10 + x % 10
        x //= 10
    return x == rev or x == rev // 10

The sum from 1 to n with a for loop over range. The end of the loop is not proved either.

def sum_to(n: int) -> int:
    total = 0
    for i in range(1, n + 1):
        total += i
    return total

Limits