Repository navigation
Expand file tree
/
Copy pathcheck-types.R
More file actions
3023 lines (2868 loc) · 81.6 KB
/
Copy pathcheck-types.R
File metadata and controls
3023 lines (2868 loc) · 81.6 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
# ============================================================================
# STANDALONE INPUT VALIDATION MODULE - ROXYGEN2 DOCUMENTED VERSION
# ============================================================================
# This file contains a complete, self-contained type-checking system
# with ALL dependencies included. No external imports required!
#
# PURPOSE: Validate function arguments and provide helpful error messages
# USAGE: source("compat-types-check-standalone-ROXYGEN.R")
# THEN: Use any of the check_*() functions like check_bool(), check_string()
#
# FILE STRUCTURE:
# 1. Type checking predicates (is_* functions)
# 2. Caller introspection (get context information)
# 3. Special NA values (different types of missing data)
# 4. Error messaging (format helpful error messages)
# 5. Main validation functions (check_* functions)
# ============================================================================
# ============================================================================
# SECTION 1: TYPE CHECKING PREDICATES
# ============================================================================
# PURPOSE: Fundamental predicates that test if a value is a specific type
# These return TRUE/FALSE based on what type of value they receive
# Used internally by the check_* validation functions
# ============================================================================
#' Test if a Value is a Boolean (TRUE or FALSE)
#'
#' @title Predicate: Is value a boolean?
#' @description
#' Tests whether a value is EXACTLY a boolean (TRUE or FALSE).
#' This is a fundamental type predicate used internally.
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x is a single TRUE or FALSE value (not NA, not vector)
#' FALSE otherwise
#'
#' @examples
#' is_bool(TRUE) # TRUE
#' is_bool(FALSE) # TRUE
#' is_bool(1) # FALSE (numeric, not boolean)
#' is_bool(c(TRUE, FALSE)) # FALSE (vector, not single)
#' is_bool(NA) # FALSE (NA is not valid)
#'
#' @keywords internal
#'
is_bool <- function(x) {
# TEST 1: Is x a logical type (not numeric, not character)?
is.logical(x) &&
# TEST 2: AND is it exactly length 1 (single value)?
length(x) == 1L &&
# TEST 3: AND is it not NA?
!is.na(x)
}
#' Test if a Value is a Single Character String
#'
#' @title Predicate: Is value a single string?
#' @description
#' Tests whether a value is a SINGLE character string.
#' Can optionally test if it matches a specific string value.
#'
#' @param x Any R value to test
#' @param string Optional string to match exactly. If NULL, any string accepted.
#'
#' @return
#' TRUE if x is a single character string
#' FALSE if x is not a string, is a vector, or is NA
#' If string parameter provided, TRUE only if x matches that exact string
#'
#' @examples
#' is_string("hello") # TRUE
#' is_string("") # TRUE (empty string is still a string)
#' is_string("hello", "hello") # TRUE (matches)
#' is_string("hello", "goodbye") # FALSE (doesn't match)
#' is_string(123) # FALSE (number)
#' is_string(c("a", "b")) # FALSE (vector)
#'
#' @keywords internal
#'
is_string <- function(x, string = NULL) {
# Early return: fail if x is not character, or not length 1, or is NA
if (!is.character(x) || length(x) != 1L || is.na(x)) {
return(FALSE)
}
# If caller provided a string to match against, check for exact match
if (!is.null(string)) {
return(identical(x, string))
}
# x is a valid string
TRUE
}
#' Test if a Value is a Character Vector
#'
#' @title Predicate: Is value a character vector?
#' @description
#' Tests whether a value is a character vector.
#' Accepts vectors of ANY length (0, 1, 2, 3, ...).
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x is a character vector (any length)
#' FALSE if x is not character type
#'
#' @examples
#' is_character("hello") # TRUE
#' is_character(c("a", "b", "c")) # TRUE
#' is_character(c()) # TRUE (empty vector)
#' is_character(123) # FALSE (numeric)
#' is_character(list("a")) # FALSE (list)
#'
#' @keywords internal
#'
is_character <- function(x) {
is.character(x)
}
#' Test if a Value is a Symbol
#'
#' @title Predicate: Is value a symbol?
#' @description
#' Tests whether a value is a symbol (unevaluated variable name).
#' Symbols are created with quote() or in function definitions.
#' Used for metaprogramming (code that operates on code).
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x is a symbol
#' FALSE otherwise
#'
#' @examples
#' is_symbol(quote(x)) # TRUE
#' is_symbol(quote(my_var)) # TRUE
#' is_symbol(x) # FALSE (evaluated)
#' is_symbol("x") # FALSE (string)
#'
#' @keywords internal
#'
is_symbol <- function(x) {
is.symbol(x) || is.name(x)
}
#' Test if a Value is a Call
#'
#' @title Predicate: Is value a call?
#' @description
#' Tests whether a value is a call (unevaluated function call).
#' Calls are created with quote() and represent unevaluated function invocations.
#' Used for metaprogramming.
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x is a call object
#' FALSE otherwise
#'
#' @examples
#' is_call(quote(sum(1, 2))) # TRUE
#' is_call(quote(f(x, y))) # TRUE
#' is_call(sum(1, 2)) # FALSE (already evaluated)
#' is_call(quote(x)) # FALSE (symbol, not call)
#'
#' @keywords internal
#'
is_call <- function(x) {
is.call(x)
}
#' Test if a Value is an Environment
#'
#' @title Predicate: Is value an environment?
#' @description
#' Tests whether a value is an environment object.
#' Environments are advanced R objects that store variables.
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x is an environment
#' FALSE otherwise
#'
#' @examples
#' is_environment(new.env()) # TRUE
#' is_environment(globalenv()) # TRUE
#' is_environment(list()) # FALSE
#'
#' @keywords internal
#'
is_environment <- function(x) {
is.environment(x)
}
#' Test if a Value is a Function
#'
#' @title Predicate: Is value a function?
#' @description
#' Tests whether a value is ANY kind of function.
#' This includes user-defined functions, built-in functions, and primitives.
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x is a function (any type)
#' FALSE otherwise
#'
#' @examples
#' is_function(function(x) x + 1) # TRUE (user-defined)
#' is_function(sum) # TRUE (built-in)
#' is_function(mean) # TRUE (built-in)
#' is_function(123) # FALSE
#'
#' @seealso [is_closure()] for user-defined functions only
#'
#' @keywords internal
#'
is_function <- function(x) {
is.function(x)
}
#' Test if a Value is a Closure
#'
#' @title Predicate: Is value a closure (user-defined function)?
#' @description
#' Tests whether a value is a closure (user-defined function).
#' More restrictive than is_function() - rejects built-in functions and primitives.
#' A closure is a function created with function() { ... }.
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x is a user-defined function (closure)
#' FALSE if x is a built-in, primitive, or not a function
#'
#' @examples
#' is_closure(function(x) x + 1) # TRUE
#' is_closure(sum) # FALSE (built-in)
#' is_closure(mean) # FALSE (built-in)
#' is_closure(123) # FALSE
#'
#' @seealso [is_function()] for all function types
#'
#' @keywords internal
#'
is_closure <- function(x) {
is.function(x) && !is.primitive(x)
}
#' Test if a Value is a Formula
#'
#' @title Predicate: Is value a formula?
#' @description
#' Tests whether a value is a formula object (y ~ x format).
#' Formulas describe relationships between variables and are used in statistical modeling.
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x is a formula object
#' FALSE otherwise
#'
#' @examples
#' is_formula(y ~ x) # TRUE
#' is_formula(y ~ x + z) # TRUE
#' is_formula(~ x) # TRUE (no left side)
#' is_formula("y ~ x") # FALSE (string)
#'
#' @keywords internal
#'
is_formula <- function(x) {
inherits(x, "formula")
}
#' Test if a Value is NULL
#'
#' @title Predicate: Is value NULL?
#' @description
#' Tests whether a value is NULL (complete absence of a value).
#' Different from NA (missing value placeholder).
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x is NULL
#' FALSE otherwise
#'
#' @examples
#' is_null(NULL) # TRUE
#' is_null(NA) # FALSE
#' is_null(list()) # FALSE
#'
#' @keywords internal
#'
is_null <- function(x) {
is.null(x)
}
#' Test if an Argument Was Provided
#'
#' @title Predicate: Was argument provided?
#' @description
#' Tests whether an argument was provided by the caller.
#' Used in functions to detect if a parameter was explicitly supplied.
#'
#' @param x The argument to test (pass unevaluated)
#'
#' @return
#' TRUE if x was not provided to the function
#' FALSE if x was provided
#'
#' @examples
#' # Inside a function definition:
#' my_func <- function(x = 5) {
#' if (is_missing(x)) {
#' # User didn't provide x, using default
#' } else {
#' # User provided x
#' }
#' }
#'
#' @keywords internal
#'
is_missing <- function(x) {
missing(x)
}
#' Test if a Value is Integerish
#'
#' @title Predicate: Is value a whole number?
#' @description
#' Tests whether a value is a whole number (even if stored as decimal type).
#' Checks the actual VALUE, not the storage type.
#' For example, 5.0 returns TRUE (it's a whole number),
#' but 5.5 returns FALSE (has a decimal part).
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x is a whole number with no fractional part
#' FALSE if x has decimals, is not numeric, is NA, or is not length 1
#'
#' @examples
#' is_integerish(5) # TRUE
#' is_integerish(5.0) # TRUE
#' is_integerish(5.5) # FALSE
#' is_integerish(3.14159) # FALSE
#' is_integerish("5") # FALSE
#'
#' @keywords internal
#'
is_integerish <- function(x) {
if (!is.numeric(x) || length(x) != 1 || is.na(x)) {
return(FALSE)
}
x == as.integer(x)
}
#' Test if a Value is a Numeric Vector
#'
#' @title Predicate: Is value a numeric vector?
#' @description
#' Tests whether a value is a numeric vector (integer or double).
#' Accepts vectors of ANY length (0, 1, 2, 3, ...).
#' Returns TRUE for both integer and double storage types.
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x is a numeric vector (any length)
#' FALSE if x is not numeric type
#'
#' @examples
#' is_numeric(5) # TRUE
#' is_numeric(c(1.5, 2.7)) # TRUE
#' is_numeric(1L) # TRUE (integer is numeric)
#' is_numeric("5") # FALSE (character)
#'
#' @keywords internal
#'
is_numeric <- function(x) {
is.numeric(x)
}
#' Test if a Value is an Integer Vector
#'
#' @title Predicate: Is value an integer vector?
#' @description
#' Tests whether a value is a strict integer vector (storage type integer).
#' More restrictive than is_numeric() - rejects doubles even if whole-valued.
#' Accepts vectors of ANY length (0, 1, 2, 3, ...).
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x is an integer vector (any length)
#' FALSE if x is double, character, or other type
#'
#' @examples
#' is_integer_vec(1L) # TRUE
#' is_integer_vec(c(1L, 2L, 3L)) # TRUE
#' is_integer_vec(1) # FALSE (double, not integer)
#' is_integer_vec(1.5) # FALSE
#'
#' @keywords internal
#'
is_integer_vec <- function(x) {
is.integer(x)
}
#' Test if a Value is a Logical Vector
#'
#' @title Predicate: Is value a logical vector?
#' @description
#' Tests whether a value is a logical vector (any length).
#' Unlike is_bool(), accepts vectors and NA values.
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x is a logical vector (any length, may contain NA)
#' FALSE if x is not logical type
#'
#' @examples
#' is_logical(TRUE) # TRUE
#' is_logical(c(TRUE, FALSE, NA)) # TRUE
#' is_logical(logical(0)) # TRUE
#' is_logical(1) # FALSE (numeric)
#'
#' @keywords internal
#'
is_logical <- function(x) {
is.logical(x)
}
#' Test if a Value is a Data Frame
#'
#' @title Predicate: Is value a data.frame?
#' @description
#' Tests whether a value inherits from data.frame.
#' Returns TRUE for data.frames, tibbles, and data.tables.
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x inherits from data.frame
#' FALSE otherwise
#'
#' @examples
#' is_data_frame(data.frame(x = 1)) # TRUE
#' is_data_frame(list(x = 1)) # FALSE
#' is_data_frame(matrix(1:4, 2, 2)) # FALSE
#'
#' @keywords internal
#'
is_data_frame <- function(x) {
inherits(x, "data.frame")
}
#' Test if a Value is a Matrix
#'
#' @title Predicate: Is value a matrix?
#' @description
#' Tests whether a value is a matrix object.
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x is a matrix
#' FALSE otherwise
#'
#' @examples
#' is_matrix(matrix(1:4, 2, 2)) # TRUE
#' is_matrix(data.frame(x = 1)) # FALSE
#' is_matrix(c(1, 2, 3)) # FALSE
#'
#' @keywords internal
#'
is_matrix <- function(x) {
is.matrix(x)
}
#' Test if a Value is a List (Not Data Frame)
#'
#' @title Predicate: Is value a plain list?
#' @description
#' Tests whether a value is a list but NOT a data.frame.
#' Data.frames are technically lists in R, but annotations using "list"
#' always mean a plain list.
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x is a list and not a data.frame
#' FALSE if x is a data.frame, vector, or other type
#'
#' @examples
#' is_list(list(1, 2, 3)) # TRUE
#' is_list(list()) # TRUE
#' is_list(data.frame(x = 1)) # FALSE (data.frame excluded)
#' is_list(c(1, 2, 3)) # FALSE (atomic vector)
#'
#' @keywords internal
#'
is_list <- function(x) {
is.list(x) && !is.data.frame(x)
}
#' Test if a Value is a Factor
#'
#' @title Predicate: Is value a factor?
#' @description
#' Tests whether a value is a factor (categorical variable).
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x is a factor
#' FALSE otherwise
#'
#' @examples
#' is_factor(factor(c("a", "b", "c"))) # TRUE
#' is_factor(c("a", "b", "c")) # FALSE (character, not factor)
#' is_factor(1:3) # FALSE
#'
#' @keywords internal
#'
is_factor <- function(x) {
is.factor(x)
}
#' Test if a Value is a Date
#'
#' @title Predicate: Is value a Date?
#' @description
#' Tests whether a value is a Date object (inherits from "Date").
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x inherits from Date
#' FALSE otherwise
#'
#' @examples
#' is_date(Sys.Date()) # TRUE
#' is_date(as.Date("2024-01-01")) # TRUE
#' is_date("2024-01-01") # FALSE (character)
#' is_date(Sys.time()) # FALSE (POSIXct)
#'
#' @keywords internal
#'
is_date <- function(x) {
inherits(x, "Date")
}
#' Test if a Value is a POSIXct Datetime
#'
#' @title Predicate: Is value a POSIXct?
#' @description
#' Tests whether a value is a POSIXct datetime object.
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x inherits from POSIXct
#' FALSE otherwise
#'
#' @examples
#' is_posixct(Sys.time()) # TRUE
#' is_posixct(as.POSIXct("2024-01-01")) # TRUE
#' is_posixct(Sys.Date()) # FALSE (Date, not POSIXct)
#' is_posixct("2024-01-01") # FALSE (character)
#'
#' @keywords internal
#'
is_posixct <- function(x) {
inherits(x, "POSIXct")
}
#' Test if a Value is an Atomic Vector (Not NULL)
#'
#' @title Predicate: Is value an atomic vector?
#' @description
#' Tests whether a value is an atomic vector (numeric, logical, character,
#' integer, complex, or raw). Excludes NULL, which base R considers atomic.
#'
#' @param x Any R value to test
#'
#' @return
#' TRUE if x is an atomic vector (not NULL)
#' FALSE if x is NULL, a list, a function, or other non-atomic type
#'
#' @examples
#' is_atomic_vec(c(1, 2, 3)) # TRUE
#' is_atomic_vec("hello") # TRUE
#' is_atomic_vec(TRUE) # TRUE
#' is_atomic_vec(NULL) # FALSE (excluded)
#' is_atomic_vec(list(1)) # FALSE (list, not atomic)
#'
#' @keywords internal
#'
is_atomic_vec <- function(x) {
is.atomic(x) && !is.null(x)
}
# ============================================================================
# SECTION 2: CALLER INTROSPECTION
# ============================================================================
# PURPOSE: Get information about the context where a function was called
# ============================================================================
#' Get the Name of an Argument
#'
#' @title Get argument name for error messages
#' @description
#' Extracts the name of an argument from the calling context.
#' Used to provide better error messages that include the actual parameter name.
#' Instead of "x must be...", it says "my_var must be...".
#'
#' @param x The argument (passed unevaluated, no quotes)
#'
#' @return
#' String containing the argument name, or "x" if extraction fails
#'
#' @examples
#' # Inside a function:
#' my_func <- function(my_var) {
#' arg_name <- caller_arg(my_var) # Gets "my_var"
#' }
#'
#' @keywords internal
#'
caller_arg <- function(x) {
tryCatch({
arg_name <- deparse(substitute(x))
if (arg_name == "x") {
return("x")
}
arg_name
}, error = function(e) {
"x"
})
}
#' Get the Calling Environment
#'
#' @title Get caller's environment
#' @description
#' Gets the environment of the code that called this function.
#' Used for error handling to know where to report the error.
#' Allows error messages to point to the correct line in user's code.
#'
#' @return
#' The environment of the calling function
#'
#' @keywords internal
#'
caller_env <- function() {
parent.frame(n = 2)
}
# ============================================================================
# SECTION 3: SPECIAL NA VALUES
# ============================================================================
# R has different types of NA for different data types
# ============================================================================
# NA for character vectors (string NA)
na_chr <- NA_character_
# NA for double/numeric vectors (number NA)
na_dbl <- NA_real_
# NA for integer vectors
na_int <- NA_integer_
# ============================================================================
# SECTION 4: ERROR MESSAGING AND FORMATTING
# ============================================================================
# PURPOSE: Create helpful, user-friendly error messages
# ============================================================================
#' Convert a Value to a Human-Readable Type Description
#'
#' @title Format value as type description
#' @description
#' Converts an R object into a human-readable description of its type and value.
#' Used in error messages to tell users what they actually passed.
#' Instead of just "wrong type", says "you passed the number 5".
#'
#' @param x The value to describe
#' @param value If TRUE, include the actual value in the description
#'
#' @return
#' String describing what x is, e.g., "the number 5", "a character vector of length 3"
#'
#' @examples
#' obj_type_friendly(5) # "the number 5"
#' obj_type_friendly("hello") # 'the string "hello"'
#' obj_type_friendly(c(1, 2, 3)) # "a double vector of length 3"
#' obj_type_friendly(NA) # "`NA`"
#' obj_type_friendly(NULL) # "`NULL`"
#'
#' @keywords internal
#'
obj_type_friendly <- function(x, value = TRUE) {
if (is.null(x)) {
return("`NULL`")
}
if (is.logical(x)) {
if (length(x) == 0) {
return("an empty logical vector")
}
if (length(x) == 1) {
if (is.na(x)) {
return("`NA`")
}
return(sprintf("`%s`", x))
}
return("a logical vector")
}
if (is.integer(x)) {
if (length(x) == 0) {
return("an empty integer vector")
}
if (length(x) == 1) {
if (is.na(x)) {
return("`NA`")
}
return(sprintf("the integer %s", x))
}
return(sprintf("an integer vector of length %d", length(x)))
}
if (is.double(x)) {
if (length(x) == 0) {
return("an empty double vector")
}
if (length(x) == 1) {
if (is.na(x)) {
return("`NA`")
}
if (is.nan(x)) {
return("`NaN`")
}
if (is.infinite(x)) {
return(sprintf("`%s`", x))
}
return(sprintf("the number %s", x))
}
return(sprintf("a double vector of length %d", length(x)))
}
if (is.character(x)) {
if (length(x) == 0) {
return("an empty character vector")
}
if (length(x) == 1) {
if (is.na(x)) {
return("`NA`")
}
if (nchar(x) == 0) {
return('an empty string ("")')
}
return(sprintf('the string "%s"', x))
}
return(sprintf("a character vector of length %d", length(x)))
}
class_name <- class(x)[1]
if (length(x) == 1) {
return(sprintf("a %s object", class_name))
}
return(sprintf("a %s object of length %d", class_name, length(x)))
}
#' Null Coalescing Operator
#'
#' @title Use first non-NULL value
#' @description
#' Returns left side if not NULL, otherwise returns right side.
#' Useful for providing fallback/default values.
#'
#' @param x The primary value
#' @param y The fallback value (used if x is NULL)
#'
#' @return x if not NULL, otherwise y
#'
#' @examples
#' NULL %||% "default" # "default"
#' "actual" %||% "default" # "actual"
#' get_value() %||% get_default() # First non-NULL
#'
#' @keywords internal
#'
`%||%` <- function(x, y) {
if (is.null(x)) y else x
}
#' Format a List Using Oxford Comma
#'
#' @title Format list with proper commas
#' @description
#' Formats a vector of strings using Oxford comma style.
#' Used in error messages like "must be a number, string, or NULL".
#' The Oxford comma (comma before "or") is standard in formal writing.
#'
#' @param chr Vector of strings to format
#' @param sep Separator between items (default: ", ")
#' @param final Final conjunction word (default: "or")
#'
#' @return
#' Formatted string with proper comma placement
#'
#' @examples
#' oxford_comma(c("a")) # "a"
#' oxford_comma(c("a", "b")) # "a or b"
#' oxford_comma(c("a", "b", "c")) # "a, b, or c"
#' oxford_comma(c("a", "b", "c", "d")) # "a, b, c, or d"
#'
#' @keywords internal
#'
oxford_comma <- function(chr, sep = ", ", final = "or") {
n <- length(chr)
if (n < 2) {
return(chr)
}
head <- chr[seq_len(n - 1)]
last <- chr[n]
head <- paste(head, collapse = sep)
if (n > 2) {
paste0(head, sep, final, " ", last)
} else {
paste0(head, " ", final, " ", last)
}
}
#' Generate a Type Validation Error Message
#'
#' @title Throw helpful type validation error
#' @description
#' Generates and throws a helpful error message when input type validation fails.
#' Core error reporting mechanism for the entire validation system.
#' Makes error messages clear and actionable for users.
#'
#' @param x The invalid value provided by user
#' @param what String or vector describing what type(s) are acceptable
#' @param allow_na If TRUE, include "`NA`" in acceptable types
#' @param allow_null If TRUE, include "`NULL`" in acceptable types
#' @param show_value If TRUE, include the actual value in error message
#' @param arg The argument name (auto-detected if not provided)
#' @param call The calling environment (auto-detected if not provided)
#'
#' @details
#' This function builds an error message like:
#' "`arg_name` must be TYPE, not ACTUAL_TYPE."
#'
#' Example error message:
#' "`x` must be `TRUE` or `FALSE`, not the string "hello"."
#'
#' @return
#' Throws an error (does not return). Stops execution.
#'
#' @keywords internal
#'
stop_input_type <- function(
x,
what,
...,
allow_na = FALSE,
allow_null = FALSE,
show_value = TRUE,
arg = caller_arg(x),
call = caller_env()
) {
# Build the list of acceptable types
if (allow_na) {
what <- c(what, "`NA`")
}
if (allow_null) {
what <- c(what, "`NULL`")
}
# Format acceptable types nicely
if (length(what) > 0) {
what <- oxford_comma(what)
}
# Build complete error message
message <- sprintf(
"%s must be %s, not %s.",
sprintf("`%s`", arg),
what,
obj_type_friendly(x, value = show_value)
)
# Throw error
stop(message, call. = FALSE)
}
# ============================================================================
# SECTION 5: MAIN VALIDATION FUNCTIONS (THE PUBLIC API)
# ============================================================================
# These are the functions users call directly to validate arguments
# ============================================================================
#' Check if Input is a Single Boolean Value
#'
#' @title Validate boolean input
#' @description
#' Validates that input is exactly TRUE or FALSE.
#' Rejects vectors, NA values (unless allowed), and non-boolean types.
#' Returns invisibly if valid, throws error if invalid.
#'
#' @param x The value to validate
#' @param allow_na If TRUE, also accept NA as valid input
#' @param allow_null If TRUE, also accept NULL as valid input
#' @param arg The argument name (auto-detected) used in error messages
#' @param call The calling environment (auto-detected) for error context
#'
#' @return
#' Invisibly returns NULL if valid
#' Throws an error if invalid
#'
#' @examples
#' check_bool(TRUE) # ✓ Valid
#' check_bool(FALSE) # ✓ Valid
#' check_bool(1) # ✗ Error (is number)
#' check_bool(c(TRUE, FALSE)) # ✗ Error (is vector)
#'
#' @seealso [check_string()], [check_number_whole()]
#'
check_bool <- function(
x,
...,
allow_na = FALSE,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()
) {
if (!missing(x)) {
if (is_bool(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
if (allow_na && identical(x, NA)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
c("`TRUE`", "`FALSE`"),
allow_na = allow_na,
allow_null = allow_null,
arg = arg,
call = call
)
}
#' Check if Input is a Boolean or Whole Number
#'
#' @title Validate boolean-or-integer input
#' @description
#' Validates that input is either TRUE/FALSE or a whole number.
#' Used for parameters like `do.trace` that accept both forms:
#' TRUE/FALSE to toggle, or an integer to set a frequency.
#'
#' @param x The value to validate
#' @param allow_na If TRUE, also accept NA as valid input
#' @param allow_null If TRUE, also accept NULL as valid input
#' @param arg The argument name (auto-detected) used in error messages
#' @param call The calling environment (auto-detected) for error context
#'
#' @return
#' Invisibly returns NULL if valid
#' Throws an error if invalid
#'
#' @examples
#' check_bool_or_number_whole(TRUE) # ✓ Valid
#' check_bool_or_number_whole(FALSE) # ✓ Valid
#' check_bool_or_number_whole(10L) # ✓ Valid (e.g. trace every 10 trees)
#' check_bool_or_number_whole(1.5) # ✗ Error (decimal)
#' check_bool_or_number_whole("yes") # ✗ Error
#'
check_bool_or_number_whole <- function(
x,
...,