Module: MilkTea::CBackend::RuntimeHelpers

Included in:
MilkTea::CBackend
Defined in:
lib/milk_tea/core/c_backend/runtime_helpers.rb

Instance Method Summary collapse

Instance Method Details

#emit_async_memory_helpersObject



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
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 195

def emit_async_memory_helpers
  [
    "#define MT_ASYNC_HEADER_SIZE (sizeof(uint64_t) + sizeof(uintptr_t))",
    "#define MT_ASYNC_MAGIC UINT64_C(0x4D5441464D454D00)",
    "",
    "static void* mt_async_alloc(uintptr_t size) {",
    "#{INDENT}char* raw = (char*) calloc(1, (size_t)(MT_ASYNC_HEADER_SIZE + size));",
    "#{INDENT}if (raw == NULL) {",
    "#{INDENT * 2}abort();",
    "#{INDENT}}",
    "#{INDENT}*(uint64_t*)raw = MT_ASYNC_MAGIC;",
    "#{INDENT}*(uintptr_t*)(raw + sizeof(uint64_t)) = 1;",
    "#{INDENT}return raw + MT_ASYNC_HEADER_SIZE;",
    "}",
    "",
    "static void mt_async_retain(void* frame) {",
    "#{INDENT}char* raw = (char*)frame - MT_ASYNC_HEADER_SIZE;",
    "#{INDENT}if (*(uint64_t*)raw != MT_ASYNC_MAGIC) return;",
    "#{INDENT}uintptr_t* ref = (uintptr_t*)(raw + sizeof(uint64_t));",
    "#{INDENT}(*ref)++;",
    "}",
    "",
    "static void mt_async_free(void* frame) {",
    "#{INDENT}char* raw = (char*)frame - MT_ASYNC_HEADER_SIZE;",
    "#{INDENT}if (*(uint64_t*)raw != MT_ASYNC_MAGIC) return;",
    "#{INDENT}uintptr_t* ref = (uintptr_t*)(raw + sizeof(uint64_t));",
    "#{INDENT}if (--(*ref) == 0) {",
    "#{INDENT * 2}free(raw);",
    "#{INDENT}}",
    "}",
  ]
end

#emit_checked_array_index_helper(type) ⇒ Object



595
596
597
598
599
600
601
602
603
604
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 595

def emit_checked_array_index_helper(type)
  helper_name = checked_array_index_helper_name(type)
  params = [c_declaration(pointer_to(array_element_type(type)), 'array'), c_declaration(Types::Registry.primitive('ptr_uint'), 'index')].join(', ')
  [
    "static inline #{c_function_declaration(pointer_to(array_element_type(type)), helper_name, params)} {",
    "#{INDENT}if (index >= #{array_length(type)}) mt_fatal(\"array index out of bounds\");",
    "#{INDENT}return &array[index];",
    "}",
  ]
end

#emit_checked_span_index_helper(type) ⇒ Object



606
607
608
609
610
611
612
613
614
615
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 606

def emit_checked_span_index_helper(type)
  helper_name = checked_span_index_helper_name(type)
  params = [c_declaration(type, 'span'), c_declaration(Types::Registry.primitive('ptr_uint'), 'index')].join(', ')
  [
    "static inline #{c_function_declaration(pointer_to(type.element_type), helper_name, params)} {",
    "#{INDENT}if (index >= span.len) mt_fatal(\"span index out of bounds\");",
    "#{INDENT}return &span.data[index];",
    "}",
  ]
end

#emit_detach_helpersObject



308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 308

def emit_detach_helpers
  [
    "typedef struct {",
    "#{INDENT}uv_thread_t thread;",
    "} mt_detach_handle;",
    "",
    "static void* mt_detach_run(void (*work)(void*), void* cap) {",
    "#{INDENT}mt_detach_handle* h = (mt_detach_handle*)malloc(sizeof(mt_detach_handle));",
    "#{INDENT}uv_thread_create(&h->thread, work, cap);",
    "#{INDENT}return h;",
    "}",
    "",
    "static void mt_detach_join(void* handle) {",
    "#{INDENT}if (!handle) return;",
    "#{INDENT}mt_detach_handle* h = (mt_detach_handle*)handle;",
    "#{INDENT}uv_thread_join(&h->thread);",
    "#{INDENT}free(h);",
    "}",
  ]
end

#emit_entrypoint_argv_helpersObject



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
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 414

def emit_entrypoint_argv_helpers
  lines = []

  if emitted_functions.any? { |function| function_uses_named_call?(function, %w[mt_entry_argv_to_span_str]) }
    lines.concat([
      "static mt_span_str mt_entry_argv_to_span_str(int32_t argc, char** argv, mt_str** items_out) {",
      "#{INDENT}uintptr_t len = argc > 0 ? (uintptr_t)argc : 0;",
      "#{INDENT}mt_str* items = NULL;",
      "#{INDENT}uintptr_t index = 0;",
      "#{INDENT}if (len > 0) {",
      "#{INDENT * 2}items = (mt_str*)malloc(len * sizeof(mt_str));",
      "#{INDENT * 2}if (items == NULL) abort();",
      "#{INDENT}}",
      "#{INDENT}while (index < len) {",
      "#{INDENT * 2}char* value = argv[index];",
      "#{INDENT * 2}items[index] = (mt_str){ .data = value, .len = (uintptr_t)strlen(value) };",
      "#{INDENT * 2}index++;",
      "#{INDENT}}",
      "#{INDENT}*items_out = items;",
      "#{INDENT}return (mt_span_str){ .data = items, .len = len };",
      "}",
    ])
  end

  if emitted_functions.any? { |function| function_uses_named_call?(function, %w[mt_free_entry_argv_strs]) }
    lines << "" unless lines.empty?
    lines.concat([
      "static void mt_free_entry_argv_strs(mt_str* items) {",
      "#{INDENT}free(items);",
      "}",
    ])
  end

  lines
end

#emit_fatal_helperObject



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
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 6

def emit_fatal_helper
  lines = []

  if uses_mt_fatal_helper?
    lines.concat([
      "static _Noreturn void mt_fatal(const char* message) {",
      "#{INDENT}fputs(message, stderr);",
      "#{INDENT}fputc('\\n', stderr);",
      "#{INDENT}abort();",
      "}",
    ])
  end

  if uses_mt_fatal_str_helper?
    lines << "" unless lines.empty?
    lines.concat([
      "static _Noreturn void mt_fatal_str(mt_str message) {",
      "#{INDENT}fwrite(message.data, 1, message.len, stderr);",
      "#{INDENT}fputc('\\n', stderr);",
      "#{INDENT}abort();",
      "}",
    ])
  end

  lines
end

#emit_field_equality_guards(lines, left, right, type, outer_c: nil, indent: 1) ⇒ Object



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
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 151

def emit_field_equality_guards(lines, left, right, type, outer_c: nil, indent: 1)
  pad = INDENT * indent
  case type
  when Types::StringView
    lines << "#{pad}if (!mt_str_equal(#{left}, #{right})) return false;"
  when Types::Variant
    if aggregate_field_creates_cycle?(type, outer_c)
      lines << "#{pad}if (#{left} != #{right}) return false;"
    else
      lines << "#{pad}if (!mt_variant_eq_#{named_type_c_name(type)}(#{left}, #{right})) return false;"
    end
  when Types::VariantArmPayload
    if aggregate_field_creates_cycle?(type.variant_type, outer_c)
      lines << "#{pad}if (#{left} != #{right}) return false;"
    else
      lines << "#{pad}if (!mt_struct_eq_#{named_type_c_name(type)}(#{left}, #{right})) return false;"
    end
  when Types::Struct
    if aggregate_field_creates_cycle?(type, outer_c)
      lines << "#{pad}if (#{left} != #{right}) return false;"
    else
      lines << "#{pad}if (!mt_struct_eq_#{named_type_c_name(type)}(#{left}, #{right})) return false;"
    end
  when Types::Nullable
    if c_backend_pointer_like_type?(type.base)
      lines << "#{pad}if (#{left} != #{right}) return false;"
    else
      lines << "#{pad}if (#{left}.has_value != #{right}.has_value) return false;"
      lines << "#{pad}if (#{left}.has_value) {"
      emit_field_equality_guards(lines, "#{left}.value", "#{right}.value", type.base, outer_c:, indent: indent + 1)
      lines << "#{pad}}"
    end
  else
    if array_type?(type)
      count = array_length(type)
      lines << "#{pad}for (uintptr_t index = 0; index < #{count}; index++) {"
      emit_field_equality_guards(lines, "#{left}[index]", "#{right}[index]", array_element_type(type), outer_c:, indent: indent + 1)
      lines << "#{pad}}"
    else
      lines << "#{pad}if (#{left} != #{right}) return false;"
    end
  end
end

#emit_foreign_temp_cstr_helpersObject



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
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 329

def emit_foreign_temp_cstr_helpers
  lines = []

  if emitted_functions.any? { |function| function_uses_named_call?(function, %w[mt_foreign_str_to_cstr_temp]) }
    lines.concat([
      "static const char* mt_foreign_str_to_cstr_temp(mt_str value) {",
      "#{INDENT}char* data = (char*)malloc(value.len + 1);",
      "#{INDENT}uintptr_t index = 0;",
      "#{INDENT}if (data == NULL) mt_fatal(\"foreign str temporary allocation failed\");",
      "#{INDENT}while (index < value.len) {",
      "#{INDENT * 2}data[index] = value.data[index];",
      "#{INDENT * 2}index++;",
      "#{INDENT}}",
      "#{INDENT}data[value.len] = '\\0';",
      "#{INDENT}return data;",
      "}",
    ])
  end

  if emitted_functions.any? { |function| function_uses_named_call?(function, %w[mt_free_foreign_cstr_temp]) }
    lines << "" unless lines.empty?
    lines.concat([
      "static void mt_free_foreign_cstr_temp(const char* value) {",
      "#{INDENT}free((void*)value);",
      "}",
    ])
  end

  if emitted_functions.any? { |function| function_uses_named_call?(function, %w[mt_foreign_strs_to_cstrs_temp]) }
    lines << "" unless lines.empty?
    lines.concat([
      "static void mt_foreign_strs_to_cstrs_temp(mt_span_str values, char*** items_out, char** data_out, uintptr_t* len_out) {",
      "#{INDENT}uintptr_t total_bytes = 0;",
      "#{INDENT}uintptr_t index = 0;",
      "#{INDENT}uintptr_t offset = 0;",
      "#{INDENT}char** items = NULL;",
      "#{INDENT}char* data = NULL;",
      "#{INDENT}while (index < values.len) {",
      "#{INDENT * 2}total_bytes += values.data[index].len + 1;",
      "#{INDENT * 2}index++;",
      "#{INDENT}}",
      "#{INDENT}if (values.len > 0) {",
      "#{INDENT * 2}items = (char**)malloc(values.len * sizeof(char*));",
      "#{INDENT * 2}if (items == NULL) mt_fatal(\"foreign string-list temporary allocation failed\");",
      "#{INDENT}}",
      "#{INDENT}if (total_bytes > 0) {",
      "#{INDENT * 2}data = (char*)malloc(total_bytes);",
      "#{INDENT * 2}if (data == NULL) {",
      "#{INDENT * 3}free(items);",
      "#{INDENT * 3}mt_fatal(\"foreign string-list temporary allocation failed\");",
      "#{INDENT * 2}}",
      "#{INDENT}}",
      "#{INDENT}index = 0;",
      "#{INDENT}while (index < values.len) {",
      "#{INDENT * 2}mt_str value = values.data[index];",
      "#{INDENT * 2}uintptr_t byte_index = 0;",
      "#{INDENT * 2}items[index] = data + offset;",
      "#{INDENT * 2}while (byte_index < value.len) {",
      "#{INDENT * 3}data[offset + byte_index] = value.data[byte_index];",
      "#{INDENT * 3}byte_index++;",
      "#{INDENT * 2}}",
      "#{INDENT * 2}data[offset + value.len] = '\\0';",
      "#{INDENT * 2}offset += value.len + 1;",
      "#{INDENT * 2}index++;",
      "#{INDENT}}",
      "#{INDENT}*items_out = items;",
      "#{INDENT}*data_out = data;",
      "#{INDENT}*len_out = values.len;",
      "}",
    ])
  end

  if emitted_functions.any? { |function| function_uses_named_call?(function, %w[mt_free_foreign_cstrs_temp]) }
    lines << "" unless lines.empty?
    lines.concat([
      "static void mt_free_foreign_cstrs_temp(char** items, char* data) {",
      "#{INDENT}free(items);",
      "#{INDENT}free(data);",
      "}",
    ])
  end

  lines
end

#emit_nullable_array_index_helper(type) ⇒ Object



617
618
619
620
621
622
623
624
625
626
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 617

def emit_nullable_array_index_helper(type)
  helper_name = nullable_array_index_helper_name(type)
  params = [c_declaration(pointer_to(array_element_type(type)), 'array'), c_declaration(Types::Registry.primitive('ptr_uint'), 'index')].join(', ')
  [
    "static inline #{c_function_declaration(pointer_to(array_element_type(type)), helper_name, params)} {",
    "#{INDENT}if (index >= #{array_length(type)}) return NULL;",
    "#{INDENT}return &array[index];",
    "}",
  ]
end

#emit_nullable_span_index_helper(type) ⇒ Object



628
629
630
631
632
633
634
635
636
637
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 628

def emit_nullable_span_index_helper(type)
  helper_name = nullable_span_index_helper_name(type)
  params = [c_declaration(type, 'span'), c_declaration(Types::Registry.primitive('ptr_uint'), 'index')].join(', ')
  [
    "static inline #{c_function_declaration(pointer_to(type.element_type), helper_name, params)} {",
    "#{INDENT}if (index >= span.len) return NULL;",
    "#{INDENT}return &span.data[index];",
    "}",
  ]
end

#emit_parallel_for_helperObject



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
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 228

def emit_parallel_for_helper
  [
    "typedef struct {",
    "#{INDENT}void (*work)(void* data, int64_t start, int64_t end);",
    "#{INDENT}void* data;",
    "#{INDENT}int64_t start;",
    "#{INDENT}int64_t end;",
    "} mt_pfor_chunk;",
    "",
    "static void mt_pfor_runner(void* arg) {",
    "#{INDENT}mt_pfor_chunk* chunk = (mt_pfor_chunk*)arg;",
    "#{INDENT}chunk->work(chunk->data, chunk->start, chunk->end);",
    "}",
    "",
    "static void mt_parallel_for(void (*work)(void* data, int64_t start, int64_t end), void* data, int64_t count) {",
    "#{INDENT}if (count <= 0) return;",
    "#{INDENT}uv_cpu_info_t* cpu_info;",
    "#{INDENT}int ncpu = 1;",
    "#{INDENT}if (uv_cpu_info(&cpu_info, &ncpu) == 0) {",
    "#{INDENT * 2}uv_free_cpu_info(cpu_info, ncpu);",
    "#{INDENT}}",
    "#{INDENT}if (ncpu < 1) ncpu = 1;",
    "#{INDENT}if (ncpu > 64) ncpu = 64;",
    "#{INDENT}if (count < (int64_t)ncpu) ncpu = (int)count;",
    "#{INDENT}int64_t chunk_size = (count + ncpu - 1) / ncpu;",
    "#{INDENT}mt_pfor_chunk chunks[64];",
    "#{INDENT}uv_thread_t threads[64];",
    "#{INDENT}int nworkers = 0;",
    "#{INDENT}for (int t = 1; t < ncpu; t++) {",
    "#{INDENT * 2}int64_t s = t * chunk_size;",
    "#{INDENT * 2}int64_t e = s + chunk_size;",
    "#{INDENT * 2}if (e > count) e = count;",
    "#{INDENT * 2}if (s >= count) break;",
    "#{INDENT * 2}chunks[nworkers].work = work;",
    "#{INDENT * 2}chunks[nworkers].data = data;",
    "#{INDENT * 2}chunks[nworkers].start = s;",
    "#{INDENT * 2}chunks[nworkers].end = e;",
    "#{INDENT * 2}uv_thread_create(&threads[nworkers], mt_pfor_runner, &chunks[nworkers]);",
    "#{INDENT * 2}nworkers++;",
    "#{INDENT}}",
    "#{INDENT}int64_t first_end = chunk_size < count ? chunk_size : count;",
    "#{INDENT}work(data, 0, first_end);",
    "#{INDENT}for (int t = 0; t < nworkers; t++) {",
    "#{INDENT * 2}uv_thread_join(&threads[t]);",
    "#{INDENT}}",
    "}",
  ]
end

#emit_spawn_all_helperObject



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
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 277

def emit_spawn_all_helper
  [
    "typedef struct {",
    "#{INDENT}void (*work)(void* data);",
    "#{INDENT}void* data;",
    "} mt_spawn_item;",
    "",
    "static void mt_spawn_item_runner(void* arg) {",
    "#{INDENT}mt_spawn_item* item = (mt_spawn_item*)arg;",
    "#{INDENT}item->work(item->data);",
    "}",
    "",
    "static void mt_spawn_all(mt_spawn_item* items, int count) {",
    "#{INDENT}if (count <= 0) return;",
    "#{INDENT}uv_thread_t threads[64];",
    "#{INDENT}int nworkers = 0;",
    "#{INDENT}for (int t = 1; t < count && nworkers < 63; t++) {",
    "#{INDENT * 2}uv_thread_create(&threads[nworkers], mt_spawn_item_runner, &items[t]);",
    "#{INDENT * 2}nworkers++;",
    "#{INDENT}}",
    "#{INDENT}items[0].work(items[0].data);",
    "#{INDENT}for (int t = 0; t < nworkers; t++) {",
    "#{INDENT * 2}uv_thread_join(&threads[t]);",
    "#{INDENT}}",
    "#{INDENT}for (int t = nworkers + 1; t < count; t++) {",
    "#{INDENT * 2}items[t].work(items[t].data);",
    "#{INDENT}}",
    "}",
  ]
end

#emit_str_buffer_helpersObject



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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 510

def emit_str_buffer_helpers
  lines = []

  if emitted_functions.any? { |function| function_uses_named_call?(function, %w[mt_str_buffer_len mt_str_buffer_as_cstr mt_str_buffer_append]) }
    lines.concat([
      "static uintptr_t mt_str_buffer_len(char* data, uintptr_t cap, uintptr_t* len, bool* dirty) {",
      "#{INDENT}if (*dirty) {",
      "#{INDENT * 2}uintptr_t current = 0;",
      "#{INDENT * 2}while (current < cap + 1 && data[current] != '\\0') {",
      "#{INDENT * 3}current++;",
      "#{INDENT * 2}}",
      "#{INDENT * 2}if (current > cap) mt_fatal(\"str_buffer text requires a trailing NUL within capacity\");",
      "#{INDENT * 2}if (!mt_is_valid_utf8(data, current)) mt_fatal(\"str_buffer text must be valid UTF-8\");",
      "#{INDENT * 2}*len = current;",
      "#{INDENT * 2}*dirty = false;",
      "#{INDENT}}",
      "#{INDENT}return *len;",
      "}",
    ])
  end

  if emitted_functions.any? { |function| function_uses_named_call?(function, %w[mt_str_buffer_as_cstr]) }
    lines << "" unless lines.empty?
    lines.concat([
      "static const char* mt_str_buffer_as_cstr(char* data, uintptr_t cap, uintptr_t* len, bool* dirty) {",
      "#{INDENT}(void)mt_str_buffer_len(data, cap, len, dirty);",
      "#{INDENT}return data;",
      "}",
    ])
  end

  if emitted_functions.any? { |function| function_uses_named_call?(function, %w[mt_str_buffer_clear]) }
    lines << "" unless lines.empty?
    lines.concat([
      "static void mt_str_buffer_clear(char* data, uintptr_t cap, uintptr_t* len, bool* dirty) {",
      "#{INDENT}memset(data, 0, cap + 1);",
      "#{INDENT}*len = 0;",
      "#{INDENT}*dirty = false;",
      "}",
    ])
  end

  if emitted_functions.any? { |function| function_uses_named_call?(function, %w[mt_str_buffer_assign]) }
    lines << "" unless lines.empty?
    lines.concat([
      "static void mt_str_buffer_assign(mt_str value, char* data, uintptr_t cap, uintptr_t* len, bool* dirty) {",
      "#{INDENT}if (value.len > cap) mt_fatal(\"str_buffer.assign exceeds capacity\");",
      "#{INDENT}memcpy(data, value.data, value.len);",
      "#{INDENT}data[value.len] = '\\0';",
      "#{INDENT}if (value.len < cap + 1) memset(data + value.len + 1, 0, cap - value.len);",
      "#{INDENT}*len = value.len;",
      "#{INDENT}*dirty = false;",
      "}",
    ])
  end

  if emitted_functions.any? { |function| function_uses_named_call?(function, %w[mt_str_buffer_append]) }
    lines << "" unless lines.empty?
    lines.concat([
      "static void mt_str_buffer_append(mt_str value, char* data, uintptr_t cap, uintptr_t* len, bool* dirty) {",
      "#{INDENT}uintptr_t current = mt_str_buffer_len(data, cap, len, dirty);",
      "#{INDENT}if (value.len > cap - current) mt_fatal(\"str_buffer.append exceeds capacity\");",
      "#{INDENT}memcpy(data + current, value.data, value.len);",
      "#{INDENT}current += value.len;",
      "#{INDENT}data[current] = '\\0';",
      "#{INDENT}*len = current;",
      "#{INDENT}*dirty = false;",
      "}",
    ])
  end

  if emitted_functions.any? { |function| function_uses_named_call?(function, %w[mt_str_buffer_prepare_write]) }
    lines << "" unless lines.empty?
    lines.concat([
      "static char* mt_str_buffer_prepare_write(char* data, uintptr_t cap, bool* dirty) {",
      "#{INDENT}data[cap] = '\\0';",
      "#{INDENT}*dirty = true;",
      "#{INDENT}return data;",
      "}",
    ])
  end

  lines
end

#emit_str_concat_helperObject



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 45

def emit_str_concat_helper
  [
    "#define MT_STR_CONCAT_BUF_SIZE 65536",
    "",
    "static _Thread_local char mt_str_concat_buf[MT_STR_CONCAT_BUF_SIZE];",
    "static _Thread_local uintptr_t mt_str_concat_offset = 0;",
    "",
    "static mt_str mt_str_concat(mt_str a, mt_str b) {",
    "#{INDENT}uintptr_t total = a.len + b.len;",
    "#{INDENT}if (total > MT_STR_CONCAT_BUF_SIZE) mt_fatal(\"str concatenation exceeds the scratch buffer budget\");",
    "#{INDENT}if (mt_str_concat_offset + total > MT_STR_CONCAT_BUF_SIZE) {",
    "#{INDENT * 2}mt_str_concat_offset = 0;",
    "#{INDENT}}",
    "#{INDENT}char* buf = mt_str_concat_buf + mt_str_concat_offset;",
    "#{INDENT}if (a.len > 0) memcpy(buf, a.data, a.len);",
    "#{INDENT}if (b.len > 0) memcpy(buf + a.len, b.data, b.len);",
    "#{INDENT}mt_str_concat_offset += total;",
    "#{INDENT}return (mt_str){ .data = buf, .len = total };",
    "}",
  ]
end

#emit_str_equality_helperObject



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 33

def emit_str_equality_helper
  [
    "static bool mt_str_equal(mt_str left, mt_str right) {",
    "#{INDENT}if (left.len != right.len) return false;",
    "#{INDENT}for (uintptr_t index = 0; index < left.len; index++) {",
    "#{INDENT * 2}if (left.data[index] != right.data[index]) return false;",
    "#{INDENT}}",
    "#{INDENT}return true;",
    "}",
  ]
end

#emit_str_literal_constants(literals) ⇒ Object



639
640
641
642
643
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 639

def emit_str_literal_constants(literals)
  literals.each_with_index.map do |value, i|
    "static const mt_str #{str_literal_name(i)} = { .data = #{value.inspect}, .len = #{value.bytesize} };"
  end
end

#emit_struct_equality_helper(struct_decl_or_type) ⇒ Object



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
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 122

def emit_struct_equality_helper(struct_decl_or_type)
  if struct_decl_or_type.is_a?(IR::StructDecl)
    outer_c = struct_decl_or_type.linkage_name
    fields = struct_decl_or_type.fields
  elsif struct_decl_or_type.is_a?(Types::VariantArmPayload)
    payload = struct_decl_or_type
    outer_c = named_type_c_name(payload)
    arm_fields = payload.variant_type.arm(payload.arm_name) || {}
    fields = arm_fields.map { |name, field_type| IR::Field.new(name:, type: field_type) }
  else
    outer_c = named_type_c_name(struct_decl_or_type)
    fields = struct_decl_or_type.fields.map { |name, field_type| IR::Field.new(name:, type: field_type) }
  end

  lines = ["static bool mt_struct_eq_#{outer_c}(struct #{outer_c} left, struct #{outer_c} right) {"]
  fields.each do |field|
    emit_field_equality_guards(
      lines,
      "left.#{sanitize_c_identifier(field.name)}",
      "right.#{sanitize_c_identifier(field.name)}",
      field.type,
      outer_c:,
    )
  end
  lines << "#{INDENT}return true;"
  lines << "}"
  lines
end

#emit_struct_equality_helpersObject



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 105

def emit_struct_equality_helpers
  struct_decls_by_linkage = (emitted_aggregate_structs + collect_generic_struct_decls).each_with_object({}) { |decl, map| map[decl.linkage_name] = decl }
  struct_equality_types
    .filter_map do |type|
      if type.is_a?(Types::VariantArmPayload)
        type
      elsif struct_decls_by_linkage.key?(named_type_c_name(type))
        struct_decls_by_linkage[named_type_c_name(type)]
      elsif type.is_a?(Types::Struct)
        # External structs (raw ABI bindings) are not lowered into
        # @program.structs, but their field layout is still known.
        type
      end
    end
    .flat_map { |decl_or_type| emit_struct_equality_helper(decl_or_type) }
end

#emit_utf8_validation_helpersObject



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
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 450

def emit_utf8_validation_helpers
  [
    "static bool mt_is_utf8_continuation_byte(unsigned char byte) {",
    "#{INDENT}return (byte & 0xC0u) == 0x80u;",
    "}",
    "",
    "static bool mt_is_valid_utf8(const char* data, uintptr_t len) {",
    "#{INDENT}uintptr_t index = 0;",
    "#{INDENT}while (index < len) {",
    "#{INDENT * 2}unsigned char lead = (unsigned char) data[index];",
    "#{INDENT * 2}if (lead < 0x80u) {",
    "#{INDENT * 3}index++;",
    "#{INDENT * 3}continue;",
    "#{INDENT * 2}}",
    "#{INDENT * 2}if (lead < 0xC2u) return false;",
    "#{INDENT * 2}if (lead < 0xE0u) {",
    "#{INDENT * 3}if (index + 1 >= len) return false;",
    "#{INDENT * 3}unsigned char byte1 = (unsigned char) data[index + 1];",
    "#{INDENT * 3}if (!mt_is_utf8_continuation_byte(byte1)) return false;",
    "#{INDENT * 3}index += 2;",
    "#{INDENT * 3}continue;",
    "#{INDENT * 2}}",
    "#{INDENT * 2}if (lead < 0xF0u) {",
    "#{INDENT * 3}if (index + 2 >= len) return false;",
    "#{INDENT * 3}unsigned char byte1 = (unsigned char) data[index + 1];",
    "#{INDENT * 3}unsigned char byte2 = (unsigned char) data[index + 2];",
    "#{INDENT * 3}if (lead == 0xE0u) {",
    "#{INDENT * 4}if (byte1 < 0xA0u || byte1 > 0xBFu) return false;",
    "#{INDENT * 3}} else if (lead == 0xEDu) {",
    "#{INDENT * 4}if (byte1 < 0x80u || byte1 > 0x9Fu) return false;",
    "#{INDENT * 3}} else if (!mt_is_utf8_continuation_byte(byte1)) {",
    "#{INDENT * 4}return false;",
    "#{INDENT * 3}}",
    "#{INDENT * 3}if (!mt_is_utf8_continuation_byte(byte2)) return false;",
    "#{INDENT * 3}index += 3;",
    "#{INDENT * 3}continue;",
    "#{INDENT * 2}}",
    "#{INDENT * 2}if (lead < 0xF5u) {",
    "#{INDENT * 3}if (index + 3 >= len) return false;",
    "#{INDENT * 3}unsigned char byte1 = (unsigned char) data[index + 1];",
    "#{INDENT * 3}unsigned char byte2 = (unsigned char) data[index + 2];",
    "#{INDENT * 3}unsigned char byte3 = (unsigned char) data[index + 3];",
    "#{INDENT * 3}if (lead == 0xF0u) {",
    "#{INDENT * 4}if (byte1 < 0x90u || byte1 > 0xBFu) return false;",
    "#{INDENT * 3}} else if (lead == 0xF4u) {",
    "#{INDENT * 4}if (byte1 < 0x80u || byte1 > 0x8Fu) return false;",
    "#{INDENT * 3}} else if (!mt_is_utf8_continuation_byte(byte1)) {",
    "#{INDENT * 4}return false;",
    "#{INDENT * 3}}",
    "#{INDENT * 3}if (!mt_is_utf8_continuation_byte(byte2) || !mt_is_utf8_continuation_byte(byte3)) return false;",
    "#{INDENT * 3}index += 4;",
    "#{INDENT * 3}continue;",
    "#{INDENT * 2}}",
    "#{INDENT * 2}return false;",
    "#{INDENT}}",
    "#{INDENT}return true;",
    "}",
  ]
end

#emit_variant_equality_helper(variant_decl) ⇒ Object



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
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 74

def emit_variant_equality_helper(variant_decl)
  outer_c = variant_decl.linkage_name
  lines = ["static bool mt_variant_eq_#{outer_c}(struct #{outer_c} left, struct #{outer_c} right) {"]
  lines << "#{INDENT}if (left.kind != right.kind) return false;"
  lines << "#{INDENT}switch (left.kind) {"

  variant_decl.arms.each do |arm|
    lines << "#{INDENT * 2}case #{outer_c}_kind_#{arm.name}:"
    if arm.fields.empty?
      lines << "#{INDENT * 3}return true;"
    else
      arm.fields.each do |field|
        emit_field_equality_guards(
          lines,
          "left.data.#{sanitize_c_identifier(arm.name)}.#{sanitize_c_identifier(field.name)}",
          "right.data.#{sanitize_c_identifier(arm.name)}.#{sanitize_c_identifier(field.name)}",
          field.type,
          outer_c:,
          indent: 3,
        )
      end
      lines << "#{INDENT * 3}return true;"
    end
  end

  lines << "#{INDENT * 2}default: return true;"
  lines << "#{INDENT}}"
  lines << "}"
  lines
end

#emit_variant_equality_helpersObject



67
68
69
70
71
72
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 67

def emit_variant_equality_helpers
  variant_decls_by_linkage = (emitted_aggregate_variants + collect_generic_variant_decls).each_with_object({}) { |decl, map| map[decl.linkage_name] = decl }
  variant_equality_types
    .filter_map { |type| variant_decls_by_linkage[named_type_c_name(type)] }
    .flat_map { |variant_decl| emit_variant_equality_helper(variant_decl) }
end

#str_literal_name(index) ⇒ Object



645
646
647
# File 'lib/milk_tea/core/c_backend/runtime_helpers.rb', line 645

def str_literal_name(index)
  "mt_str_lit_#{index}"
end