2020-03-17 03:04:32 +00:00
|
|
|
// Copyright 2016-2020, 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.
|
|
|
|
|
2021-09-30 03:11:56 +00:00
|
|
|
package pcl
|
2020-03-17 03:04:32 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/hashicorp/hcl/v2"
|
2024-06-20 09:04:33 +00:00
|
|
|
"github.com/pulumi/inflector"
|
2021-03-17 13:20:05 +00:00
|
|
|
"github.com/pulumi/pulumi/pkg/v3/codegen"
|
|
|
|
"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model"
|
|
|
|
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
|
2020-04-25 05:04:24 +00:00
|
|
|
"github.com/zclconf/go-cty/cty"
|
2020-03-17 03:04:32 +00:00
|
|
|
)
|
|
|
|
|
2020-04-03 00:38:03 +00:00
|
|
|
type NameInfo interface {
|
2020-04-25 05:04:24 +00:00
|
|
|
Format(name string) string
|
2020-04-03 00:38:03 +00:00
|
|
|
}
|
|
|
|
|
2020-04-25 05:04:24 +00:00
|
|
|
// The applyRewriter is responsible for driving the apply rewrite process. The rewriter uses a stack of contexts to
|
|
|
|
// deal with the possibility of expressions that observe outputs nested inside expressions that do not.
|
2020-04-07 02:43:16 +00:00
|
|
|
type applyRewriter struct {
|
|
|
|
nameInfo NameInfo
|
|
|
|
applyPromises bool
|
[program-gen] Emit Output-returning JSON serialization methods without rewriting applies (#15371)
### Description
A while ago we started implementing [specialized JSON serialization
methods](https://github.com/pulumi/pulumi/issues/12519) for Pulumi
programs which can accept nested outputs without having to rewrite and
combine applies.
- `Output.SerializeJson` in .NET
- `pulumi.jsonStringify` in nodejs
- `pulumi.Output.json_dumps` in Python
This PR extends program-gen for TypeScript, C# and Python to start
emitting these JSON serialization functions (when necessary). The PR
special-cases the `toJSON` PCL function when rewriting applies so that
nested outputs aren't rewritted.
Example PCL program and generated results:
> Also check out the downstream codegen tests to see improved generated
examples
```
resource vpc "aws:ec2:Vpc" {
cidrBlock = "10.100.0.0/16"
instanceTenancy = "default"
}
resource policy "aws:iam/policy:Policy" {
description = "test"
policy = toJSON({
"Version" = "2012-10-17"
"Interpolated" = "arn:${vpc.arn}:value"
"Value" = vpc.id
})
}
```
### Generated TypeScript Before
```typescript
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
const vpc = new aws.ec2.Vpc("vpc", {
cidrBlock: "10.100.0.0/16",
instanceTenancy: "default",
});
const policy = new aws.iam.Policy("policy", {
description: "test",
policy: pulumi.all([vpc.arn, vpc.id]).apply(([arn, id]) => JSON.stringify({
Version: "2012-10-17",
Interpolated: `arn:${arn}:value`,
Value: id,
})),
});
```
### Generated TypeScript After
```typescript
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
const vpc = new aws.ec2.Vpc("vpc", {
cidrBlock: "10.100.0.0/16",
instanceTenancy: "default",
});
const policy = new aws.iam.Policy("policy", {
description: "test",
policy: pulumi.jsonStringify({
Version: "2012-10-17",
Interpolated: pulumi.interpolate`arn:${vpc.arn}:value`,
Value: vpc.id,
}),
});
```
### Generated Python Before
```python
import pulumi
import json
import pulumi_aws as aws
vpc = aws.ec2.Vpc("vpc",
cidr_block="10.100.0.0/16",
instance_tenancy="default")
policy = aws.iam.Policy("policy",
description="test",
policy=pulumi.Output.all(vpc.arn, vpc.id).apply(lambda arn, id: json.dumps({
"Version": "2012-10-17",
"Interpolated": f"arn:{arn}:value",
"Value": id,
})))
```
### Generated Python After
```python
import pulumi
import json
import pulumi_aws as aws
vpc = aws.ec2.Vpc("vpc",
cidr_block="10.100.0.0/16",
instance_tenancy="default")
policy = aws.iam.Policy("policy",
description="test",
policy=pulumi.Output.json_dumps({
"Version": "2012-10-17",
"Interpolated": vpc.arn.apply(lambda arn: f"arn:{arn}:value"),
"Value": vpc.id,
}))
```
### Generated C# Before
```csharp
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Pulumi;
using Aws = Pulumi.Aws;
return await Deployment.RunAsync(() =>
{
var vpc = new Aws.Ec2.Vpc("vpc", new()
{
CidrBlock = "10.100.0.0/16",
InstanceTenancy = "default",
});
var policy = new Aws.Iam.Policy("policy", new()
{
Description = "test",
PolicyDocument = Output.Tuple(vpc.Arn, vpc.Id).Apply(values =>
{
var arn = values.Item1;
var id = values.Item2;
return JsonSerializer.Serialize(new Dictionary<string, object?>
{
["Version"] = "2012-10-17",
["Interpolated"] = $"arn:{arn}:value",
["Value"] = id,
});
}),
});
});
```
### Generated C# After
```csharp
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Pulumi;
using Aws = Pulumi.Aws;
return await Deployment.RunAsync(() =>
{
var vpc = new Aws.Ec2.Vpc("vpc", new()
{
CidrBlock = "10.100.0.0/16",
InstanceTenancy = "default",
});
var policy = new Aws.Iam.Policy("policy", new()
{
Description = "test",
PolicyDocument = Output.JsonSerialize(Output.Create(new Dictionary<string, object?>
{
["Version"] = "2012-10-17",
["Interpolated"] = vpc.Arn.Apply(arn => $"arn:{arn}:value"),
["Value"] = vpc.Id,
})),
});
});
```
## Checklist
- [ ] I have run `make tidy` to update any new dependencies
- [x] I have run `make lint` to verify my code passes the lint check
- [x] I have formatted my code using `gofumpt`
<!--- Please provide details if the checkbox below is to be left
unchecked. -->
- [x] I have added tests that prove my fix is effective or that my
feature works
<!---
User-facing changes require a CHANGELOG entry.
-->
- [x] I have run `make changelog` and committed the
`changelog/pending/<file>` documenting my change
<!--
If the change(s) in this PR is a modification of an existing call to the
Pulumi Cloud,
then the service should honor older versions of the CLI where this
change would not exist.
You must then bump the API version in
/pkg/backend/httpstate/client/api.go, as well as add
it to the service.
-->
- [ ] Yes, there are changes in this PR that warrants bumping the Pulumi
Cloud API version
<!-- @Pulumi employees: If yes, you must submit corresponding changes in
the service repo. -->
2024-02-20 15:48:46 +00:00
|
|
|
skipToJSON bool
|
2020-04-25 05:04:24 +00:00
|
|
|
|
|
|
|
activeContext applyRewriteContext
|
2020-05-07 19:15:40 +00:00
|
|
|
exprStack []model.Expression
|
2020-04-25 05:04:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type applyRewriteContext interface {
|
|
|
|
PreVisit(x model.Expression) (model.Expression, hcl.Diagnostics)
|
|
|
|
PostVisit(x model.Expression) (model.Expression, hcl.Diagnostics)
|
|
|
|
}
|
|
|
|
|
|
|
|
// An inspectContext is used when we are inside an expression that does not observe eventual values. When it
|
|
|
|
// encounters an expression that observes eventual values, it pushes a new observeContext onto the stack.
|
|
|
|
type inspectContext struct {
|
|
|
|
*applyRewriter
|
|
|
|
|
|
|
|
parent *observeContext
|
|
|
|
|
|
|
|
root model.Expression
|
2020-04-22 22:46:56 +00:00
|
|
|
}
|
|
|
|
|
2020-04-25 05:04:24 +00:00
|
|
|
// An observeContext is used when we are inside an expression that does observe eventual values. It is responsible for
|
|
|
|
// finding the values that are observed, replacing them with references to apply parameters, and replacing the root
|
|
|
|
// expression with a call to the __apply intrinsic.
|
|
|
|
type observeContext struct {
|
|
|
|
*applyRewriter
|
|
|
|
|
|
|
|
parent applyRewriteContext
|
2020-04-07 02:43:16 +00:00
|
|
|
|
|
|
|
root model.Expression
|
2020-04-25 05:04:24 +00:00
|
|
|
applyArgs []model.Expression
|
2020-04-07 02:43:16 +00:00
|
|
|
callbackParams []*model.Variable
|
|
|
|
paramReferences []*model.ScopeTraversalExpression
|
|
|
|
|
|
|
|
assignedNames codegen.StringSet
|
|
|
|
nameCounts map[string]int
|
|
|
|
}
|
|
|
|
|
2023-04-26 18:00:32 +00:00
|
|
|
func HasEventualTypes(t model.Type) bool {
|
2020-05-07 19:15:40 +00:00
|
|
|
resolved := model.ResolveOutputs(t)
|
|
|
|
return resolved != t
|
|
|
|
}
|
|
|
|
|
2023-04-26 18:00:32 +00:00
|
|
|
func (r *applyRewriter) hasEventualTypes(t model.Type) bool {
|
|
|
|
return HasEventualTypes(t)
|
|
|
|
}
|
|
|
|
|
2020-04-25 05:04:24 +00:00
|
|
|
func (r *applyRewriter) hasEventualValues(x model.Expression) bool {
|
2020-05-07 19:15:40 +00:00
|
|
|
return r.hasEventualTypes(x.Type())
|
2020-04-25 05:04:24 +00:00
|
|
|
}
|
|
|
|
|
2020-04-07 02:43:16 +00:00
|
|
|
func (r *applyRewriter) isEventualType(t model.Type) (model.Type, bool) {
|
2020-03-17 03:04:32 +00:00
|
|
|
switch t := t.(type) {
|
|
|
|
case *model.OutputType:
|
|
|
|
return t.ElementType, true
|
|
|
|
case *model.PromiseType:
|
2020-04-07 02:43:16 +00:00
|
|
|
if r.applyPromises {
|
|
|
|
return t.ElementType, true
|
|
|
|
}
|
2020-03-17 03:04:32 +00:00
|
|
|
case *model.UnionType:
|
|
|
|
types, isEventual := make([]model.Type, len(t.ElementTypes)), false
|
|
|
|
for i, t := range t.ElementTypes {
|
2020-04-07 02:43:16 +00:00
|
|
|
if element, elementIsEventual := r.isEventualType(t); elementIsEventual {
|
2020-03-17 03:04:32 +00:00
|
|
|
t, isEventual = element, true
|
|
|
|
}
|
|
|
|
types[i] = t
|
|
|
|
}
|
|
|
|
if isEventual {
|
|
|
|
return model.NewUnionType(types...), true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
|
2020-05-07 19:15:40 +00:00
|
|
|
func (r *applyRewriter) hasEventualElements(x model.Expression) bool {
|
|
|
|
t := x.Type()
|
|
|
|
if resolved, ok := r.isEventualType(t); ok {
|
|
|
|
t = resolved
|
|
|
|
}
|
|
|
|
return r.hasEventualTypes(t)
|
|
|
|
}
|
|
|
|
|
2020-04-25 05:04:24 +00:00
|
|
|
func (r *applyRewriter) isPromptArg(paramType model.Type, arg model.Expression) bool {
|
|
|
|
if !r.hasEventualValues(arg) {
|
2020-04-16 23:44:34 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
if union, ok := paramType.(*model.UnionType); ok {
|
|
|
|
for _, t := range union.ElementTypes {
|
2020-04-25 05:04:24 +00:00
|
|
|
if t != model.DynamicType && t.ConversionFrom(arg.Type()) != model.NoConversion {
|
2020-04-16 23:44:34 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
2020-04-25 05:04:24 +00:00
|
|
|
return paramType != model.DynamicType && paramType.ConversionFrom(arg.Type()) != model.NoConversion
|
2020-04-16 23:44:34 +00:00
|
|
|
}
|
|
|
|
|
2020-05-07 19:15:40 +00:00
|
|
|
func (r *applyRewriter) isIteratorExpr(x model.Expression) (bool, model.Type) {
|
|
|
|
if len(r.exprStack) < 2 {
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
parent := r.exprStack[len(r.exprStack)-2]
|
|
|
|
switch parent := parent.(type) {
|
|
|
|
case *model.ForExpression:
|
|
|
|
return x != parent.Collection, parent.ValueVariable.Type()
|
|
|
|
case *model.SplatExpression:
|
|
|
|
return x != parent.Source, parent.Item.Type()
|
|
|
|
default:
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-25 05:04:24 +00:00
|
|
|
func (r *applyRewriter) inspectsEventualValues(x model.Expression) bool {
|
|
|
|
switch x := x.(type) {
|
|
|
|
case *model.ConditionalExpression:
|
|
|
|
return r.hasEventualValues(x.TrueResult) || r.hasEventualValues(x.FalseResult)
|
2020-05-07 19:15:40 +00:00
|
|
|
case *model.ForExpression:
|
|
|
|
return r.hasEventualElements(x.Collection)
|
2020-04-25 05:04:24 +00:00
|
|
|
case *model.FunctionCallExpression:
|
[program-gen] Emit Output-returning JSON serialization methods without rewriting applies (#15371)
### Description
A while ago we started implementing [specialized JSON serialization
methods](https://github.com/pulumi/pulumi/issues/12519) for Pulumi
programs which can accept nested outputs without having to rewrite and
combine applies.
- `Output.SerializeJson` in .NET
- `pulumi.jsonStringify` in nodejs
- `pulumi.Output.json_dumps` in Python
This PR extends program-gen for TypeScript, C# and Python to start
emitting these JSON serialization functions (when necessary). The PR
special-cases the `toJSON` PCL function when rewriting applies so that
nested outputs aren't rewritted.
Example PCL program and generated results:
> Also check out the downstream codegen tests to see improved generated
examples
```
resource vpc "aws:ec2:Vpc" {
cidrBlock = "10.100.0.0/16"
instanceTenancy = "default"
}
resource policy "aws:iam/policy:Policy" {
description = "test"
policy = toJSON({
"Version" = "2012-10-17"
"Interpolated" = "arn:${vpc.arn}:value"
"Value" = vpc.id
})
}
```
### Generated TypeScript Before
```typescript
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
const vpc = new aws.ec2.Vpc("vpc", {
cidrBlock: "10.100.0.0/16",
instanceTenancy: "default",
});
const policy = new aws.iam.Policy("policy", {
description: "test",
policy: pulumi.all([vpc.arn, vpc.id]).apply(([arn, id]) => JSON.stringify({
Version: "2012-10-17",
Interpolated: `arn:${arn}:value`,
Value: id,
})),
});
```
### Generated TypeScript After
```typescript
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
const vpc = new aws.ec2.Vpc("vpc", {
cidrBlock: "10.100.0.0/16",
instanceTenancy: "default",
});
const policy = new aws.iam.Policy("policy", {
description: "test",
policy: pulumi.jsonStringify({
Version: "2012-10-17",
Interpolated: pulumi.interpolate`arn:${vpc.arn}:value`,
Value: vpc.id,
}),
});
```
### Generated Python Before
```python
import pulumi
import json
import pulumi_aws as aws
vpc = aws.ec2.Vpc("vpc",
cidr_block="10.100.0.0/16",
instance_tenancy="default")
policy = aws.iam.Policy("policy",
description="test",
policy=pulumi.Output.all(vpc.arn, vpc.id).apply(lambda arn, id: json.dumps({
"Version": "2012-10-17",
"Interpolated": f"arn:{arn}:value",
"Value": id,
})))
```
### Generated Python After
```python
import pulumi
import json
import pulumi_aws as aws
vpc = aws.ec2.Vpc("vpc",
cidr_block="10.100.0.0/16",
instance_tenancy="default")
policy = aws.iam.Policy("policy",
description="test",
policy=pulumi.Output.json_dumps({
"Version": "2012-10-17",
"Interpolated": vpc.arn.apply(lambda arn: f"arn:{arn}:value"),
"Value": vpc.id,
}))
```
### Generated C# Before
```csharp
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Pulumi;
using Aws = Pulumi.Aws;
return await Deployment.RunAsync(() =>
{
var vpc = new Aws.Ec2.Vpc("vpc", new()
{
CidrBlock = "10.100.0.0/16",
InstanceTenancy = "default",
});
var policy = new Aws.Iam.Policy("policy", new()
{
Description = "test",
PolicyDocument = Output.Tuple(vpc.Arn, vpc.Id).Apply(values =>
{
var arn = values.Item1;
var id = values.Item2;
return JsonSerializer.Serialize(new Dictionary<string, object?>
{
["Version"] = "2012-10-17",
["Interpolated"] = $"arn:{arn}:value",
["Value"] = id,
});
}),
});
});
```
### Generated C# After
```csharp
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Pulumi;
using Aws = Pulumi.Aws;
return await Deployment.RunAsync(() =>
{
var vpc = new Aws.Ec2.Vpc("vpc", new()
{
CidrBlock = "10.100.0.0/16",
InstanceTenancy = "default",
});
var policy = new Aws.Iam.Policy("policy", new()
{
Description = "test",
PolicyDocument = Output.JsonSerialize(Output.Create(new Dictionary<string, object?>
{
["Version"] = "2012-10-17",
["Interpolated"] = vpc.Arn.Apply(arn => $"arn:{arn}:value"),
["Value"] = vpc.Id,
})),
});
});
```
## Checklist
- [ ] I have run `make tidy` to update any new dependencies
- [x] I have run `make lint` to verify my code passes the lint check
- [x] I have formatted my code using `gofumpt`
<!--- Please provide details if the checkbox below is to be left
unchecked. -->
- [x] I have added tests that prove my fix is effective or that my
feature works
<!---
User-facing changes require a CHANGELOG entry.
-->
- [x] I have run `make changelog` and committed the
`changelog/pending/<file>` documenting my change
<!--
If the change(s) in this PR is a modification of an existing call to the
Pulumi Cloud,
then the service should honor older versions of the CLI where this
change would not exist.
You must then bump the API version in
/pkg/backend/httpstate/client/api.go, as well as add
it to the service.
-->
- [ ] Yes, there are changes in this PR that warrants bumping the Pulumi
Cloud API version
<!-- @Pulumi employees: If yes, you must submit corresponding changes in
the service repo. -->
2024-02-20 15:48:46 +00:00
|
|
|
// special case toJSON function because we map it to pulumi.jsonStringify which accepts anything
|
|
|
|
// such that it doesn't have to rewrite its subexpressions to apply but can be used directly
|
|
|
|
if r.skipToJSON && x.Name == "toJSON" {
|
|
|
|
return false
|
|
|
|
}
|
2020-07-16 17:26:10 +00:00
|
|
|
_, isEventual := r.isEventualType(x.Signature.ReturnType)
|
|
|
|
if isEventual {
|
|
|
|
return true
|
|
|
|
}
|
2020-04-25 05:04:24 +00:00
|
|
|
for i, arg := range x.Args {
|
|
|
|
if r.hasEventualValues(arg) && r.isPromptArg(x.Signature.Parameters[i].Type, arg) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
case *model.IndexExpression:
|
|
|
|
_, isCollectionEventual := r.isEventualType(x.Collection.Type())
|
|
|
|
return !isCollectionEventual && r.hasEventualValues(x.Collection)
|
|
|
|
case *model.SplatExpression:
|
2020-05-07 19:15:40 +00:00
|
|
|
return r.hasEventualElements(x.Source)
|
2020-04-25 05:04:24 +00:00
|
|
|
default:
|
2020-05-07 19:15:40 +00:00
|
|
|
if isIteratorExpr, elementType := r.isIteratorExpr(x); isIteratorExpr {
|
|
|
|
_, isElementEventual := r.isEventualType(elementType)
|
|
|
|
return !isElementEventual && r.hasEventualTypes(elementType)
|
|
|
|
}
|
2020-04-16 23:44:34 +00:00
|
|
|
return false
|
|
|
|
}
|
2020-04-25 05:04:24 +00:00
|
|
|
}
|
2020-04-16 23:44:34 +00:00
|
|
|
|
2020-04-25 05:04:24 +00:00
|
|
|
func (r *applyRewriter) observesEventualValues(x model.Expression) bool {
|
|
|
|
_, isEventual := r.isEventualType(x.Type())
|
|
|
|
if !isEventual {
|
|
|
|
return false
|
2020-04-16 23:44:34 +00:00
|
|
|
}
|
|
|
|
|
2020-04-25 05:04:24 +00:00
|
|
|
switch x := x.(type) {
|
|
|
|
case *model.AnonymousFunctionExpression:
|
|
|
|
return false
|
|
|
|
case *model.ConditionalExpression:
|
|
|
|
return r.hasEventualValues(x.Condition)
|
2020-05-07 19:15:40 +00:00
|
|
|
case *model.ForExpression:
|
|
|
|
_, collectionIsEventual := r.isEventualType(x.Collection.Type())
|
|
|
|
return collectionIsEventual
|
2020-04-25 05:04:24 +00:00
|
|
|
case *model.FunctionCallExpression:
|
[program-gen] Emit Output-returning JSON serialization methods without rewriting applies (#15371)
### Description
A while ago we started implementing [specialized JSON serialization
methods](https://github.com/pulumi/pulumi/issues/12519) for Pulumi
programs which can accept nested outputs without having to rewrite and
combine applies.
- `Output.SerializeJson` in .NET
- `pulumi.jsonStringify` in nodejs
- `pulumi.Output.json_dumps` in Python
This PR extends program-gen for TypeScript, C# and Python to start
emitting these JSON serialization functions (when necessary). The PR
special-cases the `toJSON` PCL function when rewriting applies so that
nested outputs aren't rewritted.
Example PCL program and generated results:
> Also check out the downstream codegen tests to see improved generated
examples
```
resource vpc "aws:ec2:Vpc" {
cidrBlock = "10.100.0.0/16"
instanceTenancy = "default"
}
resource policy "aws:iam/policy:Policy" {
description = "test"
policy = toJSON({
"Version" = "2012-10-17"
"Interpolated" = "arn:${vpc.arn}:value"
"Value" = vpc.id
})
}
```
### Generated TypeScript Before
```typescript
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
const vpc = new aws.ec2.Vpc("vpc", {
cidrBlock: "10.100.0.0/16",
instanceTenancy: "default",
});
const policy = new aws.iam.Policy("policy", {
description: "test",
policy: pulumi.all([vpc.arn, vpc.id]).apply(([arn, id]) => JSON.stringify({
Version: "2012-10-17",
Interpolated: `arn:${arn}:value`,
Value: id,
})),
});
```
### Generated TypeScript After
```typescript
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
const vpc = new aws.ec2.Vpc("vpc", {
cidrBlock: "10.100.0.0/16",
instanceTenancy: "default",
});
const policy = new aws.iam.Policy("policy", {
description: "test",
policy: pulumi.jsonStringify({
Version: "2012-10-17",
Interpolated: pulumi.interpolate`arn:${vpc.arn}:value`,
Value: vpc.id,
}),
});
```
### Generated Python Before
```python
import pulumi
import json
import pulumi_aws as aws
vpc = aws.ec2.Vpc("vpc",
cidr_block="10.100.0.0/16",
instance_tenancy="default")
policy = aws.iam.Policy("policy",
description="test",
policy=pulumi.Output.all(vpc.arn, vpc.id).apply(lambda arn, id: json.dumps({
"Version": "2012-10-17",
"Interpolated": f"arn:{arn}:value",
"Value": id,
})))
```
### Generated Python After
```python
import pulumi
import json
import pulumi_aws as aws
vpc = aws.ec2.Vpc("vpc",
cidr_block="10.100.0.0/16",
instance_tenancy="default")
policy = aws.iam.Policy("policy",
description="test",
policy=pulumi.Output.json_dumps({
"Version": "2012-10-17",
"Interpolated": vpc.arn.apply(lambda arn: f"arn:{arn}:value"),
"Value": vpc.id,
}))
```
### Generated C# Before
```csharp
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Pulumi;
using Aws = Pulumi.Aws;
return await Deployment.RunAsync(() =>
{
var vpc = new Aws.Ec2.Vpc("vpc", new()
{
CidrBlock = "10.100.0.0/16",
InstanceTenancy = "default",
});
var policy = new Aws.Iam.Policy("policy", new()
{
Description = "test",
PolicyDocument = Output.Tuple(vpc.Arn, vpc.Id).Apply(values =>
{
var arn = values.Item1;
var id = values.Item2;
return JsonSerializer.Serialize(new Dictionary<string, object?>
{
["Version"] = "2012-10-17",
["Interpolated"] = $"arn:{arn}:value",
["Value"] = id,
});
}),
});
});
```
### Generated C# After
```csharp
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Pulumi;
using Aws = Pulumi.Aws;
return await Deployment.RunAsync(() =>
{
var vpc = new Aws.Ec2.Vpc("vpc", new()
{
CidrBlock = "10.100.0.0/16",
InstanceTenancy = "default",
});
var policy = new Aws.Iam.Policy("policy", new()
{
Description = "test",
PolicyDocument = Output.JsonSerialize(Output.Create(new Dictionary<string, object?>
{
["Version"] = "2012-10-17",
["Interpolated"] = vpc.Arn.Apply(arn => $"arn:{arn}:value"),
["Value"] = vpc.Id,
})),
});
});
```
## Checklist
- [ ] I have run `make tidy` to update any new dependencies
- [x] I have run `make lint` to verify my code passes the lint check
- [x] I have formatted my code using `gofumpt`
<!--- Please provide details if the checkbox below is to be left
unchecked. -->
- [x] I have added tests that prove my fix is effective or that my
feature works
<!---
User-facing changes require a CHANGELOG entry.
-->
- [x] I have run `make changelog` and committed the
`changelog/pending/<file>` documenting my change
<!--
If the change(s) in this PR is a modification of an existing call to the
Pulumi Cloud,
then the service should honor older versions of the CLI where this
change would not exist.
You must then bump the API version in
/pkg/backend/httpstate/client/api.go, as well as add
it to the service.
-->
- [ ] Yes, there are changes in this PR that warrants bumping the Pulumi
Cloud API version
<!-- @Pulumi employees: If yes, you must submit corresponding changes in
the service repo. -->
2024-02-20 15:48:46 +00:00
|
|
|
// special case toJSON function because we map it to pulumi.jsonStringify which accepts anything
|
|
|
|
// such that it doesn't have to rewrite its subexpressions to apply but can be used directly
|
|
|
|
if r.skipToJSON && x.Name == "toJSON" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2020-04-25 05:04:24 +00:00
|
|
|
for i, arg := range x.Args {
|
|
|
|
if !r.isPromptArg(x.Signature.Parameters[i].Type, arg) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
case *model.IndexExpression:
|
2020-05-07 19:15:40 +00:00
|
|
|
if _, collectionIsEventual := r.isEventualType(x.Collection.Type()); collectionIsEventual {
|
2020-04-16 23:44:34 +00:00
|
|
|
return true
|
|
|
|
}
|
2020-04-25 05:04:24 +00:00
|
|
|
return r.hasEventualValues(x.Key)
|
|
|
|
case *model.RelativeTraversalExpression:
|
|
|
|
// A traversal is eventual if at least one of its nonterminals is eventual.
|
|
|
|
for _, p := range x.Parts[:len(x.Parts)-1] {
|
|
|
|
if _, isEventual := r.isEventualType(model.GetTraversableType(p)); isEventual {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
case *model.ScopeTraversalExpression:
|
|
|
|
// A traversal is eventual if at least one of its nonterminals is eventual.
|
|
|
|
for _, p := range x.Parts[:len(x.Parts)-1] {
|
|
|
|
if _, isEventual := r.isEventualType(model.GetTraversableType(p)); isEventual {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
case *model.SplatExpression:
|
|
|
|
_, sourceIsEventual := r.isEventualType(x.Source.Type())
|
|
|
|
return sourceIsEventual
|
|
|
|
default:
|
|
|
|
return true
|
2020-04-16 23:44:34 +00:00
|
|
|
}
|
2020-04-25 05:04:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *applyRewriter) preVisit(expr model.Expression) (model.Expression, hcl.Diagnostics) {
|
2020-05-07 19:15:40 +00:00
|
|
|
r.exprStack = append(r.exprStack, expr)
|
2020-04-25 05:04:24 +00:00
|
|
|
return r.activeContext.PreVisit(expr)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *applyRewriter) postVisit(expr model.Expression) (model.Expression, hcl.Diagnostics) {
|
2020-05-07 19:15:40 +00:00
|
|
|
x, diags := r.activeContext.PostVisit(expr)
|
|
|
|
r.exprStack = r.exprStack[:len(r.exprStack)-1]
|
|
|
|
return x, diags
|
2020-04-16 23:44:34 +00:00
|
|
|
}
|
|
|
|
|
2020-04-03 00:38:03 +00:00
|
|
|
// disambiguateName ensures that the given name is unambiguous by appending an integer starting with 1 if necessary.
|
2020-04-25 05:04:24 +00:00
|
|
|
func (ctx *observeContext) disambiguateName(name string) string {
|
2020-04-03 00:38:03 +00:00
|
|
|
if name == "" {
|
|
|
|
name = "arg"
|
|
|
|
}
|
|
|
|
|
2020-04-22 22:46:56 +00:00
|
|
|
if !ctx.assignedNames.Has(name) {
|
2020-04-03 00:38:03 +00:00
|
|
|
return name
|
|
|
|
}
|
|
|
|
|
|
|
|
root := name
|
2020-04-22 22:46:56 +00:00
|
|
|
for i := 1; ctx.nameCounts[name] != 0; i++ {
|
2020-04-03 00:38:03 +00:00
|
|
|
name = fmt.Sprintf("%s%d", root, i)
|
|
|
|
}
|
|
|
|
return name
|
|
|
|
}
|
|
|
|
|
2020-04-25 05:04:24 +00:00
|
|
|
func (ctx *observeContext) bestTraversalName(rootName string, traversal hcl.Traversal) string {
|
|
|
|
for i := len(traversal) - 1; i >= 0; i-- {
|
|
|
|
switch t := traversal[i].(type) {
|
|
|
|
case hcl.TraverseAttr:
|
|
|
|
return t.Name
|
|
|
|
case hcl.TraverseIndex:
|
|
|
|
if t.Key.Type().Equals(cty.String) {
|
|
|
|
return t.Key.AsString()
|
|
|
|
}
|
|
|
|
return inflector.Singularize(ctx.bestTraversalName(rootName, traversal[:i]))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return rootName
|
|
|
|
}
|
|
|
|
|
2020-04-03 00:38:03 +00:00
|
|
|
// bestArgName computes the "best" name for a given apply argument. If this name is unambiguous after all best names
|
|
|
|
// have been calculated, it will be assigned to the argument. Otherwise, it will go through the disambiguation process
|
|
|
|
// in disambiguateArgName.
|
2020-04-25 05:04:24 +00:00
|
|
|
func (ctx *observeContext) bestArgName(x model.Expression) string {
|
|
|
|
switch x := x.(type) {
|
|
|
|
case *model.ForExpression:
|
|
|
|
if x.Key == nil {
|
|
|
|
return inflector.Pluralize(ctx.bestArgName(x.Value))
|
2020-04-03 00:38:03 +00:00
|
|
|
}
|
2020-04-25 05:04:24 +00:00
|
|
|
case *model.FunctionCallExpression:
|
|
|
|
switch x.Name {
|
|
|
|
case IntrinsicApply:
|
2020-05-07 19:15:40 +00:00
|
|
|
_, then := ParseApplyCall(x)
|
|
|
|
return ctx.bestArgName(then.Body)
|
2020-04-25 05:04:24 +00:00
|
|
|
case "element":
|
|
|
|
return ctx.bestArgName(x.Args[0])
|
2022-04-25 19:59:30 +00:00
|
|
|
case "fileArchive", "remoteArchive", "assetArchive",
|
|
|
|
"fileAsset", "stringAsset", "remoteAsset",
|
|
|
|
"readDir", "readFile":
|
2020-04-25 05:04:24 +00:00
|
|
|
return ctx.bestArgName(x.Args[0])
|
|
|
|
case "lookup":
|
|
|
|
return ctx.bestArgName(x.Args[1])
|
|
|
|
}
|
|
|
|
return x.Name
|
|
|
|
case *model.IndexExpression:
|
|
|
|
switch model.ResolveOutputs(x.Collection.Type()).(type) {
|
|
|
|
case *model.ListType, *model.SetType, *model.TupleType:
|
|
|
|
return inflector.Singularize(ctx.bestArgName(x.Collection))
|
|
|
|
case *model.MapType, *model.ObjectType:
|
|
|
|
return ctx.bestArgName(x.Key)
|
2020-04-03 00:38:03 +00:00
|
|
|
}
|
2020-04-25 05:04:24 +00:00
|
|
|
case *model.LiteralValueExpression:
|
|
|
|
if x.Value.Type().Equals(cty.String) {
|
|
|
|
return x.Value.AsString()
|
|
|
|
}
|
|
|
|
case *model.RelativeTraversalExpression:
|
|
|
|
if n := ctx.bestTraversalName(ctx.bestArgName(x.Source), x.Traversal); n != "" {
|
|
|
|
return n
|
|
|
|
}
|
|
|
|
case *model.ScopeTraversalExpression:
|
|
|
|
if n := ctx.bestTraversalName(x.RootName, x.Traversal[1:]); n != "" {
|
|
|
|
return n
|
|
|
|
}
|
|
|
|
case *model.SplatExpression:
|
|
|
|
return inflector.Pluralize(ctx.bestArgName(x.Each))
|
|
|
|
}
|
|
|
|
|
|
|
|
switch t := model.ResolveOutputs(x.Type()).(type) {
|
|
|
|
case *model.ListType, *model.SetType, *model.TupleType:
|
|
|
|
return "values"
|
|
|
|
case *model.MapType, *model.ObjectType:
|
|
|
|
return "obj"
|
|
|
|
case *model.UnionType:
|
|
|
|
return "value"
|
2020-04-03 00:38:03 +00:00
|
|
|
default:
|
2020-04-25 05:04:24 +00:00
|
|
|
switch t {
|
|
|
|
case model.BoolType:
|
|
|
|
return "b"
|
|
|
|
case model.IntType:
|
|
|
|
return "i"
|
|
|
|
case model.NumberType:
|
|
|
|
return "n"
|
|
|
|
case model.StringType:
|
|
|
|
return "s"
|
|
|
|
case model.DynamicType:
|
|
|
|
return "obj"
|
|
|
|
default:
|
|
|
|
return "v"
|
|
|
|
}
|
2020-04-03 00:38:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// disambiguateArgName applies type-specific disambiguation to an argument name.
|
2020-04-25 05:04:24 +00:00
|
|
|
func (ctx *observeContext) disambiguateArgName(x model.Expression, bestName string) string {
|
|
|
|
if x, ok := x.(*model.ScopeTraversalExpression); ok {
|
|
|
|
if n, ok := x.Parts[0].(*Resource); ok {
|
|
|
|
// If dealing with a broken access, defer to the generic disambiguator. Otherwise, attempt to disambiguate
|
|
|
|
// by prepending the resource's variable name.
|
|
|
|
if len(x.Traversal) > 1 {
|
|
|
|
return ctx.disambiguateName(n.Name() + titleCase(bestName))
|
|
|
|
}
|
2020-04-03 00:38:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
// Hand off to the generic disambiguator.
|
2020-04-22 22:46:56 +00:00
|
|
|
return ctx.disambiguateName(bestName)
|
2020-03-17 03:04:32 +00:00
|
|
|
}
|
|
|
|
|
2020-04-25 05:04:24 +00:00
|
|
|
// rewriteApplyArg replaces a single expression with an apply parameter.
|
|
|
|
func (ctx *observeContext) rewriteApplyArg(applyArg model.Expression, paramType model.Type, traversal hcl.Traversal,
|
2023-03-03 16:36:39 +00:00
|
|
|
parts []model.Traversable, isRoot bool,
|
|
|
|
) model.Expression {
|
2020-04-25 05:04:24 +00:00
|
|
|
if len(traversal) == 0 && isRoot {
|
|
|
|
return applyArg
|
|
|
|
}
|
|
|
|
|
|
|
|
callbackParam := &model.Variable{
|
|
|
|
Name: fmt.Sprintf("<arg%d>", len(ctx.callbackParams)),
|
|
|
|
VariableType: paramType,
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx.applyArgs, ctx.callbackParams = append(ctx.applyArgs, applyArg), append(ctx.callbackParams, callbackParam)
|
|
|
|
|
|
|
|
// TODO(pdg): this risks information loss for nested output-typed properties... The `Types` array on traversals
|
|
|
|
// ought to store the original types.
|
|
|
|
resolvedParts := make([]model.Traversable, len(parts)+1)
|
|
|
|
resolvedParts[0] = callbackParam
|
|
|
|
for i, p := range parts {
|
|
|
|
resolvedParts[i+1] = model.ResolveOutputs(model.GetTraversableType(p))
|
|
|
|
}
|
|
|
|
|
|
|
|
result := &model.ScopeTraversalExpression{
|
|
|
|
Parts: resolvedParts,
|
|
|
|
RootName: callbackParam.Name,
|
|
|
|
Traversal: hcl.TraversalJoin(hcl.Traversal{hcl.TraverseRoot{Name: callbackParam.Name}}, traversal),
|
|
|
|
}
|
|
|
|
ctx.paramReferences = append(ctx.paramReferences, result)
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
|
|
|
// rewriteRelativeTraversalExpression replaces a single access to an ouptut-typed RelativeTraversalExpression with an
|
|
|
|
// apply parameter.
|
|
|
|
func (ctx *observeContext) rewriteRelativeTraversalExpression(expr *model.RelativeTraversalExpression,
|
2023-03-03 16:36:39 +00:00
|
|
|
isRoot bool,
|
|
|
|
) model.Expression {
|
2020-07-14 19:07:35 +00:00
|
|
|
// If the access is not an output() or a promise(), return the node as-is.
|
|
|
|
paramType, isEventual := ctx.isEventualType(expr.Type())
|
|
|
|
if !isEventual {
|
|
|
|
return expr
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the receiver is an eventual type, we're done.
|
|
|
|
if receiverResolvedType, isEventual := ctx.isEventualType(model.GetTraversableType(expr.Parts[0])); isEventual {
|
|
|
|
return ctx.rewriteApplyArg(expr.Source, receiverResolvedType, expr.Traversal, expr.Parts[1:], isRoot)
|
|
|
|
}
|
|
|
|
|
2020-04-25 05:04:24 +00:00
|
|
|
// Compute the type of the apply and callback arguments.
|
|
|
|
parts, traversal := expr.Parts, expr.Traversal
|
|
|
|
for i := range expr.Traversal {
|
|
|
|
partResolvedType, isEventual := paramType, true
|
|
|
|
if i < len(expr.Traversal)-1 {
|
|
|
|
partResolvedType, isEventual = ctx.isEventualType(model.GetTraversableType(expr.Parts[i+1]))
|
|
|
|
}
|
|
|
|
if isEventual {
|
|
|
|
expr.Traversal, expr.Parts = expr.Traversal[:i+1], expr.Parts[:i+1]
|
|
|
|
paramType, traversal, parts = partResolvedType, expr.Traversal[i+1:], expr.Parts[i+1:]
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ctx.rewriteApplyArg(expr, paramType, traversal, parts, isRoot)
|
|
|
|
}
|
|
|
|
|
|
|
|
// rewriteScopeTraversalExpression replaces a single access to an ouptut-typed ScopeTraversalExpression with an apply
|
|
|
|
// parameter.
|
|
|
|
func (ctx *observeContext) rewriteScopeTraversalExpression(expr *model.ScopeTraversalExpression,
|
2023-03-03 16:36:39 +00:00
|
|
|
isRoot bool,
|
|
|
|
) model.Expression {
|
2020-03-17 03:04:32 +00:00
|
|
|
// If the access is not an output() or a promise(), return the node as-is.
|
2020-04-25 05:04:24 +00:00
|
|
|
resolvedType, isEventual := ctx.isEventualType(expr.Type())
|
2020-03-17 03:04:32 +00:00
|
|
|
if !isEventual {
|
2020-04-03 00:38:03 +00:00
|
|
|
// If this is a reference to a named variable, put the name in scope.
|
|
|
|
if definition, ok := expr.Traversal[0].(Node); ok {
|
2020-04-22 22:46:56 +00:00
|
|
|
ctx.assignedNames.Add(definition.Name())
|
|
|
|
ctx.nameCounts[definition.Name()] = 1
|
2020-04-03 00:38:03 +00:00
|
|
|
}
|
2020-03-17 03:04:32 +00:00
|
|
|
return expr
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, append the access to the list of apply arguments and return an appropriate call to __applyArg.
|
|
|
|
//
|
|
|
|
// TODO: deduplicate multiple accesses to the same variable and field.
|
|
|
|
|
|
|
|
// Compute the type of the apply and callback arguments.
|
|
|
|
var applyArg *model.ScopeTraversalExpression
|
|
|
|
var paramType model.Type
|
|
|
|
var parts []model.Traversable
|
|
|
|
var traversal hcl.Traversal
|
|
|
|
|
2020-04-25 05:04:24 +00:00
|
|
|
splitTraversal := expr.Traversal.SimpleSplit()
|
|
|
|
rootResolvedType, rootIsEventual := resolvedType, true
|
|
|
|
if len(splitTraversal.Rel) > 0 {
|
|
|
|
rootResolvedType, rootIsEventual = ctx.isEventualType(model.GetTraversableType(expr.Parts[0]))
|
|
|
|
}
|
|
|
|
if rootIsEventual {
|
2020-03-17 03:04:32 +00:00
|
|
|
applyArg = &model.ScopeTraversalExpression{
|
2020-04-03 00:38:03 +00:00
|
|
|
Parts: expr.Parts[:1],
|
|
|
|
RootName: splitTraversal.Abs.RootName(),
|
|
|
|
Traversal: splitTraversal.Abs,
|
2020-03-17 03:04:32 +00:00
|
|
|
}
|
2020-04-25 05:04:24 +00:00
|
|
|
paramType, traversal, parts = rootResolvedType, expr.Traversal.SimpleSplit().Rel, expr.Parts[1:]
|
2020-03-17 03:04:32 +00:00
|
|
|
} else {
|
|
|
|
for i := range splitTraversal.Rel {
|
2020-04-25 05:04:24 +00:00
|
|
|
partResolvedType, isEventual := resolvedType, true
|
|
|
|
if i < len(splitTraversal.Rel)-1 {
|
|
|
|
partResolvedType, isEventual = ctx.isEventualType(model.GetTraversableType(expr.Parts[i+1]))
|
|
|
|
}
|
|
|
|
if isEventual {
|
|
|
|
absTraversal, relTraversal := expr.Traversal[:i+2], expr.Traversal[i+2:]
|
2020-03-17 03:04:32 +00:00
|
|
|
|
|
|
|
applyArg = &model.ScopeTraversalExpression{
|
2020-04-03 00:38:03 +00:00
|
|
|
Parts: expr.Parts[:i+2],
|
|
|
|
RootName: absTraversal.RootName(),
|
|
|
|
Traversal: absTraversal,
|
2020-03-17 03:04:32 +00:00
|
|
|
}
|
2020-04-25 05:04:24 +00:00
|
|
|
paramType, traversal, parts = partResolvedType, relTraversal, expr.Parts[i+2:]
|
2020-03-17 03:04:32 +00:00
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-25 05:04:24 +00:00
|
|
|
return ctx.rewriteApplyArg(applyArg, paramType, traversal, parts, isRoot)
|
2020-03-17 03:04:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// rewriteRoot replaces the root node in a bound expression with a call to the __apply intrinsic if necessary.
|
2020-04-25 05:04:24 +00:00
|
|
|
func (ctx *observeContext) rewriteRoot(expr model.Expression) model.Expression {
|
2023-02-17 01:23:09 +00:00
|
|
|
contract.Requiref(expr == ctx.root, "expr", "must be root expression")
|
2020-03-17 03:04:32 +00:00
|
|
|
|
2020-04-22 22:46:56 +00:00
|
|
|
if len(ctx.applyArgs) == 0 {
|
2020-03-17 03:04:32 +00:00
|
|
|
return expr
|
|
|
|
}
|
|
|
|
|
2020-04-03 00:38:03 +00:00
|
|
|
// Assign argument names.
|
2020-04-22 22:46:56 +00:00
|
|
|
for i, arg := range ctx.applyArgs {
|
2020-04-25 05:04:24 +00:00
|
|
|
bestName := ctx.nameInfo.Format(ctx.bestArgName(arg))
|
2020-04-22 22:46:56 +00:00
|
|
|
ctx.callbackParams[i].Name, ctx.nameCounts[bestName] = bestName, ctx.nameCounts[bestName]+1
|
2020-04-03 00:38:03 +00:00
|
|
|
}
|
2020-04-22 22:46:56 +00:00
|
|
|
for i, param := range ctx.callbackParams {
|
|
|
|
if ctx.nameCounts[param.Name] > 1 {
|
|
|
|
param.Name = ctx.disambiguateArgName(ctx.applyArgs[i], param.Name)
|
|
|
|
if ctx.nameCounts[param.Name] == 0 {
|
|
|
|
ctx.nameCounts[param.Name] = 1
|
2020-04-03 00:38:03 +00:00
|
|
|
}
|
2020-04-22 22:46:56 +00:00
|
|
|
ctx.assignedNames.Add(param.Name)
|
2020-04-03 00:38:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update parameter references with the assigned names.
|
2020-04-22 22:46:56 +00:00
|
|
|
for _, x := range ctx.paramReferences {
|
2020-04-03 00:38:03 +00:00
|
|
|
v := x.Parts[0].(*model.Variable)
|
|
|
|
rootTraversal := x.Traversal[0].(hcl.TraverseRoot)
|
|
|
|
x.RootName, rootTraversal.Name = v.Name, v.Name
|
|
|
|
x.Traversal[0] = rootTraversal
|
|
|
|
}
|
|
|
|
|
2020-03-17 03:04:32 +00:00
|
|
|
// Create a new anonymous function definition.
|
|
|
|
callback := &model.AnonymousFunctionExpression{
|
|
|
|
Signature: model.StaticFunctionSignature{
|
2020-04-22 22:46:56 +00:00
|
|
|
Parameters: make([]model.Parameter, len(ctx.callbackParams)),
|
2020-03-17 03:04:32 +00:00
|
|
|
ReturnType: expr.Type(),
|
|
|
|
},
|
2020-04-22 22:46:56 +00:00
|
|
|
Parameters: ctx.callbackParams,
|
2020-03-17 03:04:32 +00:00
|
|
|
Body: expr,
|
|
|
|
}
|
2020-04-22 22:46:56 +00:00
|
|
|
for i, p := range ctx.callbackParams {
|
2020-03-17 03:04:32 +00:00
|
|
|
callback.Signature.Parameters[i] = model.Parameter{Name: p.Name, Type: p.VariableType}
|
|
|
|
}
|
|
|
|
|
2020-04-22 22:46:56 +00:00
|
|
|
return NewApplyCall(ctx.applyArgs, callback)
|
2020-03-17 03:04:32 +00:00
|
|
|
}
|
|
|
|
|
2020-04-25 05:04:24 +00:00
|
|
|
func (ctx *observeContext) PreVisit(expr model.Expression) (model.Expression, hcl.Diagnostics) {
|
|
|
|
if ctx.inspectsEventualValues(expr) {
|
|
|
|
if ctx.observesEventualValues(expr) {
|
|
|
|
ctx.activeContext = &observeContext{
|
|
|
|
applyRewriter: ctx.applyRewriter,
|
|
|
|
parent: ctx,
|
|
|
|
root: expr,
|
|
|
|
assignedNames: codegen.StringSet{},
|
|
|
|
nameCounts: map[string]int{},
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
ctx.activeContext = &inspectContext{
|
|
|
|
applyRewriter: ctx.applyRewriter,
|
|
|
|
parent: ctx,
|
|
|
|
root: expr,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return expr, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ctx *observeContext) PostVisit(expr model.Expression) (model.Expression, hcl.Diagnostics) {
|
2020-04-22 22:46:56 +00:00
|
|
|
isRoot := expr == ctx.root
|
2020-03-17 03:04:32 +00:00
|
|
|
|
2020-04-16 23:44:34 +00:00
|
|
|
// TODO(pdg): arrays of outputs, for expressions, etc.
|
2020-04-25 05:04:24 +00:00
|
|
|
diagnostics := expr.Typecheck(false)
|
2023-02-17 01:23:09 +00:00
|
|
|
contract.Assertf(len(diagnostics) == 0, "error typechecking expression: %v", diagnostics)
|
2020-04-25 05:04:24 +00:00
|
|
|
|
2020-05-07 19:15:40 +00:00
|
|
|
if isIteratorExpr, _ := ctx.isIteratorExpr(expr); isIteratorExpr {
|
|
|
|
return expr, nil
|
|
|
|
}
|
|
|
|
|
2020-04-25 05:04:24 +00:00
|
|
|
switch x := expr.(type) {
|
|
|
|
case *model.RelativeTraversalExpression:
|
|
|
|
expr = ctx.rewriteRelativeTraversalExpression(x, isRoot)
|
|
|
|
case *model.ScopeTraversalExpression:
|
|
|
|
expr = ctx.rewriteScopeTraversalExpression(x, isRoot)
|
|
|
|
default:
|
|
|
|
_, isEventual := ctx.isEventualType(expr.Type())
|
|
|
|
if isEventual && ctx.inspectsEventualValues(x) {
|
|
|
|
expr = ctx.rewriteApplyArg(x, model.ResolveOutputs(x.Type()), nil, nil, isRoot)
|
|
|
|
}
|
2020-03-17 03:04:32 +00:00
|
|
|
}
|
|
|
|
if isRoot {
|
2020-04-22 22:46:56 +00:00
|
|
|
ctx.root = expr
|
|
|
|
expr = ctx.rewriteRoot(expr)
|
2020-04-25 05:04:24 +00:00
|
|
|
|
|
|
|
ctx.activeContext = ctx.parent
|
|
|
|
return ctx.activeContext.PostVisit(expr)
|
|
|
|
}
|
|
|
|
return expr, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ctx *inspectContext) PreVisit(expr model.Expression) (model.Expression, hcl.Diagnostics) {
|
|
|
|
if ctx.observesEventualValues(expr) {
|
|
|
|
observeCtx := &observeContext{
|
|
|
|
applyRewriter: ctx.applyRewriter,
|
|
|
|
parent: ctx,
|
|
|
|
root: expr,
|
|
|
|
assignedNames: codegen.StringSet{},
|
|
|
|
nameCounts: map[string]int{},
|
|
|
|
}
|
|
|
|
ctx.activeContext = observeCtx
|
2020-03-17 03:04:32 +00:00
|
|
|
}
|
|
|
|
return expr, nil
|
|
|
|
}
|
|
|
|
|
2020-04-25 05:04:24 +00:00
|
|
|
func (ctx *inspectContext) PostVisit(expr model.Expression) (model.Expression, hcl.Diagnostics) {
|
|
|
|
if expr == ctx.root {
|
|
|
|
ctx.activeContext = ctx.parent
|
|
|
|
if ctx.parent != nil {
|
|
|
|
return ctx.activeContext.PostVisit(expr)
|
2020-03-17 03:04:32 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return expr, nil
|
|
|
|
}
|
|
|
|
|
2020-04-25 05:04:24 +00:00
|
|
|
// RewriteApplies transforms all expressions that observe the resolved values of outputs and promises into calls to the
|
|
|
|
// __apply intrinsic. Expressions that generate or inspect outputs or promises are passed as arguments to these calls,
|
|
|
|
// and are replaced by references to the corresponding parameter.
|
|
|
|
//
|
|
|
|
// As an example, assuming that resource.id is an output, this transforms the following expression:
|
2020-03-17 03:04:32 +00:00
|
|
|
//
|
2022-09-14 02:12:02 +00:00
|
|
|
// toJSON({
|
|
|
|
// Version = "2012-10-17"
|
|
|
|
// Statement = [{
|
|
|
|
// Effect = "Allow"
|
|
|
|
// Principal = "*"
|
|
|
|
// Action = [ "s3:GetObject" ]
|
|
|
|
// Resource = [ "arn:aws:s3:::${resource.id}/*" ]
|
|
|
|
// }]
|
|
|
|
// })
|
2020-03-17 03:04:32 +00:00
|
|
|
//
|
|
|
|
// into this expression:
|
2020-04-25 05:04:24 +00:00
|
|
|
//
|
2022-09-14 02:12:02 +00:00
|
|
|
// __apply(resource.id, eval(id, toJSON({
|
|
|
|
// Version = "2012-10-17"
|
|
|
|
// Statement = [{
|
|
|
|
// Effect = "Allow"
|
|
|
|
// Principal = "*"
|
|
|
|
// Action = [ "s3:GetObject" ]
|
|
|
|
// Resource = [ "arn:aws:s3:::${id}/*" ]
|
|
|
|
// }]
|
|
|
|
// })))
|
2020-04-25 05:04:24 +00:00
|
|
|
//
|
|
|
|
// Here is a more advanced example, assuming that resource is an object whose properties are all outputs, this
|
|
|
|
// expression:
|
|
|
|
//
|
2022-09-14 02:12:02 +00:00
|
|
|
// "v: ${resource[resource.id]}"
|
2020-04-25 05:04:24 +00:00
|
|
|
//
|
|
|
|
// is transformed into this expression:
|
|
|
|
//
|
2022-09-14 02:12:02 +00:00
|
|
|
// __apply(__apply(resource.id,eval(id, resource[id])),eval(id, "v: ${id}"))
|
2020-03-17 03:04:32 +00:00
|
|
|
//
|
|
|
|
// This form is amenable to code generation for targets that require that outputs are resolved before their values are
|
|
|
|
// accessible (e.g. Pulumi's JS/TS libraries).
|
2020-04-07 02:43:16 +00:00
|
|
|
func RewriteApplies(expr model.Expression, nameInfo NameInfo, applyPromises bool) (model.Expression, hcl.Diagnostics) {
|
[program-gen] Emit Output-returning JSON serialization methods without rewriting applies (#15371)
### Description
A while ago we started implementing [specialized JSON serialization
methods](https://github.com/pulumi/pulumi/issues/12519) for Pulumi
programs which can accept nested outputs without having to rewrite and
combine applies.
- `Output.SerializeJson` in .NET
- `pulumi.jsonStringify` in nodejs
- `pulumi.Output.json_dumps` in Python
This PR extends program-gen for TypeScript, C# and Python to start
emitting these JSON serialization functions (when necessary). The PR
special-cases the `toJSON` PCL function when rewriting applies so that
nested outputs aren't rewritted.
Example PCL program and generated results:
> Also check out the downstream codegen tests to see improved generated
examples
```
resource vpc "aws:ec2:Vpc" {
cidrBlock = "10.100.0.0/16"
instanceTenancy = "default"
}
resource policy "aws:iam/policy:Policy" {
description = "test"
policy = toJSON({
"Version" = "2012-10-17"
"Interpolated" = "arn:${vpc.arn}:value"
"Value" = vpc.id
})
}
```
### Generated TypeScript Before
```typescript
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
const vpc = new aws.ec2.Vpc("vpc", {
cidrBlock: "10.100.0.0/16",
instanceTenancy: "default",
});
const policy = new aws.iam.Policy("policy", {
description: "test",
policy: pulumi.all([vpc.arn, vpc.id]).apply(([arn, id]) => JSON.stringify({
Version: "2012-10-17",
Interpolated: `arn:${arn}:value`,
Value: id,
})),
});
```
### Generated TypeScript After
```typescript
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
const vpc = new aws.ec2.Vpc("vpc", {
cidrBlock: "10.100.0.0/16",
instanceTenancy: "default",
});
const policy = new aws.iam.Policy("policy", {
description: "test",
policy: pulumi.jsonStringify({
Version: "2012-10-17",
Interpolated: pulumi.interpolate`arn:${vpc.arn}:value`,
Value: vpc.id,
}),
});
```
### Generated Python Before
```python
import pulumi
import json
import pulumi_aws as aws
vpc = aws.ec2.Vpc("vpc",
cidr_block="10.100.0.0/16",
instance_tenancy="default")
policy = aws.iam.Policy("policy",
description="test",
policy=pulumi.Output.all(vpc.arn, vpc.id).apply(lambda arn, id: json.dumps({
"Version": "2012-10-17",
"Interpolated": f"arn:{arn}:value",
"Value": id,
})))
```
### Generated Python After
```python
import pulumi
import json
import pulumi_aws as aws
vpc = aws.ec2.Vpc("vpc",
cidr_block="10.100.0.0/16",
instance_tenancy="default")
policy = aws.iam.Policy("policy",
description="test",
policy=pulumi.Output.json_dumps({
"Version": "2012-10-17",
"Interpolated": vpc.arn.apply(lambda arn: f"arn:{arn}:value"),
"Value": vpc.id,
}))
```
### Generated C# Before
```csharp
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Pulumi;
using Aws = Pulumi.Aws;
return await Deployment.RunAsync(() =>
{
var vpc = new Aws.Ec2.Vpc("vpc", new()
{
CidrBlock = "10.100.0.0/16",
InstanceTenancy = "default",
});
var policy = new Aws.Iam.Policy("policy", new()
{
Description = "test",
PolicyDocument = Output.Tuple(vpc.Arn, vpc.Id).Apply(values =>
{
var arn = values.Item1;
var id = values.Item2;
return JsonSerializer.Serialize(new Dictionary<string, object?>
{
["Version"] = "2012-10-17",
["Interpolated"] = $"arn:{arn}:value",
["Value"] = id,
});
}),
});
});
```
### Generated C# After
```csharp
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Pulumi;
using Aws = Pulumi.Aws;
return await Deployment.RunAsync(() =>
{
var vpc = new Aws.Ec2.Vpc("vpc", new()
{
CidrBlock = "10.100.0.0/16",
InstanceTenancy = "default",
});
var policy = new Aws.Iam.Policy("policy", new()
{
Description = "test",
PolicyDocument = Output.JsonSerialize(Output.Create(new Dictionary<string, object?>
{
["Version"] = "2012-10-17",
["Interpolated"] = vpc.Arn.Apply(arn => $"arn:{arn}:value"),
["Value"] = vpc.Id,
})),
});
});
```
## Checklist
- [ ] I have run `make tidy` to update any new dependencies
- [x] I have run `make lint` to verify my code passes the lint check
- [x] I have formatted my code using `gofumpt`
<!--- Please provide details if the checkbox below is to be left
unchecked. -->
- [x] I have added tests that prove my fix is effective or that my
feature works
<!---
User-facing changes require a CHANGELOG entry.
-->
- [x] I have run `make changelog` and committed the
`changelog/pending/<file>` documenting my change
<!--
If the change(s) in this PR is a modification of an existing call to the
Pulumi Cloud,
then the service should honor older versions of the CLI where this
change would not exist.
You must then bump the API version in
/pkg/backend/httpstate/client/api.go, as well as add
it to the service.
-->
- [ ] Yes, there are changes in this PR that warrants bumping the Pulumi
Cloud API version
<!-- @Pulumi employees: If yes, you must submit corresponding changes in
the service repo. -->
2024-02-20 15:48:46 +00:00
|
|
|
return RewriteAppliesWithSkipToJSON(expr, nameInfo, applyPromises, false)
|
|
|
|
}
|
|
|
|
|
|
|
|
func RewriteAppliesWithSkipToJSON(
|
|
|
|
expr model.Expression,
|
|
|
|
nameInfo NameInfo,
|
|
|
|
applyPromises bool,
|
|
|
|
skipToJSON bool,
|
|
|
|
) (model.Expression, hcl.Diagnostics) {
|
2020-04-25 05:04:24 +00:00
|
|
|
applyRewriter := &applyRewriter{
|
|
|
|
nameInfo: nameInfo,
|
|
|
|
applyPromises: applyPromises,
|
[program-gen] Emit Output-returning JSON serialization methods without rewriting applies (#15371)
### Description
A while ago we started implementing [specialized JSON serialization
methods](https://github.com/pulumi/pulumi/issues/12519) for Pulumi
programs which can accept nested outputs without having to rewrite and
combine applies.
- `Output.SerializeJson` in .NET
- `pulumi.jsonStringify` in nodejs
- `pulumi.Output.json_dumps` in Python
This PR extends program-gen for TypeScript, C# and Python to start
emitting these JSON serialization functions (when necessary). The PR
special-cases the `toJSON` PCL function when rewriting applies so that
nested outputs aren't rewritted.
Example PCL program and generated results:
> Also check out the downstream codegen tests to see improved generated
examples
```
resource vpc "aws:ec2:Vpc" {
cidrBlock = "10.100.0.0/16"
instanceTenancy = "default"
}
resource policy "aws:iam/policy:Policy" {
description = "test"
policy = toJSON({
"Version" = "2012-10-17"
"Interpolated" = "arn:${vpc.arn}:value"
"Value" = vpc.id
})
}
```
### Generated TypeScript Before
```typescript
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
const vpc = new aws.ec2.Vpc("vpc", {
cidrBlock: "10.100.0.0/16",
instanceTenancy: "default",
});
const policy = new aws.iam.Policy("policy", {
description: "test",
policy: pulumi.all([vpc.arn, vpc.id]).apply(([arn, id]) => JSON.stringify({
Version: "2012-10-17",
Interpolated: `arn:${arn}:value`,
Value: id,
})),
});
```
### Generated TypeScript After
```typescript
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
const vpc = new aws.ec2.Vpc("vpc", {
cidrBlock: "10.100.0.0/16",
instanceTenancy: "default",
});
const policy = new aws.iam.Policy("policy", {
description: "test",
policy: pulumi.jsonStringify({
Version: "2012-10-17",
Interpolated: pulumi.interpolate`arn:${vpc.arn}:value`,
Value: vpc.id,
}),
});
```
### Generated Python Before
```python
import pulumi
import json
import pulumi_aws as aws
vpc = aws.ec2.Vpc("vpc",
cidr_block="10.100.0.0/16",
instance_tenancy="default")
policy = aws.iam.Policy("policy",
description="test",
policy=pulumi.Output.all(vpc.arn, vpc.id).apply(lambda arn, id: json.dumps({
"Version": "2012-10-17",
"Interpolated": f"arn:{arn}:value",
"Value": id,
})))
```
### Generated Python After
```python
import pulumi
import json
import pulumi_aws as aws
vpc = aws.ec2.Vpc("vpc",
cidr_block="10.100.0.0/16",
instance_tenancy="default")
policy = aws.iam.Policy("policy",
description="test",
policy=pulumi.Output.json_dumps({
"Version": "2012-10-17",
"Interpolated": vpc.arn.apply(lambda arn: f"arn:{arn}:value"),
"Value": vpc.id,
}))
```
### Generated C# Before
```csharp
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Pulumi;
using Aws = Pulumi.Aws;
return await Deployment.RunAsync(() =>
{
var vpc = new Aws.Ec2.Vpc("vpc", new()
{
CidrBlock = "10.100.0.0/16",
InstanceTenancy = "default",
});
var policy = new Aws.Iam.Policy("policy", new()
{
Description = "test",
PolicyDocument = Output.Tuple(vpc.Arn, vpc.Id).Apply(values =>
{
var arn = values.Item1;
var id = values.Item2;
return JsonSerializer.Serialize(new Dictionary<string, object?>
{
["Version"] = "2012-10-17",
["Interpolated"] = $"arn:{arn}:value",
["Value"] = id,
});
}),
});
});
```
### Generated C# After
```csharp
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Pulumi;
using Aws = Pulumi.Aws;
return await Deployment.RunAsync(() =>
{
var vpc = new Aws.Ec2.Vpc("vpc", new()
{
CidrBlock = "10.100.0.0/16",
InstanceTenancy = "default",
});
var policy = new Aws.Iam.Policy("policy", new()
{
Description = "test",
PolicyDocument = Output.JsonSerialize(Output.Create(new Dictionary<string, object?>
{
["Version"] = "2012-10-17",
["Interpolated"] = vpc.Arn.Apply(arn => $"arn:{arn}:value"),
["Value"] = vpc.Id,
})),
});
});
```
## Checklist
- [ ] I have run `make tidy` to update any new dependencies
- [x] I have run `make lint` to verify my code passes the lint check
- [x] I have formatted my code using `gofumpt`
<!--- Please provide details if the checkbox below is to be left
unchecked. -->
- [x] I have added tests that prove my fix is effective or that my
feature works
<!---
User-facing changes require a CHANGELOG entry.
-->
- [x] I have run `make changelog` and committed the
`changelog/pending/<file>` documenting my change
<!--
If the change(s) in this PR is a modification of an existing call to the
Pulumi Cloud,
then the service should honor older versions of the CLI where this
change would not exist.
You must then bump the API version in
/pkg/backend/httpstate/client/api.go, as well as add
it to the service.
-->
- [ ] Yes, there are changes in this PR that warrants bumping the Pulumi
Cloud API version
<!-- @Pulumi employees: If yes, you must submit corresponding changes in
the service repo. -->
2024-02-20 15:48:46 +00:00
|
|
|
skipToJSON: skipToJSON,
|
2020-04-25 05:04:24 +00:00
|
|
|
}
|
|
|
|
applyRewriter.activeContext = &inspectContext{
|
|
|
|
applyRewriter: applyRewriter,
|
|
|
|
root: expr,
|
2020-04-22 22:46:56 +00:00
|
|
|
}
|
2020-04-25 05:04:24 +00:00
|
|
|
return model.VisitExpression(expr, applyRewriter.preVisit, applyRewriter.postVisit)
|
2020-03-17 03:04:32 +00:00
|
|
|
}
|