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.
| Setup | What it does | Address |
|---|---|---|
| First program | computes a function and runs its tests | #setup=first |
| Proofs | shows which postconditions and statements are proved | #setup=proof |
| Tests | shows a table of tests: input, expected, actual | #setup=tests |
| Code generation | translates the program to C, Go, Rust and seven more languages | #setup=emit |
| Reasoning in Russian | checks whether the conclusion follows from the premises | #setup=reasoning |
| Formula | translates a formula with ∀ and ∃ to flang and checks it | #setup=formula |
| Your own text | reads 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 → flang | translates a C function and checks the translation | #setup=c |
| Python → flang | translates 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
- Ctrl+Enter presses the main button of the setup.
- Half a second after an edit the playground checks the text by itself. In the setups "Your own text", "C → flang" and "Python → flang" only the button starts the check.
- The "Example…" list holds the ladder of the open setup: examples from the simplest to the hardest, with the step number before each name. Below, in the same list, are the examples of this page.
- The line under the buttons says which step is open and what to look at in the answer. After the text is edited, a hint about the ladder takes its place.
- "Share" copies a link that holds the setup and the text from the editor.
- "Reset" restores the first step of the ladder of the setup.
- The text of every setup is saved in the browser and comes back after a page reload.
- The "Terminal" tab shows the compiler output as in a terminal. The setups that translate from C and Python do not have it.
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.
| Mode | How to enter | What the keys do |
|---|---|---|
| normal | Esc | commands: moving, editing, searching |
| insert | i a I A o O | type text |
| visual | v, by lines — V | motions 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 supported | Keys |
|---|---|
| Moving | h 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 command | 3w, 2dd, 5j, 10G |
| Operators | d c y > < gu gU g~ with any motion; dd cc yy >> <<; D C x X s S Y |
| Editing | p P, r, J, ~; . repeats the last edit |
| Undo | u undoes an edit, Ctrl+R brings it back |
| Text objects | iw 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 |
| Names | gd — to the declaration of a name; K — the header of the function under the cursor |
| Completion in insert mode | Ctrl+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 right | gt 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.
| Command | What it does |
|---|---|
:w | saves the draft in the browser |
:check, :proof | checks the text; :proof opens the "Check" tab |
:test | runs the tests |
:run, :run Удвоить {"н": 2} | computes a function; the name and the arguments may follow |
:emit go | generates code in the named language |
:setup proof, :example hello | opens a setup or a step of a ladder by its name |
:set nu, :set nonu, :set rnu | line numbers: plain, none, counted from the cursor line |
:set ic, :set noic | a search that ignores letter case, and one that does not |
:help | opens this section |
:q | closes 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:
- One function and one test
- A choice: if, then, else
- A list: head and tail
- Your own type with variants
- A loop that keeps values
- 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:
- "proved" — true for every input;
- "tests only" — no violation was found, but there is no proof;
- "not proved" — there is neither a proof nor tests, or the proof kernel did not derive the goal;
- "refuted" — an input where the statement is false is shown.
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:
- A postcondition proved for all numbers
- A false postcondition and a counterexample
- A condition on the input: «требует»
- A list: a postcondition for every length
- A theorem by induction on your own type
- 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:
- One test: given and expected
- Three tests: a usual case and two edge cases
- A test that fails
- Tests with lists
- 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:
- One function in C
- A branch in Go
- A list and recursion in Python
- Your own type in Rust
- 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:
- All, all, therefore all
- A name instead of «все» (all)
- A denial: «ни один» (no one)
- A part: «некоторые» (some)
- 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:
- An equality for any two integers
- LaTeX notation and three numbers
- A condition: if, then
- The sign ∃: «there is such a number»
- A formula about a list
- 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:
- whether a conclusion follows from what was said before it;
- whether any statements contradict each other.
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:
- green "understood" — the sentence takes part in the check;
- yellow "states nothing" — there is no statement in it: it names a thing, as «Тёплое летнее утро.» (a warm summer morning) does, or asks for something, as «Запомните это правило.» (remember this rule) does; the reason stands next to it;
- grey "not understood" — the sentence was not read, and the reason stands next to it;
- grey "too long" — the sentence has more than 30 words and has to be split;
- grey "skipped: not a sentence" — the line is an entry of a list of references, a heading in capitals or a note in brackets; it is not read, and the reason stands next to it.
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:
- A correct chain
- An everyday argument
- A conclusion that does not follow
- A contradiction
- Two mistakes in one text
- A textbook definition
- A request among statements
- Sentences that are not understood
- A text with a list of references
- 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:
- A language of three commands
- Words that read as a phrase
- A rule inside a rule and a property of every rule
- Its own notation: the program comes as text
- 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:
- One function with one branch
- Three branches
- Division: a zero is found
- An int overflow
- One function calls another
- 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:
- One function with one branch
- A loop over a list
- Lists in one line
- Division: a zero is found
- Recursion on the tail of a list
- 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
- The first run downloads the compiler, about 10 MB. After that it comes from the browser cache.
- A computation gets 3 000 000 steps, a command 120 seconds.
- There is no network and there are no files: a program sees the text from the editor and the library.
- In the "Your own text" setup the kernel gets 90 seconds for the check.