-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
r_codegen.go
218 lines (204 loc) · 5.61 KB
/
r_codegen.go
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
// Copyright ©2019 The rgonomic Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package codegen
import (
"fmt"
"go/types"
"path"
"strings"
"text/template"
"unicode"
"github.com/rgonomic/rgo/internal/pkg"
)
// TODO(kortchak): Check input types for validity before making .Call.
// rCall is the template for R .Call function file generation.
func RCallTemplate(words []string, exported func(string) bool) *template.Template {
return template.Must(template.New("R .Call").Funcs(template.FuncMap{
"base": path.Base,
"snake": snake(words),
"exported": exported,
"varsOf": varsOf,
"names": names,
"doc": doc,
"typecheck": typeCheck,
"returns": returns,
"seelso": seelso,
"replace": strings.ReplaceAll,
}).Parse(`{{$pkg := .Pkg}}# Code generated by rgnonomic/rgo; DO NOT EDIT.
#' @useDynLib {{base $pkg.Path}}{{range $func := .Funcs}}
{{$params := varsOf $func.Signature.Params}}
#' {{snake $func.Func.Name}}
#'
#' {{replace $func.FuncDecl.Doc.Text "\n" "\n#' "}}
{{range $p := $params}}{{doc $p}}
{{end}}{{returns $func.Signature.Results}}{{seelso $pkg $func.Func}}
{{if exported $func.Func.Name}}#' @export
{{end -}}
{{- snake $func.Func.Name}} <- function({{names false $params}}) {
{{range $p := $params}}{{typecheck $p -}}
{{- end}} .Call("{{snake $func.Func.Name}}"{{names true $params}}, PACKAGE = "{{base $pkg.Path}}")
}{{end}}
`))
}
// doc returns an R documentation line for the variable v.
func doc(v *types.Var) string {
return fmt.Sprintf("#' @param %s is %s", v.Name(), article(rDocFor(v.Type()), false))
}
// seealso returns an @seealso documentation line linking to the fn's
// godoc.org documentation.
func seelso(pkg *types.Package, fn *types.Func) string {
return fmt.Sprintf("#' @seelso <https://godoc.org/%s#%s>", pkg.Path(), fn.Name())
}
// returns returns an R documentation table for the returned values in t.
func returns(t *types.Tuple) string {
if t.Len() == 0 {
return ""
}
var buf strings.Builder
switch t.Len() {
case 0:
case 1:
v := t.At(0)
doc := rDocFor(v.Type())
name := v.Name()
if name != "" {
name = ", " + name
}
fmt.Fprintf(&buf, "#' @return %s%s\n", article(doc, true), name)
default:
fmt.Fprintf(&buf, "#' @return A structured value containing:\n")
for i := 0; i < t.Len(); i++ {
v := t.At(i)
doc := rDocFor(v.Type())
name := v.Name()
if name == "" {
name = fmt.Sprintf("r%d", i)
}
fmt.Fprintf(&buf, "#' @return - %s, $%s\n", article(doc, false), name)
}
}
return buf.String()
}
// rDocFor returns a string describing the R type based on the given Go type.
func rDocFor(typ types.Type) string {
rtyp, length, _ := rTypeOf(typ)
switch typ := typ.Underlying().(type) {
case *types.Pointer:
return rDocFor(typ.Elem())
case *types.Struct:
return fmt.Sprintf("%s corresponding to %s", rtyp, typ)
default:
switch {
case rtyp == "list":
return rtyp
case rtyp == "SEXP":
return "arbitrary value"
case length <= 0:
if rtyp == "vector" {
return rtyp
}
return fmt.Sprintf("%s vector", rtyp)
case length == 1:
return fmt.Sprintf("scalar %s", rtyp)
default:
return fmt.Sprintf("%s vector with %d elements", rtyp, length)
}
}
}
// article returns a correct article for a given noun.
func article(noun string, capital bool) string {
vowel := "a"
if capital {
vowel = "A"
}
switch unicode.ToLower(rune(noun[0])) {
case 'a', 'e', 'i', 'o', 'u':
return vowel + "n " + noun
default:
return vowel + " " + noun
}
}
func typeCheck(p *types.Var) string {
typ := p.Type()
if typ, ok := typ.(*types.Basic); ok && typ.Kind() == types.UnsafePointer {
return ""
}
rtyp, length, nilable := rTypeOf(typ)
var check string
if nilable {
check = fmt.Sprintf(` if (!is.%[1]s(%[2]s) && !is.null(%[2]s)) {
stop("Argument '%[2]s' must be of type '%[1]s' or NULL.")
}
`, rtyp, p.Name())
} else {
check = fmt.Sprintf(` if (!is.%[1]s(%[2]s)) {
stop("Argument '%[2]s' must be of type '%[1]s'.")
}
`, rtyp, p.Name())
}
if length > 0 {
var plural string
if length != 1 {
plural = "s"
}
check += fmt.Sprintf(` if (length(%[1]s) != %[2]d) {
stop("Argument '%[1]s' must have %d element%s.")
}
`, p.Name(), length, plural)
}
return check
}
func rTypeOf(typ types.Type) (rtyp string, length int64, nilable bool) {
if pkg.IsError(typ) {
return "character", -1, true
}
switch typ := typ.Underlying().(type) {
case *types.Pointer:
rtyp, length, _ = rTypeOf(typ.Elem())
return rtyp, length, true
case *types.Basic:
return basicRtype(typ), 1, false
case *types.Slice:
elem := typ.Elem()
if etyp, ok := elem.(*types.Basic); ok {
if etyp.Kind() == types.Uint8 || etyp.Kind() == types.Int8 {
return "raw", -1, true
}
return basicRtype(etyp), -1, true
}
return "list", -1, false
case *types.Array:
elem := typ.Elem()
if etyp, ok := elem.(*types.Basic); ok {
if etyp.Kind() == types.Uint8 || etyp.Kind() == types.Int8 {
return "raw", typ.Len(), false
}
return basicRtype(etyp), typ.Len(), false
}
return "list", -1, false
case *types.Map:
return "vector", -1, true
case *types.Struct:
return "list", -1, false
}
return "", -1, false
}
func basicRtype(typ *types.Basic) string {
switch info := typ.Info(); {
case info&types.IsBoolean != 0:
return "logical"
case info&types.IsString != 0:
return "character"
case info&types.IsInteger != 0:
return "integer"
case info&types.IsFloat != 0:
return "double"
case info&types.IsComplex != 0:
return "complex"
case typ.Kind() == types.UnsafePointer:
return "SEXP"
default:
panic(fmt.Sprintf("unhandled type: %#v", typ))
}
}