Compare commits

...

10 Commits

Author SHA1 Message Date
Kyler Olsen e35f1b20e1 Added more stuff for slides 2025-12-09 23:28:11 -07:00
Kyler Olsen f8c824c5ba Added slides 2025-12-07 00:28:33 -07:00
Kyler Olsen 1ca5390105 Added back to top link 2025-11-27 20:12:34 -07:00
Kyler Olsen ce0a78b6c6 Added links to toc 2025-11-27 20:10:12 -07:00
Kyler Olsen 04274e14e3 Added io ref 2025-11-27 20:01:27 -07:00
Kyler Olsen 5dd0daed8a Updated notes on assignment and repo links 2025-11-07 21:48:18 -07:00
Kyler Olsen 5919a2895d Enhance markdown conversion and add print styles 2025-11-04 18:28:44 -07:00
Kyler Olsen 6e909840d4 Update and upload changes 2025-11-04 17:41:26 -07:00
Kyler Olsen 3336509bda v0.8.2 2025-11-03 15:03:47 -07:00
Kyler Olsen 8197e56f12 Removed AI prompt 2025-11-02 17:23:00 -07:00
33 changed files with 4641 additions and 184 deletions

View File

@ -22,9 +22,9 @@ def convert_markdown_to_html(md_path: Path, html_path: Path):
'meta',
])
html = md.convert(md_path.read_text(encoding="utf-8"))
title = md.Meta["title"][0] # type: ignore
prev_page = md.Meta["prev"][0] # type: ignore
next_page = md.Meta["next"][0] # type: ignore
title = md.Meta.get("title", (md_path.name,))[0] # type: ignore
prev_page = md.Meta.get("prev", ("",))[0] # type: ignore
next_page = md.Meta.get("next", ("",))[0] # type: ignore
prev_link = f'<a href="/{my_url_builder(prev_page, './', '.html')}">Prev</a>'
next_link = f'<a href="/{my_url_builder(next_page, './', '.html')}">Next</a>'
@ -102,6 +102,10 @@ def convert_all(source_dir: Path, output_dir: Path):
rel_path = md_file.relative_to(source_dir)
html_path = output_dir / rel_path.with_suffix(".html")
convert_markdown_to_html(md_file, html_path)
for md_file in (source_dir / '..' / "stack_lang_spec.md",):
rel_path = md_file.relative_to(source_dir / '..')
html_path = output_dir / rel_path.with_suffix(".html")
convert_markdown_to_html(md_file, html_path)
def convert_all_watch_files(source_dir: Path, output_dir: Path):
import time
@ -136,5 +140,7 @@ def convert_all_watch_files(source_dir: Path, output_dir: Path):
observer.join()
if __name__ == "__main__":
from sys import argv
convert_all(SOURCE_DIR, OUTPUT_DIR)
# convert_all_watch_files(SOURCE_DIR, OUTPUT_DIR)
if 'watch' in argv:
convert_all_watch_files(SOURCE_DIR, OUTPUT_DIR)

View File

@ -72,7 +72,111 @@ Identifier literals use the `::` prefix to push an identifier as a value rather
- Dynamic trait operations
- Meta-programming
### 11.3 Standard Library
### 11.3 Testing and Assertions
The `assert` operator provides inline testing and verification.
**Syntax**: `{ expression } { condition } assert`
The assert operator evaluates the expression block, then evaluates the condition block. If the condition returns false (or a falsy value), the program halts with an assertion failure.
**Examples**:
```
// Simple assertion
{ 2 3 + } { 5 == } assert
// Testing a function
{ 5 square } { 25 == } assert
// Multiple assertions
{ 10 3 divmod } { 3 == swap 1 == and } assert
// Assertion with message (implementation-specific)
{ 2 3 + } { 5 == } "Addition should work" assert
```
**Use Cases**:
- Unit testing
- Invariant checking
- Contract programming
- Debugging
**Testing Framework (Future)**: A more comprehensive testing framework with `test` and `test_error` operators is planned for future versions. See [Appendix F](./memory_management.html) for details.
### 11.4 Reflection
Reflection operators provide runtime type and trait information for debugging and metaprogramming.
**type_of Operator**
**Syntax**: `value type_of`
**Signature**: `(Self -- Identifier)`
Returns the type of a value as an identifier literal.
**Examples**:
```
42 type_of // Pushes ::i64
"hello" type_of // Pushes ::String
3.14 type_of // Pushes ::f64
// Use with conditionals
value type_of ::i64 ==
{ "It's an integer" print }
{ "It's not an integer" print }
if
```
**implements Operator**
**Syntax**: `value ::TraitName implements`
**Signature**: `(Self Identifier -- bool)`
Checks if a value's type implements a specific trait.
**Examples**:
```
42 ::Addable implements // => true
42 ::Drawable implements // => false
"hello" ::String implements // => true
[1 2 3] ::Iterable implements // => true
// Use with conditionals
value ::Serializable implements
{ value serialize }
{ "Cannot serialize" print }
if
```
**Use Cases**:
- Runtime type checking
- Debugging and introspection
- Dynamic dispatch based on traits
- Building generic utilities
- Error messages with type information
**Examples**:
```
// Generic print function with type info
(Self -- ) {
dup type_of to_str "Type: " swap concat print
dup ::Stringifiable implements
{ to_str print }
{ drop "Cannot print this type" print }
if
} ::debug_print fn
// Trait-based dispatch
(Self -- ) {
dup ::Drawable implements
{ draw }
{ drop "Not drawable" print }
if
} ::try_draw fn
```
### 11.5 Standard Library
The standard library provides I/O, string operations, type conversions, and utility functions. All standard library functions are automatically in scope (no imports needed in current version).
@ -91,6 +195,12 @@ The standard library provides I/O, string operations, type conversions, and util
"hello" 1 3 substr // Extract substring
"a,b,c" "," split // Split by delimiter
["a" "b"] "," join // Join with delimiter
"hello world" "world" "Stack" replace // Replace substring
" hello " trim // Remove whitespace
"hello world" "world" find // Find substring position
"hello" "hel" starts_with // Check prefix
"hello" "llo" ends_with // Check suffix
"x=%d, y=%d" [5 10] format // Format string with values
```
**Type Conversion**:
@ -104,7 +214,8 @@ The standard library provides I/O, string operations, type conversions, and util
**Array Operations**:
- Element access: `at`, `slice`
- Information: `length`, `shape`
- Combinators: `map`, `filter`, `reduce`, `each`
- Combinators: `map`, `filter`, `reduce`, `each`, `foldl`, `foldr`
- Utilities: `zip`, `enumerate`, `sum`, `mean`
- Manipulation: `concat`, `reverse`, `transpose`, `window`
> **Complete Reference**: See [Appendix A](./standard_library.html) for the full standard library reference with all functions, signatures, and examples.

View File

@ -53,15 +53,37 @@ Basic arithmetic operations work on numeric types:
2.718 ln // ( a -- result ) Natural logarithm
```
**Mathematical Functions**:
```
16 sqrt // ( a -- result ) Square root
-5 abs // ( a -- result ) Absolute value
0.0 sin // ( a -- result ) Sine (radians)
0.0 cos // ( a -- result ) Cosine (radians)
0.0 tan // ( a -- result ) Tangent (radians)
1.0 asin // ( a -- result ) Arc sine
1.0 acos // ( a -- result ) Arc cosine
1.0 atan // ( a -- result ) Arc tangent
1.0 0.0 atan2 // ( y x -- result ) Two-argument arc tangent
3.14 floor // ( a -- result ) Round down
3.14 ceil // ( a -- result ) Round up
3.14 round // ( a -- result ) Round to nearest
3 5 min // ( a b -- result ) Minimum of two values
3 5 max // ( a b -- result ) Maximum of two values
```
**Examples**:
```
10 5 + // => 15
10 3 / // => 3
10 3 % // => 1
2 10 ^ // => 1024
16 sqrt // => 4.0
-42 abs // => 42
3.14159 sin // => ~0.0
3.7 round // => 4.0
```
> **Implementation Details**: Arithmetic operators implement the `::Addable`, `::Multiplyable`, `::Exponentiable`, and `::Logarithmic` traits. See [Appendix B](./complete_trait_reference.html) for complete trait definitions and [Appendix C](./complete_operator_reference.html) for the full operator reference.
> **Implementation Details**: Arithmetic operators implement the `::Addable`, `::Multiplyable`, `::Exponentiable`, `::Logarithmic`, and `::Math` traits. See [Appendix B](./complete_trait_reference.html) for complete trait definitions and [Appendix C](./complete_operator_reference.html) for the full operator reference.
### 4.3 Comparison Operators
@ -130,4 +152,25 @@ Bitwise operations work on integer types:
> **Implementation Details**: Bitwise operators implement the `::Bitwise` trait. See [Appendix B](./complete_trait_reference.html) for the complete trait definition.
### 4.6 Randomness
Random number generation is provided through built-in operators:
```
rand // ( -- f64 ) Generate random f64 in range [0.0, 1.0)
seed // ( u64 -- ) Seed the random number generator
```
**Examples**:
```
rand // => 0.7234... (random value)
12345 seed // Seed RNG with specific value
rand // => 0.4321... (deterministic after seed)
// Random integer in range
100 rand * floor // Random integer 0-99
```
> **Implementation Note**: The specific random number generation algorithm is implementation-defined but should be a high-quality PRNG suitable for general use (not cryptography).
---

View File

@ -6,7 +6,7 @@ Next:
# Stack Language Specification
**Version**: 0.8.1
**Version**: 0.8.2
**Status**: Draft Specification
**Changes**:
- 0.5 (AI)
@ -77,5 +77,21 @@ Next:
8. **Grammar simplification** - Referenced Implementable trait instead of repeating
- 0.8.1 (Human)
1. Added links
- 0.8.2 (AI)
1. **Constants** - Added constant definition syntax and semantics
2. **Enhanced literals** - Added underscore separators, character literals, octal syntax
3. **Mathematical functions** - Added sqrt, abs, trig functions, rounding, min/max
4. **Randomness** - Added rand and seed operators
5. **Array enhancements** - Added typed array syntax and arrays of structs
6. **Collection functions** - Added zip, enumerate, sum, mean, foldl, foldr
7. **String utilities** - Added replace, trim, find, starts_with, ends_with, format
8. **Testing support** - Added assert operator for inline testing
9. **Reflection operators** - Added type_of and implements for runtime introspection
10. **Compiler directives** - Added mention of implementation-specific directives
11. **Type reference** - Added Appendix H with complete type reference
12. **Math trait** - Added comprehensive Math trait to Appendix B
13. **Overflow behavior** - Documented integer wrap and float IEEE behavior
14. **Grammar updates** - Expanded Appendix D with new syntax forms
15. **Cross-references** - Updated all references to include new operators and functions
---

View File

@ -10,7 +10,7 @@ This appendix provides a complete alphabetical reference of all operators in the
### Operator List
`!=`, `%`, `&` (bitand), `*`, `+`, `-`, `/`, `<`, `<=`, `==`, `>`, `>=`, `^`, `|` (bitor), `and`, `at`, `bitand`, `bitnot`, `bitor`, `bitxor`, `break`, `concat`, `continue`, `depth`, `drop`, `dup`, `each`, `enum`, `eval`, `filter`, `fn`, `for`, `get`, `if`, `impl`, `inher`, `lambda`, `length`, `ln`, `log`, `logb`, `map`, `match`, `not`, `or`, `over`, `pick`, `reduce`, `reverse`, `roll`, `rot`, `set`, `shl`, `shr`, `slice`, `struct`, `substr`, `swap`, `trait`, `transpose`, `union`, `while`, `window`
`!=`, `%`, `*`, `+`, `-`, `/`, `<`, `<=`, `==`, `>`, `>=`, `^`, `abs`, `acos`, `asin`, `assert`, `at`, `atan`, `atan2`, `bitand`, `bitnot`, `bitor`, `bitxor`, `break`, `ceil`, `concat`, `continue`, `cos`, `depth`, `drop`, `dup`, `each`, `ends_with`, `enum`, `enumerate`, `eval`, `filter`, `find`, `floor`, `foldl`, `foldr`, `for`, `format`, `get`, `if`, `impl`, `implements`, `inher`, `lambda`, `length`, `ln`, `log`, `logb`, `map`, `match`, `max`, `mean`, `min`, `not`, `or`, `over`, `pick`, `rand`, `reduce`, `replace`, `reverse`, `roll`, `rot`, `round`, `seed`, `set`, `shl`, `shr`, `sin`, `slice`, `split`, `sqrt`, `starts_with`, `struct`, `substr`, `sum`, `swap`, `tan`, `trait`, `transpose`, `trim`, `type_of`, `union`, `while`, `window`, `zip`
### Alphabetical Operator Reference
@ -119,7 +119,25 @@ This appendix provides a complete alphabetical reference of all operators in the
**Trait**: Exponentiable
**Description**: Raise first value to power of second (exponentiation).
**Example**: `2 8 ^ // => 256`
**See Also**: log, ln, logb
**See Also**: log, ln, sqrt
**Section**: 4.2 (Arithmetic Operators)
#### abs
**Operator Type**: Mathematical
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Return absolute value of number.
**Example**: `-42 abs // => 42`
**See Also**: min, max
**Section**: 4.2 (Arithmetic Operators)
#### acos
**Operator Type**: Mathematical
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Calculate arc cosine in radians.
**Example**: `1.0 acos // => 0.0`
**See Also**: cos, asin, atan
**Section**: 4.2 (Arithmetic Operators)
#### and
@ -131,6 +149,23 @@ This appendix provides a complete alphabetical reference of all operators in the
**See Also**: or, not
**Section**: 4.4 (Logical Operators)
#### asin
**Operator Type**: Mathematical
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Calculate arc sine in radians.
**Example**: `1.0 asin // => ~1.5708`
**See Also**: sin, acos, atan
**Section**: 4.2 (Arithmetic Operators)
#### assert
**Operator Type**: Testing
**Signature**: `(TokenString TokenString --)`
**Description**: Evaluate expression and condition, halt if condition is false.
**Example**: `{ 2 3 + } { 5 == } assert`
**See Also**: type_of, implements
**Section**: 11.3 (Testing and Assertions)
#### at
**Operator Type**: Container Access
**Signature**: `(Selectable<T> Size -- T)`
@ -140,6 +175,24 @@ This appendix provides a complete alphabetical reference of all operators in the
**See Also**: slice, length
**Section**: 7.4 (Arrays)
#### atan
**Operator Type**: Mathematical
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Calculate arc tangent in radians.
**Example**: `1.0 atan // => ~0.7854`
**See Also**: tan, atan2, asin
**Section**: 4.2 (Arithmetic Operators)
#### atan2
**Operator Type**: Mathematical
**Signature**: `(Math Math -- Math)`
**Trait**: Math
**Description**: Two-argument arc tangent using signs to determine quadrant.
**Example**: `1.0 1.0 atan2 // => ~0.7854`
**See Also**: atan, tan
**Section**: 4.2 (Arithmetic Operators)
#### bitand
**Operator Type**: Bitwise
**Signature**: `(Bitwise Bitwise -- Bitwise)`
@ -184,6 +237,15 @@ This appendix provides a complete alphabetical reference of all operators in the
**See Also**: continue, while, for
**Section**: 6.4 (Loop Control)
#### ceil
**Operator Type**: Mathematical
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Round number up to nearest integer.
**Example**: `3.14 ceil // => 4.0`
**See Also**: floor, round
**Section**: 4.2 (Arithmetic Operators)
#### concat
**Operator Type**: Container
**Signature**: `(Concatenable Concatenable -- Concatenable)`
@ -201,6 +263,15 @@ This appendix provides a complete alphabetical reference of all operators in the
**See Also**: break, while, for
**Section**: 6.4 (Loop Control)
#### cos
**Operator Type**: Mathematical
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Calculate cosine of angle in radians.
**Example**: `0.0 cos // => 1.0`
**See Also**: sin, tan, acos
**Section**: 4.2 (Arithmetic Operators)
#### depth
**Operator Type**: Stack Manipulation
**Signature**: `(-- Size)`
@ -236,6 +307,15 @@ This appendix provides a complete alphabetical reference of all operators in the
**See Also**: map, filter, reduce
**Section**: 7.4 (Arrays)
#### ends_with
**Operator Type**: String
**Signature**: `(String String -- bool)`
**Trait**: String
**Description**: Check if string ends with given suffix.
**Example**: `"hello" "lo" ends_with // => true`
**See Also**: starts_with, find
**Section**: 11.5 (String Operations)
#### enum
**Operator Type**: Definition
**Signature**: `(TokenString Identifier --)`
@ -245,6 +325,14 @@ This appendix provides a complete alphabetical reference of all operators in the
**See Also**: struct, union, trait
**Section**: 7.3 (Enums)
#### enumerate
**Operator Type**: Array
**Signature**: `(ArrayOf<T> -- ArrayOf<Pair<Size T>>)`
**Description**: Add indices to array elements.
**Example**: `["a" "b" "c"] enumerate // => [[0 "a"] [1 "b"] [2 "c"]]`
**See Also**: zip, map
**Section**: 7.4 (Arrays)
#### eval
**Operator Type**: Meta
**Signature**: `(TokenString --)`
@ -262,6 +350,24 @@ This appendix provides a complete alphabetical reference of all operators in the
**See Also**: map, reduce, each
**Section**: 7.4 (Arrays)
#### find
**Operator Type**: String
**Signature**: `(String String -- Option<Size>)`
**Trait**: String
**Description**: Find position of substring.
**Example**: `"hello world" "world" find // => Option::Some(6)`
**See Also**: starts_with, ends_with
**Section**: 11.5 (String Operations)
#### floor
**Operator Type**: Mathematical
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Round number down to nearest integer.
**Example**: `3.14 floor // => 3.0`
**See Also**: ceil, round
**Section**: 4.2 (Arithmetic Operators)
#### fn
**Operator Type**: Definition
**Signature**: `(TypeTuple TokenString Identifier --)`
@ -271,6 +377,22 @@ This appendix provides a complete alphabetical reference of all operators in the
**See Also**: lambda, trait, impl
**Section**: 5.2 (Defining Functions)
#### foldl
**Operator Type**: Array Combinator
**Signature**: `(ArrayOf<T> U TokenString -- U)`
**Description**: Left fold array with accumulator function.
**Example**: `[1 2 3 4] 0 { + } foldl // => 10`
**See Also**: foldr, reduce
**Section**: 7.4 (Arrays)
#### foldr
**Operator Type**: Array Combinator
**Signature**: `(ArrayOf<T> U TokenString -- U)`
**Description**: Right fold array with accumulator function.
**Example**: `[1 2 3 4] 0 { + } foldr // => 10`
**See Also**: foldl, reduce
**Section**: 7.4 (Arrays)
#### for
**Operator Type**: Control Flow
**Signature**: `(Size Size TokenString --)`
@ -279,6 +401,15 @@ This appendix provides a complete alphabetical reference of all operators in the
**See Also**: while, break, continue
**Section**: 6.3 (For Loops)
#### format
**Operator Type**: String
**Signature**: `(String Iterable<Stringifiable> -- String)`
**Trait**: String
**Description**: Format string with values, replacing placeholders.
**Example**: `"x=%d, y=%d" [5 10] format // => "x=5, y=10"`
**See Also**: to_str, concat
**Section**: 11.5 (String Operations)
#### get
**Operator Type**: Struct Access
**Signature**: `(Struct Identifier -- FieldValue)`
@ -304,6 +435,14 @@ This appendix provides a complete alphabetical reference of all operators in the
**See Also**: trait, inher
**Section**: 9.3 (Implementing Traits)
#### implements
**Operator Type**: Reflection
**Signature**: `(Self Identifier -- bool)`
**Description**: Check if value's type implements a specific trait.
**Example**: `42 ::Addable implements // => true`
**See Also**: type_of, assert
**Section**: 11.4 (Reflection)
#### inher
**Operator Type**: Definition
**Signature**: `(ArrayOf<Identifier> Identifier --)`
@ -374,6 +513,32 @@ This appendix provides a complete alphabetical reference of all operators in the
**See Also**: if
**Section**: 6.5 (Pattern Matching)
#### max
**Operator Type**: Mathematical
**Signature**: `(Math Math -- Math)`
**Trait**: Math
**Description**: Return the maximum of two values.
**Example**: `3 5 max // => 5`
**See Also**: min, abs
**Section**: 4.2 (Arithmetic Operators)
#### mean
**Operator Type**: Array
**Signature**: `(ArrayOf<Number> -- f64)`
**Description**: Calculate average of numeric array elements.
**Example**: `[1 2 3 4 5] mean // => 3.0`
**See Also**: sum, reduce
**Section**: 7.4 (Arrays)
#### min
**Operator Type**: Mathematical
**Signature**: `(Math Math -- Math)`
**Trait**: Math
**Description**: Return the minimum of two values.
**Example**: `3 5 min // => 3`
**See Also**: max, abs
**Section**: 4.2 (Arithmetic Operators)
#### not
**Operator Type**: Logical
**Signature**: `(Logical -- Logical)`
@ -410,14 +575,31 @@ This appendix provides a complete alphabetical reference of all operators in the
**See Also**: roll, depth
**Section**: 4.1 (Stack Operations)
#### rand
**Operator Type**: Randomness
**Signature**: `(-- f64)`
**Description**: Generate random f64 in range [0.0, 1.0).
**Example**: `rand // => 0.7234...`
**See Also**: seed
**Section**: 4.6 (Randomness)
#### reduce
**Operator Type**: Array Combinator
**Signature**: `(ArrayOf<T> T TokenString -- T)`
**Description**: Fold array with accumulator function.
**Example**: `[1 2 3 4] 0 { + } reduce // => 10`
**See Also**: map, filter, each
**See Also**: map, filter, foldl
**Section**: 7.4 (Arrays)
#### replace
**Operator Type**: String
**Signature**: `(String String String -- String)`
**Trait**: String
**Description**: Replace all occurrences of substring with replacement.
**Example**: `"hello world" "world" "Stack" replace // => "hello Stack"`
**See Also**: split, concat
**Section**: 11.5 (String Operations)
#### reverse
**Operator Type**: Array
**Signature**: `(ArrayOf<T> -- ArrayOf<T>)`
@ -444,6 +626,23 @@ This appendix provides a complete alphabetical reference of all operators in the
**See Also**: swap, roll
**Section**: 4.1 (Stack Operations)
#### round
**Operator Type**: Mathematical
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Round number to nearest integer.
**Example**: `3.7 round // => 4.0`
**See Also**: floor, ceil
**Section**: 4.2 (Arithmetic Operators)
#### seed
**Operator Type**: Randomness
**Signature**: `(u64 --)`
**Description**: Seed the random number generator with specific value.
**Example**: `12345 seed`
**See Also**: rand
**Section**: 4.6 (Randomness)
#### set
**Operator Type**: Struct Access
**Signature**: `(Value Identifier -- Struct)`
@ -470,6 +669,15 @@ This appendix provides a complete alphabetical reference of all operators in the
**See Also**: shl, bitand, bitor
**Section**: 4.5 (Bitwise Operators)
#### sin
**Operator Type**: Mathematical
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Calculate sine of angle in radians.
**Example**: `0.0 sin // => 0.0`
**See Also**: cos, tan, asin
**Section**: 4.2 (Arithmetic Operators)
#### slice
**Operator Type**: Container
**Signature**: `(Sliceable Size Size -- Sliceable)`
@ -479,6 +687,33 @@ This appendix provides a complete alphabetical reference of all operators in the
**See Also**: at, length
**Section**: 7.4 (Arrays)
#### split
**Operator Type**: String
**Signature**: `(String String -- ArrayOf<String>)`
**Trait**: String
**Description**: Split string by delimiter.
**Example**: `"a,b,c" "," split // => ["a" "b" "c"]`
**See Also**: join, substr
**Section**: 11.5 (String Operations)
#### sqrt
**Operator Type**: Mathematical
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Calculate square root.
**Example**: `16 sqrt // => 4.0`
**See Also**: ^
**Section**: 4.2 (Arithmetic Operators)
#### starts_with
**Operator Type**: String
**Signature**: `(String String -- bool)`
**Trait**: String
**Description**: Check if string starts with given prefix.
**Example**: `"hello" "hel" starts_with // => true`
**See Also**: ends_with, find
**Section**: 11.5 (String Operations)
#### struct
**Operator Type**: Definition
**Signature**: `(TypeTuple TokenString Identifier --)`
@ -495,7 +730,15 @@ This appendix provides a complete alphabetical reference of all operators in the
**Description**: Extract substring from start to end index.
**Example**: `"hello" 1 3 substr // => "el"`
**See Also**: slice, split
**Section**: 11.3 (String Operations)
**Section**: 11.5 (String Operations)
#### sum
**Operator Type**: Array
**Signature**: `(ArrayOf<Number> -- Number)`
**Description**: Sum all numeric elements in array.
**Example**: `[1 2 3 4 5] sum // => 15`
**See Also**: mean, reduce
**Section**: 7.4 (Arrays)
#### swap
**Operator Type**: Stack Manipulation
@ -506,6 +749,15 @@ This appendix provides a complete alphabetical reference of all operators in the
**See Also**: dup, rot
**Section**: 4.1 (Stack Operations)
#### tan
**Operator Type**: Mathematical
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Calculate tangent of angle in radians.
**Example**: `0.0 tan // => 0.0`
**See Also**: sin, cos, atan
**Section**: 4.2 (Arithmetic Operators)
#### trait
**Operator Type**: Definition
**Signature**: `(TokenString Identifier --)`
@ -523,6 +775,23 @@ This appendix provides a complete alphabetical reference of all operators in the
**See Also**: reverse
**Section**: 7.4 (Arrays)
#### trim
**Operator Type**: String
**Signature**: `(String -- String)`
**Trait**: String
**Description**: Remove leading and trailing whitespace.
**Example**: `" hello " trim // => "hello"`
**See Also**: split, replace
**Section**: 11.5 (String Operations)
#### type_of
**Operator Type**: Reflection
**Signature**: `(Self -- Identifier)`
**Description**: Return the type of a value as an identifier literal.
**Example**: `42 type_of // => ::i64`
**See Also**: implements, assert
**Section**: 11.4 (Reflection)
#### union
**Operator Type**: Definition
**Signature**: `(TypeTuple TokenString Identifier --)`
@ -548,4 +817,12 @@ This appendix provides a complete alphabetical reference of all operators in the
**See Also**: slice
**Section**: 7.4 (Arrays)
#### zip
**Operator Type**: Array
**Signature**: `(ArrayOf<T> ArrayOf<U> -- ArrayOf<Pair<T U>>)`
**Description**: Combine two arrays element-wise into pairs.
**Example**: `[1 2 3] [4 5 6] zip // => [[1 4] [2 5] [3 6]]`
**See Also**: enumerate, map
**Section**: 7.4 (Arrays)
---

View File

@ -23,6 +23,7 @@ This appendix contains all built-in trait definitions with complete documentatio
- Iterable<T>
- Logarithmic
- Logical
- Math
- Multiplyable
- Number
- Orderable
@ -62,7 +63,7 @@ This appendix contains all built-in trait definitions with complete documentatio
**Standard Implementations**: All numeric types (i8, i16, i32, i64, u8, u16, u32, u64, f32, f64)
**Related Traits**: Multiplyable, Number
**Related Traits**: Multiplyable, Number, Math
**See Also**: Section 4.2 (Arithmetic Operators)
@ -211,7 +212,7 @@ This appendix contains all built-in trait definitions with complete documentatio
**Related Traits**: Stringifiable, Parseable, Size
**See Also**: Section 11.3 (Type Conversion)
**See Also**: Section 11.5 (Type Conversion)
### Equatable
@ -265,7 +266,7 @@ This appendix contains all built-in trait definitions with complete documentatio
**Standard Implementations**: Numeric types
**Related Traits**: Addable, Multiplyable, Number
**Related Traits**: Addable, Multiplyable, Number, Math
**See Also**: Section 4.2 (Arithmetic Operators)
@ -382,7 +383,7 @@ This appendix contains all built-in trait definitions with complete documentatio
**Standard Implementations**: Floating point types
**Related Traits**: Exponentiable, Number
**Related Traits**: Exponentiable, Number, Math
**See Also**: Section 4.2 (Arithmetic Operators)
@ -429,6 +430,109 @@ This appendix contains all built-in trait definitions with complete documentatio
**See Also**: Section 4.4 (Logical Operators)
### Math
**Generic Parameters**: None
**Inherits**: None
**Definition**:
```
{
(Self -- Self) sqrt:
(Self -- Self) abs:
(Self -- Self) sin:
(Self -- Self) cos:
(Self -- Self) tan:
(Self -- Self) asin:
(Self -- Self) acos:
(Self -- Self) atan:
(Self Self -- Self) atan2:
(Self -- Self) floor:
(Self -- Self) ceil:
(Self -- Self) round:
(Self Self -- Self) min:
(Self Self -- Self) max:
} ::Math trait
```
**Methods**:
#### sqrt:
**Signature**: `(Self -- Self)`
**Description**: Calculate square root.
**Example**: `16 sqrt // => 4.0`
#### abs:
**Signature**: `(Self -- Self)`
**Description**: Return absolute value.
**Example**: `-42 abs // => 42`
#### sin:
**Signature**: `(Self -- Self)`
**Description**: Calculate sine (radians).
**Example**: `0.0 sin // => 0.0`
#### cos:
**Signature**: `(Self -- Self)`
**Description**: Calculate cosine (radians).
**Example**: `0.0 cos // => 1.0`
#### tan:
**Signature**: `(Self -- Self)`
**Description**: Calculate tangent (radians).
**Example**: `0.0 tan // => 0.0`
#### asin:
**Signature**: `(Self -- Self)`
**Description**: Calculate arc sine (radians).
**Example**: `1.0 asin // => ~1.5708`
#### acos:
**Signature**: `(Self -- Self)`
**Description**: Calculate arc cosine (radians).
**Example**: `1.0 acos // => 0.0`
#### atan:
**Signature**: `(Self -- Self)`
**Description**: Calculate arc tangent (radians).
**Example**: `1.0 atan // => ~0.7854`
#### atan2:
**Signature**: `(Self Self -- Self)`
**Description**: Two-argument arc tangent.
**Example**: `1.0 1.0 atan2 // => ~0.7854`
#### floor:
**Signature**: `(Self -- Self)`
**Description**: Round down to nearest integer.
**Example**: `3.14 floor // => 3.0`
#### ceil:
**Signature**: `(Self -- Self)`
**Description**: Round up to nearest integer.
**Example**: `3.14 ceil // => 4.0`
#### round:
**Signature**: `(Self -- Self)`
**Description**: Round to nearest integer.
**Example**: `3.7 round // => 4.0`
#### min:
**Signature**: `(Self Self -- Self)`
**Description**: Return minimum of two values.
**Example**: `3 5 min // => 3`
#### max:
**Signature**: `(Self Self -- Self)`
**Description**: Return maximum of two values.
**Example**: `3 5 max // => 5`
**Standard Implementations**: Numeric types (especially floating point)
**Related Traits**: Number, Addable, Multiplyable, Exponentiable, Logarithmic
**See Also**: Section 4.2 (Arithmetic Operators), Section 4.6 (Randomness)
### Multiplyable
**Generic Parameters**: None
@ -462,7 +566,7 @@ This appendix contains all built-in trait definitions with complete documentatio
**Standard Implementations**: All numeric types
**Related Traits**: Addable, Exponentiable, Number
**Related Traits**: Addable, Exponentiable, Number, Math
**See Also**: Section 4.2 (Arithmetic Operators)
@ -481,7 +585,7 @@ This appendix contains all built-in trait definitions with complete documentatio
**Standard Implementations**: All numeric types (i8, i16, i32, i64, u8, u16, u32, u64, f32, f64)
**Related Traits**: Addable, Multiplyable, Exponentiable, Comparable, Logarithmic
**Related Traits**: Addable, Multiplyable, Exponentiable, Comparable, Logarithmic, Math
**See Also**: Section 4.2 (Arithmetic Operators)
@ -581,11 +685,11 @@ This appendix contains all built-in trait definitions with complete documentatio
### Size
**Generic Parameters**: None
**Inherits**: Addable, Comparable, Convertible<i64>
**Inherits**: Addable, Comparable, Convertible
**Definition**:
```
[ ::Addable ::Comparable ::Convertible<i64> ] ::Size inher
[ ::Addable ::Comparable ::Convertible ] ::Size inher
{ } ::Size trait
```
@ -725,6 +829,11 @@ This appendix contains all built-in trait definitions with complete documentatio
{
(Self Size Size -- Self) substr:
(Self Self -- ArrayOf<Self>) split:
(Self Self String -- Self) replace:
(Self -- Self) trim:
(Self Self -- Option<Size>) find:
(Self Self -- bool) starts_with:
(Self Self -- bool) ends_with:
} ::String trait
```
@ -740,11 +849,36 @@ This appendix contains all built-in trait definitions with complete documentatio
**Description**: Split string by delimiter.
**Example**: `"a,b,c" "," split // => ["a" "b" "c"]`
#### replace:
**Signature**: `(Self Self String -- Self)`
**Description**: Replace all occurrences of substring.
**Example**: `"hello world" "world" "Stack" replace // => "hello Stack"`
#### trim:
**Signature**: `(Self -- Self)`
**Description**: Remove leading and trailing whitespace.
**Example**: `" hello " trim // => "hello"`
#### find:
**Signature**: `(Self Self -- Option<Size>)`
**Description**: Find position of substring.
**Example**: `"hello world" "world" find // => Option::Some(6)`
#### starts_with:
**Signature**: `(Self Self -- bool)`
**Description**: Check if string starts with prefix.
**Example**: `"hello" "hel" starts_with // => true`
#### ends_with:
**Signature**: `(Self Self -- bool)`
**Description**: Check if string ends with suffix.
**Example**: `"hello" "lo" ends_with // => true`
**Standard Implementations**: String type
**Related Traits**: Concatenable, Sized, Sliceable
**See Also**: Section 11.3 (String Operations)
**See Also**: Section 11.5 (String Operations)
### Stringifiable
@ -769,6 +903,6 @@ This appendix contains all built-in trait definitions with complete documentatio
**Related Traits**: Parseable, Convertible
**See Also**: Section 11.3 (Type Conversion)
**See Also**: Section 11.5 (Type Conversion)
---

View File

@ -0,0 +1,312 @@
---
Title: H Complete Type Reference
Prev: Examples and Tutorials
Next:
---
## Appendix H: Complete Type Reference
This appendix provides detailed information about all types in the language, organized alphabetically.
### Primitive Types
#### bool
**Description**: Boolean value representing true or false.
**Size**: 1 byte
**Values**: `true`, `false`
**Default**: `false`
**Traits Implemented**: Stackable, Equatable, Logical, Stringifiable
**Conversions**: to_str
**Example**:
```
true
false
5 3 > // => true
```
#### char
**Description**: Single UTF-8 character.
**Size**: 4 bytes (Unicode code point)
**Values**: Any valid Unicode character
**Literals**: `'A'`, `'\n'`, `'\u{1F600}'`
**Traits Implemented**: Stackable, Equatable, Orderable, Comparable, Stringifiable
**Conversions**: to_str
**Example**:
```
'A'
'😀'
'\n'
```
#### f32
**Description**: 32-bit floating point number (IEEE 754 single precision).
**Size**: 4 bytes
**Range**: ±1.18e-38 to ±3.40e+38
**Precision**: ~7 decimal digits
**Default**: `0.0`
**Traits Implemented**: Stackable, Addable, Multiplyable, Exponentiable, Logarithmic, Math, Orderable, Equatable, Comparable, Number, Convertible, Stringifiable, Parseable
**Conversions**: to_i8, to_i16, to_i32, to_i64, to_u8, to_u16, to_u32, to_u64, to_f64, to_str
**Overflow Behavior**: IEEE 754 (infinity/NaN)
**Example**:
```
3.14:f32
1.0:f32 2.0:f32 +
```
#### f64
**Description**: 64-bit floating point number (IEEE 754 double precision).
**Size**: 8 bytes
**Range**: ±2.23e-308 to ±1.80e+308
**Precision**: ~15 decimal digits
**Default**: `0.0` (default float type)
**Traits Implemented**: Stackable, Addable, Multiplyable, Exponentiable, Logarithmic, Math, Orderable, Equatable, Comparable, Number, Convertible, Stringifiable, Parseable
**Conversions**: to_i8, to_i16, to_i32, to_i64, to_u8, to_u16, to_u32, to_u64, to_f32, to_str
**Overflow Behavior**: IEEE 754 (infinity/NaN)
**Example**:
```
3.14
1.0 2.0 +
```
#### i8
**Description**: 8-bit signed integer.
**Size**: 1 byte
**Range**: -128 to 127
**Default**: `0`
**Traits Implemented**: Stackable, Addable, Multiplyable, Exponentiable, Logarithmic, Math, Orderable, Equatable, Comparable, Bitwise, Number, Size, Convertible, Stringifiable, Parseable
**Conversions**: to_i16, to_i32, to_i64, to_u8, to_u16, to_u32, to_u64, to_f32, to_f64, to_str
**Overflow Behavior**: Wrapping
**Example**:
```
42:i8
127:i8 1:i8 + // => -128 (wraps)
```
#### i16
**Description**: 16-bit signed integer.
**Size**: 2 bytes
**Range**: -32,768 to 32,767
**Default**: `0`
**Traits Implemented**: Stackable, Addable, Multiplyable, Exponentiable, Logarithmic, Math, Orderable, Equatable, Comparable, Bitwise, Number, Size, Convertible, Stringifiable, Parseable
**Conversions**: to_i8, to_i32, to_i64, to_u8, to_u16, to_u32, to_u64, to_f32, to_f64, to_str
**Overflow Behavior**: Wrapping
**Example**:
```
1000:i16
```
#### i32
**Description**: 32-bit signed integer.
**Size**: 4 bytes
**Range**: -2,147,483,648 to 2,147,483,647
**Default**: `0`
**Traits Implemented**: Stackable, Addable, Multiplyable, Exponentiable, Logarithmic, Math, Orderable, Equatable, Comparable, Bitwise, Number, Size, Convertible, Stringifiable, Parseable
**Conversions**: to_i8, to_i16, to_i64, to_u8, to_u16, to_u32, to_u64, to_f32, to_f64, to_str
**Overflow Behavior**: Wrapping
**Example**:
```
1000000:i32
```
#### i64
**Description**: 64-bit signed integer.
**Size**: 8 bytes
**Range**: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
**Default**: `0` (default integer type)
**Traits Implemented**: Stackable, Addable, Multiplyable, Exponentiable, Logarithmic, Math, Orderable, Equatable, Comparable, Bitwise, Number, Size, Convertible, Stringifiable, Parseable
**Conversions**: to_i8, to_i16, to_i32, to_u8, to_u16, to_u32, to_u64, to_f32, to_f64, to_str
**Overflow Behavior**: Wrapping
**Example**:
```
42
1000000000
```
#### u8
**Description**: 8-bit unsigned integer.
**Size**: 1 byte
**Range**: 0 to 255
**Default**: `0`
**Traits Implemented**: Stackable, Addable, Multiplyable, Exponentiable, Logarithmic, Math, Orderable, Equatable, Comparable, Bitwise, Number, Size, Convertible, Stringifiable, Parseable
**Conversions**: to_i8, to_i16, to_i32, to_i64, to_u16, to_u32, to_u64, to_f32, to_f64, to_str
**Overflow Behavior**: Wrapping
**Example**:
```
255:u8
```
#### u16
**Description**: 16-bit unsigned integer.
**Size**: 2 bytes
**Range**: 0 to 65,535
**Default**: `0`
**Traits Implemented**: Stackable, Addable, Multiplyable, Exponentiable, Logarithmic, Math, Orderable, Equatable, Comparable, Bitwise, Number, Size, Convertible, Stringifiable, Parseable
**Conversions**: to_i8, to_i16, to_i32, to_i64, to_u8, to_u32, to_u64, to_f32, to_f64, to_str
**Overflow Behavior**: Wrapping
**Example**:
```
65535:u16
```
#### u32
**Description**: 32-bit unsigned integer.
**Size**: 4 bytes
**Range**: 0 to 4,294,967,295
**Default**: `0`
**Traits Implemented**: Stackable, Addable, Multiplyable, Exponentiable, Logarithmic, Math, Orderable, Equatable, Comparable, Bitwise, Number, Size, Convertible, Stringifiable, Parseable
**Conversions**: to_i8, to_i16, to_i32, to_i64, to_u8, to_u16, to_u64, to_f32, to_f64, to_str
**Overflow Behavior**: Wrapping
**Example**:
```
4000000000:u32
```
#### u64
**Description**: 64-bit unsigned integer.
**Size**: 8 bytes
**Range**: 0 to 18,446,744,073,709,551,615
**Default**: `0`
**Traits Implemented**: Stackable, Addable, Multiplyable, Exponentiable, Logarithmic, Math, Orderable, Equatable, Comparable, Bitwise, Number, Size, Convertible, Stringifiable, Parseable
**Conversions**: to_i8, to_i16, to_i32, to_i64, to_u8, to_u16, to_u32, to_f32, to_f64, to_str
**Overflow Behavior**: Wrapping
**Example**:
```
18000000000000000000:u64
```
### Composite Types
#### Array<T>
**Description**: Homogeneous collection of values of type T.
**Size**: Variable (depends on length and element type)
**Syntax**: `[elements]` or `[elements :type]`
**Traits Implemented**: Stackable, ArrayOf<T>, Sized, Selectable<T>, Sliceable, Iterable<T>, Concatenable, Equatable, Stringifiable
**Operations**: at, slice, length, map, filter, reduce, each, foldl, foldr, concat, reverse, transpose, window, zip, enumerate, sum, mean
**Example**:
```
[1 2 3 4 5]
[1.0 2.0 3.0 :f32]
[[1 2] [3 4]]
```
#### String
**Description**: UTF-8 encoded string of characters.
**Size**: Variable
**Syntax**: `"text"`
**Traits Implemented**: Stackable, String, Sized, Sliceable, Concatenable, Iterable<char>, Orderable, Equatable, Comparable, Stringifiable, Parseable
**Operations**: length, concat, substr, split, join, replace, trim, find, starts_with, ends_with, format
**Example**:
```
"hello world"
"hello" " world" concat
```
#### Struct
**Description**: User-defined composite type with named fields.
**Size**: Sum of field sizes
**Syntax**: `(field_types --) { field_names: } ::Name<T>? struct`
**Traits Implemented**: Stackable, Equatable (if fields are), Stringifiable (if fields are)
**Operations**: get, set (field access)
**Example**:
```
(Number Number --) { x: y: } ::Point struct
3.0 4.0 Point
point ::x get
```
#### Union
**Description**: Tagged union with multiple possible variant types.
**Size**: Size of largest variant plus tag
**Syntax**: `(variant_types --) { variants } ::Name<T>? union`
**Traits Implemented**: Stackable, Equatable (if variants are), Stringifiable (if variants are)
**Operations**: Pattern matching with match
**Example**:
```
(T --) { Some(T) None } ::Option<T> union
42 Option::Some
Option::None
```
#### Enum
**Description**: Fixed set of named integer values.
**Size**: Size of underlying integer type (typically i64)
**Syntax**: `{ variants } ::Name enum`
**Traits Implemented**: Stackable, Equatable, Orderable, Comparable, Convertible, Stringifiable
**Operations**: Pattern matching, comparison
**Example**:
```
{ Pending: Active: Complete: } ::Status enum
Status::Active
```
### Standard Generic Types
#### Option<T>
**Description**: Represents an optional value - either Some(T) or None.
**Definition**: `(T --) { Some(T) None } ::Option<T> union`
**Use Cases**: Nullable values, error handling, optional parameters
**Traits Implemented**: Stackable, Logical (None is falsy), Equatable, Stringifiable
**Example**:
```
42 Option::Some
Option::None
opt {
Some(x) => { x print }
None => { "Nothing" print }
} match
```
#### Result<T E>
**Description**: Represents success (Ok) or failure (Err) with values.
**Definition**: `(T E --) { Ok(T) Err(E) } ::Result<T E> union`
**Use Cases**: Error handling with details, operations that can fail
**Traits Implemented**: Stackable, Logical (Err is falsy), Equatable, Stringifiable
**Example**:
```
"success" Result::Ok
"error message" Result::Err
result {
Ok(val) => { val process }
Err(e) => { e "Error: " swap concat print }
} match
```
### Special Types
#### Identifier
**Description**: Represents an identifier literal (name pushed as value).
**Syntax**: `::name`
**Traits Implemented**: Identifier, Stackable, Equatable, Stringifiable
**Use Cases**: Struct/trait definitions, field access, meta-programming
**Example**:
```
::Point
::Addable
point ::x get
```
#### TokenString
**Description**: Unparsed code block enclosed in braces.
**Syntax**: `{ code }`
**Traits Implemented**: Implementable
**Use Cases**: Function bodies, control flow blocks, lambda expressions
**Example**:
```
{ dup * }
{ 2 3 + } eval
```
#### Callable
**Description**: Executable code block created by lambda operator.
**Created By**: `lambda` operator
**Traits Implemented**: Stackable
**Use Cases**: First-class functions, higher-order operations
**Example**:
```
{ dup * } lambda ::square swap
5 square eval // => 25
```
---

View File

@ -109,6 +109,13 @@ Arrays are homogeneous collections of values.
[1 2 3 4 5] // array of i64
[1.0 2.0 3.0] // array of f64
[[1 2] [3 4]] // 2D array
// Typed arrays
[1 2 3 :i16] // array of i16
[[1.0 2.0] [3.0 4.0] :f32] // 2D array of f32
// Arrays of structs (when Point is defined)
[{1 2} {3 4} :Point] // array of Point structs
```
**Basic Operations**:
@ -134,6 +141,27 @@ These operations take TokenString arguments containing function bodies:
// Each - apply to each element (side effects)
[[1 2] [3 4]] { sum print } each
// Foldl - left fold with accumulator
[1 2 3 4] 0 { + } foldl // => 10 (same as reduce)
// Foldr - right fold with accumulator
[1 2 3 4] 0 { + } foldr // => 10 (for commutative ops)
```
**Array Utilities**:
```
// Zip - combine two arrays element-wise
[1 2 3] [4 5 6] zip // => [[1 4] [2 5] [3 6]]
// Enumerate - add indices to elements
["a" "b" "c"] enumerate // => [[0 "a"] [1 "b"] [2 "c"]]
// Sum - sum all numeric elements
[1 2 3 4 5] sum // => 15
// Mean - calculate average
[1 2 3 4 5] mean // => 3.0
```
**Array Arithmetic**:

View File

@ -1,7 +1,7 @@
---
Title: G Examples & Tutorials
Prev: Memory Management
Next:
Next:Complete Type Reference
---
## Appendix G: Examples & Tutorials
@ -255,28 +255,34 @@ Option::None // Option<T>::None
3 4 weird_math // => 28
```
#### G.4.3 Logarithm Usage
#### G.4.3 Mathematical Functions Usage
```
// Calculate log base 10
100 log print // => 2.0
1000 log print // => 3.0
// Square root
16 sqrt print // => 4.0
2.0 sqrt print // => ~1.414
// Calculate natural logarithm
2.718 ln print // => ~1.0
7.389 ln print // => ~2.0
// Trigonometric functions
0.0 sin print // => 0.0
0.0 cos print // => 1.0
1.0 atan print // => ~0.7854
// Calculate with custom base
8 2 logb print // => 3.0 (2³ = 8)
27 3 logb print // => 3.0 (3³ = 27)
// Rounding functions
3.14 floor print // => 3.0
3.14 ceil print // => 4.0
3.7 round print // => 4.0
// Combine with other operations
10 3 ^ log print // => 3.0 (log of 1000)
// Min/max
3 5 min print // => 3
3 5 max print // => 5
// Logarithm laws verification
// log(a*b) = log(a) + log(b)
10 100 * log // log(1000) = 3.0
10 log 100 log + // log(10) + log(100) = 1.0 + 2.0 = 3.0
// Absolute value
-42 abs print // => 42
// Random numbers
rand print // => 0.7234... (random)
12345 seed // Seed for deterministic results
rand print // => 0.4321... (deterministic after seed)
```
#### G.4.4 Factorial
@ -395,38 +401,137 @@ print // => 9
swap length // Length: 5
/ // Average: 30
print
// Or use built-in functions
[10 20 30 40 50] mean print // => 30.0
[1 2 3 4 5] sum print // => 15
// Zip and enumerate
[1 2 3] [4 5 6] zip print // => [[1 4] [2 5] [3 6]]
["a" "b" "c"] enumerate print // => [[0 "a"] [1 "b"] [2 "c"]]
```
#### G.4.8 Identifier Literals in Practice
#### G.4.8 String Operations
```
// Identifier literals are used in struct/trait definitions
// and field access
// String manipulation
"hello" " world" concat print // => "hello world"
"hello" 1 3 substr print // => "el"
"a,b,c" "," split print // => ["a" "b" "c"]
["a" "b" "c"] "," join print // => "a,b,c"
// Defining a struct requires ::StructName identifier literal
(Number Number --) { x: y: } ::Point struct
// String searching
"hello world" "world" find // => Option::Some(6)
"hello" "hel" starts_with print // => true
"hello" "lo" ends_with print // => true
// Field access requires ::field_name identifier literal
3.0 4.0 Point
dup ::x get print // Prints: 3.0
::y get print // Prints: 4.0
// String modification
"hello world" "world" "Stack" replace print // => "hello Stack"
" hello " trim print // => "hello"
// Dynamic field access (advanced)
"x" :: // Convert string to identifier
// (This would require string-to-identifier conversion, which
// may be a future feature)
// String formatting
"x=%d, y=%d" [5 10] format print // => "x=5, y=10"
"Name: %s, Age: %d" ["Alice" 30] format print // => "Name: Alice, Age: 30"
```
// Traits use identifier literals
{ (Self -- ) draw: } ::Drawable trait
#### G.4.9 Reflection Examples
// Implementations use identifier literals
::Drawable { ... } ::Rectangle impl
```
// Type checking
(Self -- ) {
dup type_of to_str "Type: " swap concat print
// Identifier literals are NOT used inside trait/impl bodies
// (those are method names)
{
(Self -- ) { "Drawing" print } draw: // "draw:" is method name
} ::Drawable trait
dup ::Addable implements
{ "Supports addition" print }
{ "Does not support addition" print }
if
dup ::Stringifiable implements
{ to_str print }
{ drop "Cannot convert to string" print }
if
} ::debug_print fn
42 debug_print
// Output:
// Type: i64
// Supports addition
// 42
// Dynamic dispatch based on traits
(Self -- ) {
dup ::Drawable implements
{ draw }
{ drop "Not drawable" print }
if
} ::try_draw fn
// Generic type information
(Self -- String) {
type_of to_str
} ::type_name fn
42 type_name print // => "i64"
"hello" type_name print // => "String"
[1 2 3] type_name print // => "Array<i64>"
```
#### G.4.10 Testing Examples
```
// Simple assertions
{ 2 3 + } { 5 == } assert
{ 5 square } { 25 == } assert
// Testing a function thoroughly
(Number -- Number) { dup * } ::square fn
// Test with multiple values
{ 0 square } { 0 == } assert
{ 1 square } { 1 == } assert
{ 5 square } { 25 == } assert
{ -3 square } { 9 == } assert
// Testing edge cases
(Number Number -- Number) { / } ::divide fn
// This will pass
{ 10 2 divide } { 5 == } assert
// This will halt (division by zero should be handled)
// { 10 0 divide } { ... } assert // Don't do this!
// Testing string operations
{ "hello" " world" concat } { "hello world" == } assert
{ "hello" length } { 5 == } assert
{ "hello" 1 3 substr } { "el" == } assert
```
#### G.4.11 Constants Example
```
// Define mathematical constants
3.1415926535 ::pi const
2.7182818284 ::e const
1.6180339887 ::phi const
// Use in calculations
(Number -- Number) {
dup * pi * // Area = r² * π
} ::circle_area fn
5 circle_area print // => ~78.54
// Physical constants
299792458 ::speed_of_light const // m/s
9.81 ::gravity const // m/s²
// Use in physics calculations
(Number -- Number) {
dup * 2 / gravity * // E = mgh where h = v²/2g
} ::kinetic_to_potential fn
10 kinetic_to_potential print // => ~490.5
```
---

View File

@ -10,9 +10,11 @@ This appendix provides a concise grammar reference. For complete specifications
### D.1 Lexical Grammar
**Comments**:
**Comments and Directives**:
```
line_comment ::= "//" <any characters until newline>
directive ::= "#" <implementation-specific>
shebang ::= "#!/" <path to interpreter>
```
**Identifiers**:
@ -23,15 +25,21 @@ identifier_literal ::= "::" identifier
**Integer Literals**:
```
integer ::= decimal | hexadecimal | binary
decimal ::= [0-9]+ (":" type_name)?
hexadecimal ::= "0x" [0-9a-fA-F]+
binary ::= "0b" [01]+
integer ::= decimal | hexadecimal | binary | octal
decimal ::= [0-9](_?[0-9])* (":" type_name)?
hexadecimal ::= "0x" [0-9a-fA-F](_?[0-9a-fA-F])*
binary ::= "0b" [01](_?[01])*
octal ::= "0o" [0-7](_?[0-7])*
```
**Floating Point Literals**:
```
float ::= [0-9]+ "." [0-9]+ (":" type_name)?
float ::= [0-9](_?[0-9])* "." [0-9](_?[0-9])* (":" type_name)?
```
**Character Literals**:
```
char ::= "'" (character | escape_sequence) "'"
```
**String Literals**:
@ -49,7 +57,13 @@ boolean ::= "true" | "false"
**Array Literals**:
```
array ::= "[" (expression)* "]"
array ::= "[" (expression)* (":"|type_annotation)? "]"
typed_array ::= "[" (expression)* ":" type_name "]"
```
**Constants**:
```
constant ::= literal "::" identifier "const"
```
**Token Strings**:
@ -67,7 +81,7 @@ expression ::= literal
| control_flow
| definition
literal ::= integer | float | string | boolean | array
literal ::= integer | float | string | boolean | char | array
operator ::= built_in_operator | user_defined_operator
@ -97,6 +111,7 @@ type_param ::= identifier (":" trait_constraint)?
Language constructs (fn, struct, trait, impl, enum, union, inher) are defined by operators in the `::Implementable` trait. These operators parse TokenStrings to create language-level definitions.
**High-Level Patterns**:
- Constants: `value ::name const`
- Functions: `(inputs -- outputs) { body } ::name fn`
- Structs: `(field_types --) { field_names: } ::name<type_params>? struct`
- Unions: `(variant_types --) { Variant(T) ... } ::name<type_params>? union`

View File

@ -28,10 +28,16 @@ Next: Overview
- E. [Module System](./module_system.html) (Future)
- F. [Memory Management](./memory_management.html) (Future)
- G. [Examples and Tutorials](./examples_and_tutorials.html)
- H. [Complete Type Reference](./complete_type_reference.html)
**Addendum**:
---
**Other**:
- [Missing Features](./missing_features.html)
- [SE 3250 Assignment Details](./se_3250_assignment_details.html)
- [Changed](./changes.html)
- [Full Specification](./stack_lang_spec.html)
- [C Terminal I/O Reference](./io_ref.html)
- [Assignment Slide Show](./slides/SLIDES.html)
---

346
docs/io_ref.md Normal file
View File

@ -0,0 +1,346 @@
---
Title: C Terminal I/O Reference
Prev:
Next:
---
*This was generated by ChatGPT as a reference to assist in development.*
# C99 Terminal I/O Reference
A concise, practical reference for terminal (stdin/stdout/stderr) and file I/O in **C99**. Includes common functions, behavior notes, examples, and safe-usage tips.
---
## Table of contents
1. [Overview](#1-overview)
2. [Streams and `FILE *`](#2-streams-and-file)
3. [Opening and closing streams](#3-opening-and-closing-streams)
4. [Formatted I/O (`printf`/`scanf` families)](#4-formatted-io-printfscanf-families)
5. [Format specifiers and `inttypes.h`](#6-character-io)
6. [Character I/O](#6-character-io)
7. [Line and block I/O (`fgets`, `fputs`, `fread`, `fwrite`)](#7-line-and-block-io)
8. [Buffering and `setvbuf` / `fflush`](#8-buffering-and-setvbuf-fflush)
9. [File positioning (`fseek`, `ftell`, `rewind`)](#9-file-positioning)
10. [Error handling (`feof`, `ferror`, `clearerr`, `perror`)](#10-error-handling)
11. [Temporary files](#11-temporary-files)
12. [Tips for safe and portable terminal I/O](#12-tips-for-safe-and-portable-terminal-io)
13. [Examples](#13-examples)
14. [POSIX terminal control (note)](#14-posix-terminal-control-note)
15. [Quick reference: common functions](#15-quick-reference-common-functions)
---
## 1. Overview
Standard C99 defines the `<stdio.h>` interface for input/output. Its oriented around *streams* (`FILE *`) and provides both formatted and unformatted operations. C99 also introduced `<inttypes.h>` (and `<stdint.h>`) for precise integer types and format macros.
The standard I/O streams preopened by the implementation are:
* `stdin` — standard input (usually the keyboard/pipe)
* `stdout` — standard output (usually the terminal/pipe)
* `stderr` — standard error (usually the terminal, unbuffered)
`stdout` is usually line-buffered when connected to a terminal and fully buffered when redirected to a file.
---
## 2. Streams and `FILE *`
`FILE` is an opaque type representing an I/O stream. Use pointers to `FILE` returned by `fopen`, or the standard `stdin`/`stdout`/`stderr`.
Common operations: read/write, reposition, flush, close, and check errors.
---
## 3. Opening and closing streams
```c
#include <stdio.h>
FILE *fopen(const char *pathname, const char *mode);
int fclose(FILE *stream);
```
`mode` examples:
* `"r"` — read (file must exist)
* `"w"` — write (truncate/create)
* `"a"` — append (create if needed)
* `"r+"` — read/update
* `"w+"` — read/update (truncate/create)
* Add `b` for binary: `"rb"`, `"wb"` (on POSIX `b` is ignored but required for portability to Windows)
Always check for `NULL` from `fopen` and nonzero return from `fclose`.
---
## 4. Formatted I/O (`printf`/`scanf` families)
**Output (formatted)**
```c
int printf(const char *format, ...);
int fprintf(FILE *stream, const char *format, ...);
int snprintf(char *str, size_t size, const char *format, ...);
int vprintf(const char *format, va_list ap);
```
Return value: number of characters written (excluding terminating `\0` for `snprintf`) or a negative value on error.
**Input (formatted)**
```c
int scanf(const char *format, ...);
int fscanf(FILE *stream, const char *format, ...);
int sscanf(const char *str, const char *format, ...);
```
`scanf`-style functions parse input according to `format`. They are error-prone for untrusted input — prefer `fgets` + `sscanf` or manual parsing.
**Important:** Always limit field widths for `%s` and others when using `scanf` to avoid buffer overflow: `%99s` for a 100-byte buffer.
---
## 5. Format specifiers and `inttypes.h`
Common specifiers:
* `%d``int`
* `%i``int` (auto-detects base)
* `%u``unsigned int`
* `%ld``long int`
* `%lld``long long int`
* `%zu``size_t`
* `%f``float` (promoted to `double` in `printf`/`scanf` variadic calls — use `%f` with `double` in `printf`; `scanf` expects pointer to `float` for `%f`)
* `%lf``double` for `scanf` (in `printf` `%f` and `%lf` are equivalent)
* `%Lf``long double`
* `%c``char` (or `int` in `printf`), for `scanf` expects `char *`
* `%s` — NUL-terminated string
* `%p` — pointer
* `%n` — write number of characters printed so far into `int *`
For fixed-width integer types introduced in C99, use `inttypes.h` macros
```c
#include <inttypes.h>
int32_t i32;
printf("%" PRId32 "\n", i32);
```
Common macros: `PRId32`, `PRIu64`, `PRIxPTR`, etc.
---
## 6. Character I/O
```c
int getchar(void);
int putchar(int ch);
int ungetc(int ch, FILE *stream);
int fgetc(FILE *stream);
int fputc(int ch, FILE *stream);
```
* `getchar()` is equivalent to `fgetc(stdin)`.
* Return values for `fgetc`/`getchar`: next character as an unsigned char cast to `int`, or `EOF` on end-of-file or error.
* `ungetc` pushes a character back onto the stream (one character is guaranteed).
---
## 7. Line and block I/O
**Line-based**
```c
char *fgets(char *s, int size, FILE *stream);
int fputs(const char *s, FILE *stream);
```
* `fgets` reads up to `size-1` characters or until newline; the resulting string includes the newline if present and is NUL-terminated. Returns `NULL` on EOF or error.
* Use `fgets` to safely read lines from `stdin` (avoid `gets`).
**Block-based (binary)**
```c
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
```
* Returns number of elements read/written; check against `nmemb` to detect short reads/writes.
---
## 8. Buffering and `setvbuf` / `fflush`
Buffering modes:
* Fully buffered — data collected until buffer fills (default for files).
* Line buffered — buffer flushed on newline (default for interactive `stdout`).
* Unbuffered — no buffering (default for `stderr`).
Control buffering:
```c
int setvbuf(FILE *stream, char *buf, int mode, size_t size);
int setbuf(FILE *stream, char *buf); // simpler wrapper
int fflush(FILE *stream); // flush output buffer
```
`mode` constants: `_IOFBF` (full), `_IOLBF` (line), `_IONBF` (none).
Call `fflush(stdout)` to ensure output is written (useful before `scanf` or when using `fork`).
---
## 9. File positioning
```c
int fseek(FILE *stream, long offset, int whence);
long ftell(FILE *stream);
void rewind(FILE *stream);
```
* `whence`: `SEEK_SET`, `SEEK_CUR`, `SEEK_END`.
* For binary files larger than `LONG_MAX`, POSIX defines `fseeko`/`ftello` with `off_t` (not in C99 standard).
---
## 10. Error handling
```c
int feof(FILE *stream);
int ferror(FILE *stream);
void clearerr(FILE *stream);
```
* `ferror` indicates if an error occurred on the stream.
* `perror(const char *s)` prints a human-readable error message based on `errno`.
Example pattern:
```c
if (ferror(fp)) {
perror("file read");
}
```
---
## 11. Temporary files
```c
FILE *tmpfile(void); // create and open a temporary binary file (removed on close)
char *tmpnam(char *s); // generate a filename
```
`tmpnam` is unsafe for race conditions; prefer `tmpfile` or platform-specific secure alternatives.
---
## 12. Tips for safe and portable terminal I/O
* Prefer `fgets` + `sscanf` (or manual parsing) over `scanf` to avoid buffer overflows and ambiguous input parsing.
* When printing into buffers, use `snprintf` to avoid overflows and to detect truncation (it returns the number of characters that would have been written).
* Validate `fread`/`fwrite` return values.
* Check `fopen` for `NULL` and call `perror`/inspect `errno` on failure.
* Use `fflush(stdout)` if mixing output with `fork()` or before expecting input on interactive programs.
* Use `setvbuf` if your program has special performance needs.
* For cross-platform portability, include `b` in mode strings for binary files (Windows requires it).
* Use `inttypes.h` macros for printing fixed-width integers.
---
## 13. Examples
### Read lines from stdin safely
```c
#include <stdio.h>
#include <string.h>
int main(void) {
char buf[256];
while (fgets(buf, sizeof buf, stdin)) {
// strip newline
size_t len = strlen(buf);
if (len && buf[len - 1] == '\n') buf[len - 1] = '\0';
printf("line: '%s'\n", buf);
}
return 0;
}
```
### Read integers robustly using `fgets` + `sscanf`
```c
#include <stdio.h>
int main(void) {
char line[128];
long value;
while (fgets(line, sizeof line, stdin)) {
if (sscanf(line, "%ld", &value) == 1) {
printf("got: %ld\n", value);
} else {
fprintf(stderr, "invalid input: %s", line);
}
}
}
```
### Write/read binary struct to file
```c
#include <stdio.h>
#include <stdlib.h>
struct pair { int a; double b; };
int main(void) {
struct pair p = {42, 3.14159};
FILE *f = fopen("data.bin", "wb");
if (!f) { perror("fopen"); return 1; }
if (fwrite(&p, sizeof p, 1, f) != 1) { perror("fwrite"); }
fclose(f);
f = fopen("data.bin", "rb");
struct pair q;
if (!f) { perror("fopen"); return 1; }
if (fread(&q, sizeof q, 1, f) != 1) { perror("fread"); }
fclose(f);
printf("read: %d %f\n", q.a, q.b);
}
```
---
## 14. POSIX terminal control (note)
C99 does **not** standardize low-level terminal control (raw mode, disabling echo, key-by-key input). On POSIX systems you can use `<termios.h>` and `tcgetattr`/`tcsetattr`. On Windows you use console APIs (`GetConsoleMode` / `SetConsoleMode`). These are outside the C standard and require conditional compilation and platform-specific code.
Example POSIX-only header include:
```c
#ifdef __unix__
#include <termios.h>
#endif
```
---
## 15. Quick reference: common functions
* `fopen`, `fclose` — open/close file
* `fread`, `fwrite` — block I/O
* `fgets`, `fputs` — line I/O
* `printf`, `fprintf`, `snprintf` — formatted output
* `scanf`, `fscanf`, `sscanf` — formatted input
* `fgetc`, `fputc`, `getchar`, `putchar` — character I/O
* `fflush`, `setvbuf` — flushing and buffering
* `fseek`, `ftell`, `rewind` — positioning
* `feof`, `ferror`, `clearerr`, `perror` — error handling
* `tmpfile`, `tmpnam` — temporary files
[Back to Top](#c99-terminal-io-reference)

View File

@ -6,17 +6,30 @@ Next: Primitive Types
## 2. Lexical Structure
### 2.1 Comments
### 2.1 Comments and Directives
**Single-line Comments**:
```
// Single-line comment
```
### 2.2 Identifiers
**Compiler Directives**:
The language reserves the `#` character for implementation-specific compiler directives. The `#` character cannot appear in identifiers.
```
#!/usr/bin/env stack_lang
```
Directives are implementation-specific and not part of the core language specification. Implementations may support various directives for version requirements, optimization hints, or other configuration.
### 2.2 Identifiers and Constants
**Regular Identifiers**
- Start with letter or underscore: `[a-zA-Z_][a-zA-Z0-9_]*`
- Case-sensitive
- When encountered, identifiers are executed immediately
- Cannot contain `#`, whitespace, `{}`, `[]`, `()`, `.`, `'`, `"`, or `::`
**Identifier Literals**
- Prefix with `::` to push the identifier itself onto the stack instead of executing it
@ -24,6 +37,28 @@ Next: Primitive Types
- Example: `::Addable` pushes the identifier `Addable` onto the stack
- Example: `::Point` pushes the identifier `Point` onto the stack
**Constants**
Constants are compile-time values that are immutable and available throughout the scope where they are defined.
**Syntax**: `value ::name const`
**Examples**:
```
3.1415926535 ::pi const
9.81 ::gravity const
299792458 ::speed_of_light const
// Use constants like any other value
10 pi * 2 / // Calculate circumference / 2
```
**Properties**:
- Constants can be evaluated at compile time
- Constants are immutable - they cannot be reassigned
- Constants defined at module scope are accessible via `Module::CONST_NAME` (when modules are implemented)
- Constants can be any literal value or compile-time expression
> **Advanced Usage**: See [Section 11.2](./advanced_topics.html#112-identifier-literals) for complete identifier literal rules and context-dependent behavior.
### 2.3 Literals
@ -35,12 +70,27 @@ Next: Primitive Types
42:i32 // Annotate as i32
0xFF // hexadecimal
0b1010 // binary
0o755 // octal
1_000_000 // underscore separators (ignored)
```
**Overflow Behavior**: Integer arithmetic wraps on overflow. For example, adding 1 to 127, the maximum value of an `i8`, produces -128.
**Floating Point Literals**
```
3.14 // f64 (default)
3.14:f32 // Annotate as f32
1_000.5 // underscore separators allowed
```
**Overflow Behavior**: Floating point operations follow IEEE 754 semantics, producing infinity or NaN for overflow/undefined operations.
**Character Literals**
```
'A' // Single character
'\n' // Escape sequence
'\x41' // Hexadecimal (A)
'\u{1F600}' // Unicode (😀)
```
**String Literals**
@ -69,9 +119,16 @@ false
**Array Literals**
```
[1 2 3 4 5] // array of i32
[1 2 3 4 5] // array of i64
[1.0 2.0 3.0] // array of f64
[[1 2] [3 4]] // 2D array
// Typed arrays
[1 2 3 :i16] // array of i16
[[1.0 2.0] [3.0 4.0] :f32] // 2D array of f32
// Arrays of structs (when Point is defined)
[{1 2} {3 4} :Point] // array of Point structs
```
---

View File

@ -89,4 +89,64 @@ Cons: Less granular control, memory held until arena freed
This would provide stronger type safety but add complexity to the type checker.
**Testing Framework (Future)**:
**Current State**: Basic `assert` operator is available for inline testing.
**Future Design**: A comprehensive testing framework with dedicated operators.
**Proposed Operators**:
```
// Define a test
{ { 2 3 + } { 5 == } assert } "addition test" test
// Test for expected errors
{ 1 0 / } "division by zero test" test_error
// Test suites
{
{ 2 3 + 5 == } "addition" test
{ 5 2 - 3 == } "subtraction" test
} "arithmetic tests" test_suite
```
**Features**:
- Named tests for better reporting
- Expected error testing
- Test suites for organization
- Setup/teardown hooks
- Test discovery and running
**Documentation Comments (Future)**:
**Proposed Syntax**:
```
/// Calculates the square of a number.
/// Takes a number and returns its square.
(Number -- Number) { dup * } ::square fn
/// A point in 2D space.
/// Fields:
/// x: The x-coordinate
/// y: The y-coordinate
(T T --) { x: y: } ::Point<T> struct
```
**Features**:
- Extract documentation from source
- Generate HTML/markdown documentation
- Support for examples and tests in docs
- Cross-referencing between definitions
**Advanced Compiler Directives (Future)**:
Beyond the basic shebang, future versions may support:
```
#require "0.9.0" // Minimum language version
#optimize speed // Optimization hints
#allow unsafe // Enable unsafe operations
#deprecated "Use new_fn" // Deprecation warnings
```
---

View File

@ -6,12 +6,6 @@ Next:
## Missing Features
### AI Prompt
```
Can you apply these changes? Please do not add a new missing features appendix, apply the changes to the existing document. An added Appendix H Complete Type Reference. Please keep the links as they are to separate html files (another program with split and convert the markdown after you're done) but you can add appropriate links as well. List the changes you make as v0.8.2 (AI). Return the entire document. I would prefer it as a markdown artifact instead of directly in chat. Begin with an overview of the changes you are going to make, then after I approve, create the artifact with the improved version.
```
### Overview
This addendum describes the **features that should be added** to complete the Stack Language Specification.

View File

@ -53,6 +53,8 @@ This specification is organized to support both learning and reference:
**Section 11** covers advanced topics:
- Dynamic code evaluation
- Identifier literals
- Testing and assertions
- Reflection
- Standard library overview
**Appendices** provide complete references:
@ -63,6 +65,7 @@ This specification is organized to support both learning and reference:
- E: Module System (future)
- F: Memory Management (future)
- G: Examples & Tutorials
- H: Complete Type Reference
### Reading Guide
@ -72,6 +75,6 @@ This specification is organized to support both learning and reference:
**Implementers**: Read all sections, paying special attention to Sections 8-10 and Appendices B-D for complete specifications.
**Reference lookup**: Use Appendices A-C for quick reference to standard library functions, traits, and operators.
**Reference lookup**: Use Appendices A-C and H for quick reference to standard library functions, traits, operators, and types.
---

View File

@ -28,12 +28,13 @@ You can explicitly annotate literal types:
```
42:i32 // 32-bit integer
3.14:f32 // 32-bit float
'A' // character
```
**Pointer Types**
Raw pointers (`ptr`) are a future feature. See [Appendix F](./memory_management.html) for the planned pointer type system.
> **Related**: See Section 8 for the complete type system, including composite types and type inference.
> **Related**: See Section 8 for the complete type system, including composite types and type inference. See [Appendix H](./complete_type_reference.html) for detailed information about all types.
---

View File

@ -12,10 +12,10 @@ Next:
Language Code Name: YREA **SLS** (*Stack Language Specification*)
Language Specifications: [sls.purplecello.org](https://sls.purplecello.org)
Language Specification Repository: [git.purplecello.org](https://git.purplecello.org/KylerOlsen/LangsFinalPlaning)
Language Implementation Repository: [git.purplecello.org](https://git.purplecello.org/KylerOlsen/YREA-SLS)
Language Implementation Repository (Mirror on GitHub): [github.com](https://github.com/SnowSE/final-project-KylerOlsen)
Assignment Page: [snow.instructure.com](https://snow.instructure.com/courses/1154808/assignments/16233203)
Language Specification Repository (Private): [git.purplecello.org](https://git.purplecello.org/KylerOlsen/LangsFinalPlaning)
Language Implementation Repository (Private): [git.purplecello.org](https://git.purplecello.org/KylerOlsen/YREA-SLS)
Language Implementation Repository (Mirror on GitHub) (Private): [github.com](https://github.com/SnowSE/final-project-KylerOlsen)
Assignment Page (Private): [snow.instructure.com](https://snow.instructure.com/courses/1154808/assignments/16233203)
## Assignment Description

7
docs/slides/README.md Normal file
View File

@ -0,0 +1,7 @@
# SLS Slide Show
[sls.purplecello.org/slides/SLIDES.html](https://sls.purplecello.org/slides/SLIDES.html)
[sls.purplecello.org/slides/YREA SLS.pdf](https://sls.purplecello.org/slides/YREA%20SLS.pdf)
- https://github.com/marp-team/marp
- https://github.com/marp-team/marp-cli/

615
docs/slides/SLIDES.html Normal file

File diff suppressed because one or more lines are too long

111
docs/slides/SLIDES.md Normal file
View File

@ -0,0 +1,111 @@
---
theme: default
paginate: false
backgroundColor: #fff
backgroundImage: url('./background.svg')
style: |
section.lead {
padding-bottom: 100px;
}
section {
padding-bottom: 225px;
}
section.lead > h1 > strong {
color: #375899;
font-size: 64px;
}
section.lead > p:nth-child(3) {
font-size: 16px;
}
h1 {
color: #001847;
padding-bottom: 0;
margin-bottom: 0;
}
small {
font-size: 16px;
padding-left: 16px;
}
---
![bg left:50% 90%](./sls.svg)
# **YREA SLS**
Kyler Olsen
Fall 2025
Snow College
SE 3250
[sls.purplecello.org](https://sls.purplecello.org)
---
# RPL
*HP Reverse Polish Lisp*
- Based on LISP and Forth
- Stack-oriented language with post-fix notation
- Created by HP for their calculators
<!-- ![bg right:35% 80%](./hp_calc_1.png) -->
![bg right:35% 80%](./hp_calc_2.png)
---
# Project
*YREA SLS*
- Stack-oriented language with post-fix notation
- C inspired Syntax
- Can run on an embedded system
---
# Language
*The C Language*
- Systems Programming
- Used for Python and PHP interpreters
Excellent fit for my project!
---
# Language
*The C Language*
- Manual memory management is difficult to get right.
- C development in a Linux environment was fun and rewarding.
- In the end I had a running program on a RP2040.
---
# Port 1
*Rust*
- Systems Programming (Again)
- Included build system
- Memory safe with the barrow checker
---
# Port 1
*Rust*
- Unlike previous projects in Rust, I didn't fight the barrow checker this time.
- I added exporting and importing the interpreter state in the REPL.
---
# Port 2
*Python*
- My favorite programming language (maybe C is a close second now)
- This port was very easy for me to do.
- I did add a calculator app as an alternative to the REPL or file execution.
---
# The End
<small>You may clap now</small>

BIN
docs/slides/YREA SLS.pdf Normal file

Binary file not shown.

181
docs/slides/background.svg Normal file
View File

@ -0,0 +1,181 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="1920"
height="1080"
viewBox="0 0 508 285.75"
version="1.1"
id="svg8"
inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"
sodipodi:docname="yrea slides.svg"
inkscape:export-filename="D:\other\other\yrea slides.png"
inkscape:export-xdpi="96"
inkscape:export-ydpi="96">
<defs
id="defs2">
<inkscape:path-effect
effect="bspline"
id="path-effect843"
is_visible="true"
lpeversion="1"
weight="33.333333"
steps="2"
helper_size="0"
apply_no_weight="true"
apply_with_weight="true"
only_selected="false" />
<inkscape:path-effect
effect="bspline"
id="path-effect839"
is_visible="true"
lpeversion="1"
weight="33.333333"
steps="2"
helper_size="0"
apply_no_weight="true"
apply_with_weight="true"
only_selected="false" />
<inkscape:path-effect
effect="bspline"
id="path-effect835"
is_visible="true"
lpeversion="1"
weight="33.333333"
steps="2"
helper_size="0"
apply_no_weight="true"
apply_with_weight="true"
only_selected="false" />
</defs>
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="2.8"
inkscape:cx="219.64408"
inkscape:cy="901.94443"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
inkscape:document-rotation="0"
showgrid="false"
units="px"
inkscape:window-width="1920"
inkscape:window-height="1027"
inkscape:window-x="-8"
inkscape:window-y="-8"
inkscape:window-maximized="1" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1">
<path
style="fill:#404040;fill-opacity:1;stroke:none;stroke-width:0.264583px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="M 0,0 C 4.4097359,89.95861 8.8193699,179.91514 52.917606,227.54097 97.015843,275.16679 180.7989,280.45835 264.58333,285.75 l -267.2291633,2.64583 z"
id="path833"
sodipodi:nodetypes="ccccc" />
<path
style="fill:#ffff40;fill-opacity:1;stroke:none;stroke-width:0.264583px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="M 185.20833,285.75 C 283.98636,274.28469 382.76214,262.81965 436.56169,241.65266 490.36124,220.48567 499.18051,189.61823 508,158.75 l 2.64583,129.64583 z"
id="path837"
sodipodi:nodetypes="ccccc" />
<path
style="fill:#ff4040;fill-opacity:1;stroke:none;stroke-width:0.264583px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 370.41667,285.75 c 37.04185,-11.46533 74.08276,-22.93038 97.01368,-70.55618 C 490.36126,167.56801 499.18053,83.784958 508,0 l 2.64583,288.39583 z"
id="path841"
sodipodi:nodetypes="ccccc" />
<path
id="path837-6"
style="fill:#4040ff;fill-opacity:1;stroke:none;stroke-width:0.999999px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 1920,600 c -28.218,98.7629 -56.4515,197.52008 -187.8008,274.03906 C 1645.4028,1004.0342 1522.7043,1042.0201 1400,1080 l 530,10 z"
transform="scale(0.26458333)" />
<g
id="g914"
transform="matrix(0.31102041,0,0,0.31102041,25.4,203.2)">
<g
id="layer4"
inkscape:label="Layer 4">
<circle
style="fill:#0000ff;stroke-width:9.26042;stroke-linecap:round;stroke-linejoin:round"
id="path1416"
cx="145"
cy="100"
r="100" />
</g>
<g
id="layer3"
inkscape:label="Layer 3">
<circle
style="fill:#ff0000;stroke-width:4.63021;stroke-linecap:round;stroke-linejoin:round"
id="path1404"
cx="130"
cy="100"
r="100"
inkscape:transform-center-x="59.720238"
inkscape:transform-center-y="2.2678571" />
</g>
<g
id="layer2"
inkscape:label="Layer 2">
<circle
style="fill:#ffff00;stroke-width:9.26042;stroke-linecap:round;stroke-linejoin:round"
id="path1414"
cx="115"
cy="100"
r="100" />
</g>
<g
inkscape:label="Layer 1"
id="layer1-6">
<circle
style="fill:#000000;stroke-width:9.46963;stroke-linecap:round;stroke-linejoin:round"
id="path1402"
cx="100"
cy="100"
r="100" />
<g
aria-label="YREA"
transform="scale(1.0029344,0.99707419)"
id="text1420"
style="font-size:55.7289px;line-height:1.25;font-family:'AR DESTINE';-inkscape-font-specification:'AR DESTINE';text-align:center;text-anchor:middle;stroke-width:0.210641">
<path
d="m 55.48889,104.0758 v 13.76896 H 46.726827 V 104.0758 L 32.903447,82.74208 h 10.449169 l 7.728031,11.918584 7.728031,-11.918584 h 10.449169 z"
style="font-size:55.7289px;text-align:center;text-anchor:middle;fill:#ffffff;stroke-width:0.210641"
id="path848" />
<path
d="m 91.135794,117.84476 -6.857267,-10.55802 h -4.517088 v 10.55802 H 70.999375 V 93.245672 h 8.762064 v 5.279007 H 90.319453 V 91.504144 H 70.999375 V 82.74208 h 23.728321 q 1.306146,0 2.829983,1.523837 1.523837,1.523838 1.523837,2.829984 v 15.837019 q 0,1.63268 -1.360568,2.99325 -1.360569,1.36057 -2.993252,1.36057 l 6.802844,10.55802 z"
style="font-size:55.7289px;text-align:center;text-anchor:middle;fill:#ffffff;stroke-width:0.210641"
id="path850" />
<path
d="m 120.30639,104.67445 h -6.42189 v -8.762063 h 12.29955 z m 5.22458,13.17031 H 103.32649 V 82.74208 h 22.20448 l 5.87766,8.762064 h -19.26565 v 17.578546 h 19.26565 z"
style="font-size:55.7289px;text-align:center;text-anchor:middle;fill:#ffffff;stroke-width:0.210641"
id="path852" />
<path
d="m 157.69482,117.84476 v -5.27901 h -10.61243 l -3.42864,5.27901 h -10.44917 l 20.62623,-31.837314 q 2.12249,-3.265366 5.82323,-3.265366 2.77556,0 4.78921,2.068065 2.06806,2.013642 2.06806,4.789202 v 12.462813 h -8.81649 v -5.877659 l -5.00689,7.619189 h 13.82338 v 14.04107 z"
style="font-size:55.7289px;text-align:center;text-anchor:middle;fill:#ffffff;stroke-width:0.210641"
id="path854" />
</g>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 7.1 KiB

BIN
docs/slides/hp_calc_1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 MiB

BIN
docs/slides/hp_calc_2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 MiB

175
docs/slides/sls.svg Normal file
View File

@ -0,0 +1,175 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="247.31175mm"
height="84.731728mm"
viewBox="0 0 247.31175 84.731727"
version="1.1"
id="svg8"
inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"
sodipodi:docname="sls.svg">
<defs
id="defs2">
<linearGradient
inkscape:collect="always"
id="linearGradient904">
<stop
style="stop-color:#001847;stop-opacity:1"
offset="0"
id="stop900" />
<stop
style="stop-color:#375899;stop-opacity:1"
offset="1"
id="stop902" />
</linearGradient>
<linearGradient
inkscape:collect="always"
xlink:href="#linearGradient904"
id="linearGradient843"
x1="0.75595236"
y1="30.238094"
x2="215.44643"
y2="30.238094"
gradientUnits="userSpaceOnUse" />
<filter
inkscape:collect="always"
style="color-interpolation-filters:sRGB"
id="filter850"
x="-7.6923783e-07"
width="1.0000015"
y="-2.727184e-06"
height="1.0000055">
<feGaussianBlur
inkscape:collect="always"
stdDeviation="6.9010705e-05"
id="feGaussianBlur852" />
</filter>
<linearGradient
inkscape:collect="always"
xlink:href="#linearGradient904"
id="linearGradient929"
gradientUnits="userSpaceOnUse"
x1="0.75595236"
y1="30.238094"
x2="215.44643"
y2="30.238094" />
<linearGradient
inkscape:collect="always"
xlink:href="#linearGradient904"
id="linearGradient931"
gradientUnits="userSpaceOnUse"
x1="0.75595236"
y1="30.238094"
x2="215.44643"
y2="30.238094" />
<linearGradient
inkscape:collect="always"
xlink:href="#linearGradient904"
id="linearGradient933"
gradientUnits="userSpaceOnUse"
x1="0.75595236"
y1="30.238094"
x2="215.44643"
y2="30.238094" />
<linearGradient
inkscape:collect="always"
xlink:href="#linearGradient904"
id="linearGradient935"
gradientUnits="userSpaceOnUse"
x1="0.75595236"
y1="30.238094"
x2="215.44643"
y2="30.238094" />
<linearGradient
inkscape:collect="always"
xlink:href="#linearGradient904"
id="linearGradient937"
gradientUnits="userSpaceOnUse"
x1="0.75595236"
y1="30.238094"
x2="215.44643"
y2="30.238094" />
<linearGradient
inkscape:collect="always"
xlink:href="#linearGradient904"
id="linearGradient939"
gradientUnits="userSpaceOnUse"
x1="0.75595236"
y1="30.238094"
x2="215.44643"
y2="30.238094" />
</defs>
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:zoom="0.35"
inkscape:cx="599.38016"
inkscape:cy="605.35495"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
inkscape:document-rotation="0"
showgrid="false"
fit-margin-top="12"
fit-margin-left="16"
fit-margin-right="16"
fit-margin-bottom="12"
inkscape:window-width="1920"
inkscape:window-height="1027"
inkscape:window-x="-8"
inkscape:window-y="-8"
inkscape:window-maximized="1" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(16.250258,12.000165)">
<g
aria-label="Sls&gt;_"
id="text835"
style="font-size:16px;line-height:1.25;font-family:'EB Garamond';-inkscape-font-specification:'EB Garamond, @OpticalSize=5,wght=300,wdth=112.5';font-variation-settings:'Size' 5, 'wdth' 112.5, 'wght' 300;display:inline;opacity:1;fill:url(#linearGradient939);fill-opacity:1;stroke-width:0.264583;filter:url(#filter850)">
<path
d="m 16.408399,55.778398 q -5.943599,0 -9.7535993,-2.286 -3.8099999,-2.362199 -5.4863998,-6.172199 -1.67639993,-3.8862 -1.37159994,-8.5344 H 6.5023997 q -0.6096,4.8768 2.0573999,8.0772 2.6670004,3.1242 8.1533994,3.1242 5.4102,0 8.6868,-2.5146 3.3528,-2.5908 3.3528,-7.1628 0,-2.286 -0.9906,-4.1148 -0.9144,-1.8288 -3.3528,-3.429 -2.3622,-1.6002 -6.7818,-3.1242 Q 11.2268,27.432 8.1787996,23.7744 5.2069997,20.1168 5.2069997,14.6304 q 0,-6.4007997 4.9530003,-10.2107996 5.029199,-3.80999981 13.334999,-3.80999981 7.4676,0 11.5824,4.03859981 4.114799,3.9623999 3.809999,10.7441996 h -6.705599 q 0.3048,-4.1148 -2.3622,-6.5531997 -2.667,-2.4383999 -7.1628,-2.4383999 -4.6482,0 -7.6962,2.2097999 -3.048,2.1335997 -3.048,5.6387997 0,3.6576 2.3622,6.096 2.4384,2.3622 8.763,4.6482 5.7912,2.1336 9.144,5.486399 3.429,3.2766 3.429,9.0678 0,5.1816 -2.4384,8.8392 -2.4384,3.5814 -6.7818,5.486399 -4.2672,1.905 -9.9822,1.905 z"
style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:76.2px;font-family:'DM Mono';-inkscape-font-specification:'DM Mono, Italic';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;fill:url(#linearGradient929);fill-opacity:1;stroke-width:0.264583"
id="path906" />
<path
d="m 64.795282,54.863998 q -3.2766,0 -4.8768,-1.9812 -1.6002,-2.057399 -0.9906,-5.410199 l 7.1628,-40.0811987 q 0.3048,-1.9049999 -1.524,-1.9049999 H 54.432083 L 55.422683,6.1035156e-7 h 11.201399 q 3.7338,0 5.1054,1.82879988964844 1.3716,1.7526 0.762,5.6387998 l -7.1628,39.9287987 q -0.3048,1.9812 1.524,1.9812 h 11.6586 l -0.9906,5.486399 z"
style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:76.2px;font-family:'DM Mono';-inkscape-font-specification:'DM Mono, Italic';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;fill:url(#linearGradient931);fill-opacity:1;stroke-width:0.264583"
id="path908" />
<path
d="m 107.23857,55.778398 q -7.620004,0 -11.353804,-3.505199 -3.7338,-3.5814 -3.7338,-9.2202 h 6.6294 q 0,3.048 2.209804,5.1054 2.2098,1.9812 6.7056,1.9812 4.191,0 6.85799,-1.6764 2.7432,-1.7526 2.7432,-4.8006 0,-2.7432 -2.0574,-3.8862 -2.05739,-1.2192 -6.93419,-1.905 -5.4102,-0.6096 -8.763004,-3.2766 -3.3528,-2.667 -3.3528,-7.238999 0,-4.953 4.114804,-8.0772 4.1148,-3.1242 11.7348,-3.1242 6.24839,0 9.98219,3.1242 3.7338,3.048 3.429,8.458199 h -6.4008 q 0.0762,-2.666999 -2.1336,-4.343399 -2.2098,-1.6764 -5.56259,-1.6764 -3.6576,0 -6.1722,1.3716 -2.5146,1.3716 -2.5146,4.1148 0,2.133599 2.0574,3.581399 2.1336,1.3716 6.7056,1.8288 3.65759,0.4572 6.47699,1.6002 2.8194,1.0668 4.4196,3.2766 1.6002,2.1336 1.6002,5.715 0,5.8674 -4.6482,9.2202 -4.6482,3.352799 -12.03959,3.352799 z"
style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:76.2px;font-family:'DM Mono';-inkscape-font-specification:'DM Mono, Italic';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;fill:url(#linearGradient933);fill-opacity:1;stroke-width:0.264583"
id="path910" />
<path
d="m 139.09005,48.767999 23.622,-20.7264 0.0762,-0.533399 -16.383,-19.7357997 h 8.4582 l 16.764,20.4215987 -23.3172,20.574 z"
style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:76.2px;font-family:'DM Mono';-inkscape-font-specification:'DM Mono, Italic';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;fill:url(#linearGradient935);fill-opacity:1;stroke-width:0.264583"
id="path912" />
<path
d="m 179.70453,60.731398 1.0668,-5.8674 h 34.29 l -1.143,5.8674 z"
style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:76.2px;font-family:'DM Mono';-inkscape-font-specification:'DM Mono, Italic';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;fill:url(#linearGradient937);fill-opacity:1;stroke-width:0.264583"
id="path914" />
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 8.7 KiB

View File

@ -10,18 +10,61 @@ This appendix provides a complete alphabetical reference of all standard library
### Standard Library Categories
**Array Operations**: [at](#at), [concat](#concat), [each](#each), [filter](#filter), [length](#length), [map](#map), [reduce](#reduce), [reverse](#reverse), [shape](#shape), [slice](#slice), [transpose](#transpose), [window](#window)
**Array Operations**: [at](#at), [concat](#concat), [each](#each), [enumerate](#enumerate), [filter](#filter), [foldl](#foldl), [foldr](#foldr), [length](#length), [map](#map), [mean](#mean), [reduce](#reduce), [reverse](#reverse), [shape](#shape), [slice](#slice), [sum](#sum), [transpose](#transpose), [window](#window), [zip](#zip)
**I/O Operations**: [at](#at), [concat](#concat), [each](#each), [filter](#filter)
**I/O Operations**: [input](#input), [print](#print), [read](#read), [write](#write)
**String Operations**: [length](#length), [map](#map) [reduce](#reduce), [reverse](#reverse), [shape](#shape)
**String Operations**: [concat](#concat), [ends_with](#ends_with), [find](#find), [format](#format), [join](#join), [length](#length), [replace](#replace), [split](#split), [starts_with](#starts_with), [substr](#substr), [trim](#trim)
**Type Conversion**: [slice](#slice), [to_i8, to_i16, to_i32, to_i64](#to_i8-to_i16-to_i32-to_i64), [to_u8, to_u16, to_u32, to_u64](#to_u8-to_u16-to_u32-to_u64), [to_f32, to_f64](#to_f32-to_f64), [to_str](#to_str)
**Type Conversion**: [parse](#parse), [to_f32, to_f64](#to_f32-to_f64), [to_i8, to_i16, to_i32, to_i64](#to_i8-to_i16-to_i32-to_i64), [to_str](#to_str), [to_u8, to_u16, to_u32, to_u64](#to_u8-to_u16-to_u32-to_u64)
**Utility Operations**: [transpose](#transpose), [window](#window)
**Utility Operations**: [assert](#assert), [implements](#implements), [type_of](#type_of)
### Alphabetical Reference
#### abs
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Return the absolute value of a number.
**Example**:
```
-42 abs // Returns 42
3.14 abs // Returns 3.14
```
**See Also**: [min](#min), [max](#max)
#### acos
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Calculate arc cosine (inverse cosine) in radians.
**Example**:
```
1.0 acos // Returns 0.0
0.0 acos // Returns ~1.5708 (pi/2)
```
**See Also**: [cos](#cos), [asin](#asin), [atan](#atan)
#### asin
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Calculate arc sine (inverse sine) in radians.
**Example**:
```
1.0 asin // Returns ~1.5708 (pi/2)
0.0 asin // Returns 0.0
```
**See Also**: [sin](#sin), [acos](#acos), [atan](#atan)
#### assert
**Signature**: `(TokenString TokenString --)`
**Description**: Evaluate expression and condition, halt if condition is false.
**Example**:
```
{ 2 3 + } { 5 == } assert
{ 5 square } { 25 == } assert
```
**See Also**: [type_of](#type_of), [implements](#implements)
#### at
**Signature**: `(Selectable<T> Size -- T)`
**Trait**: Selectable<T>
@ -32,6 +75,39 @@ This appendix provides a complete alphabetical reference of all standard library
```
**See Also**: [slice](#slice), [length](#length)
#### atan
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Calculate arc tangent (inverse tangent) in radians.
**Example**:
```
1.0 atan // Returns ~0.7854 (pi/4)
0.0 atan // Returns 0.0
```
**See Also**: [tan](#tan), [atan2](#atan2), [asin](#asin)
#### atan2
**Signature**: `(Math Math -- Math)`
**Trait**: Math
**Description**: Calculate two-argument arc tangent of y/x in radians, using signs to determine quadrant.
**Example**:
```
1.0 1.0 atan2 // Returns ~0.7854 (pi/4)
1.0 0.0 atan2 // Returns ~1.5708 (pi/2)
```
**See Also**: [atan](#atan), [tan](#tan)
#### ceil
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Round number up to nearest integer.
**Example**:
```
3.14 ceil // Returns 4.0
-2.7 ceil // Returns -2.0
```
**See Also**: [floor](#floor), [round](#round)
#### concat
**Signature**: `(Concatenable Concatenable -- Concatenable)`
**Trait**: Concatenable
@ -43,6 +119,17 @@ This appendix provides a complete alphabetical reference of all standard library
```
**See Also**: [join](#join), [split](#split)
#### cos
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Calculate cosine of angle in radians.
**Example**:
```
0.0 cos // Returns 1.0
3.14159 cos // Returns ~-1.0
```
**See Also**: [sin](#sin), [tan](#tan), [acos](#acos)
#### depth
**Signature**: `(-- Size)`
**Trait**: Stackable
@ -82,6 +169,26 @@ This appendix provides a complete alphabetical reference of all standard library
```
**See Also**: [map](#map), [filter](#filter)
#### ends_with
**Signature**: `(String String -- bool)`
**Trait**: String
**Description**: Check if string ends with given suffix.
**Example**:
```
"hello" "lo" ends_with // Returns true
"hello" "he" ends_with // Returns false
```
**See Also**: [starts_with](#starts_with), [find](#find)
#### enumerate
**Signature**: `(ArrayOf<T> -- ArrayOf<Pair<Size T>>)`
**Description**: Add indices to array elements.
**Example**:
```
["a" "b" "c"] enumerate // Returns [[0 "a"] [1 "b"] [2 "c"]]
```
**See Also**: [zip](#zip), [map](#map)
#### eval
**Signature**: `(TokenString --)`
**Trait**: Implementable
@ -101,6 +208,67 @@ This appendix provides a complete alphabetical reference of all standard library
```
**See Also**: [map](#map), [reduce](#reduce)
#### find
**Signature**: `(String String -- Option<Size>)`
**Trait**: String
**Description**: Find position of substring, returns Option::Some(index) or Option::None.
**Example**:
```
"hello world" "world" find // Returns Option::Some(6)
"hello world" "xyz" find // Returns Option::None
```
**See Also**: [starts_with](#starts_with), [ends_with](#ends_with)
#### floor
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Round number down to nearest integer.
**Example**:
```
3.14 floor // Returns 3.0
-2.7 floor // Returns -3.0
```
**See Also**: [ceil](#ceil), [round](#round)
#### foldl
**Signature**: `(ArrayOf<T> U TokenString -- U)`
**Description**: Left fold array with accumulator function.
**Example**:
```
[1 2 3 4] 0 { + } foldl // Returns 10
```
**See Also**: [foldr](#foldr), [reduce](#reduce)
#### foldr
**Signature**: `(ArrayOf<T> U TokenString -- U)`
**Description**: Right fold array with accumulator function.
**Example**:
```
[1 2 3 4] 0 { + } foldr // Returns 10
```
**See Also**: [foldl](#foldl), [reduce](#reduce)
#### format
**Signature**: `(String Iterable<Stringifiable> -- String)`
**Trait**: String
**Description**: Format string with values, replacing %d, %s, %f placeholders.
**Example**:
```
"x=%d, y=%d" [5 10] format // Returns "x=5, y=10"
"Hello %s" ["World"] format // Returns "Hello World"
```
**See Also**: [to_str](#to_str), [concat](#concat)
#### implements
**Signature**: `(Self Identifier -- bool)`
**Description**: Check if value's type implements a specific trait.
**Example**:
```
42 ::Addable implements // Returns true
"hello" ::String implements // Returns true
```
**See Also**: [type_of](#type_of), [assert](#assert)
#### input
**Signature**: `(String -- String)`
**Description**: Print prompt and read line from stdin.
@ -150,6 +318,37 @@ This appendix provides a complete alphabetical reference of all standard library
```
**See Also**: [filter](#filter), [reduce](#reduce), [each](#each)
#### max
**Signature**: `(Math Math -- Math)`
**Trait**: Math
**Description**: Return the maximum of two values.
**Example**:
```
3 5 max // Returns 5
-2 1 max // Returns 1
```
**See Also**: [min](#min), [abs](#abs)
#### mean
**Signature**: `(ArrayOf<Number> -- f64)`
**Description**: Calculate the average of numeric array elements.
**Example**:
```
[1 2 3 4 5] mean // Returns 3.0
```
**See Also**: [sum](#sum), [reduce](#reduce)
#### min
**Signature**: `(Math Math -- Math)`
**Trait**: Math
**Description**: Return the minimum of two values.
**Example**:
```
3 5 min // Returns 3
-2 1 min // Returns -2
```
**See Also**: [max](#max), [abs](#abs)
#### over
**Signature**: `(Self Self -- Self Self Self)`
**Trait**: Stackable
@ -190,6 +389,16 @@ This appendix provides a complete alphabetical reference of all standard library
```
**See Also**: [input](#input), [to_str](#to_str)
#### rand
**Signature**: `(-- f64)`
**Description**: Generate random f64 in range [0.0, 1.0).
**Example**:
```
rand // Returns 0.7234... (random value)
100 rand * // Random value 0.0-99.999...
```
**See Also**: [seed](#seed)
#### read
**Signature**: `(String -- String)`
**Description**: Read file contents as string.
@ -206,7 +415,17 @@ This appendix provides a complete alphabetical reference of all standard library
```
[1 2 3 4] 0 { + } reduce // Returns 10
```
**See Also**: [map](#map), [filter](#filter)
**See Also**: [map](#map), [filter](#filter), [foldl](#foldl)
#### replace
**Signature**: `(String String String -- String)`
**Trait**: String
**Description**: Replace all occurrences of substring with replacement.
**Example**:
```
"hello world" "world" "Stack" replace // Returns "hello Stack"
```
**See Also**: [split](#split), [concat](#concat)
#### reverse
**Signature**: `(ArrayOf<T> -- ArrayOf<T>)`
@ -237,6 +456,38 @@ This appendix provides a complete alphabetical reference of all standard library
```
**See Also**: [swap](#swap), [roll](#roll)
#### round
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Round number to nearest integer.
**Example**:
```
3.14 round // Returns 3.0
3.7 round // Returns 4.0
```
**See Also**: [floor](#floor), [ceil](#ceil)
#### seed
**Signature**: `(u64 --)`
**Description**: Seed the random number generator with specific value.
**Example**:
```
12345 seed // Seed RNG for deterministic results
rand // Returns deterministic value
```
**See Also**: [rand](#rand)
#### sin
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Calculate sine of angle in radians.
**Example**:
```
0.0 sin // Returns 0.0
1.5708 sin // Returns ~1.0 (pi/2)
```
**See Also**: [cos](#cos), [tan](#tan), [asin](#asin)
#### slice
**Signature**: `(Sliceable Size Size -- Sliceable)`
**Trait**: Sliceable
@ -257,6 +508,28 @@ This appendix provides a complete alphabetical reference of all standard library
```
**See Also**: [join](#join), [substr](#substr)
#### sqrt
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Calculate square root.
**Example**:
```
16 sqrt // Returns 4.0
2.0 sqrt // Returns ~1.414
```
**See Also**: [^](#operator-exponent)
#### starts_with
**Signature**: `(String String -- bool)`
**Trait**: String
**Description**: Check if string starts with given prefix.
**Example**:
```
"hello" "hel" starts_with // Returns true
"hello" "lo" starts_with // Returns false
```
**See Also**: [ends_with](#ends_with), [find](#find)
#### substr
**Signature**: `(String Size Size -- String)`
**Trait**: String
@ -267,6 +540,15 @@ This appendix provides a complete alphabetical reference of all standard library
```
**See Also**: [slice](#slice), [split](#split)
#### sum
**Signature**: `(ArrayOf<Number> -- Number)`
**Description**: Sum all numeric elements in array.
**Example**:
```
[1 2 3 4 5] sum // Returns 15
```
**See Also**: [mean](#mean), [reduce](#reduce)
#### swap
**Signature**: `(Self Self -- Self Self)`
**Trait**: Stackable
@ -277,6 +559,17 @@ This appendix provides a complete alphabetical reference of all standard library
```
**See Also**: [dup](#dup), [rot](#rot)
#### tan
**Signature**: `(Math -- Math)`
**Trait**: Math
**Description**: Calculate tangent of angle in radians.
**Example**:
```
0.0 tan // Returns 0.0
0.7854 tan // Returns ~1.0 (pi/4)
```
**See Also**: [sin](#sin), [cos](#cos), [atan](#atan)
#### to_f32, to_f64
**Signature**: `(Convertible -- f32/f64)`
**Trait**: Convertible
@ -326,6 +619,26 @@ This appendix provides a complete alphabetical reference of all standard library
```
**See Also**: [reverse](#reverse)
#### trim
**Signature**: `(String -- String)`
**Trait**: String
**Description**: Remove leading and trailing whitespace.
**Example**:
```
" hello " trim // Returns "hello"
```
**See Also**: [split](#split), [replace](#replace)
#### type_of
**Signature**: `(Self -- Identifier)`
**Description**: Return the type of a value as an identifier literal.
**Example**:
```
42 type_of // Returns ::i64
"hello" type_of // Returns ::String
```
**See Also**: [implements](#implements), [assert](#assert)
#### window
**Signature**: `(ArrayOf<T> Size -- ArrayOf<ArrayOf<T>>)`
**Description**: Create sliding windows of given size.
@ -344,4 +657,13 @@ This appendix provides a complete alphabetical reference of all standard library
```
**See Also**: [read](#read)
#### zip
**Signature**: `(ArrayOf<T> ArrayOf<U> -- ArrayOf<Pair<T U>>)`
**Description**: Combine two arrays element-wise into pairs.
**Example**:
```
[1 2 3] [4 5 6] zip // Returns [[1 4] [2 5] [3 6]]
```
**See Also**: [enumerate](#enumerate), [map](#map)
---

View File

@ -232,3 +232,54 @@ body[mode="dark"] div.logo > a {
margin-bottom: 4px;
}
}
@media print {
header, footer, a.headerlink {
display: none !important;
}
main {
padding: 0 !important;
}
body a {
color: black !important;
}
pre {
/* overflow-x: visible; */
word-wrap: normal;
}
/* pre, blockquote {
break-inside: avoid-page;
}
h1, h2, h3, h4 {
break-after: avoid-page;
} */
body[mode="dark"] {
background-color: white;
color: black;
}
body[mode="dark"] a {
color: black;
}
body[mode="dark"] code {
background-color: #eeeeee;
}
body[mode="dark"] pre {
border-color: black;
background-color: white;
}
body[mode="dark"] blockquote {
border-color: black;
border-left-color: #888888;
background-color: white;
}
}

View File

@ -24,6 +24,7 @@ The language provides many built-in traits:
- `::Comparable`, `::Equatable` - Comparison operations
- `::Logical`, `::Bitwise` - Boolean and bit operations
- `::Sized`, `::Selectable<T>`, `::Sliceable` - Container operations
- `::Math` - Mathematical functions
- `::Number` - Composite numeric operations
- And many more...
@ -181,6 +182,7 @@ This section provides a brief overview of all standard traits. For complete defi
- `::Multiplyable` - Multiplication, division, modulo (*, /, %)
- `::Exponentiable` - Exponentiation (^)
- `::Logarithmic` - Logarithm operations (log, ln, logb)
- `::Math` - Mathematical functions (sqrt, abs, sin, cos, tan, asin, acos, atan, atan2, floor, ceil, round, min, max)
- `::Number` - Composite trait combining all arithmetic and comparison
**Comparison**:
@ -206,7 +208,7 @@ This section provides a brief overview of all standard traits. For complete defi
- `::Parseable` - Parse from string (parse)
**String Operations**:
- `::String` - String-specific operations (substr, split) - inherits from Concatenable
- `::String` - String-specific operations (substr, split, replace, trim, find, starts_with, ends_with) - inherits from Concatenable
**Utilities**:
- `::Size` - Types suitable for indexing (inherits Addable, Comparable, Convertible)

View File

@ -51,7 +51,7 @@ The language distinguishes between types (what things are) and traits (how thing
} ::Point impl
```
> **Related**: See [Section 9](trait_system.html) for the complete trait system and [Appendix B](./complete_trait_reference.html) for all standard trait definitions.
> **Related**: See [Section 9](trait_system.html) for the complete trait system and [Appendix B](./complete_trait_reference.html) for all standard trait definitions. See [Appendix H](./complete_type_reference.html) for detailed information about all types.
### 8.2 Type Inference
@ -109,13 +109,13 @@ For operations that need variable numbers of arguments, use the `Iterable` trait
```
(-- Size) depth: // Zero arguments, returns stack depth
(String Iterable<Stringifiable> --) printf: // String plus iterable of printable values
(String Iterable<Stringifiable> --) format: // String plus iterable of printable values
(Iterable<T> -- T) sum: // Iterable of values, returns sum
```
**Examples**:
```
"x=%d, y=%d" [x y] printf // Format string with array of values
"x=%d, y=%d" [x y] format // Format string with array of values
[1 2 3 4 5] sum // Sum array of numbers
depth print // No arguments needed
```

View File

@ -25,6 +25,7 @@ filenames = [
"docs/module_system.md",
"docs/memory_management.md",
"docs/examples_and_tutorials.md",
"docs/complete_type_reference.md",
]
def remove_front_matter(content):
@ -118,17 +119,12 @@ def split_with_front_matter(input_combined, output_dir, metadata_file, force=Fal
order = meta_info.get("order", [])
frontmatters = meta_info.get("files", {})
# Split by H2s — each file should start with one or more H2 sections
# and we assume each original file started with an H2 or higher heading.
sections = re.split(r'(?=^## )', combined_text, flags=re.MULTILINE)
# Split by H1 or H2 headings — each original file should start with an H1 or H2 heading.
sections = re.split(r'(?=^(?:#{1,2})\s)', combined_text, flags=re.MULTILINE)
sections = [s.strip() for s in sections if s.strip()]
if len(sections) != len(order):
print(f"Warning: {len(sections)} sections found but {len(order)} files listed. "
f"Splitting by simple proportion instead.")
approx_size = len(combined_text) // len(order)
chunks = [combined_text[i*approx_size:(i+1)*approx_size] for i in range(len(order)-1)]
chunks.append(combined_text[(len(order)-1)*approx_size:])
raise Exception(f"{len(sections)} sections found but {len(order)} files listed.")
else:
chunks = sections

View File

@ -18,7 +18,8 @@
"grammar_summary.md",
"module_system.md",
"memory_management.md",
"examples_and_tutorials.md"
"examples_and_tutorials.md",
"complete_type_reference.md"
],
"files": {
"changes.md": "Title: Stack Language Specification\nPrev:\nNext:",
@ -39,6 +40,7 @@
"grammar_summary.md": "Title: D Grammar Summary\nPrev: Complete Operator Reference\nNext: Module System",
"module_system.md": "Title: E Module System\nPrev: Grammar Summary\nNext: Memory Management",
"memory_management.md": "Title: F Memory Management\nPrev: Module System\nNext: Examples and Tutorials",
"examples_and_tutorials.md": "Title: G Examples & Tutorials\nPrev: Memory Management\nNext:"
"examples_and_tutorials.md": "Title: G Examples & Tutorials\nPrev: Memory Management\nNext:Complete Type Reference",
"complete_type_reference.md": "Title: H Complete Type Reference\nPrev: Examples and Tutorials\nNext:"
}
}

File diff suppressed because it is too large Load Diff