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
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
|
The Myrddin Programming Language
Jul 2012
Updated Feb 2017
Ori Bernstein
TABLE OF CONTENTS:
1. ABOUT
2. LEXICAL CONVENTIONS
2.1. EBNF-ish
2.2. As-If Rule
3. STRUCTURE:
3.1. Whitespace and Keywords
3.2. Top Level Structure
3.3. Declarations
3.4. Packages and Uses
3.5. Scoping
4. TYPES
4.1. Primitive Types
4.2. User Defined Types
4.3. Generic Types
4.4. Traits and Impls
4.5. Type Inference
4.6. Built in Traits
5. VALUES AND EXPRESSIONS
5.1. Literal Values
5.2. Expressions
6. CONTROL FLOW
6.1. Blocks
6.2. Conditionals
6.3. Matches
6.4. Looping
6.5. Goto
7. GRAMMAR
1. ABOUT:
Myrddin is designed to be a simple, low-level programming
language. It is designed to provide the programmer with
predictable behavior and a transparent compilation model,
while at the same time providing the benefits of strong type
checking, generics, type inference, and similar. Myrddin is
not a language designed to explore the forefront of type
theory or compiler technology. It is not a language that is
focused on guaranteeing perfect safety. Its focus is on being
a practical, small, fairly well defined, and easy to
understand language for work that needs to be close to the
hardware.
Myrddin is a computer language influenced strongly by C and
ML, with ideas from too many other places to name.
2. LEXICAL CONVENTIONS:
2.1. EBNF-ish:
Syntax is defined using an informal variant of EBNF.
token: /regex/ | "quoted" | <informal description>
prod: prodname ":" expr*
expr: alt ( "|" alt )*
alt: term term*
term: prod | token | group | opt | rep
group: "(" expr ")" .
opt: "[" expr "]" .
rep: zerorep | onerep
zerorep: term "*"
onerep: term "+"
Whitespace and comments are ommitted in this description.
To put it in words, /regex/ defines a regular expression that would
match a single token in the input. "quoted" would match a single
string. <english description> contains an informal description of what
characters would match.
Productions are defined by any number of expressions, in which
expressions are '|' separated sequences of terms.
Terms can are productions or tokens, and may come with a repeat
specifier. wrapping a term in "[]" denotes that the term is repeated
0 or 1 times. suffixing it with a '*' denotes 0 or more repetitions,
and '+' denotes 1 or more repetitions.
2.2. As-If Rule:
Anything specified here may be treated however the compiler wishes,
as long as the result is observed as if the semantics specified were
followed strictly.
3. STRUCTURE:
3.1. Whitespace and Keywords:
The language is composed of several classes of tokens. There are
comments, identifiers, keywords, punctuation, and whitespace.
Comments begin with "/*" and end with "*/". They may nest.
/* this is a comment /* with another inside */ */
Alternatively, '//' may be used to denote a comment. This comment
will extend to the end of the current line. Newlines within a line
comment may not be escaped.
// this is a line comment
// it will end on this line, regardless of the trailing \
Identifiers begin with any alphabetic character or underscore, and
continue with alphanumeric characters or underscores. Currently the
compiler places a limit of 1024 bytes on the length of the identifier.
some_id_234__
Keywords are a special class of identifier that is reserved by the
language and given a special meaning. The full set of keywords are
listed below. Their meanings will be covered later in this reference
manual.
$noret _ break
castto const continue
elif else extern
false for generic
goto if impl
in match pkg
pkglocal sizeof struct
trait true type
union use var
void while
Literals are a direct representation of a data object within the
source of the program. There are several literals implemented within
the language. These are fully described in section 4.2 of this
manual.
Single semicolons (';') and newline (\n) characters are synonymous and
interchangable. They both are used to mark the end of logical lines,
and will be uniformly referred to as line terminators.
3.2. Top Level Structure:
file: (decl | package | use | impldef | traitdef | tydef)*
A file is composed of a sequence of top level elements. These
top level elements consist of:
- Declarations:
These define a constant or a variable. It's worth noting
that Myrddin has no special syntax for declaring functions,
but instead assigns a closure to a variable or constant.
- Package Definitions:
These define the list of exported values from a file. As
part of compilation, all the exported names from a package
will get merged together from all the files being built
into that package.
- Use Statements:
These import symbols for use within the file. These symbols
come from either installed packages or files within the
project being compiled.
- Type Definitions:
These define new types.
- Trait Definitions:
These define traits, which are attributes on types that
may be implemented by impl functions. They define required
functions on the type.
- Impl Statements:
These define implementations of traits, allowing an
existing trait to be attached to an existing type.
3.3. Declarations:
decl: attrs ("var" | "const" | "generic") decllist
attrs: ("exern" | "pkglocal" | "$noret")+
decllist: declbody ("," declbody)*
declbody: declcore ["=" expr]
declcore: name [":" type]
A declaration consists of a declaration class (i.e., one
of 'const', 'var', or 'generic'), followed by a declaration
name, optionally followed by a type and assignment. One thing
you may note is that unlike most other languages, there is no
special function declaration syntax. Instead, a function is
declared like any other value: by assigning its name to a
constant or variable.
const: Declares a constant value, which may not be
modified at run time. Constants must have
initializers defined.
var: Declares a variable value. This value may be
assigned to, copied from, and modified.
generic: Declares a specializable value. This value
has the same restrictions as a const, but
taking its address is not defined. The type
parameters for a generic must be explicitly
named in the declaration in order for their
substitution to be allowed.
In addition, declarations may accept a number of modifiers which
change the attributes of the declarations:
extern: Declares a variable as having external linkage.
Assigning a definition to this variable within the
file that contains the extern definition is an error.
pkglocal: Declares a variable which is local to the package.
This variable may be used from other files that
declare the same `pkg` namespace, but referring to
it from outside the namespace is an error.
$noret: Declares the function to which this is applied as
a non-returning function. This attribute is only
valid when applied to a function.
Examples:
Declare a constant with a value 123. The type is not defined,
and will be inferred:
const x = 123
Declare a variable with no value and no type defined. The
value can be assigned later (and must be assigned before use),
and the type will be inferred.
var y
Declare a generic with type '@a', and assigns it the value
'blah'. Every place that 'z' is used, it will be specialized,
and the type parameter '@a' will be substituted.
generic z : @a = blah
Declare a function f with and without type inference. Both
forms are equivalent. 'f' takes two parameters, both of type
int, and returns their sum as an int
const f = {a, b
var c : int = 42
-> a + b + c
}
const f : (a : int, b : int -> int) = {a : int, b : int -> int
var c : int = 42
-> a + b + c
}
3.4. Packages and Uses
package: "pkg" ident = decl* ";;"
use: bareuse | quoteuse
bareuse: use ident
quoteuse: use "<quoted string>"
There are two keywords for module system. 'use' is the simpler
of the two, and has two cases:
use syspkg
use "localfile"
The first form, which does not have the package name quoted, will
search the system include paths for the package listed. It does not
search relative to the file or the compiler working directory.
The quoted form searches the current directory for a use file named
"localpkg" and imports it.
The 'pkg' keyword allows you to define a (partial) package by
listing the symbols and types for export. For example,
pkg mypkg =
type mytype
const Myconst : int = 42
const myfunc : (v : int -> bool)
;;
declares a package "mypkg", which defines three exports, "mytype",
"Myconst", and "myfunc". The definitions of the values may be
defined in the 'pkg' specification, but it is preferred to implement
them in the body of the code for readability. Scanning the export
list is desirable from a readability perspective.
3.5. Scoping:
Myrddin is a lexically scoped language, with namespaces and types
defined in a way that facilitates separate compilation with minimal
burden on the linker.
In Myrddin, declarations may appear in any order, and be used at any
point at which it is in scope. Any global symbols are initialized
before the program begins. Any nonglobal symbols are initialized
on the line where they are defined. This decision allows for slightly
strange code, but allows for mutually recursive functions with no
forward declarations or special cases.
3.5.1. Scope Rules:
Myrddin follows the usual lexical scoping rules. A variable
may be defined on any line in the program. From there, any
expressions within that block and its sub blocks may refer
to it.
The variables declared in constructs starting a block are
scoped to that block. For example, in `for var i = 0; ...`,
the variable `i` is scoped to the body of the for loop.
In the function `{x, y; funcbody()}`, the variables `x` and
`y` are scoped to the body of the function.
Variables may shadow other variables in enclosing scopes, with the
exception of captured variables in pattern matches. The rules for
matches are covered in depth in section 6.3, but the rationale for
this is to prevent ambiguity when matching against defined
constants.
3.5.2. Capturing Variables:
When a closure is created, it captures all of the variables
that it refers to in its scope by value. This allows for
simple heapification of the closure.
For example:
var x = 1
var closure = {; -> x}
x++
std.put("x: {}, closure(): {}\n", x, closure())
should output:
x: 2, closure(): 1
3.5.2. Namespaces:
A namespace introduced by importing a package is gramatically
equivalent to a struct member lookup. The namespace is not
optional.
3.6. Program Initialization:
Any file may define a single function name `__init__`. This function
will be invoked before `main` runs, and after the `__init__ `function
for all files included through use statements.
4. TYPES:
type: primitivetype | compositetype | aggrtype | nametype
The language defines a number of built in primitive types. These
are not keywords, and in fact live in a separate namespace from
the variable names. Yes, this does mean that you could, if you want,
define a variable named 'int'.
There are no implicit conversions within the language. All types
must be explicitly cast if you want to convert, and the casts must
be of compatible types, as will be described later.
4.1. Primitive types:
primitivetype: misctype | inttype | flttype
misctype: "void" | "bool" | "char" | "byte"
inttype: "int8" | "uint8" |
"int16" | "uint16" |
"int32" | "uint32" |
"int64" | "uint64" |
"int" | "uint"
flttype: "flt32" | "flt64"
It is important to note that these types are not keywords, but are
instead merely predefined identifiers in the type namespace.
'void' is a type containing exactly one value, `void`. It is a full
first class value, which can be assigned between variables, stored in
arrays, and used in any place any other type is used. Void has size
`0`.
bool is a type that can only hold true and false. It can be assigned,
tested for equality, and used in the various boolean operators.
char is a 32 bit integer type, and is guaranteed to hold exactly one
Unicode codepoint. It can be assigned integer literals, tested
against, compared, and all the other usual numeric types.
The various [u]intN types hold, as expected, signed and unsigned
integers of the named sizes respectively. All arithmetic on them is
done in complement twos of bit size N.
Similarly, floats hold floating point types with the indicated
precision. They are operated on according to the IEEE754 rules.
var x : int declare x as an int
var y : float32 declare y as a 32 bit float
4.2. User Defined Types:
4.2.1: Composite Types
compositetype: ptrtype | slicetype | arraytype
ptrtype: type "#"
slicetype: type "[" ":" "]"
arraytype: type "[" expr "]" | type "[" "..." "]"
Pointers are values that contain the address of the value of their
base type. If `t` is a type, then `t#` is a `pointer to t`.
Arrays are a sequence of N values, where N is part of the type, meaning
that different sizes are incompatible. They are passed by value. Their
size must be a compile time constant.
If the array size is specified as "...", then the array has zero bytes
allocated to store it, and bounds are not checked. This is used to
facilitate flexible arrays at the end of a struct, as well as C ABI.
Slices are similar to arrays in many contemporary languages. They are
reference types that store the length of their contents. They are
declared by appending a '[,]' to the base type.
foo# type: pointer to foo
foo[N] type: array size N of foo
foo[:] type: slice of foo
4.2.2. Aggregate types:
aggrtype: tupletype | structtype | uniontype
tupletype: "(" (tupleelt ",")+ ")"
structtype: "struct" "\n" (declcore "\n"| "\n")* ";;"
uniontype: "union" "\n" ("`" Ident [type] "\n"| "\n")* ";;"
Tuples are a sequence of unnamed values. They are declared by
putting the comma separated list of types within round brackets.
Structs are aggregations of types with named members. They are
declared by putting the word 'struct' before a block of declaration
cores (ie, declarations without the storage type specifier).
Unions are a traditional sum type. The tag defines the value that may
be held by the type at the current time. If the tag has an argument,
then this value may be extracted with a pattern match. Otherwise, only
the tag may be matched against.
(int, int, char) a tuple of 2 ints and a char
struct a struct containing an int named a :
int 'a', and a char named 'b'. b : char ;;
union a union containing one of
`Thing int int or char. The values are not
`Other float32 named, but they are tagged.
;;
4.2.3. Named Types:
tydef: "type" ident ["(" params ")"] = type
params: typaram ("," typaram)*
nametype: name ["(" typeargs ")"]
typeargs: type ("," type)*
Users can define new types based on other types. These named
types may optionally have parameters, which make the type into
a parameterized type.
For example:
type size = int64
would define a new type, distinct from int64, but inheriting
the same traits.
type list(@a) = struct
next : list(@a)#
val : @a
;;
would define a parameterized type named `list`, which takes a single
type parameter `@a`. When this type is used, it must be supplied a
type argument, which will be substituted throughout the right hand
side of the type definition. For example:
var x : list(int)
would specialize the above list type to an integer. All
specializations with compatible types are compatible.
4.3. Generic types:
typaram: "@" ident ["::" paramlist]
paramlist: ident | "(" ident ("," ident)* ")"
A nametype refers to a (potentially parameterized) named type, as
defined in section 4.5.
A typaram ("@ident") is a type parameter. It is introduced as either a
parameter of a generic declaration, or as a type paramteter in a
defined type. It can be constrained by any number of traits, as
described in section 4.6.
These types must be specialized to a concrete type in order to be
used.
@foo A type parameter
named '@foo'.
4.4. Traits and Impls:
4.4.1. Traits:
traitdef: "trait" ident traittypes "=" traitbody ";;"
traittypes: typaram ["->" type ("," type)*]
traitbody: (name ":" type)*
Traits provide an interface that types implementing the trait
must conform to. They are defined using the `trait` keyword,
and implemented using the `impl` keyword.
A trait is defined over a primary type, and may also define
a number of auxiliary types that the implementation can make
more specific. The body of the trait lists a number of
declarations that must be implemented by the implementation of the
trait. This body may be empty.
For example:
trait foo @a = ;;
defines a trait named `foo`. This trait has an empty body. It
applies over a type parameter named @a.
The definition:
trait foo @a -> @aux = ;;
is similar, but also has a single auxiliary type. This type can be
used to associate types with the primary type when the impl is
specialized. For example:
trait gettable @container -> @contained =
const get : (c : @container -> @contained)
;;
would define a trait that requires a get function which accepts
a parameter of type `@container`, and returns a value of type
`@contained`.
4.4.2. Impls:
impldef: "impl" ident imptypes "=" implbody
traittypes: type ["->" type ("," type)*]
traitbody: (name [":" type] "=" expr)*
Impls take the interfaces provided by traits, and attach them
to types, as well as providing the concrete implementation of
these types. The declarations are inserted into the global
namespace, and act identically to generics in.
The declarations need not be functions.
4.5. Type Inference:
Myrddin uses a variant on the Hindley Milner type system. The
largest divergence is the lack of implicit generalization when
a type is unconstrained. In Myrddin, this unconstrained type
results in a failure in type checking.
4.5.1. Initialization:
In the Myrddin type system, each leaf expression is assigned an
appropriate type, or a placeholder. For clarity in the
description, this will be called a type variable, and indicated by
`$n`, where n is an integer which uniquely identifies the type
variable. This is an implementation detail of type inference, and
is not accessible by users.
When a generic type is encountered, it is freshened. Freshening a
generic type replaces all free type parameters in the type with a
type variable, inheriting all of the traits.. So, a type '@a' is
replaced with the type '$1', and a trait-constrained type
'@a::foo' is replaced with a trait constrained type '$1::foo'.
Once each leaf expression is assigned a type, a depth first walk
over the tree is done. Each leaf's type is resolved as well as it
can be:
- Declarations are looked up, and their types are unified with
variables that refer to them.
- string, character, and boolean literals are unified with the
specific type that represents them.
- Types are freshened. Freshening is the process of replacing
unbound type parameters with type variables, such that
'@a::(integral,numeric)' is replaced with the type variable
'$n::(integral,numeric)'.
- Union tags are registered for delayed unification, with the type
for unions being the declaration type of the variable.
Note that a generic declaration must *not* have its type unfied with
its use until after it has been freshened. This may imply that the
type of a generic must be registered for delayed unification.
4.5.2. Unification:
Once the types of the leaf nodes is initialized, type inference
proceeds via unification. Each expression using the leaves is
checked. The operator type is freshened, and then the expressions
are unified.
Unification of expressions proceeds by taking the types, and
mapping corresponding parts of the expression to each other.
For unifying two types `t1` and `t2`, the following rules are
observed:
First, the most specific mapping that has been derived is looked
up. Then, one of the following rules are followed:
Case 1:
If t1 is a type variable, and t2 is a type variable, then t1
is mapped to t2, and the list of traits from t1 is appended to
the list of traits for t2. The delayed type for t1 is
transferred to t2, if t2 does not have a delayed type yet.
Otherwise, the delayed types are unified.
Case 2:
If t1 is a type variable, and t2 is not a type variable, then
t1 is checked for recursive inclusions and trait
incompatility.
If t2 refers to t1 by value, then the type would be infinitely
sized, and therefore the program must be rejected with a type
error. If t2 does not satisfy all the traits that t1 requires,
then the program must be rejected with a type error.
Case 3:
If the type t1 is not a type variable, and t2 is a type
variable, then t1 and t2 are swapped, and the rules for case 2
are applied.
Case 4:
If neither the type `t1` and `t2` is a variable type, then the
following rules are applied, in order.
- If the types are arrays, then their sizes are checked.
If only one of the types has an array size inferred,
then the size is transferred to the other. Otherwise,
the sizes are verified for equality after constant
folding. If the sizes mismatch, then the program must be
rejected with a type error.
- If one of the types is a named type, then all the
parameters passed to the named type are unified
recursively.
- If the types are equivalent at the root (ie, $1# and
int# are both pointers at the root), then all subtypes
are recursively unfied. The number of subtypes for both
types must be the same. If the types are not equivalent
at the root, then the program must be rejected with a
type error.
- If the base type of the expression is a union, then all
union tags associated with the `t1` and `t2` are unified
recursively.
- If the base type of an expression is a struct, then all
struct members associated with `t1` and `t2` are unified
recursively.
A special case exists for variadic functions, where the type of a
variadic functon is unified argument by argument, up to the first
variadic argument. Any arguments which are part of the variadic
argument list are left unconstrained.
When all expressions are inferred, and all declaration types
have been unified with their initializer types, then delayed
unification is applied.
4.5.3. Delayed Unification
In order to allow for the assignment of literals to defined types,
when a union literal or integer literal has its type inferred,
instead of immediately unifying it with a concrete type, a delayed
unification is recorded. Because checking the validity of members
is impossible when the base type is not known, member lookups are
also inserted into the delayed unification list.
After the initial unification pass is complete, the delayed
unification list is walked, and any unifications on this list
are applied. Because a delayed unification may complete members
and permit additional auxiliary type lookups, this step may need
to be repeated a number of times, although this is rare: Usually
a single pass suffices.
4.6. Built In Traits:
4.6.1. numeric:
The numeric trait is a built in trait which implies that the
operand is a number. A number of operators require it, including
comparisons and arithmetic operations. It is present on the types
byte char
int8 uint8 int16 uint16
int32 uint32 int64 uint64
flt32 flt64
A user cannot currently implement this trait on their types.
4.6.2. integral:
The integral trait is a built in trait which implies that the
operand is an integer. A number of operators require it, including
bitwise operators and increments. It is implemented over the
following types:
byte char
int8 uint8 int16 uint16
int32 uint32 int64 uint64
A user cannot currently implement this trait on their types.
4.6.3. floating:
The floating trait is a built in trait which implies that the
operand is an floating point value. It is implemented for the
following types:
flt32 flt64
A user cannot currently implement this trait on their types.
4.6.4. indexable:
The indexable trait is a built in trait which implies that
the index operator can be used on the type. It is implemented
for slice and array types.
4.6.5. sliceable
The sliceable trait is a built in trait which implies that
the slice soperator can be used on the type. It is implemented
for slice, pointer, and array types.
A user cannot currently implement this trait on their types.
4.6.6. function:
The function trait is a built in trait which implies that the
argument is a callable function. It specifies nothing about the
parameters, which is a significant flaw. It is implemented for
all function types.
A user cannot currently implement this trait on their types.
4.6.7. iterable:
The iterable trait implies that a for loop can iterate over
the values provided by this type. The iterable trait is the
only one of the builtin traits which users can implement. It
has the signature:
trait iterable @it -> @val =
__iternext__ : (itp : @it#, valp : @val# -> bool)
__iterfin : (itp : @it#, valp : @val# -> bool)
;;
A for loop iterating over an iterable will call __iternext__
to get a value for the iteration of a loop. The result of
__iternext__ should return `true` if the loop should continue
and `false` if the loop should stop. If the loop should
continue, then the implementation of __iternext__ should store
the value for the next loop interation into val#.
__iterfin__ is called at the end of the loop to do any cleanup
of resources set up by __iternext__.
The iterable trait is implemented for slices and arrays.
5. VALUES AND EXPRESSIONS
5.1. Literal Values
5.1.1. Atomic Literals:
literal: strlit | chrlit | intlit |
boollit | voidlit | floatlit |
funclit | seqlit | tuplit
strlit: \"(byte|escape)*\"
chrlit: \'(utf8seq|escape)\'
char: <any byte value>
boollit: "true"|"false"
voidlit: "void"
escape: <any escape sequence>
intlit: "0x" digits | "0o" digits | "0b" digits | digits
floatlit: digit+"."digit+["e" digit+]
5.1.1.1. String Literals:
String literals represent a compact method of representing a
byte array. Any byte values are allowed in a string literal,
and will be spit out again by the compiler unmodified, with
the exception of escape sequences.
There are a number of escape sequences supported for both character
and string literals:
\n newline
\r carriage return
\t tab
\b backspace
\" double quote
\' single quote
\v vertical tab
\\ single slash
\0 nul character
\xDD single byte value, where DD are two hex digits.
\u{xxx} unicode escape, emitted as utf8.
String literals begin with a ", and continue to the next
unescaped ".
eg: "foo\"bar"
Multiple consecutive string literals are implicitly merged to create
a single combined string literal. To allow a string literal to span
across multiple lines, the new line characters must be escaped.
eg: "foo" \
"bar"
They have the type `byte[:]`
5.1.1.2. Character Literals:
Character literals represent a single codepoint in the
character set. A character starts with a single quote,
contains a single codepoint worth of text, encoded either as
an escape sequence or in the input character set for the
compiler (generally UTF8). They share the same set of escape
sequences as string literals.
eg: 'א', '\n', '\u{1234}'
They have the type `char`.
5.1.1.3. Integer Literals
Integers literals are a sequence of digits, beginning with a digit
and possibly separated by underscores. They may be prefixed with
"0x" to indicate that the following number is a hexadecimal value,
0o to indicate an octal value, or 0b to indicate a binary value.
Decimal values are not prefixed.
eg: 0x123_fff, 0b1111, 0o777, 1234
They have the type `@a::(numeric,integral)
5.1.1.4: Boolean Literals:
Boolean literals are spelled `true` or `false`.
Unsurprisingly, they evaluate to `true` or `false`
respectively.
eg: true, false
They have the type `bool`
5.1.1.5: Void Literals:
Void literals are spelled `void`. They evaluate to the void
value, a value that takes zero bytes storage, and contains
only the value `void`. Like my soul.
eg: void
They have type `void`.
5.1.1.6: Floating point literals:
Floating-point literals are also a sequence of digits beginning with a
digit and possibly separated by underscores. Floating point
literals are always in decimal.
eg: 123.456, 10.0e7, 1_000.
They have type `@a::(numeric,floating)`
5.1.2. Sequence and Tuple Literals:
seqlit: "[" structelts | arrayelts "]"
tuplit: "(" tuplelts ")"
structelts: ("." ident "=" expr)+
arrayelts: (expr ":" expr | expr)*
tupelts: expr ("," expr)* [","]
Sequence literals are used to initialize either a structure
or an array. They are '['-bracketed expressions, and are evaluated
Tuple literals are similarly used to initialize a tuple.
Struct literals describe a fully initialized struct value.
A struct must have at least one member specified, in
order to distinguish them from the empty array literal. All
members which are designated with a `.name` expression are
initialized to the expression passed. If an initializer is
omitted, then the value is initialized to the zero value for
that type.
Sequence literals describe either an array or a structure
literal. They begin with a '[', followed by an initializer
sequence and closing ']'. For array literals, the initializer
sequence is either an indexed initializer sequence[4], or an
unindexed initializer sequence. For struct literals, the
initializer sequence is always a named initializer sequence.
An unindexed initializer sequence is simply a comma separated
list of values. An indexed initializer sequence contains a
'#number=value' comma separated sequence, which indicates the
index of the array into which the value is inserted. A named
initializer sequence contains a comma separated list of
'.name=value' pairs.
A tuple literal is a parentheses separated list of values.
A single element tuple contains a trailing comma.
Example: Struct literal.
[.a = 42, .b="str"]
Example: Array literal:
[1,2,3], [2:3, 1:2, 0:1], []
Example: Tuple literals:
(1,), (1,'b',"three")
A tuple has the type of its constituent values grouped
into a tuple:
(@a, @b, @c, ..., @z)
5.1.3. Function Literals:
funclit: "{" arglist "\n" blockbody "}"
arglist: (ident [":" type])*
Function literals describe a function. They begin with a '{',
followed by a newline-terminated argument list, followed by a
body and closing '}'. These may be specified at any place that
an expression is specified, assigned to any variable, and are
not distinguished from expressions in any significant way.
Function literals may refer to variables outside of their scope.
These are treated differently in a number of ways. Variables with
global scope are used directly, by value.
If a function is defined where stack variables are in scope,
and it refers to them, then the stack variables shall be copied
to an environment on thes stack. That environment is scoped to
the lifetime of the stack frame in which it was defined. If it
does not refer to any of its enclosing stack variables, then
this environment will not be created or accessed by the function.
This environment must be transferrable to the heap in an
implementation specific manner.
Example: Empty function literal:
{;}
Example: Function literal
{a : int, b
-> a + b
}
Example: Nested function with environment:
const fn = {a
var b = {; a + 1}
}
A function literal has the arity of its argument list,
and shares their type if it is provided. Otherwise,
they are left generic. The same applies to the return type.
5.1.4: Labels:
label: ":" ident
goto: "goto" ident
Finally, while strictly not a literal, it's not a control
flow construct either. Labels are identifiers preceded by
colons.
eg: :my_label
They can be used as targets for gotos, as follows:
goto my_label
the ':' is not part of the label name.
5.2. Expressions:
5.2.1. Summary and Precedence:
expr: expr <binop> expr | prefixexpr | postfixexpr
postfixexpr: <prefixop> postfixexpr
prefixexpr: atomicexpr <unaryop>
Myrddin expressions should be fairly familiar to most programmers.
Expressions are represented by a precedence sorted heirarchy of
binary operators. These operators operate on prefix expressions,
which in turn operate on postfix expressions. And postfix
expressions operate on parenthesized expressions, literals, or
values.
For integers, all operations are done in complement twos
arithmetic, with the same bit width as the type being operated on.
For floating point values, the operation is according to the
IEE754 rules.
The operators are listed below in order of precedence, and a short
summary of what they do is listed given. For the sake of clarity, 'x'
will stand in for any expression composed entirely of subexpressions
with higher precedence than the current current operator. 'e' will
stand in for any expression. Assignment is right associative. All
other expressions are left associative.
Arguments are evaluated in the order of associativity. That is,
if an operator is left associative, then the left hand side of
the operator will be evaluated before the right side. If the
operator is right associative, the opposite is true.
The specific semantics are covered in later parts of section 5.2.
Precedence 13:
x Atomic expression
literal Atomic expression
(expr) Atomic expression
Precedence 12:
x.name Member lookup
x++ Postincrement
x-- Postdecrement
x# Dereference
x[e] Index
x[lo:hi] Slice
x(arg,list) Call
Precedence 11:
&x Address
!x Logical negation
~x Bitwise negation
+x Positive (no operation)
-x Negate x
Precedence 10:
x << y Shift left
x >> y Shift right
Precedence 9:
x * y Multiply
x / y Divide
x % y Modulo
Precedence 8:
x + y Add
x - y Subtract
Precedence 7:
x & y Bitwise and
Precedence 6:
x | y Bitwise or
x ^ y Bitwise xor
Precedence 5:
`Name x Union construction
Precedence 4:
x == x Equality
x != x Inequality
x > x Greater than
x >= x Greater than or equal to
x < x Less than
x <= x Less than or equal to
Precedence 3:
x && y Logical and
Precedence 2:
x || y Logical or
Precedence 1: Assignment Operators
x = y Assign Right assoc
x += y Fused add/assign Right assoc
x -= y Fused sub/assign Right assoc
x *= y Fused mul/assign Right assoc
x /= y Fused div/assign Right assoc
x %= y Fused mod/assign Right assoc
x |= y Fused or/assign Right assoc
x ^= y Fused xor/assign Right assoc
x &= y Fused and/assign Right assoc
x <<= y Fused shl/assign Right assoc
x >>= y Fused shr/assign Right assoc
Precedence 0:
-> x Return expression
5.2.2. Lvalues and Rvalues:
Expressions can largely be grouped into two categories: lvaues and
rvalues. Lvalues are expressions that may appear on the left hand
side of an assignment. Rvalues are expressions that may appear on
the right hand side of an assignment. All lvalues are also
rvalues.
Lvalues consist of the following expressions:
- Variables.
- Gaps.
- Index Expressions
- Pointer Dereferences
- Member lookups.
- Tuple constructors
Assigning to an lvalue stores the value on the rhs of the
expression into the location designated by the lhs, with the
exception of gaps and tuple constructors.
Assigning into a gap lvalue discards it.
When assigning to a tuple constructor, the rhs of the expression
is broken up elementwise and stored into each lvalue of the tuple
constructor element by element. For example:
(a, b#, _) = tuplefunc()
will store the first element of the tuple returned by tuplefunc
into a, the second into b#, and the third into the gap.
5.2.3. Atomic Expressions:
atomicexpr: ident | gap | literal | "(" expr ")" |
"sizeof" "(" type ")" | castexpr
castexpr: "(" expr ":" type ")"
gap: "_"
Atomic expressions are the building blocks of expressions, and
are either parenthesized expressions or directly represent
literals. Literals are covered in depth in section 4.2.
An identifier specifies a variable, and are looked up via
the scoping rules specified in section 4.9.
Gap expressions (`_`) represent an anonymous sink value. Anything
can be assigned to a gap, and it may be used in pattern matching.
It is equivalent to creating a new temporary that is never read
from whenever it is used. For example:
_ = 123
is equivalent to:
var anon666 = 123
In match contexts, it is equivalent to a fresh variable in the
match, again, given that it is never read from in the body of the
match.
An represents a location in the machine that can be stored
to persistently and manipulated by the programmer. An obvious
example of this would be a variable name, although
5.2.4. Cast Expressions:
Cast expressions convert a value from one type to another.
Casting proceeds according to the following rules:
SType DType Action
-------------------------------------------------------------
int/int Conversions
-------------------------------------------------------------
intN intK If n < k, sign extend the source
type, filling the top bits with the
sign bit of the source until it is the
same width as the destination type.
if n > k, truncate the top bits of the
source to the width of the destination
type.
uintN uintK If n < k, zero extend the source
type, filling the top bits with zero
until it is the same width as the
destination type.
If n > k, truncate the top bits of the
source to the width of the destination
type.
-------------------------------------------------------------
int/float conversions
-------------------------------------------------------------
intN fltN The closest representable integer value
to the source should be stored in the
destination.
uintN fltN The closest representable integer value
to the source should be stored in the
destination.
fltN intN The closest representable integer value
to the source should be stored in the
destination.
fltN uintN The closest representable integer value
to the source should be stored in the
destination.
-------------------------------------------------------------
int/pointer conversions
-------------------------------------------------------------
intN T# Extend the source value to the width
of a pointer in bits in an implementation
defined manner.
uintN T# Extend the source value to the width
of a pointer in bits in an implementation
defined manner.
T# intN Convert the address of the pointer to an
integer in an implementation specified
manner. There should exist at least one
integer type for which this conversion
will round trip.
T# uintN Convert the address of the pointer to an
integer in an implementation specified
manner. There should exist at least one
integer type for which this conversion
will round trip.
-------------------------------------------------------------
pointer/pointer conversions
-------------------------------------------------------------
T# U# If the destination type has compatible
alignment and other storage requirements,
the pointer should be converted losslessly
and in a round-tripping manner to point to
a U. If it does not have compatible
requirements, the conversion is not
required to round trip safely, but should
still produce a valid pointer.
-------------------------------------------------------------
pointer/slice conversions
-------------------------------------------------------------
T[:] T# Returns a pointer to t[0]
-------------------------------------------------------------
pointer/function conversions
-------------------------------------------------------------
(args->ret) T# Returns a pointer to an implementation
specific value representing the executable
code for the function.
-------------------------------------------------------------
arbitrary type conversions
-------------------------------------------------------------
T U Returns a T as a U. T must be transitively
defined in terms of U, or U in terms of T
for this cast to be valid.
5.2.5. Assignments:
lval = rval, lval <op>= rval
The assignment operators, group from right to left. These are the
only operators that have right associativity. All of them require
the left operand to be an lvalue. The value of the right hand side
of the expression is stored on the left hand side after this
statement has executed.
The fused assignment operators are equivalent to applying the
arithmetic or bitwise operator to the lhs and rhs of the
expression before storing into the lhs.
Type:
( e1 : @a <op>= e2 : @a ) : @a
5.2.6. Logical Or:
e1 || e2
The `||` operator returns true if the left hand side evaluates to
true. Otherwise it returns the result of evaluating the lhs. It is
guaranteed if the rhs is true, the lhs will not be evaluated.
Types:
( e1 : bool || e2 : bool ) : bool
5.2.7. Logical And:
expr && expr
The `&&` operator returns false if the left hand side evaluates to
false. Otherwise it returns the result of evaluating the lhs. It
is guaranteed if the rhs is true, the lhs will not be evaluated.
The left hand side and right hand side of the expression must
be of the same type. The whole expression evaluates to the type
of the lhs.
Type:
( e1 : bool && e2 : bool ) : bool
5.2.8: Logical Negation:
!expr
Takes the boolean expression `expr` and inverts its truth value,
evaluating to `true` when `expr` is false, and `false` when `expr`
is true.
Type:
!(expr : bool) : bool
5.2.9. Equality Comparisons:
expr == expr, expr != expr
The equality operators do a shallow identity comparison between
types. The `==` operator yields true if the values compare equal,
or false if they compare unequal. The `!=` operator evaluates to
the inverse of this.
Type:
( e1 : @a == e2 : @a ) : bool
( e1 : @a != e2 : @a ) : bool
5.2.10. Relational Comparisons:
expr > expr, expr >= expr, expr < expr, expr <= expr
The relational operators (>, >=, <, <=) compare two values
numerically. The `>` operator evaluates to true if its left
operand is greater than the right operand. The >= operand returns
true if the left operand is greater than or equal to the right
operand. The `<` and `<=` operators are similar, but compare
for less than.
Type:
( e1 : @a OP e2 : @a ) : bool
where @a :: numeric
5.2.11. Union Constructors:
`Name expr:
The union constructor operator takes the value in `expr` and wraps
it in a union. The type of the expression and the argument of the
union tag must match. The result of this expression is subject to
delayed unification, with a default value being the type of the
union the tag belongs to.
Type:
Delayed unification with the type of the union tag.
5.2.12. Bitwise:
expr | expr, expr ^ expr, expr & expr
These operators (|, ^, &) compute the bitwise or, xor, and and
of their operands respectively. The arguments must be integers.
Type:
(e1 : @a OP e2:@a) : @a
where @a :: integral
5.2.13. Addition:
expr + expr, expr - expr:
These operators (+, -) add and subtract their operands. For
integers, all operations are done in complement twos arithmetic,
with the same bit width as the type being operated on. For
floating point values, the operation is according to the IEE754
rules.
Type:
( e1 : @a OP e2 : @a ) : bool
where @a :: numeric
5.2.14. Multiplication and Division
expr * expr, expr / expr
These operators (+, -) multiply and divide their operands,
according to the usual arithmetic rules.
Type:
( e1 : @a OP e2 : @a ) : bool
where @a :: numeric
5.2.15. Modulo:
expr % expr
The modulo operator computes the remainder of the left operand
when divided by the right operand.
Type:
( e1 : @a OP e2 : @a ) : bool
where @a :: (numeric,integral)
5.2.16. Shift:
expr >> expr, expr << expr
The shift operators (>>, <<) perform right or left shift on their
operands respectively. If an operand is signed, a right shift will
shifts sign extend its operand. If it is unsigned, it will fill
the top bits with zeros.
Shifting by more bits than the size of the type is implementation
defined.
Type:
(e1 : @a OP e2:@a) : @a
where @a :: integral
5.2.17: Postincrement, Postdecrement:
expr++, expr--
These expressions evaluate to `expr`, and produce a decrement after
the expression is fully evaluated. Multiple increments and
decrements within the same expression are aggregated and applied
together. For example:
y = x++ + x++
is equivalent to:
y = x + x
x += 2
The operand must be integral.
Type:
(e1++ : @a) : @a
(e1-- : @a) : @a
where @a :: integral
5.2.18: Address:
&expr
The `&` operator computes the address of the object referred to
by `expr`. `expr` must be an lvalue.
Type:
&(expr : @a) : @a#
5.2.19: Dereference:
expr#
The `#` operator refers to the value at the pointer `expr`. This
is an lvalue, and may be stored to.
The pointer being dereferenced may have at some point come from a
cast expression. It may also be constructed by arbitrary code via
integer manipulations and system specific memory allocation.
If this happens, there are two cases. If the pointed-to type of
the accessing pointer is larger than the declaration type of the
object, the behavior is undefined. Similarly, if the pointer
value has an incompatible alignment at runtime, the behavior is
undefined. Otherwise, the value read back through the pointer is
implementation specific. These system specific values may include
trap representations.
Type:
(expr : @a#)# : @a
5.2.20: Sign Operators:
-expr, +expr
The `-` operator computes the complement two negation of the value
`expr`. It may be applied to unsigned values. The `+` operator
only exists for symmetry, and is a no-op.
Type:
OP(expr : @a) : @a
5.2.21: Member Lookup:
expr.name
Member lookup operates on two classes of types: User defined
struct and sequences. For user defined structs, the type of `expr`
must be a structure containing the member `name`. The result of
the expression is an lvalue of the type of that member.
For sequences such as slices or arrays, there is exactly one
member that may be accessed, `len`. The value returned is the
count of elements in the sequence.
Type:
(expr : <aggregate>).name : @a
(expr : <seq>).len : @idx
where @idx :: (integral,numeric)
5.2.22: Index:
expr[idx]
The indexing operator operates on slices and arrays. The
`idx`th value in the sequence is referred to. This expression
produces an lvalue.
If `idx` is larger than `expr.len` or smaller than 0, then the
program must terminate.
Type:
(expr : @a[N])[(idx : @idx)] : @a
(expr : @a[:])[(idx : @idx)] : @a
where @idx :: (integral,numeric)
5.2.23: Slice:
expr[lo:hi], expr[:hi], expr[lo:], expr[:]
The slice expression produces a sub-slice of the sequence
or pointer expression being sliced. The elements contained
in this slice are expr[lo]..expr[hi-1].
If the lower bound is omitted, then it is implicitly zero. If the
upper bound is ommitted, then it is implicitly `expr.len`.
If the bounds are not fully contained within the slice being
indexed, the program must terminate.
Type:
(expr : @a[N])[(lo : @lo) : (hi : @hi)] : @a[:]
(expr : @a[:])[(lo : @lo) : (hi : @hi)] : @a[:]
(expr : @#)[(lo : @lo) : (hi : @hi)] : @a[:]
where @lo :: (integral,numeric)
and @hi :: (integral,numeric)
5.2.24: Call:
expr()
expr(arg1, arg2)
expr(arg1, arg2, ...)
A function call expression takes an expression of type
(arg, list -> ret), and applies the arguments to it,
producing a value of type `ret`. The argument types and
arity must must match, unless the final argument is of
type `...`.
If the final type is `...`, then the `...` consumes as many
arguments as are provided, and passes both them and an
implementation defined description of their types to the function.
Type:
(expr : @fn)(e1 : @a, e2 : @b) : @ret
where @fn is a function of type (@a, @b -> @ret)
or @fn is a function of type (@a, ... -> ret)
adjusted appropriately for arity.
6. CONTROL FLOW
The control statements in Myrddin are similar to those in many other
popular languages, and with the exception of 'match', there should
be no surprises to a user of any of the Algol derived languages.
6.1. Blocks:
block: blockbody ";;"
blockbody: (decl | stmt | tydef | "\n")*
stmt: goto | break | continue | retexpr | label |
ifstmt | forstmt | whilestmt | matchstmt
Blocks are the basic building block of functionality in Myrddin. They
are simply sequences of statements that are completed one after the
other. They are generally terminated by a double semicolon (";;"),
although they may be terminated by keywords if they are part of a more
complex control flow construct.
Any declarations within the block are scoped to within the block,
and are not accessible outside of it. Their storage duration is
limited to within the block, and any attempts to access the associated
storage (via pointer, for example) is not valid.
6.2. Conditionals
ifstmt: "if" cond "\n" blockbody
("elif" blockbody)*
["else" blockbody] ";;"
If statements branch one way or the other depending on the truth
value of their argument. The truth statement is separated from the
block body
if true
std.put("The program always get here")
elif elephant != mouse
std.put("...eh.")
else
std.put("The program never gets here")
;;
6.3. Matches
matchstmt: "match" expr "\n" matchpat* ";;"
matchpat: "|" pat ":" blockbody
pat: expr
Match statements perform deep pattern matching on values. They take as
an argument a value of type 't', and match it against a list of other
values of the same type.
The patterns matched against may free variables, which will be bound
to the sub-value matched against. The patterns are checked in order,
and the first matching pattern has its body executed, after which no
other patterns will be matched. This implies that if you have specific
patterns mixed with by more general ones, the specific patterns must
come first.
All potential cases must be covered exhaustively. Non-exhaustive
matches are a compilation error.
Match patterns can be one of the following:
- Wildcard patterns
- Gap patterns
- Atomic literal patterns
- String patterns
- Union patterns
- Tuple patterns
- Struct patterns
- Array patterns
- Constant patterns
- Pointer chasing patterns
6.3.1. Wildcards and Gaps:
Wildcard patterns an identifier that is not currently in scope.
This variable name captures the variable. That is, in the body of
the match, there will be a variable in scope with the same name as
the identifier, and it will contain a copy of the value that is
being matched against. A wildcard pattern always matches
successfully.
Gap patterns are identical to wildcard patterns, but they do not
capture a copy of the value being matched against.
6.3.2. Literal and Constant Patterns:
Most pattern matches types are literal patterns. These are simply
written out as a literal value of the type that is being matched
against.
Atomic literal patterns match on a literal value. The pattern is
compared to the value using semantics equivalent to the `==`
operator. If the `==` operator would return true, the match is
successful.
String patterns match a byte sequence. The pattern is compared to
the value by first comparing the lengths. Then, each byte in the
string is compared, in turn, to the byte of the pattern. If the
length and all characters are equal, the pattern succeeds.
Union patterns compare the union tag of the pattern wtih the union
tag on the value. If there is a union body associated with the
tag, then the pattern must also have a body. This is recursively
matched on. If the tag and the body (if present) both match, this
match is considered successful.
Tuple patterns proceed to recursively check each tuple element for
a match. If all elements match, this is a successful match.
Struct patterns recursively check each named member that is
provided. Not all named members are mandatory. If a named member
is omitted, then it is equivalent to matching it against a gap
pattern. If all elements match, then this is a successful match.
Array pattenrs recursively check each member of the array that is
provided. The array length must be part of the match. If all array
elements match, then this is a successful match.
Constant patterns use a compile time constant that is in scope for
the pattern. The semantics are the same any of the literal
patterns listed above.
6.3.3. Pointer Chasing Patterns:
Pointer chasing patterns allow matching on pointer-to-values. They
are written with the `&` operator, as though you were taking the
address of the pattern being matched against.
This pattern is matched by dereferencing the value being matched,
and recursively matching the value against the pattern being
addressed.
The pointer provided to a pointer chasing match must be a valid
pointer. Providing an invalid pointer leads to undefined behavior.
6.4.4. Examples:
6.4.4.1. Wildcard:
var e = 123
match expr
| x: std.put("x = {}\n", x)
;;
6.4.4.2. Atomic Literal:
var e = 123
match expr
| 666: std.put("wrong branch\n")
| 123: std.put("correct match\n")
| _: std.put("default branch\n")
;;
6.4.4.3. Tuple Literal:
var e = (123, 999)
match expr
| (123, 666): std.put("wrong branch\n")
| (123, 999): std.put("right branch\n")
| _: std.put("default branch\n")
;;
6.4.4.3. Union Literal:
var e = `std.Some 123
match expr
| `std.Some 888: std.put("wrong branch\n")
| `std.Some 123: std.put("right branch\n")
| `std.Some x: std.put("other wrong branch\n")
| `std.None: std.put("other wrong branch\n")
;;
6.4.4.4 Struct Literal:
type s = struct
x : int
;;
var e : s = [.x=999]
match expr
| [.x=123]: td.put("wtf, x=123\n")
| [.x=x]: std.put("x={}\n", x)
;;
6.4.4.5 Pointer Chasing:
type s = struct
x : int#
;;
var p = 123
var e : s = [.x=&p]
match expr
| [.x=&123]: td.put("good, x=123\n")
| [.x=&x]: std.put("wtf, x={}\n", x)
;;
6.4. Looping
forstmt: foriter | foreach
foreach: "for" pattern "in" expr "\n" block
foriter: "for" init "\n" cond "\n" step "\n" block
whilestmt: "while" cond "\n" block
For statements come in two forms. There are the C style for loops
which begin with an initializer, followed by a test condition,
followed by an increment action. For statements run the initializer
once before the loop is run, the test each on each iteration through
the loop before the body, and the increment on each iteration after
the body. If the loop is broken out of early (for example, by a goto),
the final increment will not be run. The syntax is as follows:
for init; test; increment
blockbody()
;;
The second form is the collection iteration form. This form allows
for iterating over a collection of values contained within something
which is iterable. Currently, only the built in sequences -- arrays
and slices -- can be iterated, however, there is work going towards
allowing user defined iterables.
for pat in expr
blockbody()
;;
The pattern applied in the for loop is a full match statement style
pattern match, and will filter any elements in the iteration
expression which do not match the value.
While loops are equivalent to for loops with empty initializers
and increments. They run the test on every iteration of the loop,
and exit only if it returns false.
6.5. Goto
label: ":" ident
goto: goto ident
6. GRAMMAR:
/* top level */
file: toplev*
toplev: use | pkgdef | decl | traitdef | impldef | tydef
/* packages */
use: use ident | strlit
pkgdef: "pkg" [ident] "=" pkgbody ";;"
pkgbody: (decl | attrs tydef | traitdef | impldef)*
/* declarations */
decl: attrs ("var" | "const") decllist
attrs: ("$noret" | "extern" | "pkglocal")*
decllist: declbody ("," declbody)+
declbody: declcore ["=" expr]
declcore: ident [":" type]
/* traits */
traitdef: "trait" ident typaram [auxtypes] ("\n" | "=" traitbody ";;")
auxtypes: "->" type ("," type)*
traitbody: "\n"* (ident ":" type "\n"*)*
impldef: "impl" ident type [auxtypes] ("\n" | "=" implbody ";;")
implbody: "\n"* (ident [":" type] "=" expr "\n"*)*
/* types */
tydef: "type" typeid "=" type
typeid: ident | ident "(" typarams ")"
typarams: typaram ("," typaram)*
type: structdef | uniondef | tupledef |
compound | generic | "..."
structdef: "struct" structbody ";;"
uniondef: "union" unionbody ";;"
tupledef: "(" type ("," type)* ")"
generic: typaram ["::" traitlist]
traitlist: name | "(" name ("," name)
compound: functype | sicetype | arraytype | ptrtype | void | name
functype: "(" arglist "->" type ")"
arglist: [arg ("," arg)*]
arg: name ":" type
slicetype: type "[" ":" "]"
arraytype: type "[" (expr | "...") "]"
ptrtype: type "#"
void: "void"
/* expressions */
retexpr: "->" expr | expr
exprln: expr ";"
expr: lorepxr asnop expr | lorexpr
lorexpr: lorexpr "||" landexpr | landexpr
landexpr: landexpr "&&" cmpexpr | cmpexpr
cmpexpr: cmpexpr ("<" | "<=" | "==" | ">=" | ">") unionexpr | unionexpr
unionexpr: "`" name unionexpr | "`" name | borexpr
borexpr: borexpr ("|" | "^" ) bandexpr | bandexpr
bandexpr: bandexpr "&" addexpr | addexpr
addexpr: addexpr ("+" | "-") mulexpr
mulexpr: mulexpr ("*" | "/" | "%") shiftexpr
shiftexpr: shiftexpr ("<<" | ">>") prefixexpr
preexpr: "++" prefixexpr | "--" prefixexpr |
"!" prefixexpr | "~" prefixexpr |
"-" prefixexpr | "+" prefixexpr |
"&" prefixexpr | postexpr
postexpr: postexpr "." ident |
postexpr "++" | postexpr "--" |
postexpr "[" expr "]" |
postexpr "[" [expr] ":" [expr] "]" |
postepxr "#" |
atomicexpr
atomicexpr: ident | literal | "(" expr ")" | "sizeof" "(" type ")"
/* literals */
literal: funclit | seqlit | tuplit | simplelit
funclit: "{" [funcargs] ";" blockbody "}"
funcargs: ident [ ":" type] ("," ident [ ":" type])*
seqlit: "[" structelts | [arrayelts] "]"
arrayelts: arrayelt ("," arrayelt)*
arrayelt: ";'* expr [":" expr] ";"*
structelts: structelt ("," ";"* structelt)*
structelt: ";"* "." name "=" expr ";"*
tuplit: "(" expr "," [expr ("," expr)*] ")"
simplelit: strlist | chrlit | fltlit | boollit | voidlit | intlit
fltlit: <float literal>
boollit: "true" | "false"
voidlit: "void"
strlit: <string literal>
chrlit: <char literal>
/* statements */
blkbody: (decl | stmt | tydef | ";")*
stmt: jmpstmt | flowstmt | retexpr
jmpstmt: goto | break | continue | label
flowstmt: ifstmt | forstmt | whilestmt | matchstmt
ifstmt: "if" exprln blkbody elifs ["else" blkbody] ";;"
elifs: ("elif" exprln blkbody)*
forstmt: foriter | forstep
foriter: "for" expr "in" exprln blkbody ";;"
forstep: "for" exprln exprln exprln blkbody ";;"
whilestmt: "while" exprln blkbody ";;"
matchstmt: "match" exprln pattern* ";;"
pattern: "|" expr ":" blkbody ";"
goto: "goto" ident ";"
break: "break" ";"
continue: "continue" ";"
label: ":" ident ";"
/* misc */
name: ident | ident "." ident
asnop: "=" | "+=" | "-=" | "*=" | "/=" | "%=" |
"|=" | "^=" | "&=" | "<<=" | ">>="
/* pattern tokens */
typaram: /@[a-zA-Z_][a-zA-Z0-9_]*/
ident: /[a-zA-Z_][a-zA-Z0-9_]*/
BUGS:
|