aboutsummaryrefslogtreecommitdiff
path: root/docs/book/TYPES.html
blob: 5abe998cb0c5f9cd08d6f0b72ce93b4af3afabea (plain) (blame)
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
<!DOCTYPE HTML>
<html lang="en" class="light" dir="ltr">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>Type System - The Puck Programming Language</title>


        <!-- Custom HTML head -->

        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff">

        <link rel="icon" href="favicon.svg">
        <link rel="shortcut icon" href="favicon.png">
        <link rel="stylesheet" href="css/variables.css">
        <link rel="stylesheet" href="css/general.css">
        <link rel="stylesheet" href="css/chrome.css">
        <link rel="stylesheet" href="css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->

    </head>
    <body class="sidebar-visible no-js">
    <div id="body-container">
        <!-- Provide site root to javascript -->
        <script>
            var path_to_root = "";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script>
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script>
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('light')
            html.classList.add(theme);
            var body = document.querySelector('body');
            body.classList.remove('no-js')
            body.classList.add('js');
        </script>

        <input type="checkbox" id="sidebar-toggle-anchor" class="hidden">

        <!-- Hide / unhide sidebar before it is displayed -->
        <script>
            var body = document.querySelector('body');
            var sidebar = null;
            var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            } else {
                sidebar = 'hidden';
            }
            sidebar_toggle.checked = sidebar === 'visible';
            body.classList.remove('sidebar-visible');
            body.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded affix "><a href="../index.html">The Puck Programming Language</a></li><li class="chapter-item expanded "><a href="OVERVIEW.html"><strong aria-hidden="true">1.</strong> Basic Usage</a></li><li><ol class="section"><li class="chapter-item expanded "><div><strong aria-hidden="true">1.1.</strong> Variables and Comments</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">1.2.</strong> Basic Types</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">1.3.</strong> Functions and Calls</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">1.4.</strong> Boolean and Integer Operations</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">1.5.</strong> Conditionals and Control Flow</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">1.6.</strong> Error Handling</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">1.7.</strong> Loops and Iterators</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">1.8.</strong> Modules</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">1.9.</strong> Compile-time Programming</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">1.10.</strong> Async and Threading</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">1.11.</strong> Advanced Types</div></li></ol></li><li class="chapter-item expanded "><a href="SYNTAX.html"><strong aria-hidden="true">2.</strong> Syntax</a></li><li><ol class="section"><li class="chapter-item expanded "><div><strong aria-hidden="true">2.1.</strong> Indentation Rules [todo]</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">2.2.</strong> Reserved Keywords</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">2.3.</strong> A Formal Grammar</div></li></ol></li><li class="chapter-item expanded "><a href="TYPES.html" class="active"><strong aria-hidden="true">3.</strong> Type System</a></li><li><ol class="section"><li class="chapter-item expanded "><div><strong aria-hidden="true">3.1.</strong> Basic Types</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">3.2.</strong> Parameter Types</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">3.3.</strong> Reference Types</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">3.4.</strong> Abstract Types</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">3.5.</strong> Advanced Types</div></li></ol></li><li class="chapter-item expanded "><a href="MODULES.html"><strong aria-hidden="true">4.</strong> Module System</a></li><li><ol class="section"><li class="chapter-item expanded "><div><strong aria-hidden="true">4.1.</strong> Using Modules</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">4.2.</strong> Implicit Modules</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">4.3.</strong> Defining Module Interfaces [todo]</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">4.4.</strong> Defining an External API [todo]</div></li></ol></li><li class="chapter-item expanded "><a href="ERRORS.html"><strong aria-hidden="true">5.</strong> Error Handling</a></li><li><ol class="section"><li class="chapter-item expanded "><div><strong aria-hidden="true">5.1.</strong> Errors as Monads</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">5.2.</strong> Errors as Catchable Exceptions</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">5.3.</strong> Errors and Void Functions [todo]</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">5.4.</strong> Unrecoverable Exceptions</div></li></ol></li><li class="chapter-item expanded "><a href="ASYNC.html"><strong aria-hidden="true">6.</strong> Async System</a></li><li><ol class="section"><li class="chapter-item expanded "><div><strong aria-hidden="true">6.1.</strong> Threading [todo]</div></li></ol></li><li class="chapter-item expanded "><a href="METAPROGRAMMING.html"><strong aria-hidden="true">7.</strong> Metaprogramming</a></li><li class="chapter-item expanded "><div><strong aria-hidden="true">8.</strong> Memory Management [todo]</div></li><li><ol class="section"><li class="chapter-item expanded "><div><strong aria-hidden="true">8.1.</strong> Reference Counting Optimizations</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">8.2.</strong> Annotations and Ownership</div></li></ol></li><li class="chapter-item expanded "><a href="INTEROP.html"><strong aria-hidden="true">9.</strong> Language Interop [draft]</a></li><li><ol class="section"><li class="chapter-item expanded "><div><strong aria-hidden="true">9.1.</strong> Rust, Swift, Nim</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">9.2.</strong> Java, Kotlin</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">9.3.</strong> Python, Racket, C</div></li></ol></li><li class="chapter-item expanded "><div><strong aria-hidden="true">10.</strong> Refinement Types [draft]</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">11.</strong> Dependent Types [draft]</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">12.</strong> Effects System [draft]</div></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle">
                <div class="sidebar-resize-indicator"></div>
            </div>
        </nav>

        <!-- Track and set sidebar scroll position -->
        <script>
            var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
            sidebarScrollbox.addEventListener('click', function(e) {
                if (e.target.tagName === 'A') {
                    sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
                }
            }, { passive: true });
            var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
            sessionStorage.removeItem('sidebar-scroll');
            if (sidebarScrollTop) {
                // preserve sidebar scroll position when navigating via links within sidebar
                sidebarScrollbox.scrollTop = sidebarScrollTop;
            } else {
                // scroll sidebar to current active section when navigating via "next/previous chapter" buttons
                var activeSection = document.querySelector('#sidebar .active');
                if (activeSection) {
                    activeSection.scrollIntoView({ block: 'center' });
                }
            }
        </script>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky">
                    <div class="left-buttons">
                        <label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </label>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">The Puck Programming Language</h1>

                    <div class="right-buttons">
                        <a href="print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script>
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="typing-in-puck"><a class="header" href="#typing-in-puck">Typing in Puck</a></h1>
<blockquote>
<p>! This section <strong>needs a rewrite</strong>. Proceed with low standards.</p>
</blockquote>
<p>Puck has a comprehensive static type system, inspired by the likes of Nim, Rust, and Swift.</p>
<h2 id="basic-types"><a class="header" href="#basic-types">Basic types</a></h2>
<p>Basic types can be one-of:</p>
<ul>
<li><code>bool</code>: internally an enum.</li>
<li><code>int</code>: integer number. x bits of precision by default.
<ul>
<li><code>uint</code>: same as <code>int</code>, but unsigned for more precision.</li>
<li><code>i[\d+]</code>, <code>u[\d+]</code>: arbitrarily sized integers</li>
</ul>
</li>
<li><code>float</code>: floating-point number.
<ul>
<li><code>f32</code>, <code>f64</code>: specified float sizes</li>
</ul>
</li>
<li><code>decimal</code>: precision decimal number.
<ul>
<li><code>dec32</code>, <code>dec64</code>, <code>dec128</code>: specified decimal sizes</li>
</ul>
</li>
<li><code>byte</code>: an alias to <code>u8</code>.</li>
<li><code>char</code>: an alias to <code>u32</code>. For working with Unicode.</li>
<li><code>str</code>: a string type. mutable. packed: internally a byte-array, externally a char-array.</li>
<li><code>void</code>: an internal type designating the absence of a value. often elided.</li>
<li><code>never</code>: a type that denotes functions that do not return. distinct from returning nothing.</li>
</ul>
<p><code>bool</code> and <code>int</code>/<code>uint</code>/<code>float</code> and siblings (and subsequently <code>byte</code> and <code>char</code>) are all considered <strong>primitive types</strong> and are <em>always</em> copied (unless passed as mutable). More on when parameters are passed by value vs. passed by reference can be found in the <a href="MEMORY_MANAGEMENT.html">memory management document</a>.</p>
<p>Primitive types, alongside <code>str</code>, <code>void</code>, and <code>never</code>, form <strong>basic types</strong>. <code>void</code> and <code>never</code> will rarely be referenced by name: instead, the absence of a type typically implicitly denotes one or the other. Still, having a name is helpful in some situations.</p>
<h3 id="integers"><a class="header" href="#integers">integers</a></h3>
<p>todo</p>
<h3 id="strings"><a class="header" href="#strings">strings</a></h3>
<p>Strings are:</p>
<ul>
<li>mutable</li>
<li>internally a byte array</li>
<li>externally a char (four bytes) array</li>
<li>prefixed with their length and capacity</li>
<li>automatically resize</li>
</ul>
<p>They are also quite complicated. Puck has full support for Unicode and wishes to be intuitive, performant, and safe, as all languages wish to be. Strings present a problem that much effort has been expended on in (primarily) Swift and Rust to solve.</p>
<h2 id="abstract-types"><a class="header" href="#abstract-types">Abstract Types</a></h2>
<p>Abstract types, broadly speaking, are types described by their <em>behavior</em> rather than their <em>implementation</em>. They are more commonly know as abstract <em>data</em> types: which is confusingly similar to "algebraic data types", another term for the <a href="#advanced-types">advanced types</a> they are built out of under the hood. We refer to them here as "abstract types" to mitigate some confusion.</p>
<h3 id="iterable-types"><a class="header" href="#iterable-types">iterable types</a></h3>
<p>Iterable types can be one-of:</p>
<ul>
<li><code>array[T, size]</code>: Fixed-size arrays. Can only contain one type <code>T</code>. Of a fixed size <code>size</code> and cannot grow/shrink, but can mutate. Initialized in-place with <code>[a, b, c]</code>.</li>
<li><code>list[T]</code>: Dynamic arrays. Can only contain one type <code>T</code>. May grow/shrink dynamically. Initialized in-place with <code>[a, b, c]</code>. (this is the same as arrays!)</li>
<li><code>slice[T]</code>: Slices. Used to represent a "view" into some sequence of elements of type <code>T</code>. Cannot be directly constructed: they are <strong>unsized</strong>. Cannot grow/shrink, but their elements may be accessed and mutated. As they are underlyingly a reference to an array or list, they <strong>must not</strong> outlive the data they reference: this is non-trivial, and so slices interact in complex ways with the memory management system.</li>
<li><code>str</code>: Strings. Described above. They are alternatively treated as either <code>list[byte]</code> or <code>list[char]</code>, depending on who's asking. Initialized in-place with <code>"abc"</code>.</li>
</ul>
<p>These iterable types are commonly used, and bits and pieces of compiler magic are used here and there (mostly around initialization, and ownership) to ease use. All of these types are some sort of sequence: and implement the <code>Iter</code> interface, and so can be iterated (hence the name).</p>
<h3 id="other-abstract-types"><a class="header" href="#other-abstract-types">other abstract types</a></h3>
<p>Unlike the iterable types above, these abstract types do not have a necessarily straightforward or best implementation, and so multiple implementations are provided in the standard library.</p>
<p>These abstract data types can be one-of:</p>
<ul>
<li><code>BitSet[T]</code>: high-performance sets implemented as a bit array.
<ul>
<li>These have a maximum data size, at which point the compiler will suggest using a <code>HashSet[T]</code> instead.</li>
</ul>
</li>
<li><code>AssocTable[T, U]</code>: simple symbol tables implemented as an association list.
<ul>
<li>These do not have a maximum size. However, at some point the compiler will suggest using a <code>HashTable[T, U]</code> instead.</li>
</ul>
</li>
<li><code>HashSet[T]</code>: standard hash sets.</li>
<li><code>HashTable[T, U]</code>: standard hash tables.</li>
</ul>
<p>These abstract types do not have a natural <em>ordering</em>, unlike the iterable types above, and thus do not implement <code>Iter</code>. Despite this: for utility an <code>elems()</code> iterator based on a normalization of the elements is provided for <code>set</code> and <code>HashSet</code>, and <code>keys()</code>, <code>values()</code>, and <code>pairs()</code> iterators are provided for <code>table</code> and <code>HashTable</code> (based on a normalization of the keys). <!-- this is deterministic to prevent user reliance on shoddy randomization: see Go --></p>
<h2 id="parameter-types"><a class="header" href="#parameter-types">Parameter Types</a></h2>
<p>Some types are only valid when being passed to a function, or in similar contexts.
No variables may be assigned these types, nor may any function return them.
These are monomorphized into more specific functions at compile-time if needed.</p>
<p>Parameter types can be one-of:</p>
<ul>
<li>mutable: <code>func foo(a: mut str)</code>: Marks a parameter as mutable (parameters are immutable by default). Passed as a <code>ref</code> if not one already.</li>
<li>constant: <code>func foo(a: const str)</code>: Denotes a parameter whose value must be known at compile-time. Useful in macros, and with <code>when</code> for writing generic code.</li>
<li>generic: <code>func foo[T](a: list[T], b: T)</code>: The standard implementation of generics, where a parameter's exact type is not listed, and instead statically dispatched based on usage.</li>
<li>constrained: <code>func foo(a: str | int | float)</code>: A basic implementation of generics, where a parameter can be one-of several listed types. The only allowed operations on such parameters are those shared by each type. Makes for particularly straightforward monomorphization. <!-- - Separated with the bitwise or operator `|` rather than the symbolic or `||` or a raw `or` to give the impression that there isn't a corresponding "and" operation (the `&` operator is preoccupied with strings). --></li>
<li>functions: <code>func foo(a: (int, int) -&gt; int)</code>: First-class functions. All functions are first class - function declarations implicitly have this type, and may be bound in variable declarations. However, the function <em>type</em> is only terribly useful as a parameter type.</li>
<li>slices: <code>func foo(a: slice[...])</code>: Slices of existing lists, strings, and arrays. Generic over length. These are references under the hood, may be either immutable or mutable (with <code>mut</code>), and interact non-trivially with Puck's <a href="MEMORY_MANAGEMENT.html">ownership system</a>.</li>
<li>classes: <code>func foo(a: Stack[int])</code>: Implicit typeclasses. More in the <a href="#classes">classes section</a>.
<ul>
<li>ex. for above: <code>type Stack[T] = interface[push(mut Self, T); pop(mut Self): T]</code></li>
</ul>
</li>
<li>built-in interfaces: <code>func foo(a: struct)</code>: Included, special interfaces for being generic over <a href="#advanced-types">advanced types</a>. These include <code>struct</code>, <code>tuple</code>, <code>union</code>, <code>enum</code>, <code>interface</code>, and others.</li>
</ul>
<p>Several of these parameter types - specifically, slices, functions, and interfaces - share a common trait: they are not <em>sized</em>. The exact size of the type is not generally known until compilation - and in some cases, not even during compilation! As the size is not always rigorously known, problems arise when attempting to construct these parameter types or compose them with other types: and so this is disallowed. They may still be used with <em>indirection</em>, however - detailed in the <a href="#reference-types">section on reference types</a>.</p>
<h3 id="generic-types"><a class="header" href="#generic-types">generic types</a></h3>
<p>Functions can take a <em>generic</em> type, that is, be defined for a number of types at once:</p>
<pre><code class="language-puck"># fully generic. monomorphizes based on usage.
func add[T](a: list[T], b: T) = a.push(b)

# constrained generics. restricts possible operations to the intersection
# of defined methods on each type.
func length[T](a: str | list[T]) =
  a.len # both strings and lists have a `len` method

# alternative formulation: place the constraint on a generic parameter.
# this ensures both a and b are of the *same* type.
func add[T: int | float](a: T, b: T) = a + b
</code></pre>
<p>The syntax for generics is <code>func</code>, <code>ident</code>, followed by the names of the generic parameters in brackets <code>[T, U, V]</code>, followed by the function's parameters (which may then refer to the generic types). Generics are replaced with concrete types at compile time (monomorphization) based on their usage in function calls within the main function body.</p>
<p>Constrained generics have two syntaxes: the constraint can be defined directly on a parameter, leaving off the <code>[T]</code> box, or it may be defined within the box as <code>[T: int | float]</code> for easy reuse in the parameters.</p>
<p>Other constructions like type declarations themselves may also be generic over types. In the future, modules also may be generic: whether that is to be over types or over other modules is to be determined.</p>
<h2 id="reference-types"><a class="header" href="#reference-types">Reference Types</a></h2>
<p>Types are typically constructed by value on the stack. That is, without any level of indirection: and so type declarations that recursively refer to one another, or involve unsized types (notably including parameter types), would not be allowed. However, Puck provides several avenues for indirection.</p>
<p>Reference types can be one-of:</p>
<ul>
<li><code>ref T</code>: An owned reference to a type <code>T</code>. This is a pointer of size <code>uint</code> (native).</li>
<li><code>refc T</code>: A reference-counted reference to a type <code>T</code>. This allows escaping the borrow checker.</li>
<li><code>ptr T</code>: A manually-managed pointer to a type <code>T</code>. (very) unsafe. The compiler will yell at you.</li>
</ul>
<pre><code class="language-puck">type BinaryTree = ref struct
  left: BinaryTree
  right: BinaryTree

type AbstractTree[T] = class
  func left(self: Self): Option[AbstractTree[T]]
  func right(self: Self): Option[AbstractTree[T]]
  func data(self: Self): T

type AbstractRoot[T] = struct
  left: ref AbstractTree[T]
  right: ref AbstractTree[T]

# allowed, but unsafe &amp; strongly discouraged
type UnsafeTree = struct
  left: ptr UnsafeTree
  right: ptr UnsafeTree
</code></pre>
<p>The <code>ref</code> prefix may be placed at the top level of type declarations, or inside on a field of a structural type. <code>ref</code> types may often be more efficient when dealing with large data structures. They also provide for the usage of unsized types (functions, interfaces, slices) within type declarations.</p>
<p>The compiler abstracts over <code>ref</code> types to provide optimization for reference counts: and so a distinction between <code>Rc</code>/<code>Arc</code>/<code>Box</code> is not needed. Furthermore, access implicitly dereferences (with address access available via <code>.addr</code>), and so a <code>*</code> dereference operator is also not needed.</p>
<p>Much care has been given to make references efficient and safe, and so <code>ptr</code> should be avoided if at all possible. They are only usable inside functions explicitly marked with <code>#[safe]</code>.</p>
<p>The implementations of reference types are delved into in further detail in the <a href="MEMORY_MANAGEMENT.html">memory management document</a>.</p>
<h2 id="advanced-types"><a class="header" href="#advanced-types">Advanced Types</a></h2>
<p>The <code>type</code> keyword is used to declare aliases to custom data types. These types are <em>algebraic</em>: they function by <em>composition</em>. Such <em>algebraic data types</em> can be one-of:</p>
<ul>
<li><code>struct</code>: An unordered, named collection of types. May have default values.</li>
<li><code>tuple</code>: An ordered collection of types. Optionally named.</li>
<li><code>enum</code>: Ordinal labels, that may hold values. Their default values are their ordinality.</li>
<li><code>union</code>: Powerful matchable tagged unions a la Rust. Sum types.</li>
<li><code>class</code>: Implicit type classes. User-defined duck typing.</li>
</ul>
<p>All functions defined on the original type carry over. If this is not desired, the newtype paradigm is preferred: declaring a single-field <code>struct</code> and copying function declarations over.</p>
<p>Types may be explicitly to and from via the <code>Coerce</code> and <code>Convert</code> classes and provided <code>from</code> and <code>to</code> functions.</p>
<h3 id="structs"><a class="header" href="#structs">structs</a></h3>
<p>Structs are an <em>unordered</em> collection of named types.</p>
<p>They are declared with <code>struct[identifier: Type, ...]</code> and initialized with brackets: <code>{ field = "value", another = 500}</code>. Structs are <em>structural</em>: while the type system is fundamentally nominal, and different type declarations are treated as distinct, a struct object initialized with <code>{}</code> is usable in any context that expects a struct with the same fields.</p>
<pre><code class="language-puck">type LinkedNode[T] = ref struct
  previous: Option[LinkedNode[T]]
  next: Option[LinkedNode[T]]
  data: T

let node = { # inferred type: LinkedNode[int], from prints_data call
  previous = None, next = None
  data = 413
}

func pretty_print(node: LinkedNode[int]) =
  print node.data
  if node.next of Some(node) then
    node.pretty_print()

# structural typing!
prints_data(node)
</code></pre>
<h3 id="tuples"><a class="header" href="#tuples">tuples</a></h3>
<p>Tuples are an <em>ordered</em> collection of either named and/or unnamed types.</p>
<p>They are declared with <code>tuple[Type, identifier: Type, ...]</code> and initialized with parentheses: <code>(413, "hello", value: 40000)</code>. Syntactic sugar allows for them to be declared with <code>()</code> as well.</p>
<p>They are exclusively ordered - named types within tuples are just syntactic sugar for positional access. Passing a fully unnamed tuple into a context that expects a tuple with a named parameter is allowed (so long as the types line up).</p>
<pre><code class="language-puck">let grouping = (1, 2, 3)

func foo: tuple[str, str] = ("hello", "world")
dbg grouping.foo # prints '("hello", "world")'

func bar(a: (str, str)) = a.1
dbg grouping.bar # prints '"world"'
</code></pre>
<p>Tuples are particularly useful for "on-the-fly" types. Creating type declarations to tuples is discouraged - structs are generally a better choice, as they are fully named, support default values, and may have their layout optimized by the compiler.</p>
<h3 id="enums"><a class="header" href="#enums">enums</a></h3>
<p>Enums are <em>ordinal labels</em> that may have <em>associated values</em>.</p>
<p>They are declared with <code>enum[Label, AnotherLabel = 4, ...]</code> and are never initialized (their values are known statically). Enums may be accessed directly by their label, and are ordinal and iterable regardless of their associated value. They are useful in collecting large numbers of "magic values" that would otherwise be constants.</p>
<pre><code class="language-puck">type Keys = enum
  Left, Right, Up, Down
  A = "a"
  B = "b"
</code></pre>
<p>In the case of an identifier conflict (with other enum labels, or types, or...) they must be prefixed with the name of their associated type (separated by a dot). This is standard for identifier conflicts: and is discussed in more detail in the <a href="MODULES.html">modules document</a>.</p>
<h3 id="unions"><a class="header" href="#unions">unions</a></h3>
<p>Unions are <em>tagged</em> type unions. They provide a high-level wrapper over an inner type that must be safely accessed via pattern matching.</p>
<p>They are declared with <code>union[Variant(Type), ...]</code> and initialized with the name of a variant followed by its inner type constructor in brackets: <code>Square(side: 5)</code>. Tuples and structs are special-cased to eliminate extraneous parentheses.</p>
<pre><code class="language-puck">type Value = u64
type Ident = str
type Expr = ref union
  Literal(Value)
  Variable(Ident)
  Abstraction(param: Ident, body: Expr)
  Application(body: Expr, arg: Expr)
  Conditional(
    condition: Expr
    then_case: Expr
    else_case: Expr
  )
</code></pre>
<p>They take up as much space in memory as the largest variant, plus the size of the tag (one byte).</p>
<h4 id="pattern-matching"><a class="header" href="#pattern-matching">pattern matching</a></h4>
<p>Unions abstract over differing types. In order to <em>safely</em> be used, their inner types must be accessed via <em>pattern matching</em>: leaving no room for type confusion. Pattern matching in Puck relies on two syntactic constructs: the <code>match</code> statement, forcing qualification and handling of all possible types of a variable, and the <code>of</code> statement, querying type equality while simultaneously binding new identifiers to underspecified portions of variables.</p>
<pre><code class="language-puck">use std.tables

func eval(context: mut HashTable[Ident, Value], expr: Expr): Result[Value]
  match expr
  of Literal(value) then Okay(value)
  of Variable(ident) then
    context.get(ident).err("Variable not in context")
  of Application(body, arg) then
    if body of Abstraction(param, body as inner_body):
      context.set(param, context.eval(arg)?) # from std.tables
      context.eval(inner_body)
    else
      Error("Expected Abstraction, found {}".fmt(body))
  of Conditional(condition, then_case, else_case):
    if context.eval(condition)? == "true" then
      context.eval(then_case)
    else:
      context.eval(else_case)
  of expr then
    Error("Invalid expression {}".fmt(expr))
</code></pre>
<p>The match statement takes exclusively a list of <code>of</code> sub-expressions, and checks for exhaustivity. The <code>expr of Type(binding)</code> syntax can be reused as a conditional, in <code>if</code> statements and elsewhere.</p>
<p>The <code>of</code> <em>operator</em> is similar to the <code>is</code> operator in that it queries type equality, returning a boolean. However, unbound identifiers within <code>of</code> expressions are bound to appropriate values (if matched) and injected into the scope. This allows for succinct handling of <code>union</code> types in situations where <code>match</code> is overkill.</p>
<p>Each branch of a match expression can also have a <em>guard</em>: an arbitrary conditional that must be met in order for it to match. Guards are written as <code>where cond</code> and immediately follow the last pattern in an <code>of</code> branch, preceding <code>then</code>.</p>
<h3 id="classes"><a class="header" href="#classes">classes</a></h3>
<p>Classes can be thought of as analogous to Rust's traits: without explicit <code>impl</code> blocks and without need for the <code>derive</code> macro. Types that have functions defined on them fulfilling the class requirements implicitly implement the associated class.</p>
<p>The <code>class</code> type is composed of a list of function signatures that refer to the special type <code>Self</code> that must exist for a type to be valid. The special type <code>Self</code> is replaced with the concrete type at compile time in order to typecheck. They are declared with <code>class[signature, ...]</code>.</p>
<pre><code class="language-puck">type Stack[T] = class
  push(self: mut Self, val: T)
  pop(self: mut Self): T
  peek(self: lent Self): lent T

func takes_any_stack(stack: Stack[int]) =
  # only stack.push, stack.pop, and stack.peek are available, regardless of the concrete type passed
</code></pre>
<p>Differing from Rust, Haskell, and many others, there is no explicit <code>impl</code> block. If there exist functions for a type that satisfy all of a class's signatures, it is considered to match and the class typechecks. This may seem strange and ambiguous - but again, static typing and uniform function call syntax help make this a more reasonable design. The purpose of explicit <code>impl</code> blocks in ex. Rust is three-fold: to provide a limited form of uniform function call syntax; to explicitly group together associated code; and to disambiguate. UFCS provides for the first, the module system provides for the second, and type-based disambiguation provides for the third, with such information exposed to the user via the language server protocol.</p>
<pre><code class="language-puck">type Set[T] = class
  in(lent Self, T): bool
  add(mut Self, T)
  remove(mut Self, T): Option[T]

type Foo = struct
  a: int
  b: ref Set[int] # indirection: now perfectly valid
</code></pre>
<p>Classes cannot be constructed, as they are <strong>unsized</strong>. They serve purely as a list of valid operations on a type: no information about their memory layout is relevant. The <em>concrete type</em> fulfilling a class is known at compile time, however, and so there are no issues surrounding the use of classes as parameters, just when attempted to be used as (part of) a concrete type in ex. a struct. They can be used with <em>indirection</em>, however: as references are sized (consisting of a memory address).</p>
<pre><code class="language-puck">## The Display class. Any type implementing `str` is printable.
## Any type that is Display must necessarily also implement Debug.
pub type Display = class
  str(Self): str
  dbg(Self): str

## The Debug class. Broadly implemented for every type with compiler magic.
## Types can (and should) override the generic implementations.
pub type Debug = class
  dbg(Self): str
</code></pre>
<p>Classes also <em>cannot</em> extend or rely upon other classes in any way, nor is there any concept of a parameter satisfying two classes. In the author's experience, while such constructions are powerful, they are also an immense source of complexity, leading to less-than-useful hierarchies seen in languages like Java, and yes, Rust. Instead, if one wishes to form an class that <em>also</em> satisfies another class, they must name a new class that explicitly includes all of the other class's associated functions. Given that classes in Puck overwhelmingly only have a small handful of associated functions, and if you're using more than one class you <em>really</em> should be using a concrete type: the hope is that this will provide for explicitness and reduce complexity.</p>
<p>Classes compose well with <a href="MODULES.html">modules</a> to offer fine grained access control.</p>
<h2 id="errata"><a class="header" href="#errata">Errata</a></h2>
<h3 id="default-values"><a class="header" href="#default-values">default values</a></h3>
<p>Puck does not have any concept of <code>null</code>: all values <em>must</em> be initialized.
But always explicitly initializing types is syntactically verbose, and so most types have an associated "default value".</p>
<p><strong>Default values</strong>:</p>
<ul>
<li><code>bool</code>: <code>false</code></li>
<li><code>int</code>, <code>uint</code>, etc: <code>0</code></li>
<li><code>float</code>, etc: <code>0.0</code></li>
<li><code>char</code>: <code>'\0'</code></li>
<li><code>str</code>: <code>""</code></li>
<li><code>void</code>, <code>never</code>: unconstructable</li>
<li><code>array[T]</code>, <code>list[T]</code>: <code>[]</code></li>
<li><code>set[T]</code>, <code>table[T, U]</code>: <code>{}</code></li>
<li><code>tuple[T, U, ...]</code>: <code>(default values of its fields)</code></li>
<li><code>struct[T, U, ...]</code>: <code>{default values of its fields}</code></li>
<li><code>enum[One, Two, ...]</code>: <strong>disallowed</strong></li>
<li><code>union[T, U, ...]</code>: <strong>disallowed</strong></li>
<li><code>slice[T]</code>, <code>func</code>: <strong>disallowed</strong></li>
<li><code>ref</code>, <code>refc</code>, <code>ptr</code>: <strong>disallowed</strong></li>
</ul>
<p>For unions, slices, references, and pointers, this is a bit trickier. They all have no reasonable "default" for these types <em>aside from</em> null.
Instead of giving in, the compiler instead disallows any non-initializations or other cases in which a default value would be inserted.</p>
<p>todo: consider user-defined defaults (ex. structs)</p>
<h3 id="signatures-and-overloading"><a class="header" href="#signatures-and-overloading">signatures and overloading</a></h3>
<p>Puck supports <em>overloading</em> - that is, there may exist multiple functions, or multiple types, or multiple modules, with the same name - so long as they have a different <em>signature</em>.
The signature of a function/type/module is important. Classes, among other constructs, depend on the user having some understanding of what the compiler considers to be a signature. So we state it here explicitly:</p>
<ul>
<li>The signature of a function is its name and the <em>types</em> of each of its parameters, in order, ignoring optional parameters. Generic parameters are ???
<ul>
<li>ex. ...</li>
</ul>
</li>
<li>The signature of a type is its name and the number of generic parameters.
<ul>
<li>ex. both <code>Result[T]</code> and <code>Result[T, E]</code> are defined in <code>std.results</code></li>
</ul>
</li>
<li>The signature of a module is just its name. This may change in the future.</li>
</ul>
<h3 id="structural-subtyping"><a class="header" href="#structural-subtyping">structural subtyping</a></h3>
<p>Mention of subtyping has been on occasion in contexts surrounding structural type systems, particularly the section on distinct types, but no explicit description of what the subtyping rules are have been given.</p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="SYNTAX.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>

                            <a rel="next prefetch" href="MODULES.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="SYNTAX.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>

                    <a rel="next prefetch" href="MODULES.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>




        <script>
            window.playground_copyable = true;
        </script>


        <script src="elasticlunr.min.js"></script>
        <script src="mark.min.js"></script>
        <script src="searcher.js"></script>

        <script src="clipboard.min.js"></script>
        <script src="highlight.js"></script>
        <script src="book.js"></script>

        <!-- Custom JS scripts -->


    </div>
    </body>
</html>