aboutsummaryrefslogtreecommitdiff
path: root/docs/book/OVERVIEW.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/OVERVIEW.html
parent2d531db8eda6dfb62c2710296b5aaa3de190ac35 (diff)
docs: update website
Diffstat (limited to 'docs/book/OVERVIEW.html')
-rw-r--r--docs/book/OVERVIEW.html198
1 files changed, 121 insertions, 77 deletions
diff --git a/docs/book/OVERVIEW.html b/docs/book/OVERVIEW.html
index 083e1f0..1a4459f 100644
--- a/docs/book/OVERVIEW.html
+++ b/docs/book/OVERVIEW.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">
@@ -174,14 +174,15 @@
<div id="content" class="content">
<main>
<h1 id="an-overview-of-puck"><a class="header" href="#an-overview-of-puck">An Overview of Puck</a></h1>
-<p>Puck is an experimental, high-level, memory-safe, statically-typed, whitespace-sensitive, interface-oriented, imperative programming language with functional underpinnings. </p>
-<p>It attempts to explore designs in making functional programming paradigms comfortable to those familiar with imperative and object-oriented languages, as well as deal with some more technical problems along the way, such as integrated refinement types and typesafe interop. </p>
+<p>Puck is an experimental, high-level, memory-safe, statically-typed, whitespace-sensitive, interface-oriented, imperative programming language with functional underpinnings.</p>
+<p>It attempts to explore designs in making functional programming paradigms comfortable to those familiar with imperative and object-oriented languages, as well as deal with some more technical problems along the way, such as integrated refinement types and typesafe interop.</p>
<p>This is the language I keep in my head. It reflects the way I think and reason about code.</p>
<p>I do hope others enjoy it.</p>
+<h2 id="declarations-and-comments"><a class="header" href="#declarations-and-comments">Declarations and Comments</a></h2>
<pre><code class="language-puck">let ident: int = 413
# type annotations are optional
-var phrase = &quot;Hello, world!&quot;
-const compile_time = when linux: &quot;linux&quot; else: &quot;windows&quot;
+var phrase = "Hello, world!"
+const compile_time = when linux then "linux" else "windows"
</code></pre>
<p>Variables may be mutable (<code>var</code>), immutable (<code>let</code>), or compile-time evaluated and immutable (<code>const</code>).
Type annotations on variables and other bindings follow the name of the binding (with <code>: Type</code>), and are typically optional.
@@ -190,8 +191,7 @@ The type system is comprehensive, and complex enough to warrant delaying full co
<ul>
<li><code>int</code>, <code>uint</code>: signed and unsigned integers
<ul>
-<li><code>i8</code>/<code>i16</code>/<code>i32</code>/<code>i64</code>/<code>i128</code>: their fixed-size counterparts</li>
-<li><code>u8</code>/<code>u16</code>/<code>u32</code>/<code>u64</code>/<code>u128</code>: their fixed-size counterparts</li>
+<li><code>i[\d+]</code>, <code>u[\d+]</code>: arbitrary fixed-size counterparts</li>
</ul>
</li>
<li><code>float</code>, <code>decimal</code>: floating-point numbers
@@ -201,30 +201,33 @@ The type system is comprehensive, and complex enough to warrant delaying full co
</ul>
</li>
<li><code>byte</code>: an alias to <code>u8</code>, representing one byte</li>
-<li><code>chr</code>: an alias to <code>u32</code>, representing one Unicode character</li>
+<li><code>char</code>: an alias to <code>u32</code>, representing one Unicode character</li>
<li><code>bool</code>: defined as <code>union[false, true]</code></li>
-<li><code>array[T, S]</code>: primitive fixed-size (<code>S</code>) arrays</li>
+<li><code>array[T, size]</code>: primitive fixed-size arrays</li>
<li><code>list[T]</code>: dynamic lists</li>
-<li><code>str</code>: mutable strings. internally a <code>list[byte]</code>, externally a <code>list[chr]</code></li>
-<li><code>slice[T]</code>: borrowed &quot;views&quot; into the three types above</li>
+<li><code>str</code>: mutable strings. internally a <code>list[byte]</code>, externally a <code>list[char]</code></li>
+<li><code>slice[T]</code>: borrowed "views" into the three types above</li>
</ul>
<p>Comments are declared with <code>#</code> and run until the end of the line.
Documentation comments are declared with <code>##</code> and may be parsed by language servers and other tooling.
Multi-line comments are declared with <code>#[ ]#</code> and may be nested.
Taking cues from the Lisp family of languages, any expression may be commented out with a preceding <code>#;</code>.</p>
+<h2 id="functions-and-indentation"><a class="header" href="#functions-and-indentation">Functions and Indentation</a></h2>
<pre><code class="language-puck"></code></pre>
-<p>Functions are declared with the <code>func</code> keyword. They take an (optional) list of generic parameters (in brackets), an (optional) list of parameters (in parentheses), and <strong>must</strong> be annotated with a return type if they return a type. Every function parameter must be annotated with a type. Their type may optionally be prefixed with either <code>mut</code> or <code>static</code>: denoting a <em>mutable</em> type (types are copied into functions and thus immutable by default), or a <em>static</em> type (known to the compiler at compile time, and usable in <code>const</code> exprs). Generic parameters may each be optionally annotated with a type functioning as a <em>constraint</em>.</p>
+<p>Functions are declared with the <code>func</code> keyword. They take an (optional) list of generic parameters (in brackets), an (optional) list of parameters (in parentheses), and <strong>must</strong> be annotated with a return type if they return a type. Every function parameter must be annotated with a type. Their type may optionally be prefixed with either <code>lent</code>, <code>mut</code> or <code>const</code>: denoting an immutable or mutable borrow (more on these later), or a <em>constant</em> type (known to the compiler at compile time, and usable in <code>const</code> exprs). Generic parameters may each be optionally annotated with a type functioning as a <em>constraint</em>.</p>
<!-- Functions, constants, types, and modules may be optionally prefixed with a `pub` modifier denoting visibility outside the current scope / module. More on the module system later. -->
-<p>Whitespace is significant but flexible: functions may be declared entirely on one line if so desired. A new level of indentation after certain tokens (<code>:</code>, <code>=</code>) denotes a new level of scope. There are some places where arbitrary indentation and line breaks are allowed - as a general rule of thumb, after operators, commas, and opening parentheses. The particular rules governing indentation may be found in the <a href="SYNTAX.html#indentation-rules">syntax guide</a>.</p>
+<p>Whitespace is significant but flexible: functions may be declared entirely on one line if so desired. A new level of indentation after certain tokens (<code>=</code>, <code>do</code>, <code>then</code>) denotes a new level of scope. There are some places where arbitrary indentation and line breaks are allowed - as a general rule of thumb, after operators, commas, and opening parentheses. The particular rules governing indentation may be found in the <a href="SYNTAX.html#indentation-rules">syntax guide</a>.</p>
+<h2 id="uniform-function-call-syntax"><a class="header" href="#uniform-function-call-syntax">Uniform Function Call Syntax</a></h2>
<pre><code class="language-puck">func inc(self: list[int], by: int): list[int] =
self.map(x =&gt; x + by)
-print inc([1, 2, 3], len(&quot;four&quot;)) # 5, 6, 7
+print inc([1, 2, 3], len("four")) # 5, 6, 7
print [1, 2, 3].inc(1) # 2, 3, 4
print [1].len # 1
</code></pre>
<p>Puck supports <em>uniform function call syntax</em>: and so any function may be called using the typical syntax for method calls, that is, the first parameter of any function may be appended with a <code>.</code> and moved to precede it, in the style of a typical method. (There are no methods in Puck. All functions are statically dispatched. This may change in the future.)</p>
<p>This allows for a number of syntactic cleanups. Arbitrary functions with compatible types may be chained with no need for a special pipe operator. Object field access, module member access, and function calls are unified, reducing the need for getters and setters. Given a first type, IDEs using dot-autocomplete can fill in all the functions defined for that type. Programmers from object-oriented languages may find the lack of classes more bearable. UFCS is implemented in shockingly few languages, and so Puck joins the tiny club that previously consisted of just D and Nim.</p>
+<h2 id="basic-types"><a class="header" href="#basic-types">Basic Types</a></h2>
<pre><code class="language-puck"></code></pre>
<p>Boolean logic and integer operations are standard and as one would expect out of a typed language: <code>and</code>, <code>or</code>, <code>xor</code>, <code>not</code>, <code>shl</code>, <code>shr</code>, <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>, <code>&gt;=</code>, <code>div</code>, <code>mod</code>, <code>rem</code>. Notably:</p>
<ul>
@@ -232,88 +235,142 @@ print [1].len # 1
<li>integer division is expressed with the keyword <code>div</code> while floating point division uses <code>/</code></li>
<li><code>%</code> is absent and replaced with distinct modulus and remainder operators</li>
<li>boolean operators are bitwise and also apply to integers and floats</li>
-<li>more operators are available via the standard library</li>
+<li>more operators are available via the standard library (<code>exp</code> and <code>log</code>)</li>
</ul>
<p>The above operations are performed with <em>operators</em>, special functions that take a prefixed first argument and (often) a suffixed second argument. Custom operators may be implemented, but they must consist of only a combination of the symbols <code>=</code> <code>+</code> <code>-</code> <code>*</code> <code>/</code> <code>&lt;</code> <code>&gt;</code> <code>@</code> <code>$</code> <code>~</code> <code>&amp;</code> <code>%</code> <code>|</code> <code>!</code> <code>?</code> <code>^</code> <code>\</code> for the purpose of keeping the grammar context-free. They are are declared identically to functions.</p>
-<p>Term (in)equality is expressed with the <code>==</code> and <code>!=</code> operators. Type equality is expressed with <code>is</code>. Subtyping relations may be queried with <code>of</code>, which has the additional property of introducing new bindings in the current scope (more on this in the <a href="TYPES.html">types document</a>). <!-- Membership of collections is expressed with `in`, and is overloaded for most types. --></p>
-<pre><code class="language-puck">let phrase: str = &quot;I am a string! Wheeee! ✨&quot;
-for c in phrase:
+<p>Term (in)equality is expressed with the <code>==</code> and <code>!=</code> operators. Type equality is expressed with <code>is</code>. Subtyping relations may be queried with <code>of</code>, which has the additional property of introducing new bindings to the current scope in certain contexts (more on this in the <a href="TYPES.html">types document</a>).</p>
+<pre><code class="language-puck">let phrase: str = "I am a string! Wheeee! ✨"
+for c in phrase do
stdout.write(c) # I am a string! Wheeee! ✨
-for b in phrase.bytes():
- stdout.write(b.chr) # Error: cannot convert between u8 and chr
+for b in phrase.bytes() do
+ stdout.write(b.char) # Error: cannot convert from byte to char
print phrase.last() # ✨
</code></pre>
<p>String concatenation uses a distinct <code>&amp;</code> operator rather than overloading the <code>+</code> operator (as the complement <code>-</code> has no natural meaning for strings). Strings are unified, mutable, internally a byte array, externally a char array, and are stored as a pointer to heap data after their length and capacity (fat pointer). Chars are four bytes and represent a Unicode character in UTF-8 encoding. Slices of strings are stored as a length followed by a pointer to string data, and have non-trivial interactions with the memory management system. More details can be found in the <a href="TYPES.html">type system overview</a>.</p>
+<h2 id="conditionals-and-pattern-matching"><a class="header" href="#conditionals-and-pattern-matching">Conditionals and Pattern Matching</a></h2>
<pre><code class="language-puck"></code></pre>
-<p>Basic conditional control flow uses standard <code>if</code>/<code>elif</code>/<code>else</code> statements. The <code>when</code> statement provides a compile-time <code>if</code>. It also takes <code>elif</code> and <code>else</code> branches and is syntactic sugar for an <code>if</code> statement within a <code>static</code> block (more on those later).</p>
-<p>All values in Puck must be handled, or explicitly discarded. This allows for conditional statements and many other control flow constructs to function as <em>expressions</em>, and evaluate to a value, when an unbound value is left at the end of each of their branches' scopes. This is particularly relevant for <em>functions</em>, where it is often idiomatic to omit an explicit <code>return</code> statement. There is no attempt made to differentiate without context, and so expressions and statements often look identical in syntax.</p>
+<p>Basic conditional control flow uses standard <code>if</code>/<code>elif</code>/<code>else</code> statements. The <code>when</code> statement provides a compile-time <code>if</code>. It also takes <code>elif</code> and <code>else</code> branches and is syntactic sugar for an <code>if</code> statement within a <code>const</code> expression (more on those later).</p>
+<p>All values in Puck must be handled, or explicitly discarded. This allows for conditional statements and many other control flow constructs to function as <em>expressions</em>: and evaluate to a value when an unbound value is left at the end of each of their branches' scopes. This is particularly relevant for <em>functions</em>, where it is often idiomatic to omit an explicit <code>return</code> statement. There is no attempt made to differentiate without context, and so expressions and statements often look identical in syntax.</p>
<pre><code class="language-puck"></code></pre>
<p>Exhaustive structural pattern matching is available with the <code>match</code>/<code>of</code> statement, and is particularly useful for the <code>struct</code> and <code>union</code> types. <code>of</code> branches of a <code>match</code> statement take a <em>pattern</em>, of which the unbound identifiers within will be injected into the branch's scope. Multiple patterns may be used for one branch provided they all bind the same identifiers of the same type. Branches may be <em>guarded</em> with the <code>where</code> keyword, which takes a conditional, and will necessarily remove the branch from exhaustivity checks.</p>
<!-- todo: structural matching of lists and arrays -->
-<p>The <code>of</code> statement also stands on its own as an operator for querying subtype equality. Used as a conditional in <code>if</code> statements or <code>while</code> loops, it retains the variable injection properties of its <code>match</code> counterpart. This allows it to be used as a compact <!-- and coherent --> alternative to <code>if let</code> statements in other languages.</p>
-<pre><code class="language-puck">func may_fail: Result[T, ref Err]
+<p>The <code>of</code> statement also stands on its own as an operator for querying subtype equality. Used as a conditional in <code>if</code> statements or <code>while</code> loops, it retains the variable injection properties of its <code>match</code> counterpart. This allows it to be used as a compact and coherent alternative to <code>if let</code> statements in other languages.</p>
+<h2 id="error-handling"><a class="header" href="#error-handling">Error Handling</a></h2>
+<pre><code class="language-puck">type Result[T] = Result[T, ref Err]
+func may_fail: Result[T] = ...
</code></pre>
-<p>Error handling is done via a fusion of imperative <code>try</code>/<code>catch</code> statements and functional <code>Option</code>/<code>Result</code> types, with much syntactic sugar. Functions may <code>raise</code> errors, but should return <code>Option[T]</code> or <code>Result[T, E]</code> types instead by convention. The compiler will note functions that <code>raise</code> errors, and force explicit qualification of them via <code>try</code>/<code>catch</code> statements.</p>
-<p>A bevy of helper functions and macros are available for <code>Option</code>/<code>Result</code> types, and are documented and available in the <code>std.options</code> and <code>std.results</code> modules (included in the prelude by default). Two in particular are of note: the <code>?</code> macro accesses the inner value of a <code>Result[T, E]</code> or propagates (returns in context) the <code>Error(e)</code>, and the <code>!</code> accesses the inner value of an <code>Option[T]</code> / <code>Result[T, E]</code> or raises an error on <code>None</code> / the specific <code>Error(e)</code>. Both operators take one parameter and so are postfix. (There is additionally another <code>?</code> postfix macro, taking in a type, as a shorthand for <code>Option[T]</code>)</p>
-<p>The utility of the <code>?</code> macro is readily apparent to anyone who has written code in Rust or Swift. The utility of the <code>!</code> function is perhaps less so obvious. These errors raised by <code>!</code>, however, are known to the compiler: and they may be comprehensively caught by a single or sequence of <code>catch</code> statements. This allows for users used to a <code>try</code>/<code>catch</code> error handling style to do so with ease, with only the need to add one additional character to a function call.</p>
+<p>Error handling is done via a fusion of functional monadic types and imperative exceptions, with much syntactic sugar. Functions may <code>raise</code> exceptions, but by convention should return <code>Option[T]</code> or <code>Result[T, E]</code> types instead: these may be handled in <code>match</code> or <code>if</code>/<code>of</code> statements. The compiler will track functions that <code>raise</code> errors, and warn on those that are not handled explicitly via <code>try</code>/<code>with</code> statements.</p>
+<p>A bevy of helper functions and macros are available for <code>Option</code>/<code>Result</code> types, and are documented and available in the <code>std.options</code> and <code>std.results</code> modules (included in the prelude by default). Two in particular are of note: the <code>?</code> macro accesses the inner value of a <code>Result[T, E]</code> or propagates (returns in context) the <code>Error(e)</code>, and the <code>!</code> accesses the inner value of an <code>Option[T]</code> / <code>Result[T, E]</code> or raises an error on <code>None</code> / the specific <code>Error(e)</code>. Both operators take one parameter and so are postfix. The <code>?</code> and <code>!</code> macros are overloaded and additionally function on types as shorthand for <code>Option[T]</code> and <code>Result[T]</code> respectively.</p>
+<p>The utility of the <code>?</code> macro is readily apparent to anyone who has written code in Rust or Swift. The utility of the <code>!</code> function is perhaps less so obvious. These errors raised by <code>!</code>, however, are known to the compiler: and they may be comprehensively caught by a single or sequence of <code>catch</code> statements. This allows for users used to a <code>try</code>/<code>with</code> error handling style to do so with ease, with only the need to add one additional character to a function call.</p>
<p>More details may be found in <a href="ERRORS.html">error handling overview</a>.</p>
-<pre><code class="language-puck">loop:
- print &quot;This will never normally exit.&quot;
+<h2 id="blocks-and-loops"><a class="header" href="#blocks-and-loops">Blocks and Loops</a></h2>
+<pre><code class="language-puck">loop
+ print "This will never normally exit."
break
-for i in 0 .. 3: # exclusive
- for j in 0 ..= 3: # inclusive
- print &quot;{} {}&quot;.fmt(i, j)
+for i in 0 .. 3 do # exclusive
+ for j in 0 ..= 3 do # inclusive
+ print "{} {}".fmt(i, j)
</code></pre>
<p>Three types of loops are available: <code>for</code> loops, <code>while</code> loops, and infinite loops (<code>loop</code> loops). For loops take a binding (which may be structural, see pattern matching) and an iterable object and will loop until the iterable object is spent. While loops take a condition that is executed upon the beginning of each iteration to determine whether to keep looping. Infinite loops are infinite are infinite are infinite are infinite are infinite are infinite and must be manually broken out of.</p>
-<p>There is no special concept of iterators: iterable objects are any object that implements the <code>Iter[T]</code> interface (more on those in <a href="TYPES.html">the type system document</a>), that is, provides a <code>self.next()</code> function returning an <code>Option[T]</code>. As such, iterators are first-class constructs. For loops can be thought of as while loops that unwrap the result of the <code>next()</code> function and end iteration upon a <code>None</code> value. While loops, in turn, can be thought of as infinite loops with an explicit conditional break.</p>
+<p>There is no special concept of iterators: iterable objects are any object that implements the <code>Iter[T]</code> class (more on those in <a href="TYPES.html">the type system document</a>), that is, provides a <code>self.next()</code> function returning an <code>Option[T]</code>. As such, iterators are first-class constructs. For loops can be thought of as while loops that unwrap the result of the <code>next()</code> function and end iteration upon a <code>None</code> value. While loops, in turn, can be thought of as infinite loops with an explicit conditional break.</p>
<p>The <code>break</code> keyword immediately breaks out of the current loop, and the <code>continue</code> keyword immediately jumps to the next iteration of the current loop. Loops may be used in conjunction with blocks for more fine-grained control flow manipulation.</p>
-<pre><code class="language-puck">block:
+<pre><code class="language-puck">block
statement
let x = block:
let y = read_input()
transform_input(y)
-block foo:
- for i in 0 ..= 100:
- block bar:
- if i == 10: break foo
+block foo
+ for i in 0 ..= 100 do
+ block bar
+ if i == 10 then break foo
print i
</code></pre>
<p>Blocks provide arbitrary scope manipulation. They may be labelled or unlabelled. The <code>break</code> keyword additionally functions inside of blocks and without any parameters will jump out of the current enclosing block (or loop). It may also take a block label as a parameter for fine-grained scope control.</p>
+<h2 id="module-system"><a class="header" href="#module-system">Module System</a></h2>
<pre><code class="language-puck"></code></pre>
<p>Code is segmented into modules. Modules may be made explicit with the <code>mod</code> keyword followed by a name, but there is also an implicit module structure in every codebase that follows the structure and naming of the local filesystem. For compatibility with filesystems, and for consistency, module names are exclusively lowercase (following the same rules as Windows).</p>
<p>A module can be imported into another module by use of the <code>use</code> keyword, taking a path to a module or modules. Contrary to the majority of languages ex. Python, unqualified imports are <em>encouraged</em> - in fact, are idiomatic (and the default) - type-based disambiguation and official LSP support are intended to remove any ambiguity.</p>
-<p>Within a module, functions, types, constants, and other modules may be <em>exported</em> for use by other modules with the <code>pub</code> keyword. All such identifiers are private by default and only accessible module-locally without. Modules are first-class and may be bound, inspected, modified, and returned. As such, imported modules may be <em>re-exported</em> for use by other modules by binding them to a public constant, i.e. <code>use my_module; pub const my_module = my_module</code>.</p>
+<p>Within a module, functions, types, constants, and other modules may be <em>exported</em> for use by other modules with the <code>pub</code> keyword. All such identifiers are private by default and only accessible module-locally without. Modules are first-class and may be bound, inspected, modified, and returned. As such, imported modules may be <em>re-exported</em> for use by other modules by binding them to a public constant.</p>
<p>More details may be found in the <a href="MODULES.html">modules document</a>.</p>
+<h2 id="compile-time-programming"><a class="header" href="#compile-time-programming">Compile-time Programming</a></h2>
<pre><code class="language-puck"></code></pre>
-<p>Compile-time programming may be done via the previously-mentioned <code>const</code> keyword and <code>when</code> statements: or via <code>const</code> <em>blocks</em>. All code within a <code>const</code> block is evaluated at compile-time and all assignments and allocations made are propagated to the compiled binary as static data.</p>
-<p>Further compile-time programming may be done via metaprogramming: compile-time manipulation of the abstract syntax tree. The macro system is complex, and a description may be found in the <a href="METAPROGRAMMING.html">metaprogramming document</a>.</p>
+<p>Compile-time programming may be done via the previously-mentioned <code>const</code> keyword and <code>when</code> statements: or via <code>const</code> <em>blocks</em>. All code within a <code>const</code> block is evaluated at compile-time and all assignments and allocations made are propagated to the compiled binary as static data. Further compile-time programming may be done via macros: compile-time manipulation of the abstract syntax tree. The macro system is complex, and a description may be found in the <a href="METAPROGRAMMING.html">metaprogramming document</a>.</p>
+<h2 id="async-system-and-threading"><a class="header" href="#async-system-and-threading">Async System and Threading</a></h2>
<pre><code class="language-puck"></code></pre>
<p>The async system is <em>colourblind</em>: the special <code>async</code> macro will turn any function <em>call</em> returning a <code>T</code> into an asynchronous call returning a <code>Future[T]</code>. The special <code>await</code> function will wait for any <code>Future[T]</code> and return a <code>T</code> (or an error). Async support is included in the standard library in <code>std.async</code> in order to allow for competing implementations. More details may be found in the <a href="ASYNC.html">async document</a>.</p>
<p>Threading support is complex and also regulated to external libraries. OS-provided primitives will likely provide a <code>spawn</code> function, and there will be substantial restrictions for memory safety. I really haven't given much thought to this.</p>
-<pre><code class="language-puck"></code></pre>
-<p>Details on memory safety, references and pointers, and deep optimizations may be found in the <a href="MEMORY_MANAGEMENT.html">memory management overview</a>.
-The memory model intertwines deeply with the type system. <!-- todo --></p>
-<pre><code class="language-puck"></code></pre>
-<p>Finally, a few notes on the type system are in order.</p>
-<p>Types are declared with the <code>type</code> keyword and are transparent aliases.
-That is, <code>type Foo = Bar</code> means that any function defined for <code>Bar</code> is defined for <code>Foo</code> - that is, objects of type <code>Foo</code> can be used any time an object of type <code>Bar</code> is called for.
-If such behavior is not desired, the <code>distinct</code> keyword forces explicit qualification and conversion of types. <code>type Foo = distinct Baz</code> will force a type <code>Foo</code> to be wrapped in a call to the constructor <code>Baz()</code> before being passed to such functions.</p>
-<p>Types, like functions, can be <em>generic</em>: declared with &quot;holes&quot; that may be filled in with other types upon usage. A type must have all its holes filled before it can be constructed. The syntax for generics in types much resembles the syntax for generics in functions, and <em>constraints</em> and the like also apply.</p>
+<h2 id="memory-management"><a class="header" href="#memory-management">Memory Management</a></h2>
+<pre><code class="language-puck"># Differences in Puck and Rust types in declarations and at call sights.
+func foo(a:
+ lent T → &amp;'a T
+ mut T → &amp;'a mut T
+ T → T
+):
+ lent T → &amp;'a T
+ mut T → &amp;'a mut T
+ T → T
+
+let t: T = ...
+foo( # this is usually elided
+ lent t → &amp;t
+ mut t → &amp;mut t
+ t → t
+)
+</code></pre>
+<p>Puck copies Rust-style ownership near verbatim. <code>&amp;T</code> corresponds to <code>lent T</code>, <code>&amp;mut T</code> to <code>mut T</code>, and <code>T</code> to <code>T</code>: with <code>T</code> implicitly convertible to <code>lent T</code> and <code>mut T</code> at call sites. A major goal of Puck is for all lifetimes to be inferred: there is no overt support for lifetime annotations, and it is likely code with strange lifetimes will be rejected before it can be inferred. (Total inference, however, <em>is</em> a goal.)</p>
+<p>Another major difference is the consolidation of <code>Box</code>, <code>Rc</code>, <code>Arc</code>, <code>Cell</code>, <code>RefCell</code> into just two (magic) types: <code>ref</code> and <code>refc</code>. <code>ref</code> takes the role of <code>Box</code>, and <code>refc</code> both the role of <code>Rc</code> and <code>Arc</code>: while <code>Cell</code> and <code>RefCell</code> are disregarded. The underlying motivation for compiler-izing these types is to make deeper compiler optimizations accessible: particularly with <code>refc</code>, where the existing ownership framework is used to eliminate counts. Details on memory safety, references and pointers, and deep optimizations may be found in the <a href="MEMORY_MANAGEMENT.html">memory management overview</a>.</p>
+<h2 id="types-system"><a class="header" href="#types-system">Types System</a></h2>
+<pre><code class="language-puck"># The type Foo is defined here as an alias to a list of bytes.
+type Foo = list[byte]
+
+# implicit conversion to Foo in declarations
+let foo: Foo = [1, 2, 3]
+
+func fancy_dbg(self: Foo) =
+ print "Foo:"
+ # iteration is defined for list[byte]
+ # so self is implicitly converted from Foo to list[byte]
+ for elem in self do
+ dbg(elem)
+
+# NO implicit conversion to Foo on calls
+[4, 5, 6].foo_dbg # this fails!
+
+Foo([4, 5, 6]).foo_dbg # prints: Foo:\n 4\n\ 5\n 6\n
+</code></pre>
+<p>Finally, a few notes on the type system are in order. Types are declared with the <code>type</code> keyword and are aliases: all functions defined on a type carry over to its alias, though the opposite is not true. Functions defined on the alias <em>must</em> take an object known to be a type of that alias: exceptions are made for type declarations, but at call sites this means that conversion must be explicit.</p>
+<pre><code class="language-puck"># We do not want functions defined on list[byte] to carry over,
+# as strings function differently (operating on chars).
+# So we declare `str` as a struct, rather than a type alias.
+pub type str = struct
+ data: list[byte]
+
+# However, the underlying `empty` function is still useful.
+# So we expose it in a one-liner alias.
+# In the future, a `with` macro may be available to ease carryover.
+pub func empty(self: str): bool = self.data.empty
+
+# Alternatively, if we want total transparent type aliasing, we can use constants.
+pub const MyAlias: type = VeryLongExampleType
+</code></pre>
+<p>If one wishes to define a new type <em>without</em> previous methods accessible, the newtype paradigm is preferred: declaring a single-field <code>struct</code>, and manually implementing functions that carry over. It can also be useful to have <em>transparent</em> type aliases, that is, simply a shorter name to refer to an existing type. These do not require type conversion, implicit or explicit, and can be used freely and interchangeably with their alias. This is done with constants.</p>
+<p>Types, like functions, can be <em>generic</em>: declared with "holes" that may be filled in with other types upon usage. A type must have all its holes filled before it can be constructed. The syntax for generics in types much resembles the syntax for generics in functions, and generic <em>constraints</em> and the like also apply.</p>
+<h2 id="structs-and-tuples"><a class="header" href="#structs-and-tuples">Structs and Tuples</a></h2>
<pre><code class="language-puck">type MyStruct = struct
a: str
b: str
-type MyTuple = tuple[str, b: str]
+type MyTuple = (str, b: str)
-let a: MyTuple = (&quot;hello&quot;, &quot;world&quot;)
+let a: MyTuple = ("hello", "world")
print a.1 # world
print a.b # world
</code></pre>
-<p>Struct and tuple types are declared with <code>struct[&lt;fields&gt;]</code> and <code>tuple[&lt;fields&gt;]</code>, respectively. Their declarations make them look similar at a glance, but they differ fairly fundamentally. Structs are <em>unordered</em>, and every field must be named. They may be constructed with <code>{}</code> brackets. Tuples are <em>ordered</em> and so field names are optional - names are just syntactic sugar for positional access. Tuples may be constructed with <code>()</code> parenthesis.</p>
-<p>I am undecided whether to allow <em>structural subtyping</em>: that is, <code>{a: Type, b: Type, c: Type}</code> being valid in a context expecting <code>{a: Type, b: Type}</code>. This has benefits (multiple inheritance with no boilerplate) but also downsides (obvious).</p>
-<p>It is worth noting that there is no concept of <code>pub</code> at a field level on structs - a type is either fully transparent, or fully opaque. This is because such partial transparency breaks with structural initialization (how could one provide for hidden fields?). An idiomatic workaround is to model the desired field structure with a public-facing interface.</p>
+<p>Struct and tuple types are declared with <code>struct[&lt;fields&gt;]</code> and <code>tuple[&lt;fields&gt;]</code>, respectively. Their declarations make them look similar at a glance, but they differ fairly fundamentally. Structs are <em>unordered</em>, and every field must be named. They may be constructed with <code>{}</code> brackets. Tuples are <em>ordered</em> and so field names are optional - names are just syntactic sugar for positional access (<code>foo.0</code>, <code>bar.1</code>, ...). Tuples are constructed with <code>()</code> parentheses: and also may be <em>declared</em> with such, as syntactic sugar for <code>tuple[...]</code>.</p>
+<p>It is worth noting that there is no concept of <code>pub</code> at a field level on structs - a type is either fully transparent, or fully opaque. This is because such partial transparency breaks with structural initialization (how could one provide for hidden fields?). However, the <code>@[opaque]</code> attribute allows for expressing that the internal fields of a struct are not to be accessed or initialized: this, however, is only a compiler warning and can be totally suppressed with <code>@[allow(opaque)]</code>.</p>
+<h2 id="unions-and-enums"><a class="header" href="#unions-and-enums">Unions and Enums</a></h2>
<pre><code class="language-puck">type Expr = union
Literal(int)
Variable(str)
@@ -323,18 +380,21 @@ print a.b # world
<p>Union types are composed of a list of <em>variants</em>. Each variant has a <em>tag</em> and an <em>inner type</em> the union wraps over. Before the inner type can be accessed, the tag must be pattern matched upon, in order to handle all possible values. These are also known as <em>sum types</em> or <em>tagged unions</em> in other languages.</p>
<p>Union types are the bread and butter of structural pattern matching. Composed with structs and tuples, unions provide for a very general programming construct commonly referred to as an <em>algebraic data type</em>.
This is often useful as an idiomatic and safer replacement for inheritance.</p>
-<pre><code class="language-puck">pub type Iter[T] = interface
+<pre><code class="language-puck"></code></pre>
+<p>Enum types are similarly composed of a list of <em>variants</em>. These variants, however, are static values: assigned at compile-time, and represented under the hood by a single integer. They function similarly to unions, and can be passed through to functions and pattern matched upon, however their underlying simplicity and default values mean they are much more useful for collecting constants and acting as flags than anything else.</p>
+<h2 id="classes"><a class="header" href="#classes">Classes</a></h2>
+<pre><code class="language-puck">pub type Iter[T] = class
next(mut Self): T?
-pub type Peek[T] = interface
+pub type Peek[T] = class
next(mut Self): T?
peek(mut Self): T?
peek_nth(mut Self, int): T?
</code></pre>
-<p>Interface types function much as type classes in Haskell or traits in Rust do. They are not concrete types, and cannot be constructed - instead, their utility is via indirection, as parameters or as <code>ref</code> types, providing constraints that some concrete type must meet. They consist of a list of function signatures, implementations of which must exist for the given type in order to compile.</p>
-<p>Their major difference, however, is that Puck's interfaces are <em>implicit</em>: there is no <code>impl</code> block that implementations of their associated functions have to go under. If functions for a concrete type exist satisfying some interface, the type implements that interface. This does run the risk of accidentally implementing an interface one does not desire to, but the author believes such situations are few and far between, well worth the decreased syntactic and semantic complexity, and mitigatable with tactical usage of the <code>distinct</code> keyword.</p>
-<p>As the compiler makes no such distinction between fields and single-argument functions on a type when determining identifier conflicts, interfaces similarly make no such distinction. They <em>do</em> distinguish mutable and immutable parameters, those being part of the type signature.</p>
-<p>Interfaces are widely used throughout the standard library to provide general implementations of such conveniences like iteration, debug and display printing, generic error handling, and much more.</p>
+<p>Class types function much as type classes in Haskell or traits in Rust do. They are not concrete types, and cannot be constructed - instead, their utility is via indirection, as parameters in functions or as <code>ref</code> types in structures, providing constraints that some concrete type must meet. They consist of a list of function signatures, implementations of which must exist for the given type passed in in order to compile.</p>
+<p>Their major difference, however, is that Puck's classes are <em>implicit</em>: there is no <code>impl</code> block that implementations of their associated functions have to go under. If functions for a concrete type exist satisfying some class, the type implements that class. This does run the risk of accidentally implementing a class one does not desire to, but the author believes such situations are few and far between and well worth the decreased syntactic and semantic complexity. As a result, however, classes are entirely unable to guarantee any invariants hold (like <code>PartialOrd</code> or <code>Ord</code> in Rust do).</p>
+<p>As the compiler makes no such distinction between fields and single-argument functions on a type when determining identifier conflicts, classes similarly make no such distinction. They <em>do</em> distinguish borrowed/mutable/owned parameters, those being part of the type signature.</p>
+<p>Classes are widely used throughout the standard library to provide general implementations of such conveniences like iteration, debug and display printing, generic error handling, and much more.</p>
</main>
@@ -365,22 +425,6 @@ pub type Peek[T] = interface
</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>