-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
bind.go
1621 lines (1413 loc) 路 47.8 KB
/
bind.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
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
// Copyright 2016-2021, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package schema
import (
_ "embed"
"fmt"
"io"
"math"
"net/url"
"os"
"path"
"reflect"
"regexp"
"sort"
"strings"
"github.com/blang/semver"
"github.com/hashicorp/hcl/v2"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/santhosh-tekuri/jsonschema/v5"
"github.com/segmentio/encoding/json"
)
//go:embed pulumi.json
var metaSchema string
var MetaSchema *jsonschema.Schema
func init() {
compiler := jsonschema.NewCompiler()
compiler.LoadURL = func(u string) (io.ReadCloser, error) {
if u == "blob://pulumi.json" {
return io.NopCloser(strings.NewReader(metaSchema)), nil
}
return jsonschema.LoadURL(u)
}
MetaSchema = compiler.MustCompile("blob://pulumi.json")
}
func sortedKeys(m interface{}) []string {
rv := reflect.ValueOf(m)
keys := make([]string, 0, rv.Len())
for it := rv.MapRange(); it.Next(); {
keys = append(keys, it.Key().String())
}
sort.Strings(keys)
return keys
}
func memberPath(section, token string, rest ...string) string {
path := fmt.Sprintf("#/%v/%v", section, url.PathEscape(token))
if len(rest) != 0 {
path += "/" + strings.Join(rest, "/")
}
return path
}
func errorf(path, message string, args ...interface{}) *hcl.Diagnostic {
contract.Require(path != "", "path")
summary := path + ": " + fmt.Sprintf(message, args...)
return &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: summary,
}
}
func validateSpec(spec PackageSpec) (hcl.Diagnostics, error) {
bytes, err := json.Marshal(spec)
if err != nil {
return nil, err
}
var raw interface{}
if err = json.Unmarshal(bytes, &raw); err != nil {
return nil, err
}
if err = MetaSchema.Validate(raw); err == nil {
return nil, nil
}
validationError, ok := err.(*jsonschema.ValidationError)
if !ok {
return nil, err
}
var diags hcl.Diagnostics
var appendError func(err *jsonschema.ValidationError)
appendError = func(err *jsonschema.ValidationError) {
if err.InstanceLocation != "" && err.Message != "" {
diags = diags.Append(errorf("#"+err.InstanceLocation, "%v", err.Message))
}
for _, err := range err.Causes {
appendError(err)
}
}
appendError(validationError)
return diags, nil
}
// bindSpec converts a serializable PackageSpec into a Package. This function includes a loader parameter which
// works as a singleton -- if it is nil, a new loader is instantiated, else the provided loader is used. This avoids
// breaking downstream consumers of ImportSpec while allowing us to extend schema support to external packages.
//
// A few notes on diagnostics and errors in spec binding:
//
// - Unless an error is *fatal*--i.e. binding is fundamentally unable to proceed (e.g. because a provider for a
// package failed to load)--errors should be communicated as diagnostics. Fatal errors should be communicated as
// error values.
// - Semantic errors during type binding should not be fatal. Instead, they should return an `InvalidType`. The
// invalid type is accepted in any position, and carries diagnostics that explain the semantic error during binding.
// This allows binding to continue and produce as much information as possible for the end user.
// - Diagnostics may be rendered to users by downstream tools, and should be written with schema authors in mind.
// - Diagnostics _must_ contain enough contextual information for a user to be able to understand the source of the
// diagnostic. Until we have line/column information, we use JSON pointers to the offending entities. These pointers
// are passed around using `path` parameters. The `errorf` function is provided as a utility to easily create a
// diagnostic error that is appropriately tagged with a JSON pointer.
func bindSpec(spec PackageSpec, languages map[string]Language, loader Loader,
validate bool) (*Package, hcl.Diagnostics, error) {
var diags hcl.Diagnostics
// Validate the package against the metaschema.
if validate {
validationDiags, err := validateSpec(spec)
if err != nil {
return nil, nil, fmt.Errorf("validating spec: %w", err)
}
diags = diags.Extend(validationDiags)
}
types, pkgDiags, err := newBinder(spec.Info(), packageSpecSource{&spec}, loader, nil)
if err != nil {
return nil, nil, err
}
defer contract.IgnoreClose(types)
diags = diags.Extend(pkgDiags)
diags = diags.Extend(spec.validateTypeTokens())
config, configDiags, err := bindConfig(spec.Config, types)
if err != nil {
return nil, nil, err
}
diags = diags.Extend(configDiags)
provider, resources, resourceDiags, err := types.finishResources(sortedKeys(spec.Resources))
if err != nil {
return nil, nil, err
}
diags = diags.Extend(resourceDiags)
functions, functionDiags, err := types.finishFunctions(sortedKeys(spec.Functions))
if err != nil {
return nil, nil, err
}
diags = diags.Extend(functionDiags)
typeList, typeDiags, err := types.finishTypes(sortedKeys(spec.Types))
if err != nil {
return nil, nil, err
}
diags = diags.Extend(typeDiags)
pkg := types.pkg
pkg.Config = config
pkg.Types = typeList
pkg.Provider = provider
pkg.Resources = resources
pkg.Functions = functions
pkg.resourceTable = types.resourceDefs
pkg.functionTable = types.functionDefs
pkg.typeTable = types.typeDefs
pkg.resourceTypeTable = types.resources
if err := pkg.ImportLanguages(languages); err != nil {
return nil, nil, err
}
return pkg, diags, nil
}
// Create a new binder.
//
// bindTo overrides the PackageReference field contained in generated types.
func newBinder(info PackageInfoSpec, spec specSource, loader Loader,
bindTo PackageReference) (*types, hcl.Diagnostics, error) {
var diags hcl.Diagnostics
// Validate that there is a name
if info.Name == "" {
diags = diags.Append(errorf("#/name", "no name provided"))
}
// Parse the version, if any.
var version *semver.Version
if info.Version != "" {
v, err := semver.ParseTolerant(info.Version)
if err != nil {
diags = diags.Append(errorf("#/version", "failed to parse semver: %v", err))
} else {
version = &v
}
}
// Parse the module format, if any.
moduleFormat := "(.*)"
if info.Meta != nil && info.Meta.ModuleFormat != "" {
moduleFormat = info.Meta.ModuleFormat
}
moduleFormatRegexp, err := regexp.Compile(moduleFormat)
if err != nil {
diags = diags.Append(errorf("#/meta/moduleFormat", "failed to compile regex: %v", err))
}
language := make(map[string]interface{}, len(info.Language))
for name, v := range info.Language {
language[name] = json.RawMessage(v)
}
pkg := &Package{
moduleFormat: moduleFormatRegexp,
Name: info.Name,
DisplayName: info.DisplayName,
Version: version,
Description: info.Description,
Keywords: info.Keywords,
Homepage: info.Homepage,
License: info.License,
Attribution: info.Attribution,
Repository: info.Repository,
PluginDownloadURL: info.PluginDownloadURL,
Publisher: info.Publisher,
AllowedPackageNames: info.AllowedPackageNames,
LogoURL: info.LogoURL,
Language: language,
}
// We want to use the same loader instance for all referenced packages, so only instantiate the loader if the
// reference is nil.
var loadCtx io.Closer
if loader == nil {
cwd, err := os.Getwd()
if err != nil {
return nil, nil, err
}
ctx, err := plugin.NewContext(nil, nil, nil, nil, cwd, nil, false, nil)
if err != nil {
return nil, nil, err
}
loader, loadCtx = NewPluginLoader(ctx.Host), ctx
}
// Create a type binder.
types := &types{
pkg: pkg,
spec: spec,
loader: loader,
loadCtx: loadCtx,
typeDefs: map[string]Type{},
functionDefs: map[string]*Function{},
resourceDefs: map[string]*Resource{},
resources: map[string]*ResourceType{},
arrays: map[Type]*ArrayType{},
maps: map[Type]*MapType{},
unions: map[string]*UnionType{},
tokens: map[string]*TokenType{},
inputs: map[Type]*InputType{},
optionals: map[Type]*OptionalType{},
bindToReference: bindTo,
}
return types, diags, nil
}
// BindSpec converts a serializable PackageSpec into a Package. Any semantic errors encountered during binding are
// contained in the returned diagnostics. The returned error is only non-nil if a fatal error was encountered.
func BindSpec(spec PackageSpec, loader Loader) (*Package, hcl.Diagnostics, error) {
return bindSpec(spec, nil, loader, true)
}
// ImportSpec converts a serializable PackageSpec into a Package. Unlike BindSpec, ImportSpec does not validate its
// input against the Pulumi package metaschema. ImportSpec should only be used to load packages that are assumed to be
// well-formed (e.g. packages referenced for program code generation or by a root package being used for SDK
// generation). BindSpec should be used to load and validate a package spec prior to generating its SDKs.
func ImportSpec(spec PackageSpec, languages map[string]Language) (*Package, error) {
// Call the internal implementation that includes a loader parameter.
pkg, diags, err := bindSpec(spec, languages, nil, false)
if err != nil {
return nil, err
}
if diags.HasErrors() {
return nil, diags
}
return pkg, nil
}
func importPartialSpec(spec PartialPackageSpec, languages map[string]Language, loader Loader) (*PartialPackage, error) {
pkg := &PartialPackage{
spec: &spec,
languages: languages,
}
types, diags, err := newBinder(spec.PackageInfoSpec, partialPackageSpecSource{&spec}, loader, pkg)
if err != nil {
return nil, err
}
if diags.HasErrors() {
return nil, diags
}
pkg.types = types
return pkg, nil
}
// ImportPartialSpec converts a serializable PartialPackageSpec into a PartialPackage. Unlike a typical Package, a
// PartialPackage loads and binds its members on-demand rather than at import time. This is useful when the entire
// contents of a package are not needed (e.g. for referenced packages).
func ImportPartialSpec(spec PartialPackageSpec, languages map[string]Language) (*PartialPackage, error) {
return importPartialSpec(spec, languages, nil)
}
type specSource interface {
GetTypeDefSpec(token string) (ComplexTypeSpec, bool, error)
GetFunctionSpec(token string) (FunctionSpec, bool, error)
GetResourceSpec(token string) (ResourceSpec, bool, error)
}
type packageSpecSource struct {
spec *PackageSpec
}
func (s packageSpecSource) GetTypeDefSpec(token string) (ComplexTypeSpec, bool, error) {
spec, ok := s.spec.Types[token]
return spec, ok, nil
}
func (s packageSpecSource) GetFunctionSpec(token string) (FunctionSpec, bool, error) {
spec, ok := s.spec.Functions[token]
return spec, ok, nil
}
func (s packageSpecSource) GetResourceSpec(token string) (ResourceSpec, bool, error) {
if token == "pulumi:providers:"+s.spec.Name {
return s.spec.Provider, true, nil
}
spec, ok := s.spec.Resources[token]
return spec, ok, nil
}
type partialPackageSpecSource struct {
spec *PartialPackageSpec
}
func (s partialPackageSpecSource) GetTypeDefSpec(token string) (ComplexTypeSpec, bool, error) {
rawSpec, ok := s.spec.Types[token]
if !ok {
return ComplexTypeSpec{}, false, nil
}
var spec ComplexTypeSpec
if err := parseJSONPropertyValue(rawSpec, &spec); err != nil {
return ComplexTypeSpec{}, false, err
}
return spec, true, nil
}
func (s partialPackageSpecSource) GetFunctionSpec(token string) (FunctionSpec, bool, error) {
rawSpec, ok := s.spec.Functions[token]
if !ok {
return FunctionSpec{}, false, nil
}
var spec FunctionSpec
if err := parseJSONPropertyValue(rawSpec, &spec); err != nil {
return FunctionSpec{}, false, err
}
return spec, true, nil
}
func (s partialPackageSpecSource) GetResourceSpec(token string) (ResourceSpec, bool, error) {
var rawSpec json.RawMessage
if token == "pulumi:providers:"+s.spec.Name {
rawSpec = s.spec.Provider
} else {
raw, ok := s.spec.Resources[token]
if !ok {
return ResourceSpec{}, false, nil
}
rawSpec = raw
}
var spec ResourceSpec
if err := parseJSONPropertyValue(rawSpec, &spec); err != nil {
return ResourceSpec{}, false, err
}
return spec, true, nil
}
// types facilitates interning (only storing a single reference to an object) during schema processing. The fields
// correspond to fields in the schema, and are populated during the binding process.
type types struct {
pkg *Package
spec specSource
loader Loader
loadCtx io.Closer
typeDefs map[string]Type // objects and enums
functionDefs map[string]*Function // function definitions
resourceDefs map[string]*Resource // resource definitions
resources map[string]*ResourceType
arrays map[Type]*ArrayType
maps map[Type]*MapType
unions map[string]*UnionType
tokens map[string]*TokenType
inputs map[Type]*InputType
optionals map[Type]*OptionalType
// A pointer to the package reference that `types` is a part of if it exists.
bindToReference PackageReference
}
func (t *types) Close() error {
if t.loadCtx != nil {
return t.loadCtx.Close()
}
return nil
}
// The package which bound types will link back to.
func (t *types) externalPackage() PackageReference {
if t.bindToReference != nil {
return t.bindToReference
}
return t.pkg.Reference()
}
// nolint: goconst
func (t *types) bindPrimitiveType(path, name string) (Type, hcl.Diagnostics) {
switch name {
case "boolean":
return BoolType, nil
case "integer":
return IntType, nil
case "number":
return NumberType, nil
case "string":
return StringType, nil
default:
return invalidType(errorf(path, "unknown primitive type %v", name))
}
}
// typeSpecRef contains the parsed fields from a type spec reference.
type typeSpecRef struct {
URL *url.URL // The parsed URL
Package string // The package component of the schema ref
Version *semver.Version // The version component of the schema ref
Kind string // The kind of reference: 'resources', 'types', or 'provider'
Token string // The type token
}
const (
resourcesRef = "resources"
typesRef = "types"
providerRef = "provider"
)
// Validate an individual name token.
func (spec *PackageSpec) validateTypeToken(allowedPackageNames map[string]bool, section, token string) hcl.Diagnostics {
diags := hcl.Diagnostics{}
path := memberPath(section, token)
var packageName string
if i := strings.Index(token, ":"); i != -1 {
packageName = token[:i]
}
if !allowedPackageNames[packageName] {
error := errorf(path, "invalid token '%s' (must have package name '%s')", token, spec.Name)
diags = diags.Append(error)
}
return diags
}
// This is for validating non-reference type tokens.
func (spec *PackageSpec) validateTypeTokens() hcl.Diagnostics {
diags := hcl.Diagnostics{}
allowedPackageNames := map[string]bool{spec.Name: true}
for _, prefix := range spec.AllowedPackageNames {
allowedPackageNames[prefix] = true
}
for t := range spec.Resources {
diags = diags.Extend(spec.validateTypeToken(allowedPackageNames, "resources", t))
}
for t := range spec.Types {
diags = diags.Extend(spec.validateTypeToken(allowedPackageNames, "types", t))
}
for t := range spec.Functions {
diags = diags.Extend(spec.validateTypeToken(allowedPackageNames, "functions", t))
}
return diags
}
// Regex used to parse external schema paths. This is declared at the package scope to avoid repeated recompilation.
var refPathRegex = regexp.MustCompile(`^/?(?P<package>[-\w]+)/(?P<version>v[^/]*)/schema\.json$`)
func (t *types) parseTypeSpecRef(refPath, ref string) (typeSpecRef, hcl.Diagnostics) {
parsedURL, err := url.Parse(ref)
if err != nil {
return typeSpecRef{}, hcl.Diagnostics{errorf(refPath, "failed to parse ref URL '%s': %v", ref, err)}
}
// Parse the package name and version if the URL contains a path. If there is no path--if the URL is just a
// fragment--then the reference refers to the package being bound.
pkgName, pkgVersion := t.pkg.Name, t.pkg.Version
if len(parsedURL.Path) > 0 {
path, err := url.PathUnescape(parsedURL.Path)
if err != nil {
return typeSpecRef{}, hcl.Diagnostics{errorf(refPath, "failed to unescape path '%s': %v", parsedURL.Path, err)}
}
pathMatch := refPathRegex.FindStringSubmatch(path)
if len(pathMatch) != 3 {
return typeSpecRef{}, hcl.Diagnostics{errorf(refPath, "failed to parse path '%s'", path)}
}
pkg, versionToken := pathMatch[1], pathMatch[2]
version, err := semver.ParseTolerant(versionToken)
if err != nil {
return typeSpecRef{}, hcl.Diagnostics{errorf(refPath, "failed to parse package version '%s': %v", versionToken, err)}
}
pkgName, pkgVersion = pkg, &version
}
// Parse the fragment into a reference kind and token. The fragment is in one of two forms:
// 1. #/provider
// 2. #/(resources|types)/some:type:token
//
// Unfortunately, early code generators were lax and emitted unescaped backslashes in the type token, so we can't
// just split on "/".
fragment := path.Clean(parsedURL.EscapedFragment())
if path.IsAbs(fragment) {
fragment = fragment[1:]
}
kind, token := "", ""
slash := strings.Index(fragment, "/")
if slash == -1 {
kind = fragment
} else {
kind, token = fragment[:slash], fragment[slash+1:]
}
switch kind {
case "provider":
if token != "" {
return typeSpecRef{}, hcl.Diagnostics{errorf(refPath, "invalid provider reference '%v'", ref)}
}
token = "pulumi:providers:" + pkgName
case "resources", "types":
token, err = url.PathUnescape(token)
if err != nil {
return typeSpecRef{}, hcl.Diagnostics{errorf(refPath, "failed to unescape token '%s': %v", token, err)}
}
default:
return typeSpecRef{}, hcl.Diagnostics{errorf(refPath, "invalid type reference '%v'", ref)}
}
return typeSpecRef{
URL: parsedURL,
Package: pkgName,
Version: pkgVersion,
Kind: kind,
Token: token,
}, nil
}
func versionEquals(a, b *semver.Version) bool {
// We treat "nil" as "unconstrained".
if a == nil || b == nil {
return true
}
return a.Equals(*b)
}
func (t *types) newInputType(elementType Type) Type {
if _, ok := elementType.(*InputType); ok {
return elementType
}
typ, ok := t.inputs[elementType]
if !ok {
typ = &InputType{ElementType: elementType}
t.inputs[elementType] = typ
}
return typ
}
func (t *types) newOptionalType(elementType Type) Type {
if _, ok := elementType.(*OptionalType); ok {
return elementType
}
typ, ok := t.optionals[elementType]
if !ok {
typ = &OptionalType{ElementType: elementType}
t.optionals[elementType] = typ
}
return typ
}
func (t *types) newMapType(elementType Type) Type {
typ, ok := t.maps[elementType]
if !ok {
typ = &MapType{ElementType: elementType}
t.maps[elementType] = typ
}
return typ
}
func (t *types) newArrayType(elementType Type) Type {
typ, ok := t.arrays[elementType]
if !ok {
typ = &ArrayType{ElementType: elementType}
t.arrays[elementType] = typ
}
return typ
}
func (t *types) newUnionType(
elements []Type, defaultType Type, discriminator string, mapping map[string]string) *UnionType {
union := &UnionType{
ElementTypes: elements,
DefaultType: defaultType,
Discriminator: discriminator,
Mapping: mapping,
}
if typ, ok := t.unions[union.String()]; ok {
return typ
}
t.unions[union.String()] = union
return union
}
func (t *types) bindTypeDef(token string) (Type, hcl.Diagnostics, error) {
// Check to see if this type has already been bound.
if typ, ok := t.typeDefs[token]; ok {
return typ, nil, nil
}
// Check to see if we have a definition for this type. If we don't, just return nil.
spec, ok, err := t.spec.GetTypeDefSpec(token)
if err != nil || !ok {
return nil, nil, err
}
path := memberPath("types", token)
// Is this an object type?
if spec.Type == "object" {
// Declare the type.
//
// It's important that we set the token here. This package interns types so that they can be equality-compared
// for identity. Types are interned based on their string representation, and the string representation of an
// object type is its token. While this doesn't affect object types directly, it breaks the interning of types
// that reference object types (e.g. arrays, maps, unions)
obj := &ObjectType{Token: token, IsOverlay: spec.IsOverlay}
obj.InputShape = &ObjectType{Token: token, PlainShape: obj, IsOverlay: spec.IsOverlay}
t.typeDefs[token] = obj
diags, err := t.bindObjectTypeDetails(path, obj, token, spec.ObjectTypeSpec)
if err != nil {
return nil, diags, err
}
return obj, diags, nil
}
// Otherwise, bind an enum type.
enum, diags := t.bindEnumType(token, spec)
t.typeDefs[token] = enum
return enum, diags, nil
}
func (t *types) bindResourceTypeDef(token string) (*ResourceType, hcl.Diagnostics, error) {
if typ, ok := t.resources[token]; ok {
return typ, nil, nil
}
res, diags, err := t.bindResourceDef(token)
if err != nil {
return nil, nil, err
}
if res == nil {
return nil, nil, nil
}
typ := &ResourceType{Token: token, Resource: res}
t.resources[token] = typ
return typ, diags, nil
}
func (t *types) bindTypeSpecRef(path string, spec TypeSpec, inputShape bool) (Type, hcl.Diagnostics, error) {
path = path + "/$ref"
// Explicitly handle built-in types so that we don't have to handle this type of path during ref parsing.
switch spec.Ref {
case "pulumi.json#/Archive":
return ArchiveType, nil, nil
case "pulumi.json#/Asset":
return AssetType, nil, nil
case "pulumi.json#/Json":
return JSONType, nil, nil
case "pulumi.json#/Any":
return AnyType, nil, nil
}
ref, refDiags := t.parseTypeSpecRef(path, spec.Ref)
if refDiags.HasErrors() {
typ, _ := invalidType(refDiags...)
return typ, refDiags, nil
}
// If this is a reference to an external sch
referencesExternalSchema := ref.Package != t.pkg.Name || !versionEquals(ref.Version, t.pkg.Version)
if referencesExternalSchema {
pkg, err := LoadPackageReference(t.loader, ref.Package, ref.Version)
if err != nil {
return nil, nil, fmt.Errorf("resolving package %v: %w", ref.URL, err)
}
switch ref.Kind {
case typesRef:
typ, ok, err := pkg.Types().Get(ref.Token)
if err != nil {
return nil, nil, fmt.Errorf("loading type %v: %w", ref.Token, err)
}
if !ok {
typ, diags := invalidType(errorf(path, "type %v not found in package %v", ref.Token, ref.Package))
return typ, diags, nil
}
if obj, ok := typ.(*ObjectType); ok && inputShape {
typ = obj.InputShape
}
return typ, nil, nil
case resourcesRef, providerRef:
typ, ok, err := pkg.Resources().GetType(ref.Token)
if err != nil {
return nil, nil, fmt.Errorf("loading type %v: %w", ref.Token, err)
}
if !ok {
typ, diags := invalidType(errorf(path, "resource type %v not found in package %v", ref.Token, ref.Package))
return typ, diags, nil
}
return typ, nil, nil
}
}
switch ref.Kind {
case typesRef:
// Try to bind this as a reference to a type defined by this package.
typ, diags, err := t.bindTypeDef(ref.Token)
if err != nil {
return nil, diags, err
}
switch typ := typ.(type) {
case *ObjectType:
// If the type is an object type, we might need to return its input shape.
if inputShape {
return typ.InputShape, diags, nil
}
return typ, diags, nil
case *EnumType:
return typ, diags, nil
default:
contract.Assert(typ == nil)
}
// If the type is not a known type, bind it as an opaque token type.
tokenType, ok := t.tokens[ref.Token]
if !ok {
tokenType = &TokenType{Token: ref.Token}
if spec.Type != "" {
ut, primDiags := t.bindPrimitiveType(path, spec.Type)
diags = diags.Extend(primDiags)
tokenType.UnderlyingType = ut
}
t.tokens[ref.Token] = tokenType
}
return tokenType, diags, nil
case resourcesRef, providerRef:
typ, diags, err := t.bindResourceTypeDef(ref.Token)
if err != nil {
return nil, diags, err
}
if typ == nil {
typ, diags := invalidType(errorf(path, "resource type %v not found in package %v", ref.Token, ref.Package))
return typ, diags, nil
}
return typ, diags, nil
default:
typ, diags := invalidType(errorf(path, "failed to parse ref %s", spec.Ref))
return typ, diags, nil
}
}
func (t *types) bindTypeSpecOneOf(path string, spec TypeSpec, inputShape bool) (Type, hcl.Diagnostics, error) {
var diags hcl.Diagnostics
if len(spec.OneOf) < 2 {
diags = diags.Append(errorf(path+"/oneOf", "oneOf should list at least two types"))
}
var defaultType Type
if spec.Type != "" {
dt, primDiags := t.bindPrimitiveType(path+"/type", spec.Type)
diags = diags.Extend(primDiags)
defaultType = dt
}
elements := make([]Type, len(spec.OneOf))
for i, spec := range spec.OneOf {
e, typDiags, err := t.bindTypeSpec(fmt.Sprintf("%s/oneOf/%v", path, i), spec, inputShape)
diags = diags.Extend(typDiags)
if err != nil {
return nil, diags, err
}
elements[i] = e
}
var discriminator string
var mapping map[string]string
if spec.Discriminator != nil {
if spec.Discriminator.PropertyName == "" {
diags = diags.Append(errorf(path, "discriminator must provide a property name"))
}
discriminator = spec.Discriminator.PropertyName
mapping = spec.Discriminator.Mapping
}
return t.newUnionType(elements, defaultType, discriminator, mapping), diags, nil
}
func (t *types) bindTypeSpec(path string, spec TypeSpec,
inputShape bool) (result Type, diags hcl.Diagnostics, err error) {
// NOTE: `spec.Plain` is the spec of the type, not to be confused with the
// `Plain` property of the underlying `Property`, which is passed as
// `plainProperty`.
if inputShape && !spec.Plain {
defer func() {
result = t.newInputType(result)
}()
}
if spec.Ref != "" {
return t.bindTypeSpecRef(path, spec, inputShape)
}
if spec.OneOf != nil {
return t.bindTypeSpecOneOf(path, spec, inputShape)
}
// nolint: goconst
switch spec.Type {
case "boolean", "integer", "number", "string":
typ, typDiags := t.bindPrimitiveType(path+"/type", spec.Type)
diags = diags.Extend(typDiags)
return typ, diags, nil
case "array":
if spec.Items == nil {
diags = diags.Append(errorf(path, "missing \"items\" property in array type spec"))
typ, _ := invalidType(diags...)
return typ, diags, nil
}
elementType, elementDiags, err := t.bindTypeSpec(path+"/items", *spec.Items, inputShape)
diags = diags.Extend(elementDiags)
if err != nil {
return nil, diags, err
}
return t.newArrayType(elementType), diags, nil
case "object":
elementType, elementDiags, err := t.bindTypeSpec(path, TypeSpec{Type: "string"}, inputShape)
contract.Assert(len(elementDiags) == 0)
contract.Assert(err == nil)
if spec.AdditionalProperties != nil {
et, elementDiags, err := t.bindTypeSpec(path+"/additionalProperties", *spec.AdditionalProperties, inputShape)
diags = diags.Extend(elementDiags)
if err != nil {
return nil, diags, err
}
elementType = et
}
return t.newMapType(elementType), diags, nil
default:
diags = diags.Append(errorf(path+"/type", "unknown type kind %v", spec.Type))
typ, _ := invalidType(diags...)
return typ, diags, nil
}
}
func plainType(typ Type) Type {
for {
switch t := typ.(type) {
case *InputType:
typ = t.ElementType
case *OptionalType:
typ = t.ElementType
case *ObjectType:
if t.PlainShape == nil {
return t
}
typ = t.PlainShape
default:
return t
}
}
}
func bindConstValue(path, kind string, value interface{}, typ Type) (interface{}, hcl.Diagnostics) {
if value == nil {
return nil, nil
}
typeError := func(expectedType string) hcl.Diagnostics {
return hcl.Diagnostics{errorf(path, "invalid constant of type %T for %v %v", value, expectedType, kind)}
}
switch typ = plainType(typ); typ {
case BoolType:
if _, ok := value.(bool); !ok {
return false, typeError("boolean")
}
case IntType:
v, ok := value.(float64)
if !ok {
return 0, typeError("integer")
}
if math.Trunc(v) != v || v < math.MinInt32 || v > math.MaxInt32 {
return 0, typeError("integer")
}
value = int32(v)
case NumberType:
if _, ok := value.(float64); !ok {
return 0.0, typeError("number")
}
case StringType:
if _, ok := value.(string); !ok {
return 0.0, typeError("string")
}
default:
if _, isInvalid := typ.(*InvalidType); isInvalid {
return nil, nil
}
return nil, hcl.Diagnostics{errorf(path, "type %v cannot have a constant value; only booleans, integers, "+
"numbers and strings may have constant values", typ)}
}
return value, nil
}
func bindDefaultValue(path string, value interface{}, spec *DefaultSpec, typ Type) (*DefaultValue, hcl.Diagnostics) {
if value == nil && spec == nil {
return nil, nil
}
var diags hcl.Diagnostics
if value != nil {
typ = plainType(typ)
switch typ := typ.(type) {
case *UnionType:
if typ.DefaultType != nil {
return bindDefaultValue(path, value, spec, typ.DefaultType)
}
for _, elementType := range typ.ElementTypes {
v, diags := bindDefaultValue(path, value, spec, elementType)
if !diags.HasErrors() {
return v, diags