-
Notifications
You must be signed in to change notification settings - Fork 235
/
Copy pathparse.R
76 lines (61 loc) · 1.87 KB
/
parse.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
parse_package <- function(base_path, load_code) {
env <- load_code(base_path)
parsed <- lapply(package_files(base_path), parse_file, env = env)
blocks <- unlist(parsed, recursive = FALSE)
list(env = env, blocks = blocks)
}
parse_text <- function(text) {
file <- tempfile()
writeLines(text, file)
on.exit(unlink(file))
env <- new.env(parent = parent.env(globalenv()))
setPackageName("roxygen_devtest", env)
sys.source(file, envir = env)
blocks <- parse_file(file, env)
list(env = env, blocks = blocks)
}
parse_file <- function(file, env) {
parsed <- parse(file = file, keep.source = TRUE)
if (length(parsed) == 0) return()
refs <- getSrcref(parsed)
comment_refs <- comments(refs)
extract <- function(call, ref, comment_ref) {
preref <- parse_preref(comment_ref, file)
if (length(preref) == 0) return()
preref$object <- object_from_call(call, env, preref)
preref$srcref <- list(filename = file, lloc = as.vector(ref))
add_defaults(preref)
}
Map(extract, parsed, refs, comment_refs)
}
# For each src ref, find the comment block preceeding it
comments <- function(refs) {
srcfile <- attr(refs[[1]], "srcfile")
# first_line, first_byte, last_line, last_byte
com <- vector("list", length(refs))
for(i in seq_along(refs)) {
# Comments begin after last line of last block, and continue to
# first line of this block
if (i == 1) {
first_byte <- 1
first_line <- 1
} else {
first_byte <- refs[[i - 1]][4] + 1
first_line <- refs[[i - 1]][3]
}
last_line <- refs[[i]][1]
last_byte <- refs[[i]][2] - 1
if (last_byte == 0) {
if (last_line == 1) {
last_byte <- 1
last_line <- 1
} else {
last_line <- last_line - 1
last_byte <- 1e3
}
}
lloc <- c(first_line, first_byte, last_line, last_byte)
com[[i]] <- srcref(srcfile, lloc)
}
com
}