aboutsummaryrefslogtreecommitdiff
path: root/docs/book/TYPES.html
diff options
context:
space:
mode:
authorJJ2024-05-17 00:40:34 +0000
committerJJ2024-05-17 00:40:34 +0000
commite04af86491d97b297406cc4cd0d77fbbfc3a94c4 (patch)
tree6a97523e328f6070ae201ea325beb26d09e5c430 /docs/book/TYPES.html
parent2d531db8eda6dfb62c2710296b5aaa3de190ac35 (diff)
docs: update website
Diffstat (limited to 'docs/book/TYPES.html')
-rw-r--r--docs/book/TYPES.html271
1 files changed, 106 insertions, 165 deletions
diff --git a/docs/book/TYPES.html b/docs/book/TYPES.html
index 488aa6d..5abe998 100644
--- a/docs/book/TYPES.html
+++ b/docs/book/TYPES.html
@@ -7,7 +7,7 @@
<!-- Custom HTML head -->
-
+
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
@@ -182,11 +182,10 @@
<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. <!-- - overflow into bigints for safety and ease of cryptographical code. -->
+<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>i8</code>, <code>i16</code>, <code>i32</code>, <code>i64</code>, <code>i128</code>: specified integer size</li>
-<li><code>u8</code>, <code>u16</code>, <code>u32</code>, <code>u64</code>, <code>u128</code>: specified integer size</li>
+<li><code>i[\d+]</code>, <code>u[\d+]</code>: arbitrarily sized integers</li>
</ul>
</li>
<li><code>float</code>: floating-point number.
@@ -194,19 +193,19 @@
<li><code>f32</code>, <code>f64</code>: specified float sizes</li>
</ul>
</li>
-<li><code>decimal</code>: precision decimal number. <!-- https://en.wikipedia.org/wiki/IEEE_754 -->
+<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>: a distinct alias to <code>u32</code>. For working with Unicode. <!-- - these are *packed* when part of a string: and so indexing directly into a string is a no-op. string access is O(n), swift-style. --></li>
-<li><code>str</code>: a string type. mutable. internally a byte-array: externally a char-array.</li>
-<li><code>void</code>: an internal type designating the absence of a value. often elided. <!-- - possibly, the empty tuple. then would `empty` be better? or `unit`? --></li>
-<li><code>never</code>: a type that denotes functions that do not return. distinct from returning nothing. <!-- - the bottom type. --></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 combine with <code>str</code>, <code>void</code>, and <code>never</code> to 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>
+<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>
@@ -216,18 +215,18 @@
<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 like a list</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 &quot;algebraic data types&quot;, 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 &quot;abstract types&quot; to mitigate some confusion.</p>
+<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[S, T]</code>: Fixed-size arrays. Can only contain one type <code>T</code>. Of a fixed size <code>S</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!) <!-- Disambiguated from arrays in much the same way uints are disambiguated from ints. --></li>
-<li><code>slice[T]</code>: Slices. Used to represent a &quot;view&quot; 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. <!-- possible syntax sugar: `[T]` --></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>&quot;abc&quot;</code>.</li>
+<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>
@@ -255,12 +254,12 @@ These are monomorphized into more specific functions at compile-time if needed.<
<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>static: <code>func foo(a: static 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>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>interfaces: <code>func foo(a: Stack[int])</code>: Implicit typeclasses. More in the <a href="#interfaces">interfaces section</a>.
+<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>
@@ -270,33 +269,34 @@ These are monomorphized into more specific functions at compile-time if needed.<
<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">func add[T](a: list[T], b: T) =
- return a.add(b)
+<pre><code class="language-puck"># fully generic. monomorphizes based on usage.
+func add[T](a: list[T], b: T) = a.push(b)
-func length[T](a: T) =
- return a.len # monomorphizes based on usage.
- # lots of things use .len, but only a few called by this do.
- # throws a warning if exported for lack of specitivity.
+# 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
-func length(a: str | list) =
- return a.len
+# 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>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 modules and type declarations themselves may also be generic.</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 two avenues for indirection.</p>
+<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 automatically-managed reference to type <code>T</code>. This is a pointer of size <code>uint</code> (native).</li>
-<li><code>ptr T</code>: A manually-managed pointer to type <code>T</code>. (very) unsafe. The compiler will yell at you.</li>
+<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] = interface
+type AbstractTree[T] = class
func left(self: Self): Option[AbstractTree[T]]
func right(self: Self): Option[AbstractTree[T]]
func data(self: Self): T
@@ -311,57 +311,61 @@ type UnsafeTree = struct
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. Much care has been given to make references efficient and safe, and so <code>ptr</code> should be avoided if at all possible. The compiler will yell at you if you use it (or any other unsafe features).</p>
-<p>The implementation of <code>ref</code> is delved into in further detail in the <a href="MEMORY_MANAGEMENT.html">memory management document</a>.</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 composition. Algebraic data types can be one-of:</p>
+<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>interface</code>: Implicit typeclasses. User-defined duck typing.</li>
+<li><code>class</code>: Implicit type classes. User-defined duck typing.</li>
</ul>
-<p>There also exist <code>distinct</code> types: while <code>type</code> declarations define an alias to an existing or new type, <code>distinct</code> types define a type that must be explicitly converted to/from. This is useful for having some level of separation from the implicit interfaces that abound.</p>
+<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: &quot;value&quot;, another: 500}</code>.</p>
-<pre><code class="language-puck">type LinkedNode[T] = struct
- previous, next: Option[ref LinkedNode[T]]
+<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 = {
- previous: None, next: None
- data: 413
+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):
+ if node.next of Some(node) then
node.pretty_print()
# structural typing!
prints_data(node)
</code></pre>
-<p>Structs are <em>structural</em> and so structs composed entirely of fields with the same signature (identical in name and type) are considered <em>equivalent</em>.
-This is part of a broader structural trend in the type system, and is discussed in detail in the section on <a href="#subtyping">subtyping</a>.</p>
<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, &quot;hello&quot;, value: 40000)</code>. Syntax sugar allows for them to be declared with <code>()</code> as well.</p>
-<p>They are exclusively ordered - named types within tuples are just syntax 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 in order.</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[string, string] = (&quot;hello&quot;, &quot;world&quot;)
+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 &quot;on-the-fly&quot; types. Creating type aliases to tuples is discouraged - structs are generally a better choice for custom type declarations.</p>
+<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 &quot;magic values&quot;, that would otherwise be constants.</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 = &quot;a&quot;
- B = &quot;b&quot;
+ 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>
@@ -387,83 +391,90 @@ type Expr = ref union
func eval(context: mut HashTable[Ident, Value], expr: Expr): Result[Value]
match expr
- of Literal(value): Okay(value)
- of Variable(ident):
- context.get(ident).err(&quot;Variable not in context&quot;)
- of Application(body, arg):
+ 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(&quot;Expected Abstraction, found {}&quot;.fmt(body))
+ else
+ Error("Expected Abstraction, found {}".fmt(body))
of Conditional(condition, then_case, else_case):
- if context.eval(condition)? == &quot;true&quot;:
+ if context.eval(condition)? == "true" then
context.eval(then_case)
else:
context.eval(else_case)
- of expr:
- Error(&quot;Invalid expression {}&quot;.fmt(expr))
+ 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 the colon.</p>
-<h3 id="interfaces"><a class="header" href="#interfaces">interfaces</a></h3>
-<p>Interfaces 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 fulfilling the interface requirements implicitly implement the associated interface.</p>
-<p>The <code>interface</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>interface[signature, ...]</code>.</p>
-<pre><code class="language-puck">type Stack[T] = interface
+<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: 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 methods
+ # 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 an interface's signatures, it is considered to match and the interface 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 the third is proposed to not matter.</p>
-<p>Interfaces cannot be constructed because they are <strong>unsized</strong>. They serve purely as a list of valid operations on a type within a context: no information about their memory layout is relevant. The concrete type fulfilling an interface is known at compile time, however, and so there are no issues surrounding interfaces as parameters, just when attempted to be used as (part of) a concrete type. They can be used as part of a concrete type with <em>indirection</em>, however: <code>type Foo = struct[a: int, b: ref interface[...]]</code> is perfectly valid.</p>
-<p>Interfaces also <em>cannot</em> extend or rely upon other interfaces in any way. There is no concept of an interface extending an interface. There is no concept of a parameter satisfying two interfaces. In the author's experience, while such constructions are powerful, they are also an immense source of complexity, leading to less-than-useful interface hierarchies seen in languages like Java, and yes, Rust.</p>
-<p>Instead, if one wishes to form an interface that <em>also</em> satisfies another interface, they must include all of the other interface's associated functions within the new interface. Given that interfaces overwhelmingly only have a handful of associated functions, and if you're using more than one interface you <em>really</em> should be using a concrete type, the hope is that this will provide explicitness.</p>
-<!-- While functions are the primary way of performing operations on types, they are not the only way, and listing all explicitly can be painful - instead, it can be desired to be able to *associate a type* and any field access or existing functions on that type with the interface. todo: i have not decided on the syntax for this yet. -->
-<p>Interfaces compose with <a href="MODULES.html">modules</a> to offer fine grained access control.</p>
-<!-- todo: I have not decided whether the names of parameters is / should be relevant, or enforcable, or present. I'm leaning towards them not being present. But if they are enforcable, it makes it harder to implicitly implement the wrong interface. Design notes to consider: https://blog.rust-lang.org/2015/05/11/traits.html -->
-<h3 id="type-aliases-and-distinct-types"><a class="header" href="#type-aliases-and-distinct-types">type aliases and distinct types</a></h3>
-<p>Any type can be declared as an <em>alias</em> to a type simply by assigning it to such. All functions defined on the original type carry over, and functions expecting one type may receive the other with no issues.</p>
-<pre><code class="language-puck">type Float = float
+<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>It is no more than an alias. When explicit conversion between types is desired and functions carrying over is undesired, <code>distinct</code> types may be used.</p>
-<pre><code class="language-puck">type MyFloat = distinct float
-let foo: MyFloat = MyFloat(192.68)
+<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>Types then must be explicitly converted via constructors.</p>
+<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 &quot;default value&quot;.</p>
+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>&quot;&quot;</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>: <code>&lt;first label&gt;</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>ptr</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 &quot;default&quot; for these types <em>aside from</em> null.
+<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, so long as they have the same <em>signature</em>.
-The signature of a function / type / module is important. Interfaces, among other constructs, depend on the user having some understanding of what the compiler considers to be a signature.
-So, it is stated here explicitly:</p>
+<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. Optional parameters are ignored. Generic parameters are ???
+<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>
@@ -475,62 +486,8 @@ So, it is stated here explicitly:</p>
</li>
<li>The signature of a module is just its name. This may change in the future.</li>
</ul>
-<h3 id="subtyping"><a class="header" href="#subtyping">subtyping</a></h3>
+<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>
-<p>Subtyping is the implicit conversion of compatible types, usually in a one-way direction. The following types are implicitly convertible:</p>
-<ul>
-<li><code>uint</code> ==&gt; <code>int</code></li>
-<li><code>int</code> ==&gt; <code>float</code></li>
-<li><code>uint</code> ==&gt; <code>float</code></li>
-<li><code>string</code> ==&gt; <code>list[char]</code> (the opposite no, use <code>pack</code>)</li>
-<li><code>array[T; n]</code> ==&gt; <code>list[T]</code></li>
-<li><code>struct[a: T, b: U, ...]</code> ==&gt; <code>struct[a: T, b: U]</code></li>
-<li><code>union[A: T, B: U]</code> ==&gt; <code>union[A: T, B: U, ...]</code></li>
-</ul>
-<h3 id="inheritance"><a class="header" href="#inheritance">inheritance</a></h3>
-<p>Puck is not an object-oriented language. Idiomatic design patterns in object-oriented languages are harder to accomplish and not idiomatic here.</p>
-<p>But, Puck has a number of features that somewhat support the object-oriented paradigm, including:</p>
-<ul>
-<li>uniform function call syntax</li>
-<li>structural typing / subtyping</li>
-<li>interfaces</li>
-</ul>
-<pre><code class="language-puck">type Building = struct
- size: struct[length, width: uint]
- color: enum[Red, Blue, Green]
- location: tuple[longitude, latitude: float]
-
-type House = struct
- size: struct[length, width: uint]
- color: enum[Red, Blue, Green]
- location: tuple[longitude, latitude: float]
- occupant: str
-
-func init(_: type[House]): House =
- { size: {length, width: 500}, color: Red
- location: (0.0, 0.0), occupant: &quot;Barry&quot; }
-
-func address(building: Building): str =
- let number = int(building.location.0 / building.location.1).abs
- let street = &quot;Logan Lane&quot;
- return number.str &amp; &quot; &quot; &amp; street
-
-# subtyping! methods!
-print House.init().address()
-
-func address(house: House): str =
- let number = int(house.location.0 - house.location.1).abs
- let street = &quot;Logan Lane&quot;
- return number.str &amp; &quot; &quot; &amp; street
-
-# overriding! (will warn)
-print address(House.init())
-
-# abstract types! inheritance!
-type Addressable = interface for Building
- func address(self: Self)
-</code></pre>
-<p>These features may <em>compose</em> into code that closely resembles its object-oriented counterpart. But make no mistake! Puck is static first and functional somewhere in there: dynamic dispatch and the like are not accessible (currently).</p>
</main>
@@ -561,22 +518,6 @@ type Addressable = interface for Building
</div>
- <!-- Livereload script (if served using the cli tool) -->
- <script>
- const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
- const wsAddress = wsProtocol + "//" + location.host + "/" + "__livereload";
- const socket = new WebSocket(wsAddress);
- socket.onmessage = function (event) {
- if (event.data === "reload") {
- socket.close();
- location.reload();
- }
- };
-
- window.onbeforeunload = function() {
- socket.close();
- }
- </script>