bend-lang 0.2.38

A high-level, massively parallel programming language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
# Syntax

This file provides a reference of each possible syntax of bend programming language.

Click [here](#imp-syntax) to see the syntax for "imp", the variant of bend that looks like an imperative language like python.

Click [here](#fun-syntax) to see the syntax for "fun", the variant of bend that looks like a functional language like Haskell or ML.

Click [here](#import-syntax) to see the import syntax.

Click [here](#comments) to see the syntax for commenting code.

Click [here](#imp-type-syntax) to see the imperative type syntax.

Click [here](#fun-type-syntax) to see the functional type syntax.

Both syntaxes can be mixed in the same file like the example below:

```python
object Point { x, y }

type MyTree = (Node ~left ~right) | (Leaf value)

type Bool:
  True
  False

#{
  The identity function is a function that always returns the value that
  was used as its argument.
#}
def identity(x):
  return x

main =
  let result = (identity 41)
  (+ result 1)
```

<div id="imp-syntax"></div>

# Imp Syntax

## Top-level definitions

### Def

Defines a top level function.

```python
def add(x: u24, y: u24) -> u24:
  result = x + y
  return result

def unchecked two() -> u24:
  return 2

def main() -> u24:
  return add(40, two)
```

A function definition is composed by a name, a sequence of parameters and a body.

A top-level name can be anything matching the regex `[A-Za-z0-9_.-/]+`, except it can't have `__` (used for generated names) or start with `//`.

The last statement of each function must either be a `return` or a selection statement (`if`, `switch`, `match`, `fold`)
where all branches `return`.

Each parameter of the function can receive a type annotation with `param_name: type` and the return value of the function can also be annotated with `def fn_name(args) -> return_type:`.

We can force the type-checker to run or not on a specific function by adding `checked` or `unchecked` between `def` and the function name.

### Type

Defines an algebraic data type.

```python
type Option:
  Some { value }
  None

type Tree(T):
  Node { value: T, ~left: Tree(T), ~right: Tree(T) }
  Leaf
```

Type names must be unique, and should have at least one constructor.

For a generic or polymorphic type, all type variables used in the constructors must be declared first in the type definition with `type Name(type_var1, ...):`

Each constructor is defined by a name followed by its fields. The fields can be annotated with types that will be checked when creating values of that type.

The `~` notation indicates a recursive field. To use `fold` statements with a type its recursive fields must be correctly marked with `~`.

The constructor names inherit the name of their types and become functions (`Tree/Node` and `Tree/Leaf` in this case).
The exact function they become depends on the encoding.

Read [defining data types](./defining-data-types.md) to know more.

### Object

Defines a type with a single constructor (like a struct, a record or a class).

```python
object Pair(A, B) { fst: A, snd: B }

object Function(T) { name: String, args, body: T }

object Vec { len, data }
```

The constructor created from this definition has the same name as the type.

Since it only has one constructor, `fold`ing a recursive `object` requires some additional stop condition apart from pattern matching on the value itself (like an `if` statement).

## Statements

### Assignment

```python
value = 2
return value

(first, second) = (1, 2)
return second

{x y} = {2 3}
```

Assigns a value to a variable.

It's possible to assign to a pattern, like a tuple or superposition, which will destructure the value returned by the expression.

```python
(first, second) = (1, 2)

first, second = 1, 2
```

### Use

```rust
use x = 2 + 3
return x + x
```

Inline copies of the declared bind, it is equivalent to this code:

```rust
return ((2 + 3) + (2 + 3))
```

### In-Place Operation

```python
x += 1
return x
```

The in-place operation does an infix operation and re-assigns a variable.

The operations are:

- Addition `+=`
- Subtraction `-=`
- Multiplication `*=`
- Division `/=`
- Bit And `&=`
- Bit Or `|=`
- Bit Xor `^=`
- Mapper `@=`

The mapper in-place operation applies a function and re-assigns the variable:

```python
x = "hello"
x @= String/uppercase
```

### Return

```python
return "hello"
```

Returns the expression that follows. The last statement of each branch of a function must be a `return`.

```py
# Allowed, all branches return
def max(a, b):
  if a > b:
    return a
  else:
    return b
```

```py
# Not allowed, early return
def Foo(x):
  if test_condition(x):
    return "err"
  else:
    y = map(x)

  return y
```

```py
# Not allowed, one of the branches doesn't return
def Foo(a, b):
  if a < b:
    return a
  else:
    c = a + b
```

### If

```python
if condition:
  return 0
else:
  return 1
```

A branching statement where `else` is mandatory.

The condition must return a `u24` number, where 0 will run the `else` branch and any other value will return the first one.

It is possible to make if-chains using `elif`:

```python
if condition1:
  return 0
elif condition2:
  return 1
elif condition3:
  return 2
else:
  return 3
```

The conditions are evaluated in order, one by one, stopping at the first successful case.

### Switch

```python
switch x = 5:
  case 0:
    return 6
  case 1:
    return 7
  case _:
    return x-2
```

A switch binds a variable name to the result of a given condition and branches to the case matching its value. Cases
must be listed from least to greatest, beginning with `0` and incrementing by 1. The last case must be `_`, which
catches all values not explicitly enumerated. Switches may only be used with native numbers values.

In the last case, the predecessor value is available with the name `bound_var-next_num`, where `bound_var` is the variable
set by the condition and `next_num` is the expected value of the next case. For example, the above example code returns
`3`, since `x-2` is bound to `5 - 2` and the value of `x` doesn't match any explicit case.

This switch statement is equivalent to the `if` from the previous section:

```python
switch _ = condition:
  case 0:
    # else branch
    return 1
  case _:
    # then branch
    return 0
```

### Match

```python
match x = Option/none:
  case Option/some:
    y = x.value
  case Option/none:
    y = 0
```

A pattern matching statement, the cases must be the constructor names of the matching value.

It is possible to bind a variable name to the matching value. The fields of the matched constructor are bound to `matched_var.field_name`.

### Fold

```python
fold x = Tree/Leaf:
  case Tree/Node:
    return x.value + x.left + x.right
  case Tree/Leaf:
    return 0
```

A fold statement. Reduces the given value with the given match cases.

It is possible to bind a variable name to the matching value. Just like in `match`, the fields are bound to `matched_var.field_name`.

For fields notated with `~` in the type definition, the fold function is called implicitly.

It is equivalent to the inline recursive function:

```python
def fold(x: Tree(u24)) -> u24:
  match x:
    case Tree/Node:
      return x.value + fold(x.left) + fold(x.right)
    case Tree/Leaf:
      return 0
...
fold(Tree/Leaf)
```

### Bend

Bend can be used to create recursive data structures:

```rust
bend x = 0:
  when x < 10:
    left = fork(x + 1)
    right = fork(x + 1)
    y = Tree/Node(left, right)
  else:
    y = Tree/Leaf(x)
```

Which binds a variable to the return of an inline recursive function.
The function `fork` is available inside the `when` arm of the `bend` and calls it recursively.

It is possible to pass multiple state variables, which can be initialized:

```python
bend x = 1, y = 2 ...:
  when condition(x, y, ...):
    ...
```

When calling `fork`, the function must receive the same number of arguments as the number of state variables.

It is equivalent to this inline recursive function:

```python
def bend(x, y, ...):
  if condition(x, y, ...):
    ...
    return ... bend(x, y, ...) ...
  else:
    return ...
```

### Open

```python
p = Point { x: 1, y: 2 }
open Point: p
return Point { x: p.x * p.x, y: p.y * p.y }
```

Brings the inner fields of an object into scope. The original variable can still be accessed, but doing so will cause any used fields to be duplicated.

It's equivalent to pattern matching on the object, with the restriction that its type must have only one constructor.

```python
open Point: p
...

# Equivalent to:
match p:
  Point:
    ...
```

### With block

```python
with Result:
  x <- safe_div(2, 0)
  return x
```

A monadic `with` block.

Where `x <- ...` performs a monadic operation.

Expects `Result` to be a type defined with `type` or `object` and the function `Result/bind` to be defined.
The monadic bind function should be of type `(Result a) -> (a -> Result b) -> Result b`, like this:

```python
def Result/bind(res, nxt):
  match res:
    case Result/Ok:
      nxt = undefer(nxt)
      return nxt(res.value)
    case Result/Err:
      return res
```

However, the second argument, `nxt`, is actually a deferred call to the continuation, passing any free variables as arguments.
Therefore, all `bind` functions must call the builtin function `undefer` before using the value of `nxt`, as in the example above.
This is necessary to ensure that the continuation in recursive monadic functions stays lazy and doesn't expand infinitely.

This is an example of a recursive function that would loop if passing the variable `a` to the recursive call `Result/foo(a, b)` was not deferred:

```python
def Result/foo(x, y):
  with Result:
    a <- Result/Ok(1)
    if b:
      b = Result/Err(x)
    else:
      b = Result/Ok(y)
    b <- b
    return Result/foo(a, b)
```

Other statements are allowed inside the `with` block and it can both return a value at the end and bind a variable, like branching statements do.

```python
# Also ok:
with Result:
  x <- safe_div(2, 0);
  y = x
return y
```

The name `wrap` is bound inside a `with` block as a shorthand for `Type/wrap`,
and it calls the unit function of the monad, also called `pure` in some languages:

```python
def Result/wrap(x):
  return Result/Ok(x)

with Result:
  x <- some_operation(...)
  y <- some_operation(...)
  return wrap(x * y)
```

### Def

Creates a local function visible in the current block capturing variables:

```python
def main() -> _:
  y = 41
  x = 1
  def aux_add(x):
    return x + y
  return aux_add(x)
```

## Expressions

### Variables

```python
some_var

foo/bar
```

A variable can be anything matching the regex `[A-Za-z0-9_.-/]+` but with some restrictions:

- It can not start with `//`
- It can not contain `__`

A variable is a name for some immutable expression. It is possible to rebind variables with the same name.

```python
x = 1
x = x + 1
```

Note that `-` is also used for negative numbers and as the numeric operator. Bend's grammar is greedily parsed from left to right, meaning that `x-3` always represents a name and not `x - 3` or a sequence of expressions like in `[x -3]`.

### Lambdas

```python
lambda x: x

lambda x, y: y

λx y: x
```

Lambdas represents anonymous inline functions, it can bind a variable and has an expression as body.

Using `,` is optional.

### Unscoped Lambdas and Variables

```python
lambda $x: $x

λ$x $y: $x
```

Like lambdas, with the exception that the variable starts with a `$` sign. Every unscoped variable in a function must have a unique name and must be used exactly once.

Unscoped variables are not transformed and linearized like normal scoped variables.

Read [using scopeless lambdas](/docs/using-scopeless-lambdas.md) to know more about their behavior.

### Function Call

```python
callee(arg_1, arg_2, arg_n)
```

A call is written with a callee followed by a list of arguments. Arguments can be optionally separated by `,`.

The effect of a function call is to substitute the callee with it's body and replace the arguments by the passed variables.

The called function can be any expression and it supports partial applications.

Optionally, if you call a function by its name, you can used named arguments:

```python
callee(expr1, expr2, arg4 = expr3, arg3 = expr4)
```

In case named arguments are used, they must come after the positional arguments and the function must be called with exactly the number of arguments of its definition.

### Eraser

```python
*

eraser = *

*(41 + 1)  # applies 41 + 1 to `*` erasing the number and returns `*`

* = 41 + 1 # erases 41 + 1
```

The effect of an eraser is to free memory. Erasers behave like a `null`.

It's impossible to compare or match eraser values.

It is implicitly inserted for variables that have not been used:

```python
def constant(x):
  return 8345
```

### Tuple

```python
(3, 9)
```

A Tuple is surrounded by `(` `)` and should contain 2 or more elements. Elements are separated by `,`.

### Superposition

```python
{1 2 3}
```

A superposition of values is defined using `{` `}` with at least 2 expressions inside. Elements can be optionally separated by `,`.

Read [sups and dups](./dups-and-sups.md) to know more.

### Numbers and Infix Operations

Currently, bend supports 3 types of numbers: floats, integers and unsigned integers. All of then are 24 bit sized.

```python
f24 = +88.012

i24 = -42

u24 = 42
```

Currently, We can't write operations that mix two types of number but we can explicitly convert between them.

| Operation             | Syntax   | Supported Types  |
| --------------------- | -------- | ---------------- |
| Addition              | x + y    | int, float, uint |
| Subtraction           | x - y    | int, float, uint |
| Multiplication        | x \* y   | int, float, uint |
| Division              | x / y    | int, float, uint |
| Remainder             | x % y    | int, float, uint |
| Exponentiation        | x \*\* y | float            |
| Equal                 | x == y   | int, float, uint |
| Not Equal             | x != y   | int, float, uint |
| Less Than             | x < y    | int, float, uint |
| Greater Than          | x > y    | int, float, uint |
| Less Than or Equal    | x <= y   | int, float, uint |
| Greater Than or Equal | x >= y   | int, float, uint |
| Bitwise And           | x & y    | int, uint        |
| Bitwise Or            | x \| y   | int, uint        |
| Bitwise Xor           | x ^ y    | int, uint        |
| Bitwise Right Shift   | x >> y   | uint             |
| Bitwise Left Shift    | x << y   | uint             |

Hexadecimal and binary floating-point literals are also supported.

In these representations, each digit after the point is divided according to the base’s power of the digit's position.
Specifically, for hexadecimal floating-point numbers, each place after the dot represents a fraction of 16 to the power of the digit's depth.
Similarly, for binary floating-point numbers, each place after the dot represents a fraction of 2 to the power of the digit's depth.

```python
0xA.A == 10.625

0b111.111 == 7.875
```

### Constructor Literals

Constructors are just functions.
A Constructor expression is equivalent to calling a Constructor function, they have 2 syntaxes:

```python
# Constructor syntax, requires all field names
Type/Ctr { field1: 4, field2: 8 }

# Function syntax
Type/Ctr(field1 = 4, field2 = 8)

Type/Ctr(4, field2 = 8)

Type/Ctr(4, 8)

Type/Ctr(4) # Can be partially applied if not using named arguments
```

### Character Literal

```python
'x'
```

A Character is surrounded with `'`. Accepts unicode characters, unicode escapes in the form '\u{hex value}' and is desugared to the unicode codepoint as an `u24`.

Only supports unicode codepoints up to `0xFFFFFF`.

### Symbol Literal

```python
# Becomes 2146 (33 << 6 + 34)
`hi`
```

A Symbol encodes a up to 4 base64 characters as a `u24` number. It is surrounded by `\``.

Empty characters are interpreted as `A` which has value 0, meaning that `B` is the same as `AAAB`.

### String Literal

```python
"Hello, World!"
```

A String literal is surrounded with `"`. Accepts the same values as characters literals.

It is desugared to constructor calls of the built-in type String, `String/cons(head, ~tail)` and `String/nil` .

### List Literal

```python
[1, 2, "three"]
```

A List literal is surrounded by `[` `]`. The elements must be separated by `,`.

It is desugared to constructor calls of the built-in type List, `List/cons(head, ~tail)` and `List/nil` .

### Tree Literals

```python
![![1, 2], ![3, 4]]
```

The Tree literals `![]` and `!` are used to create values of the built-in type `Tree`.

`![a b]` is equivalent to `Tree/Node(a, b)`.

`!x` is equivalent to `Tree/Leaf(x)`.

### Map Literals

```python
{ 0: 4, `hi`: "bye", 'c': 2 + 3 }
x[0] = 5     # Assigns the key 0 to the value 5
return x[0]  # Gets the value of the key 0
```

Bend has a built-in binary tree map data structure where the key is a `u24`, meaning you can use numbers, characters, and symbols as keys.

### List Comprehension

```python
[x + 1 for x in list]

[x + 1 for x in list if x > 2]
```

A List Comprehension generates a new list, it can be extracted in 3 parts.

`[expression . iterator . condition]`

Expression: The expression to be performed in the iterator element.

Iterator: Binds a name to the list elements.

Condition: Optional, is used to filter the list elements.

It is desugared to a fold statement:

```python
fold list:
  List/cons:
    if condition:
      List/cons(list.head, list.tail)
    else:
      list.tail
  List/nil:
    List/nil
```

<div id="fun-syntax"></div>

# Fun Syntax

## Top-level definitions

```rust
type Name
  = (Ctr1 arg1 arg2)
  | Ctr2

Name (Ctr1 sub_arg1 sub_arg2) arg3 = rule0_body
Name Ctr2 arg3 = rule1_body
```

A top-level name can be anything matching the regex `[A-Za-z0-9_.-/]+`, except it can't have `__` (used for generated names) or start with `//`.

### Function Definitions

A function definition is composed of a sequence of pattern matching equations.
Each rule is the name of the function, a sequence of patterns and then the body.

```rust
identity x = x

(Bool.neg True)  = False
(Bool.neg False) = True

MapMaybe (Some val) f = (Some (f val))
MapMaybe None f = None

Pair.get (fst, snd) f = (f fst snd)
```

A rule pattern can be:

- A variable.
- A number.
- A constructor.
- A tuple.
- A superposition.
- A wildcard `*`.

And the builtin types that desugar to one of the above:

- A list (becomes a constructor).
- A string (becomes a constructor).
- A natural number (becomes a constructor).
- A character (becomes a number).
- A symbol (becomes a number);

Unscoped variables can't be defined in a rule pattern.

The rule body is a term, there are no statements in the Fun variant of Bend.

Read [pattern matching](./pattern-matching.md) to learn about what exactly the rules for pattern matching equations are.

### Type

Defines an Algebraic Data Type, it should have at least one constructor.

```rust
type Tree
  = (Leaf value)
  | (Node ~left ~right)
  | Nil
```

`Tree` is the ADT name and it should be unique, except that it can be used once by a constructor name.

Each constructor is defined by a name followed by its fields. The `~` notation describes a recursive field.

The constructors inherit the name of their types and become functions (`Tree/Node` and `Tree/Leaf` in this case).

## Terms

### Variables

A variable can be anything matching the regex `[A-Za-z0-9_.-/]+` but with some restrictions:

- It can not start with `//`
- It can not contain `__`

A variable is a name for some immutable expression. It is possible to rebind variables with the same name.

```rust
let x = 1
let x = (+ x 1)
```

### Lambda

```rust
@x x

λx x

λ(fst, snd) snd

λ{x y} x
```

Lambdas represents anonymous inline functions, it can be written with `λ` or `@` followed by a pattern and a term.

A tuple or duplication pattern is equivalent to a lambda followed by a `let`.

```rust
λ(fst, snd) snd
λa let (fst, snd) = a; snd

λ{x y} (x y)
λa let {x y} = a; (x y)
```

### Unscoped Variables

```rust
λ$x $x
```

Like a normal scoped variable, but starts with a `$` sign. Every unscoped variable in a function must have a unique name and must be used exactly once.
They can be defined anywhere a scoped variable would be defined in a term, like in a lambda or a `let`.

Unscoped variables are not transformed and linearized like normal scoped variables.

Read [using scopeless lambdas](/docs/using-scopeless-lambdas.md) to know more about.

### Application

```rust
(fun arg_1 arg_2 ... arg_n)
```

An application is surrounded by `(` `)`, written in lisp style.

> Lambdas have a higher precedence, so `(@x x 1)` and `((@x x) 1)` means the same thing.

### Tuples

```rust
(1, 2, 3)
```

A tuple is surrounded by `(` `)`, with the difference that it's elements are separated by `,`.

### Superposition

```rust
{1 2 3}
```

A superposition of values is defined using `{` `}` with at least 2 terms inside.

Read [sups and dups](./dups-and-sups.md) to know more.

### Let-bindings

```rust
let x = (+ 1 2)
x

let (fst, snd, era) = (1, 2, *);
(+ fst snd)

let {f1 f2} = λx x;
(f1 f2)

let $x = (some_fn $x);
*
```

> `*` is an eraser term.

A let term uses a pattern, it can be:

- A variable / unscoped variable.
- A tuple.
- A superposition.

The let term will expects a binding value followed by a `next` term.

Using `;` is optional.

### Use

```rust
use x = (+ 2 3)
(+ x x)
```

Inline copies of the declared bind, it is equivalent to this code:

```rust
(+ (+ 2 3) (+ 2 3))
```

### Switch

```rust
switch n {
  0: "zero"
  1: "one"
  _: "greater than 1"
}

switch x = (+ 1 1) {
  0: 42;
  _: x-1;
}
```

A switch for native numbers, it can hold a name binding if the matching term is not a variable.

The cases need to be typed from `0` to a wildcard `_` in sequence.

In the last case, the predecessor value is available with the name `bound_var-next_num`, where `bound_var` is the variable
set by the condition and `next_num` is the expected value of the next case. For example, the above example code returns
`1`, since `x-1` is bound to `(+ 1 1) - 1` and the value of `x` doesn't match any explicit case.

Using `;` is optional.

### Match

```rust
match opt = (Some "Bend") {
  Some: opt.value;
  None: "No name";
}
```

A pattern match expression, it can hold a name binding if the matching term is not a variable.

It is possible to use a _wildcard_, a named variable or `*` as default cases.

It is desugared according to the chosen encoding. Read [pattern matching](./pattern-matching.md) to know more.

Using `;` is optional.

### If

```rust
if condition {
  ...then
} else {
  ...else
}
```

A branching expression where `else` is mandatory.

The condition must return a `u24` number, where 0 will run the `else` branch and any other value will return the first one.

It is equivalent to this switch:

```rust
switch _ = condition {
  0: else
  _: then
}
```

It is possible to make if-chains using `elif`:

```rust
if condition1 {
  0
} elif condition2 {
  1
} elif condition3 {
  2
} else {
  3
}
```

### Bend

Bend can be used to create recursive data structures:

```rust
main =
  bend x = 0 {
    when (< x 3):
      (Tree/Node (fork (+ x 1)) (fork (+ x 1)))
    else:
      (Tree/Leaf x)
  }
```

Which binds a variable to the return of an inline recursive function.
The function `fork` is available inside the `when` arm of the `bend` and calls it recursively.

It is possible to pass multiple state variables, which can be initialized:

```rust
bend x = 0, y = 1 ... {
  when (condition x y ...):
    ...
}
```

When calling `fork`, the function must receive the same number of arguments as the number of state variables.

It is equivalent to this inline recursive function:

```rust
bend x y ... =
  if (condition x y ...) {
    ...
    ... (bend x y ...) ...
  } else {
    ...
  }
```

### Open

```rust
let x = (Pair 1 2);
open Pair x;
(+ x.fst x.snd)
```

Brings the inner fields of an object into scope. The original variable can still be accessed, but doing so will cause any used fields to be duplicated.

It's equivalent to pattern matching on the value, with the restriction that its type must have only one constructor.

```rust
let x = (Pair 1 2)
match x {
  Pair: (+ x.fst x.snd)
}
```

### With block

```rust
Result/bind (Result/Ok val) nxt = ((undefer nxt) val)
Result/bind err _nxt = err

div a b = switch b {
  0: (Result/Err "Div by 0")
  _: (Result/Ok (/ a b))
}

rem a b = switch b {
  0: (Result/Err "Mod by 0")
  _: (Result/Ok (% a b))
}

Main = with Result {
  ask y = (div 3 2);
  ask x = (rem y 0);
  x
}
```

Receives a type defined with `type` and expects `Result/bind` to be defined as a monadic bind function.
It should be of type `(Result a) -> (a -> Result b) -> Result b`, like in the example above.

However, the second argument, `nxt`, is actually a deferred call to the continuation, passing any free variables as arguments.
Therefore, all `bind` functions must call the builtin function `undefer` before using the value of `nxt`, as in the example above.
This is necessary to ensure that the continuation in recursive monadic functions stays lazy and doesn't expand infinitely.

This is an example of a recursive function that would loop if passing the variable `a` to the recursive call `Result/foo(a, b)` was not deferred:

```python
Result/foo x y = with Result {
  ask a = (Result/Ok 1)
  ask b = if b {
    (Result/Err x)
  } else {
    (Result/Ok y)
  }
  (Result/foo a b)
}
```

Inside a `with` block, you can use `ask`, to access the continuation value of the monadic operation.

```rust
ask y = (div 3 2)
ask x = (rem y 0)
x

# Becomes
(Result/bind (div 3 2) λy (Result/bind (rem y 0) λx x))
```

It can be used to force a sequence of operations. Since the continuation receives the result through a lambda, it is only fully evaluated after something is applied to it.

The name `wrap` is bound inside a `with` block as a shorthand for `Type/wrap`,
the equivalent as a `pure` function in other functional languages:

```rust
Result/wrap x = (Result/Ok x)

with Result {
  ask x = (some_operation ...)
  ask y = (some_operation ...)
  (wrap (* x y))
}
```

### Def

Creates a local function visible in the current block capturing variables:

```rust
main =
  let base = 0
  def aux [] = base
      aux (List/Cons head tail) = (+ head (aux tail))
  (aux [1, 2, 3])
```

### Numbers and operations

Currently, bend supports 3 types of numbers: floats, integers and unsigned integers. All of then are 24 bit sized.

```rust
f24 = +88.012

i24 = -42

u24 = 42
```

Currently, the 3 number types cannot be mixed.

| Operation             | Syntax     | Supported Types  |
| --------------------- | ---------- | ---------------- |
| Addition              | (+ x y)    | int, float, uint |
| Subtraction           | (- x y)    | int, float, uint |
| Multiplication        | (\* x y)   | int, float, uint |
| Division              | (/ x y)    | int, float, uint |
| Remainder             | (% x y)    | int, float, uint |
| Exponentiation        | (\*\* x y) | float            |
| Equal                 | (== x y)   | int, float, uint |
| Not Equal             | (!= x y)   | int, float, uint |
| Less Than             | (< x y)    | int, float, uint |
| Greater Than          | (> x y)    | int, float, uint |
| Less Than or Equal    | (<= x y)   | int, float, uint |
| Greater Than or Equal | (>= x y)   | int, float, uint |
| Bitwise And           | (& x y)    | int, uint        |
| Bitwise Or            | (\| x y)   | int, uint        |
| Bitwise Xor           | (^ x y)    | int, uint        |
| Bitwise Right Shift   | (>> x y)   | uint             |
| Bitwise Left Shift    | (<< x y)   | uint             |

Hexadecimal and binary floating-point literals are also supported.

In these representations, each digit after the point is divided according to the base’s power of the digit's position.
Specifically, for hexadecimal floating-point numbers, each place after the dot represents a fraction of 16 to the negative power of the digit's depth.
Similarly, for binary floating-point numbers, each place after the dot represents a fraction of 2 to the negative power of the digit's depth.

```python
(== 0xA.A 10.625)

(== 0b111.111 7.875)
```

### Character Literal

```rust
'a'
```

A Character is surrounded with `'`. Accepts unicode characters, unicode escapes in the form '\u{hex value}' and is desugared to the unicode codepoint as an `u24`.

Only supports unicode codepoints up to `0xFFFFFF`.

### Symbol Literal

```python
# Becomes 2146 (33 << 6 + 34)
`hi`
```

A Symbol encodes a up to 4 base64 characters as a `u24` number. It is surrounded by `\``.

Empty characters are interpreted as `A` which has value 0, meaning that `B` is the same as `AAAB`.

### String Literal

```rust
"Hello"
```

A String literal is surrounded with `"`. Accepts the same values as characters literals.

The syntax above is desugared to:

```
(String.cons 'H' (String.cons 'e' (String.cons 'l' (String.cons 'l' (String.cons 'o' String.nil)))))
```

### List Literal

```rust
[1, 2, 3 4]
```

The syntax above is desugared to:

```
(List.cons 1 (List.cons 2 (List.cons 3 (List.cons 4 List.nil))))
```

Using `,` is optional.

### Tree Literals

```python
![![1, 2], ![3, 4]]
```

The Tree literals `![]` and `!` are used to create values of the built-in type `Tree`.

`![a b]` is equivalent to `Tree/Node(a, b)`.

`!x` is equivalent to `Tree/Leaf(x)`.

### Nat Literal

```rust
#3
```

The syntax above is desugared to:

```
(Nat/succ (Nat/succ (Nat/succ Nat/zero)))
```

# Native HVM definitions

```py
# This function causes two ports to be linked and returns *.
# This can be used to interpret a lambda as an application and apply something to it for example.
# It can be used like this: `let * = (link_ports @x x y)`
hvm link_ports:
  (a (b *))
  & (c a) ~ (d e)
  & (e b) ~ (d c)

# Casts a `u24` to itself.
# We can give type annotations to HVM definitions.
hvm u24_to_u24 -> (u24 -> u24):
  ($([u24] ret) ret)
```

It's also possible to define functions using HVM syntax. This can be
thought of as a way to write "HVM assembly" directly in a Bend program.
You can find the reference of this syntax in the [HVM paper](https://github.com/HigherOrderCO/HVM/blob/main/paper/PAPER.pdf).

This is meant for writing things that would otherwise be hard or
impossible to write in normal Bend syntax.

It will also ignore all term-level compiler passes and so can be
useful for writing programs with exact behaviour that won't ever be
changed or optimized by the compiler.

<div id="import-syntax"></div>

# Import Syntax

### Import Relative to the File

Paths starting with `./` or `../` are imported relative to the file.

### Import Relative to the Main Folder

Paths that do not start with `./` or `../` are relative to the folder of the main file.

## Syntax

### Import Specific Names from a File, or Files from a Folder

```py
from path import name
from path import (name1, name2)
import (path/name1, path/name2)
```

### Import All Names from a File, or All Files from a Folder

```py
from path import *
```

### Aliasing Imports

```py
from path import name as alias
from path import (name1 as Alias1, name2 as Alias2)
import path as alias
import (path/name1 as Alias1, path/name2 as Alias2)
```

<div id="comments"></div>

# Comments

## Syntax

### Single Line Comment

Use `#` to indicate a single line comment.

```py
# Single line comment

def main():
  # return 0
```

### Multi Line Comment

Use `#{ ... #}` to indicate a multi-line comment.

Multi-line commenting should also be used to document code.
Documentation for functions is meant to be written as a multiline comment right above the function.
```py
#{
  Expects two arguments to be passed.

  This function always returns the second value that was used as argument.
#}
def second(x: A, y: B) -> B:
  return y
```

<div id="imp-type-syntax"></div>

# Imp Type Syntax

## Variable

Any name represents a type variable.

Used in generic or polymorphic type definitions.

```python
# T is a type variable
type Option(T):
  Some { value: T }
  None

# A is a type variable
def id(x: A) -> A:
  return x
```

## Constructor

`Ctr(...)` represents a constructor type.

Used for defining custom data types or algebraic data types.
Can contain other types as parameters.

```python
def head(list: List(T)) -> Option(T)
  match list:
    case List/Nil:
      return Option/None
    case List/Cons:
      return Option/Some(list.head)
```

## Any

`Any` represents the untyped type.

It accepts values of alls type and will forcefully cast any type to `Any`.

Can be used for values that can't be statically typed, either because
they are unknown (like in raw IO calls), because they contain untypable
expressions (like unscoped variables), or because the expression cannot
be typed with the current type system (like the self application `lambda x: x(x)`).

```python
def main -> Any:
  return 24
```

## None

`None` represents the eraser `*` or absence of a value.

Often used to indicate that a function doesn't return anything.

```python
def none -> None:
  return *
```

## Hole

`_` represents a hole type.

This will let the type checker infer the most general type for an argument or return value.

```python
def increment(x: _) -> _:
  return x + 1
```

## u24

`u24` represents an unsigned 24-bit integer.

```python
def zero -> u24:
  return 0
```

## i24

`i24` represents a signed 24-bit integer.

```python
def random_integer -> i24:
  return -42
```

## f24

`f24` represents a 24-bit floating-point number.

```python
def PI -> f24:
  return 3.14
```

## Tuple

`(_, _, ...)` represents a tuple type.

Can contain two or more types separated by commas.

```python
def make_tuple(fst: A, snd: B) -> (A, B):
  return (fst, snd)
```

## Function

`a -> b` represents a function type.

`a` is the input type, and `b` is the output type.

```python
def apply(f: A -> B, arg: A) -> B:
  return f(arg)
```

<div id="fun-type-syntax"></div>

# Fun Type Syntax

## Variable

Any name represents a type variable.

Used in generic or polymorphic type definitions.

```python
# T is a type variable
type (Option T)
  = (Some T)
  | None

# A is a type variable
id : A -> A
id x = x
```

## Constructor

`(Ctr ...)` represents a constructor type.

Used for defining custom data types or algebraic data types.
Can contain other types as parameters.

```python
head : (List T) -> (Option T)
head [] = Option/None
head (List/Cons head _) = (Option/Some head)
```

## Any

`Any` represents the untyped type.

It accepts values of alls type and will forcefully cast any type to `Any`.

Can be used for values that can't be statically typed, either because
they are unknown (like in raw IO calls), because they contain untypable
expressions (like unscoped variables), or because the expression cannot
be typed with the current type system (like the self application `λx (x x)`).

```python
main : Any
main = @x x
```

## None

`None` represents the eraser `*` or absence of a value.

Often used to indicate that a function doesn't return anything.

```python
none : None
none = *
```

## Hole

`_` represents a hole type.

This will let the type checker infer the most general type for an argument or return value.

```python
increment : _ -> _
increment x = (+ x 1)
```

## u24

`u24` represents an unsigned 24-bit integer.

```python
zero : u24
zero = 0
```

## i24

`i24` represents a signed 24-bit integer.

```python
random_integer : i24
random_integer = -24
```

## f24

`f24` represents a 24-bit floating-point number.

```python
PI : f24
PI = 3.14
```

## Tuple

`(_, _, ...)` represents a tuple type.

Can contain two or more types separated by commas.

```python
make_tuple : A -> B -> (A, B)
make_tuple fst snd = (fst, snd)
```

## Function

`a -> b` represents a function type.

`a` is the input type, and `b` is the output type.

```python
apply : (A -> B) -> A -> B
apply f arg = (f arg)
```