Debian Codegraph @

buildtags/buildtags.go

raw symbols SCIP
1 // Package buildtags provides types for representing and manipulating build constraints.
2 //
3 // In Go, build constraints are represented as comments in source code together with file naming conventions. For example
4 //
5 // // +build linux,386 darwin,!cgo
6 // // +build !purego
7 //
8 // Any terms provided in the filename can be thought of as an implicit extra
9 // constraint comment line. Collectively, these are referred to as
10 // “constraints”. Each line is a “constraint”. Within each constraint the
11 // space-separated terms are “options”, and within that the comma-separated
12 // items are “terms” which may be negated with at most one exclaimation mark.
13 //
14 // These represent a boolean formulae. The constraints are evaluated as the AND
15 // of constraint lines; a constraint is evaluated as the OR of its options and
16 // an option is evaluated as the AND of its terms. Overall build constraints are
17 // a boolean formula that is an AND of ORs of ANDs.
18 //
19 // This level of complexity is rarely used in Go programs. Therefore this
20 // package aims to provide access to all these layers of nesting if required,
21 // but make it easy to forget about for basic use cases too.
22 package buildtags
23
24 import (
25 "errors"
26 "fmt"
27 "strings"
28 "unicode"
29 )
30
31 // Reference: https://github.com/golang/go/blob/204a8f55dc2e0ac8d27a781dab0da609b98560da/src/go/build/doc.go#L73-L92
32 //
33 // // A build constraint is evaluated as the OR of space-separated options;
34 // // each option evaluates as the AND of its comma-separated terms;
35 // // and each term is an alphanumeric word or, preceded by !, its negation.
36 // // That is, the build constraint:
37 // //
38 // // // +build linux,386 darwin,!cgo
39 // //
40 // // corresponds to the boolean formula:
41 // //
42 // // (linux AND 386) OR (darwin AND (NOT cgo))
43 // //
44 // // A file may have multiple build constraints. The overall constraint is the AND
45 // // of the individual constraints. That is, the build constraints:
46 // //
47 // // // +build linux darwin
48 // // // +build 386
49 // //
50 // // corresponds to the boolean formula:
51 // //
52 // // (linux OR darwin) AND 386
53 //
54
55 // Interface represents a build constraint.
56 type Interface interface {
57 ConstraintsConvertable
58 fmt.GoStringer
59 Evaluate(v map[string]bool) bool
60 Validate() error
61 }
62
63 // ConstraintsConvertable can be converted to a Constraints object.
64 type ConstraintsConvertable interface {
65 ToConstraints() Constraints
66 }
67
68 // ConstraintConvertable can be converted to a Constraint.
69 type ConstraintConvertable interface {
70 ToConstraint() Constraint
71 }
72
73 // OptionConvertable can be converted to an Option.
74 type OptionConvertable interface {
75 ToOption() Option
76 }
77
78 // Constraints represents the AND of a list of Constraint lines.
79 type Constraints []Constraint
80
81 // And builds Constraints that will be true if all of its constraints are true.
82 func And(cs ...ConstraintConvertable) Constraints {
83 constraints := Constraints{}
84 for _, c := range cs {
85 constraints = append(constraints, c.ToConstraint())
86 }
87 return constraints
88 }
89
90 // ToConstraints returns cs.
91 func (cs Constraints) ToConstraints() Constraints { return cs }
92
93 // Validate validates the constraints set.
94 func (cs Constraints) Validate() error {
95 for _, c := range cs {
96 if err := c.Validate(); err != nil {
97 return err
98 }
99 }
100 return nil
101 }
102
103 // Evaluate the boolean formula represented by cs under the given assignment of
104 // tag values. This is the AND of the values of the constituent Constraints.
105 func (cs Constraints) Evaluate(v map[string]bool) bool {
106 r := true
107 for _, c := range cs {
108 r = r && c.Evaluate(v)
109 }
110 return r
111 }
112
113 // GoString represents Constraints as +build comment lines.
114 func (cs Constraints) GoString() string {
115 s := ""
116 for _, c := range cs {
117 s += c.GoString()
118 }
119 return s
120 }
121
122 // Constraint represents the OR of a list of Options.
123 type Constraint []Option
124
125 // Any builds a Constraint that will be true if any of its options are true.
126 func Any(opts ...OptionConvertable) Constraint {
127 c := Constraint{}
128 for _, opt := range opts {
129 c = append(c, opt.ToOption())
130 }
131 return c
132 }
133
134 // ParseConstraint parses a space-separated list of options.
135 func ParseConstraint(expr string) (Constraint, error) {
136 c := Constraint{}
137 for _, field := range strings.Fields(expr) {
138 opt, err := ParseOption(field)
139 if err != nil {
140 return c, err
141 }
142 c = append(c, opt)
143 }
144 return c, nil
145 }
146
147 // ToConstraints returns the list of constraints containing just c.
148 func (c Constraint) ToConstraints() Constraints { return Constraints{c} }
149
150 // ToConstraint returns c.
151 func (c Constraint) ToConstraint() Constraint { return c }
152
153 // Validate validates the constraint.
154 func (c Constraint) Validate() error {
155 for _, o := range c {
156 if err := o.Validate(); err != nil {
157 return err
158 }
159 }
160 return nil
161 }
162
163 // Evaluate the boolean formula represented by c under the given assignment of
164 // tag values. This is the OR of the values of the constituent Options.
165 func (c Constraint) Evaluate(v map[string]bool) bool {
166 r := false
167 for _, o := range c {
168 r = r || o.Evaluate(v)
169 }
170 return r
171 }
172
173 // GoString represents the Constraint as one +build comment line.
174 func (c Constraint) GoString() string {
175 s := "// +build"
176 for _, o := range c {
177 s += " " + o.GoString()
178 }
179 return s + "\n"
180 }
181
182 // Option represents the AND of a list of Terms.
183 type Option []Term
184
185 // Opt builds an Option from the list of Terms.
186 func Opt(terms ...Term) Option {
187 return Option(terms)
188 }
189
190 // ParseOption parses a comma-separated list of terms.
191 func ParseOption(expr string) (Option, error) {
192 opt := Option{}
193 for _, t := range strings.Split(expr, ",") {
194 opt = append(opt, Term(t))
195 }
196 return opt, opt.Validate()
197 }
198
199 // ToConstraints returns Constraints containing just this option.
200 func (o Option) ToConstraints() Constraints { return o.ToConstraint().ToConstraints() }
201
202 // ToConstraint returns a Constraint containing just this option.
203 func (o Option) ToConstraint() Constraint { return Constraint{o} }
204
205 // ToOption returns o.
206 func (o Option) ToOption() Option { return o }
207
208 // Validate validates o.
209 func (o Option) Validate() error {
210 for _, t := range o {
211 if err := t.Validate(); err != nil {
212 return fmt.Errorf("invalid term %q: %w", t, err)
213 }
214 }
215 return nil
216 }
217
218 // Evaluate the boolean formula represented by o under the given assignment of
219 // tag values. This is the AND of the values of the constituent Terms.
220 func (o Option) Evaluate(v map[string]bool) bool {
221 r := true
222 for _, t := range o {
223 r = r && t.Evaluate(v)
224 }
225 return r
226 }
227
228 // GoString represents the Option as a comma-separated list of terms.
229 func (o Option) GoString() string {
230 var ts []string
231 for _, t := range o {
232 ts = append(ts, t.GoString())
233 }
234 return strings.Join(ts, ",")
235 }
236
237 // Term is an atomic term in a build constraint: an identifier or its negation.
238 type Term string
239
240 // Not returns a term for the negation of ident.
241 func Not(ident string) Term {
242 return Term("!" + ident)
243 }
244
245 // ToConstraints returns Constraints containing just this term.
246 func (t Term) ToConstraints() Constraints { return t.ToOption().ToConstraints() }
247
248 // ToConstraint returns a Constraint containing just this term.
249 func (t Term) ToConstraint() Constraint { return t.ToOption().ToConstraint() }
250
251 // ToOption returns an Option containing just this term.
252 func (t Term) ToOption() Option { return Option{t} }
253
254 // IsNegated reports whether t is the negation of an identifier.
255 func (t Term) IsNegated() bool { return strings.HasPrefix(string(t), "!") }
256
257 // Name returns the identifier for this term.
258 func (t Term) Name() string {
259 return strings.TrimPrefix(string(t), "!")
260 }
261
262 // Validate the term.
263 func (t Term) Validate() error {
264 // Reference: https://github.com/golang/go/blob/204a8f55dc2e0ac8d27a781dab0da609b98560da/src/cmd/go/internal/imports/build.go#L110-L112
265 //
266 // if strings.HasPrefix(name, "!!") { // bad syntax, reject always
267 // return false
268 // }
269 //
270 if strings.HasPrefix(string(t), "!!") {
271 return errors.New("at most one '!' allowed")
272 }
273
274 if len(t.Name()) == 0 {
275 return errors.New("empty tag name")
276 }
277
278 // Reference: https://github.com/golang/go/blob/204a8f55dc2e0ac8d27a781dab0da609b98560da/src/cmd/go/internal/imports/build.go#L121-L127
279 //
280 // // Tags must be letters, digits, underscores or dots.
281 // // Unlike in Go identifiers, all digits are fine (e.g., "386").
282 // for _, c := range name {
283 // if !unicode.IsLetter(c) && !unicode.IsDigit(c) && c != '_' && c != '.' {
284 // return false
285 // }
286 // }
287 //
288 for _, c := range t.Name() {
289 if !unicode.IsLetter(c) && !unicode.IsDigit(c) && c != '_' && c != '.' {
290 return fmt.Errorf("character '%c' disallowed in tags", c)
291 }
292 }
293
294 return nil
295 }
296
297 // Evaluate the term under the given set of identifier values.
298 func (t Term) Evaluate(v map[string]bool) bool {
299 return (t.Validate() == nil) && (v[t.Name()] == !t.IsNegated())
300 }
301
302 // GoString returns t.
303 func (t Term) GoString() string { return string(t) }
304
305 // SetTags builds a set where the given list of identifiers are true.
306 func SetTags(idents ...string) map[string]bool {
307 v := map[string]bool{}
308 for _, ident := range idents {
309 v[ident] = true
310 }
311 return v
312 }