-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathffi.R
More file actions
2476 lines (2288 loc) · 67.4 KB
/
ffi.R
File metadata and controls
2476 lines (2288 loc) · 67.4 KB
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
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Rtinycc - TinyCC for R
# Copyright (C) 2025-2026 Sounkou Mahamane Toure
# SPDX-License-Identifier: GPL-3.0-or-later
# FFI Class and High-Level API
# Bun-style FFI with API mode compilation
# FFI object class
new_rtinycc_symbol_return_spec <- function(
type,
type_info,
length_arg = NULL,
free = NULL
) {
structure(
list(
type = type,
type_info = type_info,
length_arg = length_arg,
free = free
),
class = c("rtinycc_symbol_return_spec", "rtinycc_symbol_spec_component")
)
}
new_rtinycc_bound_symbol <- function(
name,
args,
arg_type_info,
returns,
return_spec,
variadic = FALSE,
varargs = NULL,
varargs_types = NULL,
varargs_type_info = NULL,
varargs_min = NULL,
varargs_max = NULL,
varargs_mode = NULL,
helper_kind = NULL,
helper_operation = NULL
) {
classes <- c("rtinycc_bound_symbol", "rtinycc_symbol_spec")
if (!is.null(helper_kind)) {
classes <- c(
str_interp("rtinycc_helper_symbol_{helper_kind}"),
"rtinycc_helper_symbol",
classes
)
}
structure(
list(
name = name,
args = args,
arg_type_info = arg_type_info,
returns = returns,
return_spec = return_spec,
variadic = variadic,
varargs = varargs,
varargs_types = varargs_types,
varargs_type_info = varargs_type_info,
varargs_min = varargs_min,
varargs_max = varargs_max,
varargs_mode = varargs_mode,
helper_kind = helper_kind,
helper_operation = helper_operation
),
class = classes
)
}
helper_symbol_kind <- function(x) {
if (!inherits(x, "rtinycc_helper_symbol")) {
stop("Expected rtinycc_helper_symbol object", call. = FALSE)
}
x$helper_kind
}
helper_symbol_operation <- function(x) {
if (!inherits(x, "rtinycc_helper_symbol")) {
stop("Expected rtinycc_helper_symbol object", call. = FALSE)
}
x$helper_operation
}
rtinycc_struct_field_spec <- function(ffi, struct_name, field_name) {
if (is.null(ffi$structs) || is.null(ffi$structs[[struct_name]])) {
return(NULL)
}
ffi$structs[[struct_name]][[field_name]] %||% NULL
}
rtinycc_is_bitfield_spec <- function(field_spec) {
is.list(field_spec) && isTRUE(field_spec$bitfield)
}
rtinycc_nested_struct_type_name <- function(field_spec) {
type_name <- if (is.list(field_spec)) {
field_spec$type %||% NULL
} else if (is.character(field_spec) && length(field_spec) == 1) {
field_spec
} else {
NULL
}
if (
is.null(type_name) || !is.character(type_name) || length(type_name) != 1
) {
return(NULL)
}
if (!startsWith(type_name, "struct:")) {
return(NULL)
}
sub("^struct:", "", type_name)
}
is_rtinycc_bound_symbol <- function(x) {
inherits(x, "rtinycc_bound_symbol")
}
as_rtinycc_helper_symbol <- function(
sym_name,
sym,
helper_kind,
helper_operation
) {
out <- as_rtinycc_bound_symbol(sym_name, sym)
new_rtinycc_bound_symbol(
name = out$name,
args = out$args,
arg_type_info = out$arg_type_info,
returns = out$returns,
return_spec = out$return_spec,
variadic = out$variadic,
varargs = out$varargs,
varargs_types = out$varargs_types,
varargs_type_info = out$varargs_type_info,
varargs_min = out$varargs_min,
varargs_max = out$varargs_max,
varargs_mode = out$varargs_mode,
helper_kind = helper_kind,
helper_operation = helper_operation
)
}
as_rtinycc_bound_symbol <- function(sym_name, sym) {
if (is_rtinycc_bound_symbol(sym)) {
return(sym)
}
if (is.null(sym$args)) {
sym$args <- list()
}
variadic <- isTRUE(sym$variadic)
has_varargs <- !is.null(sym$varargs)
has_varargs_types <- !is.null(sym$varargs_types)
if (
!is.null(sym$variadic) &&
(!is.logical(sym$variadic) || length(sym$variadic) != 1)
) {
stop(
"Symbol '",
sym_name,
"' variadic must be TRUE/FALSE",
call. = FALSE
)
}
if (variadic) {
if (length(sym$args) == 0) {
stop(
"Symbol '",
sym_name,
"' variadic functions need at least one fixed argument",
call. = FALSE
)
}
if (has_varargs && has_varargs_types) {
stop(
"Symbol '",
sym_name,
"' cannot set both 'varargs' and 'varargs_types'",
call. = FALSE
)
}
if (!has_varargs && !has_varargs_types) {
stop(
"Symbol '",
sym_name,
"' variadic functions require 'varargs' or 'varargs_types'",
call. = FALSE
)
}
} else if (
has_varargs ||
has_varargs_types ||
!is.null(sym$varargs_min) ||
!is.null(sym$varargs_max)
) {
stop(
"Symbol '",
sym_name,
"' has variadic fields but variadic is not TRUE",
call. = FALSE
)
}
arg_type_info <- lapply(seq_along(sym$args), function(i) {
check_ffi_type(
sym$args[[i]],
str_interp("symbol '{sym_name}' argument {i}")
)
})
for (i in seq_along(arg_type_info)) {
type_info <- arg_type_info[[i]]
if (is_callback_async_type(type_info)) {
sig <- parse_callback_type(type_info)
uses_sexp <- identical(trimws(sig$return_type), "SEXP") ||
identical(trimws(sig$return_type), "sexp") ||
any(trimws(sig$arg_types) %in% c("SEXP", "sexp"))
if (uses_sexp) {
stop(
"Symbol '",
sym_name,
"' async callback argument ",
i,
" cannot use SEXP arguments or return type",
call. = FALSE
)
}
}
}
if (!"returns" %in% names(sym)) {
stop(
"Symbol '",
sym_name,
"' missing 'returns' specification",
call. = FALSE
)
}
if (is.list(sym$returns)) {
if (is.null(sym$returns$type)) {
stop(
"Symbol '",
sym_name,
"' return must include 'type'",
call. = FALSE
)
}
ret_type <- sym$returns$type
ret_info <- check_ffi_type(
ret_type,
str_interp("symbol '{sym_name}' return")
)
if (!is.null(ret_info$kind) && ret_info$kind == "array") {
if (is.null(sym$returns$length_arg)) {
stop(
"Symbol '",
sym_name,
"' array return requires 'length_arg'",
call. = FALSE
)
}
if (
!is.numeric(sym$returns$length_arg) ||
length(sym$returns$length_arg) != 1 ||
is.na(sym$returns$length_arg) ||
sym$returns$length_arg != as.integer(sym$returns$length_arg)
) {
stop(
"Symbol '",
sym_name,
"' array return length_arg must be a single integer",
call. = FALSE
)
}
if (!is.null(sym$args) && length(sym$args) > 0) {
if (
sym$returns$length_arg < 1 ||
sym$returns$length_arg > length(sym$args)
) {
stop(
"Symbol '",
sym_name,
"' array return length_arg out of range",
call. = FALSE
)
}
}
} else if (!is.null(sym$returns$length_arg) || !is.null(sym$returns$free)) {
stop(
"Symbol '",
sym_name,
"' non-array return cannot set length_arg/free",
call. = FALSE
)
}
return_spec <- new_rtinycc_symbol_return_spec(
type = ret_type,
type_info = ret_info,
length_arg = sym$returns$length_arg,
free = isTRUE(sym$returns$free)
)
} else {
ret_info <- check_ffi_type(
sym$returns,
str_interp("symbol '{sym_name}' return")
)
return_spec <- new_rtinycc_symbol_return_spec(
type = sym$returns,
type_info = ret_info
)
}
varargs_type_info <- NULL
if (variadic) {
if (has_varargs_types) {
if (length(sym$varargs_types) == 0) {
stop(
"Symbol '",
sym_name,
"' varargs_types must be non-empty",
call. = FALSE
)
}
varargs_type_info <- lapply(seq_along(sym$varargs_types), function(i) {
vtype <- sym$varargs_types[[i]]
vinfo <- check_ffi_type(
vtype,
str_interp("symbol '{sym_name}' varargs_types {i}")
)
if (!is.null(vinfo$kind) && vinfo$kind != "scalar") {
stop(
"Symbol '",
sym_name,
"' varargs_types ",
i,
" must be a scalar FFI type",
call. = FALSE
)
}
if (
ffi_type_family(vinfo) %in%
c("callback", "callback_async") ||
identical(vtype, "sexp")
) {
stop(
"Symbol '",
sym_name,
"' varargs_types ",
i,
" cannot be callback/sexp",
call. = FALSE
)
}
vinfo
})
if (is.null(sym$varargs_min)) {
sym$varargs_min <- 0L
}
if (is.null(sym$varargs_max)) {
sym$varargs_max <- sym$varargs_min
}
if (
!is.numeric(sym$varargs_min) ||
length(sym$varargs_min) != 1 ||
is.na(sym$varargs_min) ||
sym$varargs_min < 0 ||
sym$varargs_min != as.integer(sym$varargs_min)
) {
stop(
"Symbol '",
sym_name,
"' varargs_min must be a non-negative integer",
call. = FALSE
)
}
if (
!is.numeric(sym$varargs_max) ||
length(sym$varargs_max) != 1 ||
is.na(sym$varargs_max) ||
sym$varargs_max < 0 ||
sym$varargs_max != as.integer(sym$varargs_max)
) {
stop(
"Symbol '",
sym_name,
"' varargs_max must be a non-negative integer",
call. = FALSE
)
}
sym$varargs_min <- as.integer(sym$varargs_min)
sym$varargs_max <- as.integer(sym$varargs_max)
if (sym$varargs_min > sym$varargs_max) {
stop(
"Symbol '",
sym_name,
"' varargs_min must be <= varargs_max",
call. = FALSE
)
}
sym$varargs_mode <- "types"
sym$varargs <- NULL
} else {
if (length(sym$varargs) == 0) {
stop(
"Symbol '",
sym_name,
"' variadic functions require non-empty 'varargs' type list",
call. = FALSE
)
}
max_varargs <- length(sym$varargs)
if (is.null(sym$varargs_min)) {
sym$varargs_min <- max_varargs
}
if (
!is.numeric(sym$varargs_min) ||
length(sym$varargs_min) != 1 ||
is.na(sym$varargs_min) ||
sym$varargs_min < 0 ||
sym$varargs_min > max_varargs ||
sym$varargs_min != as.integer(sym$varargs_min)
) {
stop(
"Symbol '",
sym_name,
"' varargs_min must be a single integer between 0 and length(varargs)",
call. = FALSE
)
}
sym$varargs_min <- as.integer(sym$varargs_min)
sym$varargs_max <- max_varargs
varargs_type_info <- lapply(seq_along(sym$varargs), function(i) {
vtype <- sym$varargs[[i]]
vinfo <- check_ffi_type(
vtype,
str_interp("symbol '{sym_name}' vararg {i}")
)
if (!is.null(vinfo$kind) && vinfo$kind != "scalar") {
stop(
"Symbol '",
sym_name,
"' vararg ",
i,
" must be a scalar FFI type",
call. = FALSE
)
}
if (
ffi_type_family(vinfo) %in%
c("callback", "callback_async") ||
identical(vtype, "sexp")
) {
stop(
"Symbol '",
sym_name,
"' vararg ",
i,
" cannot be callback/sexp",
call. = FALSE
)
}
vinfo
})
sym$varargs_mode <- "prefix"
sym$varargs_types <- NULL
}
} else {
sym$varargs_min <- NULL
sym$varargs_max <- NULL
sym$varargs_types <- NULL
sym$varargs_mode <- NULL
}
new_rtinycc_bound_symbol(
name = sym_name,
args = sym$args,
arg_type_info = arg_type_info,
returns = sym$returns,
return_spec = return_spec,
variadic = variadic,
varargs = sym$varargs,
varargs_types = sym$varargs_types,
varargs_type_info = varargs_type_info,
varargs_min = sym$varargs_min,
varargs_max = sym$varargs_max,
varargs_mode = sym$varargs_mode
)
}
tcc_ffi_object <- function() {
structure(
list(
state = NULL,
symbols = list(),
headers = character(0),
c_code = character(0),
options = character(0),
libraries = character(0),
lib_paths = character(0),
include_paths = character(0),
output = "memory",
compiled = FALSE,
wrapper_symbols = character(0),
globals = list()
),
class = "tcc_ffi"
)
}
#' Create a new FFI compilation context
#'
#' Initialize a Bun-style FFI context for API-mode compilation.
#' This is the entry point for the modern FFI API.
#'
#' @return A tcc_ffi object with chaining support
#' @export
#' @examples
#' ffi <- tcc_ffi()
tcc_ffi <- function() {
tcc_ffi_object()
}
#' Set output type for FFI compilation
#'
#' @param ffi A tcc_ffi object
#' @param output One of "memory", "dll", "exe"
#' @return Updated tcc_ffi object (for chaining)
#' @export
tcc_output <- function(ffi, output = c("memory", "dll", "exe")) {
if (!inherits(ffi, "tcc_ffi")) {
stop("Expected tcc_ffi object", call. = FALSE)
}
output <- match.arg(output)
ffi$output <- output
ffi
}
#' Add include path to FFI context
#'
#' @param ffi A tcc_ffi object
#' @param path Include directory path
#' @return Updated tcc_ffi object (for chaining)
#' @export
tcc_include <- function(ffi, path) {
if (!inherits(ffi, "tcc_ffi")) {
stop("Expected tcc_ffi object", call. = FALSE)
}
ffi$include_paths <- c(ffi$include_paths, path)
ffi
}
#' Add library path to FFI context
#'
#' @param ffi A tcc_ffi object
#' @param path Library directory path
#' @return Updated tcc_ffi object (for chaining)
#' @export
tcc_library_path <- function(ffi, path) {
if (!inherits(ffi, "tcc_ffi")) {
stop("Expected tcc_ffi object", call. = FALSE)
}
ffi$lib_paths <- c(ffi$lib_paths, path)
ffi
}
#' Add TinyCC compiler options to FFI context
#'
#' Append raw options that are passed to `tcc_set_options()` before compiling
#' generated wrappers (for example `"-O2"` or `"-Wall"`).
#'
#' @param ffi A tcc_ffi object
#' @param options Character vector of option fragments
#' @return Updated tcc_ffi object (for chaining)
#' @export
tcc_options <- function(ffi, options) {
if (!inherits(ffi, "tcc_ffi")) {
stop("Expected tcc_ffi object", call. = FALSE)
}
if (missing(options)) {
stop("`options` must be provided", call. = FALSE)
}
if (is.null(options)) {
ffi$options <- character(0)
return(ffi)
}
opts <- as.character(options)
if (!length(opts)) {
stop("`options` must not be empty", call. = FALSE)
}
opts <- trimws(opts)
if (any(!nzchar(opts))) {
stop("`options` entries must be non-empty strings", call. = FALSE)
}
ffi$options <- c(ffi$options, opts)
ffi
}
rtinycc_exact_library_name <- function(path) {
str_interp(":{basename(path)}")
}
rtinycc_add_library_file <- function(ffi, path) {
ffi$lib_paths <- c(ffi$lib_paths, dirname(path))
ffi$libraries <- c(ffi$libraries, rtinycc_exact_library_name(path))
ffi
}
#' Add library to link against
#'
#' @param ffi A tcc_ffi object
#' @param library Library name (e.g., "m", "sqlite3") or a path to a
#' shared library (e.g., "libm.so.6"). When a path or platform library file
#' name is provided, the library directory is added automatically and TinyCC
#' is asked to link that exact file name. This keeps versioned runtime
#' libraries such as `libm.so.6` distinct from generic linker names such as
#' `m`/`libm.so`.
#' @return Updated tcc_ffi object (for chaining)
#' @export
tcc_library <- function(ffi, library) {
if (!inherits(ffi, "tcc_ffi")) {
stop("Expected tcc_ffi object", call. = FALSE)
}
libs <- as.character(library)
for (lib in libs) {
if (!nzchar(lib)) {
next
}
lib_name <- lib
# If a path or a file name with extension is provided, resolve it and link
# the exact file name via TinyCC's -l:<filename> path. Do not collapse a
# versioned runtime file such as libm.so.6 to -lm: some systems, including
# CRAN's Fedora flavor, do not install the unversioned development symlink.
if (file.exists(lib) || grepl("[/\\\\]", lib)) {
if (!file.exists(lib)) {
found_path <- tcc_find_library(lib)
if (is.null(found_path)) {
stop("Library not found: ", lib, call. = FALSE)
}
lib <- found_path
}
ffi <- rtinycc_add_library_file(ffi, lib)
next
} else if (grepl("\\.(so|dylib|dll)(\\..*)?$", lib, ignore.case = TRUE)) {
found_path <- tcc_find_library(lib)
if (is.null(found_path)) {
stop("Library not found: ", lib, call. = FALSE)
}
ffi <- rtinycc_add_library_file(ffi, found_path)
next
}
if (nzchar(lib_name)) {
ffi$libraries <- c(ffi$libraries, lib_name)
}
}
ffi
}
#' Declare a global variable getter
#'
#' Register a global C symbol so the compiled object exposes getter/setter
#' functions `global_<name>_get()` and `global_<name>_set()`.
#'
#' @details
#' Globals are limited to scalar FFI types. Array types are rejected.
#' Scalar conversions follow the same rules as wrapper arguments:
#'
#' - Integer inputs (`i8`, `i16`, `i32`, `u8`, `u16`) must be finite and
#' within range; `NA` values error.
#' - Large integer types (`i64`, `u32`, `u64`) are mediated through R numeric
#' (double). Values must be integer-valued and within range; for `i64`/`u64`
#' only exact integers up to $2^53$ are accepted.
#' - Getter wrappers for `i64`/`u64` warn when the stored value exceeds R's
#' exact integer range for numeric vectors.
#' - `bool` rejects `NA` logicals.
#'
#' Ownership notes:
#'
#' - `ptr` globals store the raw address from an external pointer. If the
#' external pointer owns memory, keep it alive; otherwise the pointer may
#' be freed while the global still points to it.
#' - `cstring` globals store a borrowed pointer to R's string data
#' (UTF-8 translation). Do not free it; for C-owned strings prefer a `ptr`
#' global and manage lifetime explicitly (e.g., with `tcc_cstring()`).
#'
#' @note
#' Global helpers are generated inside the compiled TCC unit. Recompiling
#' creates a new instance of the global variable; existing compiled objects
#' continue to refer to their own copy.
#'
#' @param ffi A tcc_ffi object
#' @param name Global symbol name
#' @param type FFI type for the global (scalar types only)
#' @return Updated tcc_ffi object (for chaining)
#' @export
#'
#' @examples
#' ffi <- tcc_ffi() |>
#' tcc_source("int global_counter = 7;") |>
#' tcc_global("global_counter", "i32") |>
#' tcc_compile()
#' ffi$global_global_counter_get()
tcc_global <- function(ffi, name, type) {
if (!inherits(ffi, "tcc_ffi")) {
stop("Expected tcc_ffi object", call. = FALSE)
}
if (!is.character(name) || length(name) != 1 || !nzchar(name)) {
stop("Global name must be a non-empty string", call. = FALSE)
}
if (!is.character(type) || length(type) != 1 || !nzchar(type)) {
stop("Global type must be a non-empty string", call. = FALSE)
}
type_info <- check_ffi_type(type, "global")
if (!is.null(type_info$kind) && type_info$kind == "array") {
stop("Global type cannot be an array type", call. = FALSE)
}
if (type == "void") {
stop("Global type cannot be void", call. = FALSE)
}
if (is.null(ffi$globals)) {
ffi$globals <- list()
}
ffi$globals[[name]] <- type
ffi
}
#' Add C headers
#'
#' @param ffi A tcc_ffi object
#' @param header Header string or include directive
#' @return Updated tcc_ffi object (for chaining)
#' @export
tcc_header <- function(ffi, header) {
if (!inherits(ffi, "tcc_ffi")) {
stop("Expected tcc_ffi object", call. = FALSE)
}
ffi$headers <- c(ffi$headers, header)
ffi
}
#' Add C source code
#'
#' @param ffi A tcc_ffi object
#' @param code C source code string
#' @return Updated tcc_ffi object (for chaining)
#' @export
tcc_source <- function(ffi, code) {
if (!inherits(ffi, "tcc_ffi")) {
stop("Expected tcc_ffi object", call. = FALSE)
}
ffi$c_code <- c(ffi$c_code, as.character(code))
ffi
}
#' Bind symbols with type specifications
#'
#' Define symbols with Bun-style type specifications for API mode.
#' This is the core of the declarative FFI API.
#'
#' @param ffi A tcc_ffi object
#' @param ... Named list of symbol definitions. Each definition is a list with:
#' \itemize{
#' \item args: List of fixed FFI argument types (e.g., list("i32", "f64"))
#' \item returns: FFI type for return value (e.g., "f64", "cstring")
#' \item variadic: Set TRUE for C varargs functions
#' \item varargs: Legacy typed variadic tail (exact/prefix mode)
#' \item varargs_types: Allowed scalar FFI types for true variadic tails
#' \item varargs_min: Minimum number of trailing varargs
#' \item varargs_max: Maximum number of trailing varargs (required for
#' true variadic mode, defaults to \code{varargs_min})
#' \item code: Optional C code for the symbol (for embedded functions)
#' }
#' Callback arguments should use the form \code{callback:<signature>} (e.g.,
#' \code{callback:double(double)}). The generated trampoline expects a
#' \code{tcc_callback_ptr(cb)} to the corresponding user-data parameter in
#' the C API. For thread-safe scheduling, use
#' \code{callback_async:<signature>} which enqueues the call on the main
#' thread and returns a default value immediately.
#' @return Updated tcc_ffi object (for chaining)
#' @export
#' @examples
#' ffi <- tcc_ffi() |>
#' tcc_bind(
#' add = list(args = list("i32", "i32"), returns = "i32"),
#' greet = list(args = list("cstring"), returns = "cstring")
#' )
tcc_bind <- function(ffi, ...) {
if (!inherits(ffi, "tcc_ffi")) {
stop("Expected tcc_ffi object", call. = FALSE)
}
symbols <- list(...)
# Validate and normalize each symbol definition into a classed spec.
for (sym_name in names(symbols)) {
ffi$symbols[[sym_name]] <- as_rtinycc_bound_symbol(
sym_name,
symbols[[sym_name]]
)
}
ffi
}
#' Compile FFI bindings
#'
#' Compile the defined symbols into callable functions.
#' This generates C wrapper code and compiles it with TinyCC.
#'
#' @param ffi A tcc_ffi object
#' @param verbose Print compilation info
#' @return A tcc_compiled object with callable functions
#' @export
tcc_compile <- function(ffi, verbose = FALSE) {
if (!inherits(ffi, "tcc_ffi")) {
stop("Expected tcc_ffi object", call. = FALSE)
}
if (
length(ffi$symbols) == 0 &&
length(ffi$structs) == 0 &&
length(ffi$unions) == 0 &&
length(ffi$enums) == 0 &&
length(ffi$globals) == 0
) {
stop(
"No symbols, structs, unions, enums, or globals defined. Use tcc_bind(), tcc_struct(), tcc_union(), tcc_enum(), or tcc_global() first.",
call. = FALSE
)
}
# Generate C code (always R API mode now)
c_code <- generate_ffi_code(
symbols = ffi$symbols,
headers = ffi$headers,
c_code = ffi$c_code,
is_external = FALSE,
structs = ffi$structs,
unions = ffi$unions,
enums = ffi$enums,
globals = ffi$globals,
container_of = ffi$container_of,
field_addr = ffi$field_addr,
struct_raw_access = ffi$struct_raw_access,
introspect = ffi$introspect
)
if (verbose) {
message("Generated C code:\n", c_code)
}
state <- tcc_ffi_create_state(ffi, output = ffi$output)
tcc_ffi_compile_state(
state = state,
c_code = c_code,
libraries = ffi$libraries,
target = "FFI bindings"
)
# Create callable object
compiled <- tcc_compiled_object(
state,
ffi$symbols,
ffi$output,
ffi$structs,
ffi$unions,
ffi$enums,
ffi$globals,
ffi$container_of,
ffi$field_addr,
ffi$struct_raw_access,
ffi$introspect
)
# Store the recipe so the object can be recompiled after deserialization
compiled$.ffi <- ffi
compiled
}
tcc_runtime_library_paths <- function() {
paths <- file.path(R.home("lib"))
if (.Platform$OS.type == "windows") {
# On Windows, R.dll lives in bin/<arch>; TCC needs it for R API symbols.
paths <- c(paths, file.path(R.home(), "bin", .Platform$r_arch))
}
normalizePath(paths, winslash = "/", mustWork = FALSE)
}
tcc_ffi_create_state <- function(ffi, output = ffi$output) {
state <- tcc_state(
output = output,
include_path = c(
tcc_include_paths(),
ffi$include_paths,
file.path(R.home("include"))
),
lib_path = c(
tcc_lib_paths(),
ffi$lib_paths,
tcc_runtime_library_paths()
)
)
if (!is.null(ffi$options) && length(ffi$options) > 0) {
rc <- tcc_set_options(state, paste(ffi$options, collapse = " "))
if (rc < 0) {
stop("Failed to apply TinyCC compiler options", call. = FALSE)
}
}
state
}
tcc_ffi_compile_state <- function(state, c_code, libraries, target) {
for (lib in libraries) {
result <- tcc_add_library(state, lib)
if (result < 0) {
stop(
"Failed to add library '", lib, "' while compiling ", target,
call. = FALSE
)
}
}
# Always link against R's shared library so TCC can resolve
# R API symbols (and any symbols R itself exports).
tcc_add_library(state, "R")
result <- tcc_compile_string(state, c_code)
if (result != 0) {
stop("Failed to compile ", target, call. = FALSE)
}
# Register host symbols for macOS compatibility before relocation.
.Call(RC_libtcc_add_host_symbols, state)
result <- tcc_relocate(state)
if (result != 0) {
stop("Failed to relocate compiled code for ", target, call. = FALSE)
}
invisible(state)
}
infer_variadic_arg_type <- function(x, allowed_types) {
if (inherits(x, "externalptr")) {
if ("ptr" %in% allowed_types) {
return("ptr")
}
stop(
"external pointer variadic argument requires allowed type 'ptr'",
call. = FALSE
)
}
if (is.character(x) && length(x) == 1) {
if ("cstring" %in% allowed_types) {
return("cstring")
}
stop(
"character variadic argument requires allowed type 'cstring'",
call. = FALSE
)
}
if (is.logical(x) && length(x) == 1) {
if ("bool" %in% allowed_types) {
return("bool")
}
stop(
"logical variadic argument requires allowed type 'bool'",
call. = FALSE
)
}
if (is.raw(x) && length(x) == 1) {
if ("u8" %in% allowed_types) {
return("u8")
}
if ("i8" %in% allowed_types) {
return("i8")