cemc 0.1.2

Cem language compiler - A concatenative language with green threads and linear types
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# prelude.cem - Auto-imported Utilities for Cem
#
# This file contains commonly-used utilities that are automatically available
# in every Cem program without explicit import.
#
# Contents:
# - Option<T> utilities
# - Result<T,E> utilities
# - Basic List operations
# - Common patterns

# Import core combinators (always available)
# import core

# ============================================================================
# OPTION UTILITIES
# ============================================================================

# NOTE: Option type and constructors (Some, None) are built into the compiler

: is-some ( Option(A) -- Bool )
  # Check if Option contains a value
  #
  # Example:
  #   Some(42) is-some  # Stack: true
  #   None is-some      # Stack: false
  match
    Some(_) => [ true ]
    None => [ false ]
  end ;

: is-none ( Option(A) -- Bool )
  # Check if Option is None
  is-some not ;

: unwrap ( Option(A) -- A )
  # Extract value from Option, panic if None
  # UNSAFE: Only use when you're certain Option is Some
  #
  # Example:
  #   Some(42) unwrap  # Stack: 42
  #   None unwrap      # PANIC!
  match
    Some => [ ]
    None => [ "unwrap called on None" panic ]
  end ;

: unwrap-or ( Option(A) A -- A )
  # Extract value from Option, or use default if None
  #
  # Example:
  #   Some(42) 0 unwrap-or  # Stack: 42
  #   None 0 unwrap-or      # Stack: 0
  swap match
    Some => [ swap drop ]
    None => [ ]
  end ;

: unwrap-or-else ( Option(A) [-- A] -- A )
  # Extract value from Option, or compute default if None
  # Lazy evaluation: quotation only called if needed
  #
  # Example:
  #   None [ "default" ] unwrap-or-else  # Stack: "default"
  swap match
    Some => [ drop ]
    None => [ call ]
  end ;

: expect ( Option(A) String -- A )
  # Extract value from Option, panic with message if None
  #
  # Example:
  #   None "value required" expect  # PANIC with message
  swap match
    Some => [ drop ]
    None => [ panic ]
  end ;

: map-option ( Option(A) [A -- B] -- Option(B) )
  # Apply function to value inside Option, or return None
  #
  # Example:
  #   Some(5) [ 2 * ] map-option  # Stack: Some(10)
  #   None [ 2 * ] map-option     # Stack: None
  swap match
    Some => [ call Some ]
    None => [ drop None ]
  end ;

: and-then ( Option(A) [A -- Option(B)] -- Option(B) )
  # Chain Option-returning operations (flatMap / bind)
  #
  # Example:
  #   Some(5) [ dup 10 < [ Some ] [ drop None ] if ] and-then
  #   # Returns Some(5) because 5 < 10
  swap match
    Some => [ call ]
    None => [ drop None ]
  end ;

: filter-option ( Option(A) [A -- Bool] -- Option(A) )
  # Keep value only if it satisfies predicate
  #
  # Example:
  #   Some(5) [ 10 < ] filter-option  # Stack: Some(5)
  #   Some(15) [ 10 < ] filter-option # Stack: None
  swap match
    Some => [
      dup rot call
      [ Some ] [ drop None ] if
    ]
    None => [ drop None ]
  end ;

: option-or ( Option(A) Option(A) -- Option(A) )
  # Return first Option if Some, otherwise second
  #
  # Example:
  #   Some(5) Some(10) option-or  # Stack: Some(5)
  #   None Some(10) option-or     # Stack: Some(10)
  over is-some
  [ swap drop ]
  [ drop ]
  if ;

: flatten-option ( Option(Option(A)) -- Option(A) )
  # Flatten nested Option
  #
  # Example:
  #   Some(Some(42)) flatten-option  # Stack: Some(42)
  #   Some(None) flatten-option      # Stack: None
  match
    Some => [ ]
    None => [ None ]
  end ;

# ============================================================================
# RESULT UTILITIES
# ============================================================================

# NOTE: Result type and constructors (Ok, Err) are built into the compiler

: is-ok ( Result(T,E) -- Bool )
  # Check if Result is Ok
  #
  # Example:
  #   Ok(42) is-ok   # Stack: true
  #   Err("failed") is-ok  # Stack: false
  match
    Ok => [ drop true ]
    Err => [ drop false ]
  end ;

: is-err ( Result(T,E) -- Bool )
  # Check if Result is Err
  is-ok not ;

: unwrap-result ( Result(T,E) -- T )
  # Extract value from Result, panic if Err
  # UNSAFE: Only use when certain Result is Ok
  match
    Ok => [ ]
    Err => [ "unwrap called on Err: " swap concat panic ]
  end ;

: unwrap-err ( Result(T,E) -- E )
  # Extract error from Result, panic if Ok
  # UNSAFE: Only use when certain Result is Err
  match
    Ok => [ "unwrap-err called on Ok" panic ]
    Err => [ ]
  end ;

: unwrap-or-result ( Result(T,E) T -- T )
  # Extract value from Result, or use default if Err
  swap match
    Ok => [ swap drop ]
    Err => [ drop ]
  end ;

: expect-result ( Result(T,E) String -- T )
  # Extract value from Result, panic with message if Err
  swap match
    Ok => [ drop ]
    Err => [ swap concat panic ]
  end ;

: map-ok ( Result(T,E) [T -- U] -- Result(U,E) )
  # Apply function to Ok value, leave Err unchanged
  #
  # Example:
  #   Ok(5) [ 2 * ] map-ok   # Stack: Ok(10)
  #   Err("bad") [ 2 * ] map-ok  # Stack: Err("bad")
  swap match
    Ok => [ call Ok ]
    Err => [ drop Err ]
  end ;

: map-err ( Result(T,E) [E -- F] -- Result(T,F) )
  # Apply function to Err value, leave Ok unchanged
  swap match
    Ok => [ drop Ok ]
    Err => [ call Err ]
  end ;

: and-then-result ( Result(T,E) [T -- Result(U,E)] -- Result(U,E) )
  # Chain Result-returning operations (flatMap / bind)
  #
  # Example:
  #   Ok(5) [ dup 0 > [ Ok ] [ drop Err("negative") ] if ] and-then-result
  swap match
    Ok => [ call ]
    Err => [ drop Err ]
  end ;

: or-else-result ( Result(T,E) [E -- Result(T,F)] -- Result(T,F) )
  # Chain on error path
  swap match
    Ok => [ drop Ok ]
    Err => [ call ]
  end ;

: result-or ( Result(T,E) Result(T,E) -- Result(T,E) )
  # Return first Result if Ok, otherwise second
  over is-ok
  [ swap drop ]
  [ drop ]
  if ;

# ============================================================================
# BIND OPERATOR (for chaining operations)
# ============================================================================

: bind ( Option(A) [A -- Option(B)] -- Option(B) )
  # Alias for and-then, clearer for chaining
  and-then ;

: bind-result ( Result(T,E) [T -- Result(U,E)] -- Result(U,E) )
  # Alias for and-then-result, clearer for chaining
  and-then-result ;

# ============================================================================
# CONVERSION UTILITIES
# ============================================================================

: option-to-result ( Option(A) E -- Result(A,E) )
  # Convert Option to Result, using provided error
  #
  # Example:
  #   Some(42) "missing value" option-to-result  # Stack: Ok(42)
  #   None "missing value" option-to-result      # Stack: Err("missing value")
  swap match
    Some => [ drop Ok ]
    None => [ Err ]
  end ;

: result-to-option ( Result(T,E) -- Option(T) )
  # Convert Result to Option, discarding error
  #
  # Example:
  #   Ok(42) result-to-option     # Stack: Some(42)
  #   Err("bad") result-to-option # Stack: None
  match
    Ok => [ Some ]
    Err => [ drop None ]
  end ;

# ============================================================================
# LIST BASICS (more in data/list.cem)
# ============================================================================

# NOTE: List type and constructors (Cons, Nil) are built into the compiler

: is-empty ( List(A) -- Bool )
  # Check if list is empty
  match
    Nil => [ true ]
    Cons => [ drop drop false ]
  end ;

: head ( List(A) -- Option(A) )
  # Get first element of list
  #
  # Example:
  #   Cons(1, Cons(2, Nil)) head  # Stack: Some(1)
  #   Nil head                    # Stack: None
  match
    Nil => [ None ]
    Cons => [ drop Some ]
  end ;

: tail ( List(A) -- Option(List(A)) )
  # Get list without first element
  match
    Nil => [ None ]
    Cons => [ swap drop Some ]
  end ;

: length ( List(A) -- Int )
  # Get length of list
  0 swap [ drop 1 + ] fold ;

: map ( List(A) [A -- B] -- List(B) )
  # Apply function to each element
  #
  # Example:
  #   Cons(1, Cons(2, Nil)) [ 2 * ] map  # Stack: Cons(2, Cons(4, Nil))
  swap match
    Nil => [ drop Nil ]
    Cons => [
      [ dup ] dip
      [ [ dip ] dip ] dip
      map
      Cons
    ]
  end ;

: filter ( List(A) [A -- Bool] -- List(A) )
  # Keep only elements that satisfy predicate
  #
  # Example:
  #   Cons(1, Cons(2, Cons(3, Nil))) [ 2 < ] filter
  #   # Stack: Cons(1, Nil)
  swap match
    Nil => [ drop Nil ]
    Cons => [
      [ dup ] dip
      [ [ dip ] dip ] dip
      [ filter Cons ]
      [ drop filter ]
      if
    ]
  end ;

: fold ( List(A) B [B A -- B] -- B )
  # Reduce list to single value
  #
  # Example:
  #   Cons(1, Cons(2, Cons(3, Nil))) 0 [ + ] fold  # Stack: 6
  swap match
    Nil => [ drop ]
    Cons => [
      [ swap ] dip
      [ [ dip ] dip ] dip
      fold
    ]
  end ;

# ============================================================================
# COMMON PATTERNS
# ============================================================================

: panic ( String -- )
  # Abort program with error message
  # TODO: Needs runtime support
  # For now, this is a placeholder
  drop ;

: todo ( String -- A )
  # Mark unimplemented code
  # Panics with "TODO: " message
  "TODO: " swap concat panic ;

: unreachable ( String -- A )
  # Mark code that should never execute
  # Panics with "UNREACHABLE: " message
  "UNREACHABLE: " swap concat panic ;

# ============================================================================
# DEBUGGING UTILITIES
# ============================================================================

: debug-print ( A -- A )
  # Print value for debugging, keep it on stack
  # TODO: Needs runtime support for generic printing
  dup print ;

: debug-stack ( A -- A )
  # Print current stack depth
  # TODO: Needs runtime introspection
  dup "Stack depth: " print ;

# ============================================================================
# EXAMPLES
# ============================================================================

# Example 1: Chaining Option operations
# : parse-and-double ( String -- Option(Int) )
#   parse-int                    # String -- Option(Int)
#   [ 2 * ] map-option           # Option(Int) -- Option(Int)
#   [ 100 < ] filter-option ;    # Option(Int) -- Option(Int)

# Example 2: Chaining Result operations
# : safe-divide ( Int Int -- Result(Int, String) )
#   dup 0 =
#   [ drop drop Err("division by zero") ]
#   [ / Ok ]
#   if ;
#
# : compute ( Int Int -- Result(Int, String) )
#   safe-divide
#   [ 10 + ] map-ok
#   [ "Error: " swap concat ] map-err ;

# Example 3: Using bind for clean chaining
# : process-user ( String -- Result(User, Error) )
#   parse-user          # Result(RawUser, Error)
#   [ validate ] bind-result
#   [ normalize ] bind-result
#   [ save ] bind-result ;

# Example 4: Converting between Option and Result
# : get-config ( String -- Result(String, String) )
#   lookup-env-var              # String -- Option(String)
#   "env var not set" option-to-result ;

# End of prelude.cem