diff --git a/docs/advanced_topics.md b/docs/advanced_topics.md index df6aea3..4c4d0f7 100644 --- a/docs/advanced_topics.md +++ b/docs/advanced_topics.md @@ -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. diff --git a/docs/basic_operations.md b/docs/basic_operations.md index 63ffbab..cba5f12 100644 --- a/docs/basic_operations.md +++ b/docs/basic_operations.md @@ -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). + --- diff --git a/docs/changes.md b/docs/changes.md index 4f5a8a3..b673476 100644 --- a/docs/changes.md +++ b/docs/changes.md @@ -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 --- diff --git a/docs/complete_operator_reference.md b/docs/complete_operator_reference.md index f80bb62..50b31e5 100644 --- a/docs/complete_operator_reference.md +++ b/docs/complete_operator_reference.md @@ -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 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 -- ArrayOf>)` +**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)` +**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 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 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 -- 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 --)` @@ -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 -- 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 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 -- ArrayOf)` @@ -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)` +**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)` +**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 ArrayOf -- ArrayOf>)` +**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) + --- diff --git a/docs/complete_trait_reference.md b/docs/complete_trait_reference.md index fa44f47..fa64ffc 100644 --- a/docs/complete_trait_reference.md +++ b/docs/complete_trait_reference.md @@ -23,6 +23,7 @@ This appendix contains all built-in trait definitions with complete documentatio - Iterable - 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 +**Inherits**: Addable, Comparable, Convertible **Definition**: ``` -[ ::Addable ::Comparable ::Convertible ] ::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) split: + (Self Self String -- Self) replace: + (Self -- Self) trim: + (Self Self -- Option) 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)` +**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) --- diff --git a/docs/complete_type_reference.md b/docs/complete_type_reference.md new file mode 100644 index 0000000..e521377 --- /dev/null +++ b/docs/complete_type_reference.md @@ -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 +**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, Sized, Selectable, Sliceable, Iterable, 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, 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? 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? union` +**Traits Implemented**: Stackable, Equatable (if variants are), Stringifiable (if variants are) +**Operations**: Pattern matching with match +**Example**: +``` +(T --) { Some(T) None } ::Option 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 +**Description**: Represents an optional value - either Some(T) or None. +**Definition**: `(T --) { Some(T) None } ::Option 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 +**Description**: Represents success (Ok) or failure (Err) with values. +**Definition**: `(T E --) { Ok(T) Err(E) } ::Result 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 +``` + +--- diff --git a/docs/data_structures.md b/docs/data_structures.md index 0b44f40..0b5cd5a 100644 --- a/docs/data_structures.md +++ b/docs/data_structures.md @@ -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**: diff --git a/docs/examples_and_tutorials.md b/docs/examples_and_tutorials.md index 8821eaa..ad2d35d 100644 --- a/docs/examples_and_tutorials.md +++ b/docs/examples_and_tutorials.md @@ -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::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 + + 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 -// Identifier literals are NOT used inside trait/impl bodies -// (those are method names) -{ - (Self -- ) { "Drawing" print } draw: // "draw:" is method name -} ::Drawable trait +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" +``` + +#### 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 ``` --- diff --git a/docs/grammar_summary.md b/docs/grammar_summary.md index ca66150..a2d9dd9 100644 --- a/docs/grammar_summary.md +++ b/docs/grammar_summary.md @@ -10,9 +10,11 @@ This appendix provides a concise grammar reference. For complete specifications ### D.1 Lexical Grammar -**Comments**: +**Comments and Directives**: ``` line_comment ::= "//" +directive ::= "#" +shebang ::= "#!/" ``` **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? struct` - Unions: `(variant_types --) { Variant(T) ... } ::name? union` diff --git a/docs/index.md b/docs/index.md index fadea86..b618fbd 100644 --- a/docs/index.md +++ b/docs/index.md @@ -28,6 +28,7 @@ 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**: - [Missing Features](./missing_features.html) diff --git a/docs/lexical_structure.md b/docs/lexical_structure.md index 2a0869a..c932e0a 100644 --- a/docs/lexical_structure.md +++ b/docs/lexical_structure.md @@ -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 ``` --- diff --git a/docs/memory_management.md b/docs/memory_management.md index 18a4e36..8910ef5 100644 --- a/docs/memory_management.md +++ b/docs/memory_management.md @@ -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 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 +``` + --- diff --git a/docs/overview.md b/docs/overview.md index 422f758..1e02ba1 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -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. --- diff --git a/docs/primitive_types.md b/docs/primitive_types.md index 506a811..de388a2 100644 --- a/docs/primitive_types.md +++ b/docs/primitive_types.md @@ -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. --- diff --git a/docs/standard_library.md b/docs/standard_library.md index bb75f78..a2e9700 100644 --- a/docs/standard_library.md +++ b/docs/standard_library.md @@ -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 Size -- T)` **Trait**: Selectable @@ -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 -- ArrayOf>)` +**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)` +**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 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 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 -- 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 -- 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 -- ArrayOf)` @@ -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)` +**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 Size -- ArrayOf>)` **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 ArrayOf -- ArrayOf>)` +**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) + --- diff --git a/docs/trait_system.md b/docs/trait_system.md index d9e308f..3cf22c8 100644 --- a/docs/trait_system.md +++ b/docs/trait_system.md @@ -24,6 +24,7 @@ The language provides many built-in traits: - `::Comparable`, `::Equatable` - Comparison operations - `::Logical`, `::Bitwise` - Boolean and bit operations - `::Sized`, `::Selectable`, `::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) diff --git a/docs/type_system.md b/docs/type_system.md index 950beae..8ec8bd7 100644 --- a/docs/type_system.md +++ b/docs/type_system.md @@ -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 --) printf: // String plus iterable of printable values +(String Iterable --) format: // String plus iterable of printable values (Iterable -- 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 ``` diff --git a/manage_docs.py b/manage_docs.py index 44a5332..b8f0c4a 100644 --- a/manage_docs.py +++ b/manage_docs.py @@ -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 diff --git a/metadata.json b/metadata.json index 2b788b3..2220d44 100644 --- a/metadata.json +++ b/metadata.json @@ -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:" } } \ No newline at end of file