-
Notifications
You must be signed in to change notification settings - Fork 315
/
QC.R
10364 lines (9607 loc) · 408 KB
/
QC.R
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
# File src/library/tools/R/QC.R
# Part of the R package, https://www.R-project.org
#
# Copyright (C) 1995-2024 The R Core Team
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# A copy of the GNU General Public License is available at
# https://www.R-project.org/Licenses/
## R CMD check uses
## .find_charset
## .check_namespace
## .check_package_depends
## .check_demo_index
## .check_vignette_index
## .check_package_subdirs
## .check_citation
## .check_package_ASCII_code
## .check_package_code_syntax
## .check_packages_used
## .check_package_code_shlib
## .check_package_code_startup_functions
## .check_package_code_assign_to_globalenv
## .check_package_code_attach
## .check_package_code_data_into_globalenv
## .check_package_code_class_is_string
## .check_code_usage_in_package
## .check_bogus_return
## .check_dotInternal
## .check_package_parseRd
## .check_Rd_xrefs
## undoc
## codoc
## codocData
## codocClasses
## checkDocFiles
## checkDocStyle
## checkFF
## checkS3methods
## checkReplaceFuns
## .check_package_datasets
## .check_package_compact_datasets
## .check_package_compact_sysdata
## .check_make_vars
## .createExdotR (testing.R)
## .runPackageTestsR (testing.R)
## .get_LaTeX_errors_from_log_file
## .check_package_CRAN_incoming
## checkRdContents
## R CMD build uses .check_package_subdirs
## NB: 'tools' cannot use NAMESPACE imports from utils, as it exists first
## "The language elements" : all are .Primitive *and* print as .Primitive("...")
langElts <- c("(", "{", ":", "~",
"<-", "<<-", "=",
"[", "[[", "[[<-", "[<-", "@", "@<-", "$", "$<-",
"&&", "||",
"break", "for", "function", "if", "next", "repeat", "return", "while")
## Code "existing conceptually" in base,
## typically function names of default methods for .Primitive s:
conceptual_base_code <- c("c.default")
##' a "default" print method (see NAMESPACE):
.print.via.format <- function(x, ...) {
writeLines(format(x, ...))
invisible(x)
}
## utility for whether Rd sources are available.
.haveRds <- function(dir)
{
## either source package or pre-2.10.0 installed package
dir.exists (file.path(dir, "man")) ||
file.exists(file.path(dir, "help", "paths.rds"))
}
### * undoc/F/out
undoc <-
function(package, dir, lib.loc = NULL)
{
## Argument handling.
## <NOTE>
## Earlier versions used to give an error if there were no Rd
## objects. This is not right: if there is code or data but no
## documentation, everything is undocumented ...
## </NOTE>
if(!missing(package)) {
if(length(package) != 1L)
stop("argument 'package' must be of length 1")
dirdir <- dirname(dir <- find.package(package, lib.loc))
## Using package installed in @code{dir} ...
is_base <- package == "base"
all_doc_topics <- Rd_aliases(package, lib.loc = dirdir)
## Load package into code_env.
if(!is_base)
.load_package_quietly(package, dirdir)
code_env <- .package_env(package)
code_objs <- ls(envir = code_env, all.names = TRUE)
pkgname <- package
}
else {
if(missing(dir))
stop("you must specify 'package' or 'dir'")
pkgname <- basename(dir)
dirdir <- dirname(dir)
## Using sources from directory @code{dir} ...
if(!dir.exists(dir))
stop(gettextf("directory '%s' does not exist", dir),
domain = NA)
else
dir <- file_path_as_absolute(dir)
is_base <- pkgname == "base"
all_doc_topics <- Rd_aliases(dir = dir)
code_env <- new.env(hash = TRUE)
code_dir <- file.path(dir, "R")
if(dir.exists(code_dir)) {
dfile <- file.path(dir, "DESCRIPTION")
meta <- if(file_test("-f", dfile))
.read_description(dfile)
else
character()
.source_assignments_in_code_dir(code_dir, code_env, meta)
sys_data_file <- file.path(code_dir, "sysdata.rda")
if(file_test("-f", sys_data_file))
load(sys_data_file, code_env)
}
code_objs <- ls(envir = code_env, all.names = TRUE)
if(file.exists(file.path(dir, "NAMESPACE")) &&
## Code in NAMESPACE could e.g. check the version of one of
## its Imports.
!inherits(tryCatch(nsInfo <-
parseNamespaceFile(pkgname,
dirdir),
error = identity),
"error")) {
## Look only at exported objects (and not declared S3
## methods).
OK <- intersect(code_objs, nsInfo$exports)
for(p in nsInfo$exportPatterns)
OK <- c(OK, grep(p, code_objs, value = TRUE))
code_objs <- unique(OK)
}
}
## Find the data sets to work on.
data_dir <- file.path(dir, "data")
data_objs <- if(dir.exists(data_dir))
unlist(.try_quietly(list_data_in_pkg(dir = dir)),
use.names = FALSE)
else
character()
## There was a time when packages contained code or data (or both).
## But not anymore ...
if(!missing(package) && !length(code_objs) && !length(data_objs)
&& getOption("verbose"))
message("neither code nor data objects found")
if(!is_base) {
## Code objects in add-on packages with names starting with a
## dot are considered 'internal' (not user-level) by
## convention.
if(!config_val_to_logical(Sys.getenv("_R_CHECK_UNDOC_USE_ALL_NAMES_",
"FALSE")))
code_objs <- grep("^[^.].*", code_objs, value = TRUE)
else {
code_objs <- code_objs %w/o% c(".Depends")
code_objs <- code_objs[!(startsWith(code_objs, ".__C__") |
startsWith(code_objs, ".__T__"))]
}
## Note that this also allows us to get rid of S4 meta objects
## (with names starting with '.__C__' or '.__M__'; well, as long
## as there are none in base).
## Implicit generic functions exist to turn method dispatch on
## in this package, but their definition and documentation belongs
## to the package in their package slot, so eliminate any
## foreign generic functions from code_objs
if(.isMethodsDispatchOn()) {
is <- methods::is # speed
code_objs <-
Filter(function(f) {
fdef <- code_env[[f]] # faster than get()
## Running methods::is() on data sets can trigger
## loading additional packages for which startup
## messages et al need suppressing ...
if(suppressMessages(is(fdef, "genericFunction")))
fdef@package == pkgname
else
TRUE
},
code_objs)
}
## Allow group generics to be undocumented other than in base.
## In particular, those from methods partially duplicate base
## and are documented in base's groupGenerics.Rd.
code_objs <- setdiff(code_objs,
c("Arith", "Compare", "Complex", "Logic",
"Math", "Math2", "Ops", "Summary", "matrixOps"))
}
undoc_things <-
list("code objects" =
unique(setdiff(code_objs, all_doc_topics)),
"data sets" =
unique(setdiff(data_objs, all_doc_topics)))
if(.isMethodsDispatchOn()) {
## Undocumented S4 classes?
S4_classes <- methods::getClasses(code_env)
## <NOTE>
## There is no point in worrying about exportClasses directives
## in a NAMESPACE file when working on a package source dir, as
## we only source the assignments, and hence do not get any
## S4 classes or methods.
## </NOTE>
## The bad ones:
S4_classes <-
S4_classes[vapply(S4_classes, utils:::topicName, " ",
type = "class", USE.NAMES = FALSE)
%notin% all_doc_topics]
undoc_things <-
c(undoc_things, list("S4 classes" = unique(S4_classes)))
}
if(.isMethodsDispatchOn()) {
## Undocumented S4 methods?
## <NOTE>
## There is no point in worrying about exportMethods directives
## in a NAMESPACE file when working on a package source dir, as
## we only source the assignments, and hence do not get any
## S4 classes or methods.
## </NOTE>
.make_S4_method_siglist <- function(g) {
mlist <- .get_S4_methods_list(g, code_env)
sigs <- .make_siglist(mlist) # s/#/,/g
if(length(sigs))
paste0(g, ",", sigs)
else
character()
}
S4_methods <- lapply(.get_S4_generics(code_env),
.make_S4_method_siglist)
S4_methods <- as.character(unlist(S4_methods, use.names = FALSE))
## The bad ones:
S4_methods <-
S4_methods[vapply(S4_methods, utils:::topicName, " ",
type="method", USE.NAMES = FALSE)
%notin% all_doc_topics]
undoc_things <-
c(undoc_things,
list("S4 methods" =
unique(sub("([^,]*),(.*)",
"generic '\\1' and siglist '\\2'",
S4_methods))))
}
if(is_base) {
## We use .ArgsEnv and .GenericArgsEnv in checkS3methods() and
## codoc(), so we check here that the set of primitives has not
## been changed.
ff <- as.list(baseenv(), all.names = TRUE)
prims <- names(ff)[vapply(ff, is.primitive, NA)]
prototypes <- sort(c(names(.ArgsEnv), names(.GenericArgsEnv)))
extras <- setdiff(prototypes, prims)
if(length(extras))
undoc_things <- c(undoc_things, list(prim_extra = extras))
miss <- setdiff(prims, c(langElts, prototypes))
if(length(miss))
undoc_things <- c(undoc_things, list(primitives = miss))
}
class(undoc_things) <- "undoc"
undoc_things
}
format.undoc <-
function(x, ...)
{
.fmt <- function(i) {
tag <- names(x)[i]
msg <- switch(tag,
"code objects" =
gettext("Undocumented code objects:"),
"data sets" =
gettext("Undocumented data sets:"),
"S4 classes" =
gettext("Undocumented S4 classes:"),
"S4 methods" =
gettext("Undocumented S4 methods:"),
prim_extra =
gettext("Prototyped non-primitives:"),
gettextf("Undocumented %s:", tag))
c(msg,
## We avoid markup for indicating S4 methods, hence need to
## special-case output for these ...
if(tag == "S4 methods") {
strwrap(x[[i]], indent = 2L, exdent = 4L)
} else {
.pretty_format(x[[i]])
})
}
as.character(unlist(lapply(which(lengths(x) > 0L), .fmt)))
}
### * codoc
##
is_data_for_dataset <- function(e) ## trigger for data(foo) or data(foo, package="bar") and similar
length(e) >= 2L && e[[1L]] == quote(data) && e[[2L]] != quote(...) && length(e) <= 4L
codoc <-
function(package, dir, lib.loc = NULL,
use.values = NULL, verbose = getOption("verbose"))
{
has_namespace <- FALSE
## Argument handling.
if(!missing(package)) {
if(length(package) != 1L)
stop("argument 'package' must be of length 1")
dir <- find.package(package, lib.loc)
## Using package installed in @code{dir} ...
code_dir <- file.path(dir, "R")
if(!dir.exists(code_dir))
stop(gettextf("directory '%s' does not contain R code", dir),
domain = NA)
if(!.haveRds(dir))
stop(gettextf("directory '%s' does not contain Rd objects", dir),
domain = NA)
is_base <- basename(dir) == "base"
dirdir <- dirname(dir)
## Load package into code_env.
if(!is_base)
.load_package_quietly(package, dirdir)
code_env <- .package_env(package)
objects_in_code <- sort(names(code_env))
if(is_base) {
objects_in_code_or_namespace <- objects_in_code
} else {
has_namespace <- TRUE
ns_env <- asNamespace(package)
S3Table <- ns_env[[".__S3MethodsTable__."]]
functions_in_S3Table <- ls(S3Table, all.names = TRUE)
objects_in_ns <-
setdiff(sort(names(ns_env)),
c(".__NAMESPACE__.", ".__S3MethodsTable__."))
ns_S3_methods_db <- getNamespaceInfo(package, "S3methods")
ns_S3_methods <- if(is.null(ns_S3_methods_db))
character()
else
paste(ns_S3_methods_db[, 1L],
ns_S3_methods_db[, 2L],
sep = ".")
objects_in_code_or_namespace <-
unique(c(objects_in_code, objects_in_ns, ns_S3_methods))
objects_in_ns <- setdiff(objects_in_ns, objects_in_code)
}
package_name <- package
}
else {
if(missing(dir))
stop("you must specify 'package' or 'dir'")
## Using sources from directory @code{dir} ...
if(!dir.exists(dir))
stop(gettextf("directory '%s' does not exist", dir), domain = NA)
## else
package_name <- basename(dir) # early, before resolving sym.links etc in next line:
dirdir <- dirname(dir) # early, ...
dir <- file_path_as_absolute(dir)
code_dir <- file.path(dir, "R")
if(!dir.exists(code_dir))
stop(gettextf("directory '%s' does not contain R code", dir),
domain = NA)
if(!.haveRds(dir))
stop(gettextf("directory '%s' does not contain Rd objects", dir),
domain = NA)
is_base <- package_name == "base"
code_env <- new.env(hash = TRUE)
dfile <- file.path(dir, "DESCRIPTION")
meta <- if(file_test("-f", dfile)) .read_description(dfile) else character()
.source_assignments_in_code_dir(code_dir, code_env, meta)
sys_data_file <- file.path(code_dir, "sysdata.rda")
if(file_test("-f", sys_data_file)) load(sys_data_file, code_env)
objects_in_code <- sort(names(code_env))
objects_in_code_or_namespace <- objects_in_code
## Does the package have a NAMESPACE file?
## Also, do not attempt to find S3 methods.
if(file.exists(file.path(dir, "NAMESPACE")) &&
## Code in NAMESPACE could e.g. check the version of one of
## its Imports.
!inherits(tryCatch(nsInfo <-
parseNamespaceFile(package_name,
dirdir),
error = identity),
"error")) {
has_namespace <- TRUE
objects_in_ns <- objects_in_code
functions_in_S3Table <- character()
ns_env <- code_env
## Look only at exported objects.
OK <- intersect(objects_in_code, nsInfo$exports)
for(p in nsInfo$exportPatterns)
OK <- c(OK, grep(p, objects_in_code, value = TRUE))
objects_in_code <- unique(OK)
}
}
## Find the data sets to work on.
data_dir <- file.path(dir, "data")
if(dir.exists(data_dir)) {
data_sets_in_code_variables <-
.try_quietly(list_data_in_pkg(dir = dir))
data_sets_in_code <- names(data_sets_in_code_variables)
} else
data_sets_in_code <- data_sets_in_code_variables <- character()
## Find the function objects to work on.
functions_in_code <-
Filter(function(f) {
## This is expensive
f <- get(f, envir = code_env)
typeof(f) == "closure"
},
objects_in_code)
## Sourcing all R code files in the package is a problem for base,
## where this misses the .Primitive functions. Hence, when checking
## base for objects shown in \usage but missing from the code, we
## get the primitive functions from the version of R we are using.
## Maybe one day we will have R code for the primitives as well ...
## As from R 2.5.0 we do for most generics.
if(is_base) {
objects_in_base <-
sort(names(baseenv()))
objects_in_code <-
c(objects_in_code,
conceptual_base_code,
Filter(.is_primitive_in_base, objects_in_base),
c(".First.lib", ".Last.lib", ".Random.seed",
".onLoad", ".onAttach", ".onDetach", ".onUnload"))
objects_in_code_or_namespace <- objects_in_code
known_env <- .make_S3_primitive_generic_env(code_env, fixup=TRUE)
extras <- ls(known_env, all.names = TRUE)
functions_in_code <- c(functions_in_code, extras)
code_env <- known_env
known_env <- .make_S3_primitive_nongeneric_env(code_env)
extras <- ls(known_env, all.names = TRUE)
functions_in_code <- c(functions_in_code, extras)
code_env <- known_env
}
## Build a list with the formals of the functions in the code
## indexed by the names of the functions.
function_args_in_code <-
lapply(functions_in_code,
function(f) formals(get(f, envir = code_env))) # get is expensive
names(function_args_in_code) <- functions_in_code
if(has_namespace) {
functions_in_ns <-
Filter(function(f) {
f <- get(f, envir = ns_env) # get is expensive
is.function(f) && (length(formals(f)) > 0L)
},
objects_in_ns)
function_args_in_ns <-
lapply(functions_in_ns,
function(f) formals(get(f, envir = ns_env)))
names(function_args_in_ns) <- functions_in_ns
function_args_in_S3Table <-
lapply(functions_in_S3Table, function(f) formals(S3Table[[f]]))
names(function_args_in_S3Table) <- functions_in_S3Table
tmp <- c(function_args_in_code, function_args_in_S3Table,
function_args_in_ns)
keep <- !duplicated(names(tmp))
function_args_in_code <- tmp[keep]
functions_in_code <- names(function_args_in_code)
}
if(.isMethodsDispatchOn()) {
## <NOTE>
## There is no point in worrying about exportMethods directives
## in a NAMESPACE file when working on a package source dir, as
## we only source the assignments, and hence do not get any
## S4 classes or methods.
## </NOTE>
## <NOTE>
## In principle, we can get codoc checking for S4 methods
## documented explicitly using the \S4method{GENERIC}{SIGLIST}
## markup by adding the corresponding "pseudo functions" using
## the Rd markup as their name. However note that the formals
## recorded in the methods db only pertain to the signature, not
## to the ones of the function actually registered ... hence we
## use methods::unRematchDefinition() which knows how to extract
## the formals in the method definition from the
## function(ARGLIST) {
## .local <- function(FORMALS) BODY
## .local(ARGLIST)
## }
## redefinitions obtained by methods::rematchDefinition().
## </NOTE>
check_S4_methods <-
!isFALSE(as.logical(Sys.getenv("_R_CHECK_CODOC_S4_METHODS_")))
if(check_S4_methods) {
unRematchDef <- methods::unRematchDefinition
get_formals_from_method_definition <- function(m)
formals(unRematchDef(m))
lapply(.get_S4_generics(code_env),
function(f) {
mlist <- .get_S4_methods_list(f, code_env)
sigs <- .make_siglist(mlist)
if(!length(sigs)) return()
nm <- sprintf("\\S4method{%s}{%s}", f, sigs)
args <- lapply(mlist,
get_formals_from_method_definition)
names(args) <- nm
functions_in_code <<-
c(functions_in_code, nm)
function_args_in_code <<-
c(function_args_in_code, args)
})
}
}
check_codoc <- function(fName, ffd) {
## Compare the formals of the function in the code named 'fName'
## and formals 'ffd' obtained from the documentation.
ffc <- function_args_in_code[[fName]]
ident <- if(isFALSE(use.values)) {
ffc <- names(ffc)
ffd <- names(ffd)
identical(ffc, ffd)
} else {
identical(names(ffc), names(ffd)) &&
{
vffc <- as.character(ffc) # values
vffd <- as.character(ffd) # values
if(!isTRUE(use.values)) {
ind <- nzchar(vffd)
vffc <- vffc[ind]
vffd <- vffd[ind]
}
identical(vffc, vffd)
}
}
if(!ident)
list(list(name = fName, code = ffc, docs = ffd))
} #{check_codoc}
db <- if(!missing(package))
Rd_db(package, lib.loc = dirdir)
else
Rd_db(dir = dir)
## <FIXME>
## How exactly do we recognize docs for defunct/deprecated?
db_names <- .Rd_get_names_from_Rd_db(db)
## pkg-defunct.Rd is not expected to list arguments
ind <- db_names %in% paste0(package_name, "-defunct")
db <- db[!ind]
## </FIXME>
db_usages <- lapply(db, .Rd_get_section, "usage")
## FIXME: all db_usages entries are full of "srcref" which are never used
db_usages <- lapply(db_usages, .parse_usage_as_much_as_possible)
ind <- vapply(db_usages,
function(x) !is.null(attr(x, "bad_lines")), NA, USE.NAMES=FALSE)
bad_lines <- lapply(db_usages[ind], attr, "bad_lines")
bad_doc_objects <- list()
functions_in_usages <- character()
variables_in_usages <- character()
data_sets_in_usages <- character()
functions_in_usages_not_in_code <- list()
data_sets_in_usages_not_in_code <- list()
variables_in_usages_not_in_code <- list()
objects_as_in <- c(objects_in_code_or_namespace
, names(compatibilityEnv()) # objects in other platforms
, if(missing(package) && str_parse_logic(meta["LazyData"], FALSE))
unlist(data_sets_in_code_variables, use.names = FALSE)
, if(is_base)
c("NA", "NULL", "Inf", "NaN", "TRUE", "FALSE", ".Autoloaded")
)
for(nm in names(db)) {
exprs <- db_usages[[nm]]
if(!length(exprs)) next
## Get variable names and data set usages first, mostly for
## curiosity.
ind <- vapply(exprs, is.name, NA, USE.NAMES=FALSE)
if(any(ind)) {
variables <- vapply(exprs[ind], deparse, "")
variables_in_usages <- c(variables_in_usages, variables)
variables <- setdiff(variables, objects_as_in)
if(length(variables))
variables_in_usages_not_in_code[[nm]] <- variables
exprs <- exprs[!ind]
}
exprs <- exprs[vapply(exprs, is.call, NA, USE.NAMES=FALSE)]
ind <- vapply(exprs, is_data_for_dataset, NA, USE.NAMES=FALSE)
if(any(ind)) {
data_sets <- vapply(exprs[ind],
function(e) as.character(e[[2L]]),
"")
data_sets_in_usages <- c(data_sets_in_usages, data_sets)
data_sets <- setdiff(data_sets, data_sets_in_code)
if(length(data_sets))
data_sets_in_usages_not_in_code[[nm]] <- data_sets
exprs <- exprs[!ind]
}
## Split out replacement function usages.
ind <- vapply(exprs, .is_call_from_replacement_function_usage, NA, USE.NAMES=FALSE)
replace_exprs <- exprs[ind]
exprs <- exprs[!ind]
## Ordinary functions.
functions <- vapply(exprs, function(e) as.character(e[[1L]]), "")
## Catch assignments: checkDocFiles() will report these, so drop
## them here.
## And also unary/binary operators
ind <- (functions %notin% c("<-", "=", "+", "-"))
exprs <- exprs[ind]
functions <- functions[ind]
functions <- .transform_S3_method_markup(as.character(functions))
ind <- functions %in% functions_in_code
bad_functions <-
mapply(functions[ind],
exprs[ind],
FUN = function(x, y)
check_codoc(x, as.pairlist(as.alist.call(y[-1L]))),
SIMPLIFY = FALSE)
## Replacement functions.
if(length(replace_exprs)) {
replace_funs <-
paste0(vapply(replace_exprs,
function(e) as.character(e[[2L]][[1L]]),
""),
"<-")
replace_funs <- .transform_S3_method_markup(replace_funs)
functions <- c(functions, replace_funs)
ind <- (replace_funs %in% functions_in_code)
if(any(ind)) {
bad_replace_funs <-
mapply(replace_funs[ind],
replace_exprs[ind],
FUN = function(x, y)
check_codoc(x,
as.pairlist(c(as.alist.call(y[[2L]][-1L]),
as.alist.symbol(y[[3L]])))),
SIMPLIFY = FALSE)
bad_functions <-
c(bad_functions, bad_replace_funs)
}
}
bad_functions <- do.call(c, bad_functions)
if(length(bad_functions))
bad_doc_objects[[nm]] <- bad_functions
## Determine functions with a \usage entry in the documentation
## but 'missing from the code'. If a package has a namespace, we
## really need to look at all objects in the namespace (hence
## 'objects_as_in' contains 'objects_in_code_or_namespace'),
## as one can access the internal
## symbols via ':::' and hence package developers might want to
## provide function usages for some of the internal functions.
## <FIXME>
## We may still have \S4method{}{} entries in functions, which
## cannot have a corresponding object in the code. Hence, we
## remove these function entries, but should really do better,
## by comparing the explicit \usage entries for S4 methods to
## what is actually in the code. We most likely also should do
## something similar for S3 methods.
ind <- grepl(.S4_method_markup_regexp, functions)
if(any(ind))
functions <- functions[!ind]
## </FIXME>
bad_functions <- setdiff(functions, objects_as_in)
if(length(bad_functions))
functions_in_usages_not_in_code[[nm]] <- bad_functions
functions_in_usages <- c(functions_in_usages, functions)
}
## Determine (function) objects in the code without a \usage entry.
## Of course, these could still be 'documented' via \alias.
## </NOTE>
## Older versions only printed this information without returning it
## (in case 'verbose' was true). We now add this as an attribute to
## the bad_doc_objects returned.
## </NOTE>
objects_in_code_not_in_usages <-
setdiff(objects_in_code,
c(functions_in_usages, variables_in_usages))
functions_in_code_not_in_usages <-
intersect(functions_in_code, objects_in_code_not_in_usages)
## (Note that 'functions_in_code' does not necessarily contain all
## (exported) functions in the package.)
## Determine functions which have no usage but really should have.
## If there is no namespace (including base), we have no idea.
## If there is one, everything "exported" (in the package env)
## should also have a \usage, apart from
## * Defunct functions
## * S4 generics. Note that as per R-exts,
## exporting methods on a generic in the namespace will also
## export the generic, and exporting a generic in the namespace
## will also export its methods.
## so it seems there is really no way to figure out whether an
## exported S4 generic should have a \usage entry or not ...
functions_missing_from_usages <-
if(!has_namespace && !is_base)
character()
else {
functions <- functions_in_code_not_in_usages
if(is_base)
functions <-
setdiff(functions,
c(sprintf("%s.%s",
.S3_methods_table[, 1L],
.S3_methods_table[, 2L]),
c(".First.sys", ".OptRequireMethods",
"+", "-")))
else {
pname <- basename(dir)
if(pname == "utils")
functions <- functions %w/o% "?"
else if(pname == "grDevices")
functions <- functions %w/o% "x11"
}
if(.isMethodsDispatchOn()) {
## Drop the functions which have S4 methods.
functions <-
setdiff(functions, names(.get_S4_generics(code_env)))
}
## Drop the defunct functions.
is_defunct <- function(f) {
f <- get(f, envir = code_env) # get is expensive
if(!is.function(f)) return(FALSE)
b <- body(f)
repeat {
if(!is.call(b)) return(FALSE)
if((length(b) > 1L) && (b[[1L]] == as.name("{")))
b <- b[[2L]]
else
break
}
b[[1L]] == as.name(".Defunct")
}
functions[!vapply(functions, is_defunct, NA, USE.NAMES=FALSE)]
}
objects_missing_from_usages <-
if(!has_namespace) character() else {
c(functions_missing_from_usages,
setdiff(objects_in_code_not_in_usages,
c(functions_in_code, data_sets_in_code)))
}
attr(bad_doc_objects, "objects_in_code_not_in_usages") <-
objects_in_code_not_in_usages
attr(bad_doc_objects, "functions_in_code_not_in_usages") <-
functions_in_code_not_in_usages
attr(bad_doc_objects, "functions_in_usages_not_in_code") <-
functions_in_usages_not_in_code
attr(bad_doc_objects, "function_args_in_code") <-
function_args_in_code
attr(bad_doc_objects, "data_sets_in_usages_not_in_code") <-
data_sets_in_usages_not_in_code
if(config_val_to_logical(Sys.getenv("_R_CHECK_CODOC_VARIABLES_IN_USAGES_",
"FALSE"))) {
attr(bad_doc_objects, "variables_in_usages_not_in_code") <-
variables_in_usages_not_in_code
}
attr(bad_doc_objects, "objects_missing_from_usages") <-
objects_missing_from_usages
attr(bad_doc_objects, "functions_missing_from_usages") <-
functions_missing_from_usages
attr(bad_doc_objects, "has_namespace") <- has_namespace
attr(bad_doc_objects, "bad_lines") <- bad_lines
class(bad_doc_objects) <- "codoc"
bad_doc_objects
}
print.codoc <-
function(x, ...)
{
functions_in_usages_not_in_code <-
attr(x, "functions_in_usages_not_in_code")
if(length(functions_in_usages_not_in_code)) {
for(fname in names(functions_in_usages_not_in_code)) {
writeLines(gettextf("Functions or methods with usage in Rd file '%s' but not in code:",
fname))
.pretty_print(sQuote(unique(functions_in_usages_not_in_code[[fname]])))
writeLines("")
}
}
data_sets_in_usages_not_in_code <-
attr(x, "data_sets_in_usages_not_in_code")
if(length(data_sets_in_usages_not_in_code)) {
for(fname in names(data_sets_in_usages_not_in_code)) {
writeLines(gettextf("Data with usage in Rd file '%s' but not in code:",
fname))
.pretty_print(sQuote(unique(data_sets_in_usages_not_in_code[[fname]])))
writeLines("")
}
}
variables_in_usages_not_in_code <-
attr(x, "variables_in_usages_not_in_code")
if(length(variables_in_usages_not_in_code)) {
for(fname in names(variables_in_usages_not_in_code)) {
writeLines(gettextf("Variables with usage in Rd file '%s' but not in code:",
fname))
.pretty_print(sQuote(unique(variables_in_usages_not_in_code[[fname]])))
writeLines("")
}
}
## In general, functions in the code which only have an \alias but
## no \usage entry are not necessarily a problem---they might be
## mentioned in other parts of the Rd object documenting them, or be
## 'internal'. However, if a package has a namespace, then all
## *exported* functions should have \usage entries (apart from
## defunct functions and S4 generics, see the above comments for
## functions_missing_from_usages). Currently, this information is
## returned in the codoc object but not shown. Eventually, we might
## add something like
## functions_missing_from_usages <-
## attr(x, "functions_missing_from_usages")
## if(length(functions_missing_from_usages)) {
## writeLines("Exported functions without usage information:")
## .pretty_print(functions_in_code_not_in_usages)
## writeLines("")
## }
## similar to the above.
if(!length(x))
return(invisible(x))
has_only_names <- is.character(x[[1L]][[1L]][["code"]])
format_args <- function(s) {
if(!length(s))
"function()"
else if(has_only_names)
paste0("function(", paste(s, collapse = ", "), ")")
else {
s <- paste(deparse(s), collapse = "")
s <- gsub(" = ([,\\)])", "\\1", s)
s <- gsub("<unescaped bksl>", "\\", s, fixed = TRUE)
s <- gsub("^pairlist", "function", s)
gsub("^as.pairlist\\(alist\\((.*)\\)\\)$", "function(\\1)", s)
}
}
summarize_mismatches_in_names <- function(nfc, nfd) {
if(length(nms <- setdiff(nfc, nfd)))
writeLines(c(gettext(" Argument names in code not in docs:"),
strwrap(paste(nms, collapse = " "),
indent = 4L, exdent = 4L)))
if(length(nms <- setdiff(nfd, nfc)))
writeLines(c(gettext(" Argument names in docs not in code:"),
strwrap(paste(nms, collapse = " "),
indent = 4L, exdent = 4L)))
len <- min(length(nfc), length(nfd))
if(len) {
len <- seq_len(len)
nfc <- nfc[len]
nfd <- nfd[len]
ind <- which(nfc != nfd)
len <- length(ind)
if(len) {
if(len > 3L) {
writeLines(gettext(" Mismatches in argument names (first 3):"))
ind <- ind[1L:3L]
} else {
writeLines(gettext(" Mismatches in argument names:"))
}
for(i in ind) {
writeLines(sprintf(" Position: %d Code: %s Docs: %s",
i, nfc[i], nfd[i]))
}
}
}
}
summarize_mismatches_in_values <- function(ffc, ffd) {
## Be nice, and match arguments by names first.
nms <- intersect(names(ffc), names(ffd))
vffc <- ffc[nms]
vffd <- ffd[nms]
ind <- which(as.character(vffc) != as.character(vffd))
len <- length(ind)
if(len) {
if(len > 3L) {
writeLines(gettext(" Mismatches in argument default values (first 3):"))
ind <- ind[1L:3L]
} else {
writeLines(gettext(" Mismatches in argument default values:"))
}
for(i in ind) {
multiline <- FALSE
cv <- deparse(vffc[[i]])
if(length(cv) > 1L) {
cv <- paste(cv, collapse = "\n ")
multiline <- TRUE
}
dv <- deparse(vffd[[i]])
if(length(dv) > 1L) {
dv <- paste(dv, collapse = "\n ")
multiline <- TRUE
}
dv <- gsub("<unescaped bksl>", "\\", dv, fixed = TRUE)
sep <- if(multiline) "\n " else " "
writeLines(sprintf(" Name: '%s'%sCode: %s%sDocs: %s",
nms[i], sep, cv, sep, dv))
}
}
}
summarize_mismatches <- function(ffc, ffd) {
if(has_only_names)
summarize_mismatches_in_names(ffc, ffd)
else {
summarize_mismatches_in_names(names(ffc), names(ffd))
summarize_mismatches_in_values(ffc, ffd)
}
}
for(fname in names(x)) {
writeLines(gettextf("Codoc mismatches from Rd file '%s':",
fname))
xfname <- x[[fname]]
for(i in seq_along(xfname)) {
ffc <- xfname[[i]][["code"]]
ffd <- xfname[[i]][["docs"]]
writeLines(c(xfname[[i]][["name"]],
strwrap(gettextf("Code: %s", format_args(ffc)),
indent = 2L, exdent = 17L),
strwrap(gettextf("Docs: %s", format_args(ffd)),
indent = 2L, exdent = 17L)))
summarize_mismatches(ffc, ffd)
}
writeLines("")
}
invisible(x)
}
### * codocClasses
codocClasses <-
function(package, lib.loc = NULL)
{
## Compare the 'structure' of S4 classes in an installed package
## between code and documentation.
## Currently, only compares the slot names.
## <NOTE>
## This is patterned after the current codoc().
## It would be useful to return the whole information on class slot
## names found in the code and matching documentation (rather than
## just the ones with mismatches).
## Currently, we only return the names of all classes checked.
## </NOTE>