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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
/**
 * Cem Runtime - Stack Machine Implementation
 *
 * This file implements the runtime stack operations for Cem.
 */

#define _POSIX_C_SOURCE 200809L
#include "stack.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Compile-time assertions to verify ABI assumptions
// The LLVM codegen assumes bool is 1 byte (i8) - verify this at compile time
_Static_assert(sizeof(bool) == 1, "LLVM codegen assumes bool is 1 byte (i8)");
_Static_assert(sizeof(StackCell) == 32,
               "LLVM codegen assumes StackCell is 32 bytes");

// ============================================================================
// Utility Functions
// ============================================================================

StackCell *alloc_cell(void) {
  StackCell *cell = (StackCell *)malloc(sizeof(StackCell));
  if (!cell) {
    runtime_error("Out of memory");
  }
  cell->next = NULL;
  return cell;
}

void free_cell(StackCell *cell) {
  if (!cell)
    return;

  // Free owned resources based on tag
  if (cell->tag == TAG_STRING && cell->value.s) {
    free(cell->value.s);
  }
  // TODO: Free variant data when implemented

  free(cell);
}

void free_stack(StackCell *stack) {
  while (stack) {
    StackCell *next = stack->next;
    free_cell(stack);
    stack = next;
  }
}

// Runtime error handler
// Note: Currently uses exit(1) for simplicity. In a production runtime,
// this could be replaced with setjmp/longjmp or return error codes up the
// call stack. However, for a stack machine runtime, errors are typically
// unrecoverable (stack corruption, type errors, etc.), so exit(1) is
// acceptable for this phase of development.
//
// MEMORY LEAK BEHAVIOR: This function is marked __attribute__((noreturn))
// and immediately exits the process. Any memory allocated before the error
// (including partially constructed StackCells) will leak. This is acceptable
// because:
// 1. The process terminates immediately (OS reclaims all memory)
// 2. Runtime errors indicate unrecoverable conditions (type errors, stack
//    corruption, etc.)
// 3. Attempting cleanup during error handling could cause further corruption
//
// Example: string_concat allocates a temp buffer, then calls push_string.
// If push_string fails with runtime_error(), the temp buffer leaks. This is
// safe because exit(1) terminates the process immediately.
void runtime_error(const char *message) {
  fprintf(stderr, "Runtime error: %s\n", message);
  exit(1);
}

void print_stack(StackCell *stack) {
  printf("Stack (top to bottom): ");
  StackCell *current = stack;
  while (current) {
    switch (current->tag) {
    case TAG_INT:
      printf("%lld ", (long long)current->value.i);
      break;
    case TAG_BOOL:
      printf("%s ", current->value.b ? "true" : "false");
      break;
    case TAG_STRING:
      printf("\"%s\" ", current->value.s);
      break;
    case TAG_QUOTATION:
      printf("<quotation> ");
      break;
    case TAG_VARIANT:
      printf("<variant:%u> ", current->value.variant.tag);
      break;
    }
    current = current->next;
  }
  printf("\n");
}

// ============================================================================
// Stack Operations
// ============================================================================

StackCell *dup(StackCell *stack) {
  if (!stack) {
    runtime_error("dup: stack underflow");
  }

  StackCell *new_cell = alloc_cell();
  new_cell->tag = stack->tag;

  // Deep copy the value
  switch (stack->tag) {
  case TAG_INT:
    new_cell->value.i = stack->value.i;
    break;
  case TAG_BOOL:
    new_cell->value.b = stack->value.b;
    break;
  case TAG_STRING:
    new_cell->value.s = strdup(stack->value.s);
    if (!new_cell->value.s) {
      free_cell(new_cell);
      runtime_error("dup: out of memory");
    }
    break;
  case TAG_QUOTATION:
    new_cell->value.quotation = stack->value.quotation;
    break;
  case TAG_VARIANT:
    // TODO: Implement variant copying
    free_cell(new_cell);
    runtime_error("dup: variant copying not yet implemented");
    break;
  }

  new_cell->next = stack;
  return new_cell;
}

StackCell *drop(StackCell *stack) {
  if (!stack) {
    runtime_error("drop: stack underflow");
  }

  StackCell *rest = stack->next;
  free_cell(stack);
  return rest;
}

StackCell *swap(StackCell *stack) {
  if (!stack || !stack->next) {
    runtime_error("swap: stack underflow");
  }

  StackCell *first = stack;
  StackCell *second = stack->next;
  StackCell *rest = second->next;

  second->next = first;
  first->next = rest;

  return second;
}

StackCell *over(StackCell *stack) {
  if (!stack || !stack->next) {
    runtime_error("over: stack underflow");
  }

  StackCell *second = stack->next;
  StackCell *new_cell = alloc_cell();
  new_cell->tag = second->tag;

  // Deep copy second element
  switch (second->tag) {
  case TAG_INT:
    new_cell->value.i = second->value.i;
    break;
  case TAG_BOOL:
    new_cell->value.b = second->value.b;
    break;
  case TAG_STRING:
    new_cell->value.s = strdup(second->value.s);
    if (!new_cell->value.s) {
      free_cell(new_cell);
      runtime_error("over: out of memory");
    }
    break;
  case TAG_QUOTATION:
    new_cell->value.quotation = second->value.quotation;
    break;
  case TAG_VARIANT:
    free_cell(new_cell);
    runtime_error("over: variant copying not yet implemented");
    break;
  }

  new_cell->next = stack;
  return new_cell;
}

StackCell *rot(StackCell *stack) {
  if (!stack || !stack->next || !stack->next->next) {
    runtime_error("rot: stack underflow");
  }

  StackCell *first = stack;
  StackCell *second = stack->next;
  StackCell *third = second->next;
  StackCell *rest = third->next;

  // Rotate: A B C -> B C A
  second->next = third;
  third->next = first;
  first->next = rest;

  return second;
}

// ============================================================================
// Arithmetic Operations
// ============================================================================
// Note: All arithmetic operations use wrapping semantics (like Rust's
// wrapping_*). Integer overflow wraps around according to two's complement
// representation. This is standard behavior for stack-based concatenative
// languages.

StackCell *add(StackCell *stack) {
  if (!stack || !stack->next) {
    runtime_error("add: stack underflow");
  }
  if (stack->tag != TAG_INT || stack->next->tag != TAG_INT) {
    runtime_error("add: type error (expected Int Int)");
  }

  int64_t b = stack->value.i;
  int64_t a = stack->next->value.i;

  StackCell *rest = stack->next->next;
  free_cell(stack->next);
  free_cell(stack);

  return push_int(rest, a + b);
}

StackCell *subtract(StackCell *stack) {
  if (!stack || !stack->next) {
    runtime_error("subtract: stack underflow");
  }
  if (stack->tag != TAG_INT || stack->next->tag != TAG_INT) {
    runtime_error("subtract: type error (expected Int Int)");
  }

  int64_t b = stack->value.i;
  int64_t a = stack->next->value.i;

  StackCell *rest = stack->next->next;
  free_cell(stack->next);
  free_cell(stack);

  return push_int(rest, a - b);
}

StackCell *multiply(StackCell *stack) {
  if (!stack || !stack->next) {
    runtime_error("multiply: stack underflow");
  }
  if (stack->tag != TAG_INT || stack->next->tag != TAG_INT) {
    runtime_error("multiply: type error (expected Int Int)");
  }

  int64_t b = stack->value.i;
  int64_t a = stack->next->value.i;

  StackCell *rest = stack->next->next;
  free_cell(stack->next);
  free_cell(stack);

  return push_int(rest, a * b);
}

StackCell *divide_op(StackCell *stack) {
  if (!stack || !stack->next) {
    runtime_error("divide: stack underflow");
  }
  if (stack->tag != TAG_INT || stack->next->tag != TAG_INT) {
    runtime_error("divide: type error (expected Int Int)");
  }

  int64_t b = stack->value.i;
  int64_t a = stack->next->value.i;

  if (b == 0) {
    runtime_error("divide: division by zero");
  }

  StackCell *rest = stack->next->next;
  free_cell(stack->next);
  free_cell(stack);

  return push_int(rest, a / b);
}

// ============================================================================
// Comparison Operations
// ============================================================================

StackCell *less_than(StackCell *stack) {
  if (!stack || !stack->next) {
    runtime_error("less_than: stack underflow");
  }
  if (stack->tag != TAG_INT || stack->next->tag != TAG_INT) {
    runtime_error("less_than: type error (expected Int Int)");
  }

  int64_t b = stack->value.i;
  int64_t a = stack->next->value.i;

  StackCell *rest = stack->next->next;
  free_cell(stack->next);
  free_cell(stack);

  return push_bool(rest, a < b);
}

StackCell *greater_than(StackCell *stack) {
  if (!stack || !stack->next) {
    runtime_error("greater_than: stack underflow");
  }
  if (stack->tag != TAG_INT || stack->next->tag != TAG_INT) {
    runtime_error("greater_than: type error (expected Int Int)");
  }

  int64_t b = stack->value.i;
  int64_t a = stack->next->value.i;

  StackCell *rest = stack->next->next;
  free_cell(stack->next);
  free_cell(stack);

  return push_bool(rest, a > b);
}

StackCell *equal(StackCell *stack) {
  if (!stack || !stack->next) {
    runtime_error("equal: stack underflow");
  }

  bool result = false;

  // Check if tags match
  if (stack->tag == stack->next->tag) {
    switch (stack->tag) {
    case TAG_INT:
      result = (stack->value.i == stack->next->value.i);
      break;
    case TAG_BOOL:
      result = (stack->value.b == stack->next->value.b);
      break;
    case TAG_STRING:
      result = (strcmp(stack->value.s, stack->next->value.s) == 0);
      break;
    case TAG_QUOTATION:
      result = (stack->value.quotation == stack->next->value.quotation);
      break;
    case TAG_VARIANT:
      // TODO: Implement variant equality
      runtime_error("equal: variant comparison not yet implemented");
      break;
    }
  }

  StackCell *rest = stack->next->next;
  free_cell(stack->next);
  free_cell(stack);

  return push_bool(rest, result);
}

// ============================================================================
// Push Operations
// ============================================================================

StackCell *push_int(StackCell *stack, int64_t value) {
  StackCell *cell = alloc_cell();
  cell->tag = TAG_INT;
  cell->value.i = value;
  cell->next = stack;
  return cell;
}

StackCell *push_bool(StackCell *stack, bool value) {
  StackCell *cell = alloc_cell();
  cell->tag = TAG_BOOL;
  cell->value.b = value;
  cell->next = stack;
  return cell;
}

StackCell *push_string(StackCell *stack, const char *value) {
  StackCell *cell = alloc_cell();
  cell->tag = TAG_STRING;
  cell->value.s = strdup(value);
  if (!cell->value.s) {
    runtime_error("push_string: out of memory");
  }
  cell->next = stack;
  return cell;
}

StackCell *push_quotation(StackCell *stack, void *func_ptr) {
  StackCell *cell = alloc_cell();
  cell->tag = TAG_QUOTATION;
  cell->value.quotation = func_ptr;
  cell->next = stack;
  return cell;
}

// ============================================================================
// String Operations
// ============================================================================

StackCell *string_length(StackCell *stack) {
  if (!stack) {
    runtime_error("string_length: stack underflow");
  }
  if (stack->tag != TAG_STRING) {
    runtime_error("string_length: expected string on top of stack");
  }
  if (!stack->value.s) {
    runtime_error("string_length: NULL string pointer");
  }

  // Calculate length (returns byte count, not UTF-8 character count)
  int64_t len = (int64_t)strlen(stack->value.s);

  // Pop string and push length
  StackCell *rest = stack->next;
  free_cell(stack);

  return push_int(rest, len);
}

StackCell *string_concat(StackCell *stack) {
  if (!stack || !stack->next) {
    runtime_error("string_concat: stack underflow");
  }
  if (stack->tag != TAG_STRING || stack->next->tag != TAG_STRING) {
    runtime_error("string_concat: expected two strings on stack");
  }

  // Get both strings (top is second operand, next is first operand)
  char *str2 = stack->value.s;
  char *str1 = stack->next->value.s;

  // NULL pointer checks
  if (!str1 || !str2) {
    runtime_error("string_concat: NULL string pointer");
  }

  // Calculate lengths and check for overflow
  size_t len1 = strlen(str1);
  size_t len2 = strlen(str2);

  // Check for size_t overflow: len1 + len2 + 1
  if (len1 > SIZE_MAX - len2 - 1) {
    runtime_error("string_concat: string too long (overflow)");
  }
  size_t total_len = len1 + len2 + 1;

  // Allocate new string
  char *result = malloc(total_len);
  if (!result) {
    runtime_error("string_concat: out of memory");
  }

  // Concatenate using memcpy (safer than strcpy/strcat)
  memcpy(result, str1, len1);
  memcpy(result + len1, str2, len2);
  result[len1 + len2] = '\0';

  // Pop both strings BEFORE push_string (in case push_string fails)
  StackCell *rest = stack->next->next;
  free_cell(stack->next);
  free_cell(stack);

  // Push result (this makes its own copy)
  StackCell *new_cell = push_string(rest, result);

  // Free our temporary buffer
  free(result);

  return new_cell;
}

StackCell *string_equal(StackCell *stack) {
  if (!stack || !stack->next) {
    runtime_error("string_equal: stack underflow");
  }
  if (stack->tag != TAG_STRING || stack->next->tag != TAG_STRING) {
    runtime_error("string_equal: expected two strings on stack");
  }

  // NULL pointer checks
  if (!stack->value.s || !stack->next->value.s) {
    runtime_error("string_equal: NULL string pointer");
  }

  // Compare strings
  bool result = (strcmp(stack->value.s, stack->next->value.s) == 0);

  // Pop both strings
  StackCell *rest = stack->next->next;
  free_cell(stack->next);
  free_cell(stack);

  return push_bool(rest, result);
}

// ============================================================================
// Control Flow Operations (Placeholders)
// ============================================================================

StackCell *call_quotation(StackCell *stack) {
  if (!stack) {
    runtime_error("call_quotation: stack underflow");
  }
  if (stack->tag != TAG_QUOTATION) {
    runtime_error("call_quotation: expected quotation on top of stack");
  }

  // Pop the quotation
  void *func_ptr = stack->value.quotation;
  StackCell *rest = stack->next;
  free(stack);

  // Call the function pointer with the rest of the stack
  // The function has signature: StackCell* (*)(StackCell*)
  typedef StackCell *(*QuotationFunc)(StackCell *);
  QuotationFunc func = (QuotationFunc)func_ptr;
  return func(rest);
}

StackCell *if_then_else(StackCell *stack) {
  // TODO: Implement when control flow is supported
  runtime_error("if_then_else: not yet implemented");
  return stack;
}