2020-05-19 08:18:38 +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.
|
|
|
|
|
|
|
|
package dotnet
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"math/big"
|
|
|
|
"strings"
|
|
|
|
|
2024-03-24 00:06:57 +00:00
|
|
|
"github.com/pulumi/pulumi/pkg/v3/codegen"
|
|
|
|
|
2020-05-19 08:18:38 +00:00
|
|
|
"github.com/hashicorp/hcl/v2"
|
|
|
|
"github.com/hashicorp/hcl/v2/hclsyntax"
|
2021-03-17 13:20:05 +00:00
|
|
|
"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model"
|
2021-09-30 03:11:56 +00:00
|
|
|
"github.com/pulumi/pulumi/pkg/v3/codegen/pcl"
|
2021-03-17 13:20:05 +00:00
|
|
|
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
|
|
|
|
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
|
2022-07-21 19:04:02 +00:00
|
|
|
"github.com/zclconf/go-cty/cty"
|
2020-05-19 08:18:38 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type nameInfo int
|
|
|
|
|
|
|
|
func (nameInfo) Format(name string) string {
|
|
|
|
return makeValidIdentifier(name)
|
|
|
|
}
|
|
|
|
|
2022-07-21 19:04:02 +00:00
|
|
|
func (g *generator) rewriteExpression(expr model.Expression, typ model.Type, rewriteApplies bool) model.Expression {
|
2021-09-30 03:11:56 +00:00
|
|
|
expr = pcl.RewritePropertyReferences(expr)
|
2022-07-21 19:04:02 +00:00
|
|
|
var diags hcl.Diagnostics
|
|
|
|
if rewriteApplies {
|
[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
|
|
|
skipToJSONWhenRewritingApplies := true
|
|
|
|
expr, diags = pcl.RewriteAppliesWithSkipToJSON(expr, nameInfo(0), !g.asyncInit, skipToJSONWhenRewritingApplies)
|
2022-07-21 19:04:02 +00:00
|
|
|
}
|
|
|
|
|
2022-07-07 20:15:47 +00:00
|
|
|
expr, convertDiags := pcl.RewriteConversions(expr, typ)
|
2022-07-21 19:04:02 +00:00
|
|
|
diags = diags.Extend(convertDiags)
|
2020-05-19 08:18:38 +00:00
|
|
|
if g.asyncInit {
|
|
|
|
expr = g.awaitInvokes(expr)
|
|
|
|
} else {
|
|
|
|
expr = g.outputInvokes(expr)
|
|
|
|
}
|
2022-07-13 21:29:34 +00:00
|
|
|
g.diagnostics = g.diagnostics.Extend(diags)
|
2020-05-19 08:18:38 +00:00
|
|
|
return expr
|
|
|
|
}
|
|
|
|
|
2022-07-21 19:04:02 +00:00
|
|
|
// lowerExpression amends the expression with intrinsics for C# generation.
|
|
|
|
func (g *generator) lowerExpression(expr model.Expression, typ model.Type) model.Expression {
|
|
|
|
rewriteApplies := true
|
|
|
|
return g.rewriteExpression(expr, typ, rewriteApplies)
|
|
|
|
}
|
|
|
|
|
|
|
|
// lowerExpressionWithoutApplies is the same as lowerExpression
|
|
|
|
// but without rewriting applies. Made especially for function invokes that are returning outputs
|
|
|
|
func (g *generator) lowerExpressionWithoutApplies(expr model.Expression, typ model.Type) model.Expression {
|
|
|
|
rewriteApplies := false
|
|
|
|
return g.rewriteExpression(expr, typ, rewriteApplies)
|
|
|
|
}
|
|
|
|
|
|
|
|
// awaitInvokes wraps each call to `invoke` with a call to the `await` intrinsic. This rewrite should only be used
|
|
|
|
// if we are generating an async Initialize, in which case the apply rewriter should also be configured not to treat
|
|
|
|
// promises as eventuals. Note that this depends on the fact that invokes are the only way to introduce promises
|
2020-05-19 08:18:38 +00:00
|
|
|
// in to a Pulumi program; if this changes in the future, this transform will need to be applied in a more general way
|
|
|
|
// (e.g. by the apply rewriter).
|
2022-07-21 19:04:02 +00:00
|
|
|
func (g *generator) awaitInvokes(x model.Expression) model.Expression {
|
2023-02-17 01:23:09 +00:00
|
|
|
contract.Assertf(g.asyncInit,
|
|
|
|
"awaitInvokes can be used only if we are generating an async Initialize")
|
2022-07-21 19:04:02 +00:00
|
|
|
|
2020-05-19 08:18:38 +00:00
|
|
|
rewriter := func(x model.Expression) (model.Expression, hcl.Diagnostics) {
|
|
|
|
// Ignore the node if it is not a call to invoke.
|
|
|
|
call, ok := x.(*model.FunctionCallExpression)
|
2021-09-30 03:11:56 +00:00
|
|
|
if !ok || call.Name != pcl.Invoke {
|
2020-05-19 08:18:38 +00:00
|
|
|
return x, nil
|
|
|
|
}
|
|
|
|
|
2023-06-03 07:23:38 +00:00
|
|
|
if _, isPromise := call.Type().(*model.PromiseType); isPromise {
|
|
|
|
return newAwaitCall(call), nil
|
|
|
|
}
|
2020-05-19 08:18:38 +00:00
|
|
|
|
2023-06-03 07:23:38 +00:00
|
|
|
return call, nil
|
2020-05-19 08:18:38 +00:00
|
|
|
}
|
|
|
|
x, diags := model.VisitExpression(x, model.IdentityVisitor, rewriter)
|
2023-02-17 01:23:09 +00:00
|
|
|
contract.Assertf(len(diags) == 0, "unexpected diagnostics: %v", diags)
|
2020-05-19 08:18:38 +00:00
|
|
|
return x
|
|
|
|
}
|
|
|
|
|
2022-07-21 19:04:02 +00:00
|
|
|
// outputInvokes wraps each call to `invoke` with a call to the `output` intrinsic. This rewrite should only be used if
|
|
|
|
// resources are instantiated within a stack constructor, where `await` operator is not available. We want to avoid the
|
|
|
|
// nastiness of working with raw `Task` and wrap it into Pulumi's Output immediately to be able to `Apply` on it.
|
|
|
|
// Note that this depends on the fact that invokes are the only way to introduce promises
|
2020-05-19 08:18:38 +00:00
|
|
|
// in to a Pulumi program; if this changes in the future, this transform will need to be applied in a more general way
|
|
|
|
// (e.g. by the apply rewriter).
|
2022-07-21 19:04:02 +00:00
|
|
|
func (g *generator) outputInvokes(x model.Expression) model.Expression {
|
2020-05-19 08:18:38 +00:00
|
|
|
rewriter := func(x model.Expression) (model.Expression, hcl.Diagnostics) {
|
|
|
|
// Ignore the node if it is not a call to invoke.
|
|
|
|
call, ok := x.(*model.FunctionCallExpression)
|
2021-09-30 03:11:56 +00:00
|
|
|
if !ok || call.Name != pcl.Invoke {
|
2020-05-19 08:18:38 +00:00
|
|
|
return x, nil
|
|
|
|
}
|
|
|
|
|
2023-07-10 13:05:18 +00:00
|
|
|
if call.Type() == model.DynamicType {
|
|
|
|
// ignore if the return type of the invoke is dynamic
|
|
|
|
// this means that we are working with an unknown invoke
|
|
|
|
return x, nil
|
|
|
|
}
|
|
|
|
|
2022-07-21 19:04:02 +00:00
|
|
|
_, isOutput := call.Type().(*model.OutputType)
|
|
|
|
if isOutput {
|
|
|
|
return x, nil
|
|
|
|
}
|
|
|
|
|
2020-05-19 08:18:38 +00:00
|
|
|
_, isPromise := call.Type().(*model.PromiseType)
|
2023-02-17 01:23:09 +00:00
|
|
|
contract.Assertf(isPromise, "invoke should return a promise, got %v", call.Type())
|
2020-05-19 08:18:38 +00:00
|
|
|
|
2022-07-21 19:04:02 +00:00
|
|
|
return newOutputCall(call), nil
|
2020-05-19 08:18:38 +00:00
|
|
|
}
|
|
|
|
x, diags := model.VisitExpression(x, model.IdentityVisitor, rewriter)
|
2023-02-17 01:23:09 +00:00
|
|
|
contract.Assertf(len(diags) == 0, "unexpected diagnostics: %v", diags)
|
2020-05-19 08:18:38 +00:00
|
|
|
return x
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) GetPrecedence(expr model.Expression) int {
|
|
|
|
// TODO(msh): Current values copied from Node, update based on
|
|
|
|
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/
|
|
|
|
switch expr := expr.(type) {
|
|
|
|
case *model.ConditionalExpression:
|
|
|
|
return 4
|
|
|
|
case *model.BinaryOpExpression:
|
|
|
|
switch expr.Operation {
|
|
|
|
case hclsyntax.OpLogicalOr:
|
|
|
|
return 5
|
|
|
|
case hclsyntax.OpLogicalAnd:
|
|
|
|
return 6
|
|
|
|
case hclsyntax.OpEqual, hclsyntax.OpNotEqual:
|
|
|
|
return 11
|
|
|
|
case hclsyntax.OpGreaterThan, hclsyntax.OpGreaterThanOrEqual, hclsyntax.OpLessThan,
|
|
|
|
hclsyntax.OpLessThanOrEqual:
|
|
|
|
return 12
|
|
|
|
case hclsyntax.OpAdd, hclsyntax.OpSubtract:
|
|
|
|
return 14
|
|
|
|
case hclsyntax.OpMultiply, hclsyntax.OpDivide, hclsyntax.OpModulo:
|
|
|
|
return 15
|
|
|
|
default:
|
|
|
|
contract.Failf("unexpected binary expression %v", expr)
|
|
|
|
}
|
|
|
|
case *model.UnaryOpExpression:
|
|
|
|
return 17
|
|
|
|
case *model.FunctionCallExpression:
|
|
|
|
switch expr.Name {
|
|
|
|
case intrinsicAwait:
|
|
|
|
return 17
|
|
|
|
default:
|
|
|
|
return 20
|
|
|
|
}
|
|
|
|
case *model.ForExpression, *model.IndexExpression, *model.RelativeTraversalExpression, *model.SplatExpression,
|
|
|
|
*model.TemplateJoinExpression:
|
|
|
|
return 20
|
|
|
|
case *model.AnonymousFunctionExpression, *model.LiteralValueExpression, *model.ObjectConsExpression,
|
|
|
|
*model.ScopeTraversalExpression, *model.TemplateExpression, *model.TupleConsExpression:
|
|
|
|
return 22
|
|
|
|
default:
|
|
|
|
contract.Failf("unexpected expression %v of type %T", expr, expr)
|
|
|
|
}
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) GenAnonymousFunctionExpression(w io.Writer, expr *model.AnonymousFunctionExpression) {
|
|
|
|
switch len(expr.Signature.Parameters) {
|
|
|
|
case 0:
|
|
|
|
g.Fgen(w, "()")
|
|
|
|
case 1:
|
|
|
|
g.Fgenf(w, "%s", expr.Signature.Parameters[0].Name)
|
|
|
|
g.Fgenf(w, " => %v", expr.Body)
|
|
|
|
default:
|
|
|
|
g.Fgen(w, "values =>\n")
|
|
|
|
g.Fgenf(w, "%s{\n", g.Indent)
|
|
|
|
g.Indented(func() {
|
|
|
|
for i, p := range expr.Signature.Parameters {
|
|
|
|
g.Fgenf(w, "%svar %s = values.Item%d;\n", g.Indent, p.Name, i+1)
|
|
|
|
}
|
|
|
|
g.Fgenf(w, "%sreturn %v;\n", g.Indent, expr.Body)
|
|
|
|
})
|
|
|
|
g.Fgenf(w, "%s}", g.Indent)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) GenBinaryOpExpression(w io.Writer, expr *model.BinaryOpExpression) {
|
|
|
|
opstr, precedence := "", g.GetPrecedence(expr)
|
|
|
|
switch expr.Operation {
|
|
|
|
case hclsyntax.OpAdd:
|
|
|
|
opstr = "+"
|
|
|
|
case hclsyntax.OpDivide:
|
|
|
|
opstr = "/"
|
|
|
|
case hclsyntax.OpEqual:
|
|
|
|
opstr = "=="
|
|
|
|
case hclsyntax.OpGreaterThan:
|
|
|
|
opstr = ">"
|
|
|
|
case hclsyntax.OpGreaterThanOrEqual:
|
|
|
|
opstr = ">="
|
|
|
|
case hclsyntax.OpLessThan:
|
|
|
|
opstr = "<"
|
|
|
|
case hclsyntax.OpLessThanOrEqual:
|
|
|
|
opstr = "<="
|
|
|
|
case hclsyntax.OpLogicalAnd:
|
|
|
|
opstr = "&&"
|
|
|
|
case hclsyntax.OpLogicalOr:
|
|
|
|
opstr = "||"
|
|
|
|
case hclsyntax.OpModulo:
|
|
|
|
opstr = "%"
|
|
|
|
case hclsyntax.OpMultiply:
|
|
|
|
opstr = "*"
|
|
|
|
case hclsyntax.OpNotEqual:
|
|
|
|
opstr = "!="
|
|
|
|
case hclsyntax.OpSubtract:
|
|
|
|
opstr = "-"
|
|
|
|
default:
|
|
|
|
opstr, precedence = ",", 1
|
|
|
|
}
|
|
|
|
|
|
|
|
g.Fgenf(w, "%.[1]*[2]v %[3]v %.[1]*[4]o", precedence, expr.LeftOperand, opstr, expr.RightOperand)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) GenConditionalExpression(w io.Writer, expr *model.ConditionalExpression) {
|
|
|
|
g.Fgenf(w, "%.4v ? %.4v : %.4v", expr.Condition, expr.TrueResult, expr.FalseResult)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) GenForExpression(w io.Writer, expr *model.ForExpression) {
|
2023-06-02 14:59:46 +00:00
|
|
|
switch expr.Collection.Type().(type) {
|
|
|
|
case *model.ListType, *model.TupleType:
|
|
|
|
if expr.KeyVariable == nil {
|
|
|
|
g.Fgenf(w, "%.20v", expr.Collection)
|
|
|
|
} else {
|
|
|
|
g.Fgenf(w, "%.20v.Select((value, i) => new { Key = i.ToString(), Value = pair.Value })",
|
|
|
|
expr.Collection)
|
|
|
|
}
|
|
|
|
case *model.MapType:
|
|
|
|
if expr.KeyVariable == nil {
|
|
|
|
g.Fgenf(w, "(%.v).Values", expr.Collection)
|
|
|
|
} else {
|
|
|
|
g.Fgenf(w, "%.20v.Select(pair => new { pair.Key, pair.Value })", expr.Collection)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-28 18:30:00 +00:00
|
|
|
switch expr.Type().(type) {
|
|
|
|
case *model.ListType:
|
|
|
|
// the result of the expression is a list
|
|
|
|
if expr.Condition != nil {
|
|
|
|
g.Fgenf(w, ".Where(%s => %.v)", expr.ValueVariable.Name, expr.Condition)
|
2023-06-02 14:59:46 +00:00
|
|
|
}
|
2023-07-28 18:30:00 +00:00
|
|
|
|
|
|
|
g.Fgenf(w, ".Select(%s => \n", expr.ValueVariable.Name)
|
|
|
|
|
|
|
|
g.Fgenf(w, "%s{\n", g.Indent)
|
|
|
|
g.Indented(func() {
|
|
|
|
g.Fgenf(w, "%sreturn %v;", g.Indent, expr.Value)
|
|
|
|
})
|
|
|
|
g.Fgen(w, "\n")
|
|
|
|
// .ToList() is added so that the expressions returns `List<T>
|
|
|
|
// which can be implicitly converted to InputList<T>
|
|
|
|
g.Fgenf(w, "%s}).ToList()", g.Indent)
|
|
|
|
case *model.MapType:
|
|
|
|
// the result of the expression is a dictionary
|
|
|
|
g.Fgen(w, ".ToDictionary(item => {\n")
|
|
|
|
g.Indented(func() {
|
|
|
|
if expr.KeyVariable != nil && pcl.VariableAccessed(expr.KeyVariable.Name, expr.Key) {
|
|
|
|
g.Fgenf(w, "%svar %s = item.Key;\n", g.Indent, expr.KeyVariable.Name)
|
|
|
|
}
|
|
|
|
|
|
|
|
if expr.ValueVariable != nil && pcl.VariableAccessed(expr.ValueVariable.Name, expr.Key) {
|
|
|
|
g.Fgenf(w, "%svar %s = item.Value;\n", g.Indent, expr.ValueVariable.Name)
|
|
|
|
}
|
|
|
|
|
|
|
|
g.Fgenf(w, "%sreturn %s;\n", g.Indent, expr.Key)
|
|
|
|
})
|
|
|
|
|
|
|
|
g.Fgenf(w, "%s}, item => {\n", g.Indent)
|
|
|
|
g.Indented(func() {
|
|
|
|
if expr.KeyVariable != nil && pcl.VariableAccessed(expr.KeyVariable.Name, expr.Value) {
|
|
|
|
g.Fgenf(w, "%svar %s = item.Key;\n", g.Indent, expr.KeyVariable.Name)
|
|
|
|
}
|
|
|
|
|
|
|
|
if expr.ValueVariable != nil && pcl.VariableAccessed(expr.ValueVariable.Name, expr.Value) {
|
|
|
|
g.Fgenf(w, "%svar %s = item.Value;\n", g.Indent, expr.ValueVariable.Name)
|
|
|
|
}
|
|
|
|
|
|
|
|
g.Fgenf(w, "%sreturn %v;\n", g.Indent, expr.Value)
|
|
|
|
})
|
|
|
|
|
|
|
|
g.Fgenf(w, "%s})", g.Indent)
|
|
|
|
}
|
2020-05-19 08:18:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) genApply(w io.Writer, expr *model.FunctionCallExpression) {
|
|
|
|
// Extract the list of outputs and the continuation expression from the `__apply` arguments.
|
2021-09-30 03:11:56 +00:00
|
|
|
applyArgs, then := pcl.ParseApplyCall(expr)
|
2020-05-19 08:18:38 +00:00
|
|
|
|
|
|
|
if len(applyArgs) == 1 {
|
|
|
|
// If we only have a single output, just generate a normal `.Apply`
|
|
|
|
g.Fgenf(w, "%.v.Apply(%.v)", applyArgs[0], then)
|
|
|
|
} else {
|
|
|
|
// Otherwise, generate a call to `Output.Tuple().Apply()`.
|
|
|
|
g.Fgen(w, "Output.Tuple(")
|
|
|
|
for i, o := range applyArgs {
|
|
|
|
if i > 0 {
|
|
|
|
g.Fgen(w, ", ")
|
|
|
|
}
|
|
|
|
g.Fgenf(w, "%.v", o)
|
|
|
|
}
|
|
|
|
|
|
|
|
g.Fgenf(w, ").Apply(%.v)", then)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) genRange(w io.Writer, call *model.FunctionCallExpression, entries bool) {
|
|
|
|
g.genNYI(w, "Range %.v %.v", call, entries)
|
|
|
|
}
|
|
|
|
|
|
|
|
var functionNamespaces = map[string][]string{
|
2022-04-25 19:59:30 +00:00
|
|
|
"assetArchive": {"System.Collections.Generic"},
|
2022-01-21 14:03:25 +00:00
|
|
|
"readDir": {"System.IO", "System.Linq"},
|
|
|
|
"readFile": {"System.IO"},
|
2022-03-16 00:05:36 +00:00
|
|
|
"cwd": {"System.IO"},
|
2022-01-21 14:03:25 +00:00
|
|
|
"filebase64": {"System", "System.IO"},
|
|
|
|
"filebase64sha256": {"System", "System.IO", "System.Security.Cryptography", "System.Text"},
|
|
|
|
"toJSON": {"System.Text.Json", "System.Collections.Generic"},
|
|
|
|
"toBase64": {"System"},
|
2022-09-16 23:12:29 +00:00
|
|
|
"fromBase64": {"System"},
|
2022-01-21 14:03:25 +00:00
|
|
|
"sha1": {"System.Security.Cryptography", "System.Text"},
|
2023-06-11 09:05:10 +00:00
|
|
|
"singleOrNone": {"System.Linq"},
|
2020-05-19 08:18:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) genFunctionUsings(x *model.FunctionCallExpression) []string {
|
2021-09-30 03:11:56 +00:00
|
|
|
if x.Name != pcl.Invoke {
|
2020-05-19 08:18:38 +00:00
|
|
|
return functionNamespaces[x.Name]
|
|
|
|
}
|
|
|
|
|
|
|
|
pkg, _ := g.functionName(x.Args[0])
|
|
|
|
return []string{fmt.Sprintf("%s = Pulumi.%[1]s", pkg)}
|
|
|
|
}
|
|
|
|
|
2022-04-18 09:03:42 +00:00
|
|
|
func (g *generator) genSafeEnum(w io.Writer, to *model.EnumType) func(member *schema.Enum) {
|
|
|
|
return func(member *schema.Enum) {
|
|
|
|
// We know the enum value at the call site, so we can directly stamp in a
|
|
|
|
// valid enum instance. We don't need to convert.
|
|
|
|
pkg, name := enumName(to)
|
|
|
|
contract.Assertf(pkg != "", "pkg cannot be empty")
|
|
|
|
contract.Assertf(name != "", "name cannot be empty")
|
|
|
|
memberTag := member.Name
|
|
|
|
if memberTag == "" {
|
|
|
|
memberTag = member.Value.(string)
|
|
|
|
}
|
|
|
|
memberTag, err := makeSafeEnumName(memberTag, name)
|
|
|
|
contract.AssertNoErrorf(err, "Enum is invalid")
|
|
|
|
g.Fgenf(w, "%s.%s.%s", pkg, name, memberTag)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func enumName(enum *model.EnumType) (string, string) {
|
|
|
|
components := strings.Split(enum.Token, ":")
|
|
|
|
contract.Assertf(len(components) == 3, "malformed token %v", enum.Token)
|
[program-gen] Fix enum resolution from types of the form Union[string, Enum] and emit fully qualified enum cases (#15696)
# Description
This PR improves enum type resolution from strings. When we try to
resolve `Union[string, Enum]` for a string expression, we choose
`string` because it is the more general type since not every string is
assignable to `Enum`. However, here we spacial case strings that are
actually part of that `Enum`.
The result is that `pcl.LowerConversion` will choose `Enum` from
`Union[string, Enum]` when the value of the input string is compatible
with the enum. This greatly improves program-gen for all of typescript,
python, csharp and go which now will emit the fully qualified enum cases
instead of emitting strings.
Closes https://github.com/pulumi/pulumi-dotnet/issues/41 which is
supposed to be a duplicate of
https://github.com/pulumi/pulumi-azure-native/issues/2616 but that is
not the case (the former is about unions of objects, the latter is
unions of enums and strings)
## 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-03-15 17:49:12 +00:00
|
|
|
modParts := strings.Split(components[1], "/")
|
|
|
|
// if the token has the format {pkg}:{mod}/{name}:{Name}
|
|
|
|
// then we simplify into {pkg}:{mod}:{Name}
|
|
|
|
if len(modParts) == 2 && strings.EqualFold(modParts[1], components[2]) {
|
|
|
|
components[1] = modParts[0]
|
|
|
|
}
|
2022-04-18 09:03:42 +00:00
|
|
|
enumName := tokenToName(enum.Token)
|
|
|
|
e, ok := pcl.GetSchemaForType(enum)
|
|
|
|
if !ok {
|
|
|
|
return "", ""
|
|
|
|
}
|
2023-02-17 01:23:09 +00:00
|
|
|
et := e.(*schema.EnumType)
|
|
|
|
def, err := et.PackageReference.Definition()
|
|
|
|
contract.AssertNoErrorf(err, "error loading definition for package %q", et.PackageReference.Name())
|
2024-05-30 22:43:12 +00:00
|
|
|
var namespaceMap map[string]string
|
|
|
|
pkgInfo, ok := def.Language["csharp"].(CSharpPackageInfo)
|
|
|
|
if ok {
|
|
|
|
namespaceMap = pkgInfo.Namespaces
|
|
|
|
}
|
|
|
|
|
2022-04-18 09:03:42 +00:00
|
|
|
namespace := namespaceName(namespaceMap, components[0])
|
|
|
|
if components[1] != "" && components[1] != "index" {
|
|
|
|
namespace += "." + namespaceName(namespaceMap, components[1])
|
|
|
|
}
|
|
|
|
return namespace, enumName
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) genIntrensic(w io.Writer, from model.Expression, to model.Type) {
|
|
|
|
to = pcl.LowerConversion(from, to)
|
|
|
|
output, isOutput := to.(*model.OutputType)
|
|
|
|
if isOutput {
|
|
|
|
to = output.ElementType
|
|
|
|
}
|
|
|
|
switch to := to.(type) {
|
|
|
|
case *model.EnumType:
|
|
|
|
pkg, name := enumName(to)
|
|
|
|
if pkg == "" || name == "" {
|
|
|
|
// Something has gone wrong. Produce a best effort result.
|
|
|
|
g.Fgenf(w, "%.v", from)
|
|
|
|
return
|
|
|
|
}
|
2024-05-30 22:43:12 +00:00
|
|
|
|
|
|
|
convertFn := func() string {
|
|
|
|
if to.Type.Equals(model.StringType) {
|
|
|
|
return fmt.Sprintf("System.Enum.Parse<%s.%s>", pkg, name)
|
|
|
|
}
|
|
|
|
|
2022-04-18 09:03:42 +00:00
|
|
|
panic(fmt.Sprintf(
|
|
|
|
"Unsafe enum conversions from type %s not implemented yet: %s => %s",
|
|
|
|
from.Type(), from, to))
|
|
|
|
}
|
2024-05-30 22:43:12 +00:00
|
|
|
|
2022-04-18 09:03:42 +00:00
|
|
|
if isOutput {
|
2024-05-30 22:43:12 +00:00
|
|
|
g.Fgenf(w, "%.v.Apply(%s)", from, convertFn())
|
2022-04-18 09:03:42 +00:00
|
|
|
} else {
|
2022-12-01 22:41:24 +00:00
|
|
|
diag := pcl.GenEnum(to, from, g.genSafeEnum(w, to), func(from model.Expression) {
|
2024-05-30 22:43:12 +00:00
|
|
|
g.Fgenf(w, "%s(%v)", convertFn(), from)
|
2022-04-18 09:03:42 +00:00
|
|
|
})
|
2022-12-01 22:41:24 +00:00
|
|
|
if diag != nil {
|
|
|
|
g.diagnostics = append(g.diagnostics, diag)
|
|
|
|
}
|
2022-04-18 09:03:42 +00:00
|
|
|
}
|
|
|
|
default:
|
|
|
|
g.Fgenf(w, "%.v", from) // <- probably wrong w.r.t. precedence
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-02 14:59:46 +00:00
|
|
|
func (g *generator) genEntries(w io.Writer, expr *model.FunctionCallExpression) {
|
|
|
|
switch model.ResolveOutputs(expr.Args[0].Type()).(type) {
|
|
|
|
case *model.ListType, *model.TupleType:
|
|
|
|
if call, ok := expr.Args[0].(*model.FunctionCallExpression); ok && call.Name == "range" {
|
|
|
|
g.genRange(w, call, true)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
g.Fgenf(w, "%.20v.Select((v, k) => new { Key = k, Value = v })", expr.Args[0])
|
|
|
|
case *model.MapType, *model.ObjectType:
|
|
|
|
g.Fgenf(w, "%.20v.Select(pair => new { pair.Key, pair.Value })", expr.Args[0])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-21 19:04:02 +00:00
|
|
|
func (g *generator) withinAwaitBlock(run func()) {
|
|
|
|
if g.insideAwait {
|
|
|
|
// already inside await block?
|
|
|
|
// only run the function
|
|
|
|
run()
|
|
|
|
} else {
|
|
|
|
// not inside await? flag it as true, run the function,
|
|
|
|
// then set it back to false
|
|
|
|
g.insideAwait = true
|
|
|
|
run()
|
|
|
|
g.insideAwait = false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-19 08:18:38 +00:00
|
|
|
func (g *generator) GenFunctionCallExpression(w io.Writer, expr *model.FunctionCallExpression) {
|
|
|
|
switch expr.Name {
|
2021-09-30 03:11:56 +00:00
|
|
|
case pcl.IntrinsicConvert:
|
2020-05-19 08:18:38 +00:00
|
|
|
switch arg := expr.Args[0].(type) {
|
|
|
|
case *model.ObjectConsExpression:
|
|
|
|
g.genObjectConsExpression(w, arg, expr.Type())
|
|
|
|
default:
|
2022-04-18 09:03:42 +00:00
|
|
|
g.genIntrensic(w, expr.Args[0], expr.Signature.ReturnType)
|
2020-05-19 08:18:38 +00:00
|
|
|
}
|
2021-09-30 03:11:56 +00:00
|
|
|
case pcl.IntrinsicApply:
|
2022-07-21 19:04:02 +00:00
|
|
|
switch expr.Args[0].(type) {
|
|
|
|
case *model.ScopeTraversalExpression:
|
|
|
|
traversal := expr.Args[0].(*model.ScopeTraversalExpression)
|
|
|
|
if len(traversal.Parts) == 1 {
|
|
|
|
_, isInvoke := g.functionInvokes[traversal.RootName]
|
|
|
|
if isInvoke {
|
|
|
|
switch expr.Args[1].(type) {
|
|
|
|
case *model.AnonymousFunctionExpression:
|
|
|
|
anonFunction := expr.Args[1].(*model.AnonymousFunctionExpression)
|
|
|
|
g.Fgenf(w, "%v", anonFunction.Body)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-19 08:18:38 +00:00
|
|
|
g.genApply(w, expr)
|
|
|
|
case intrinsicAwait:
|
2022-07-21 19:04:02 +00:00
|
|
|
g.withinAwaitBlock(func() {
|
|
|
|
g.Fgenf(w, "await %.17v", expr.Args[0])
|
|
|
|
})
|
|
|
|
|
2020-05-19 08:18:38 +00:00
|
|
|
case intrinsicOutput:
|
2022-07-21 19:04:02 +00:00
|
|
|
// if we are calling Output.Create(FuncInvokeAsync())
|
|
|
|
// then we can simplify to just FuncInvoke() which already returns Output
|
2022-10-08 12:46:25 +00:00
|
|
|
if funcExpr, isFunc := expr.Args[0].(*model.FunctionCallExpression); isFunc && funcExpr.Name == pcl.Invoke {
|
2022-07-21 19:04:02 +00:00
|
|
|
_, fullFunctionName := g.functionName(funcExpr.Args[0])
|
|
|
|
g.Fprintf(w, "%s.Invoke(", fullFunctionName)
|
|
|
|
functionParts := strings.Split(fullFunctionName, ".")
|
|
|
|
functionName := functionParts[len(functionParts)-1]
|
|
|
|
innerFunc, isFunc := funcExpr.Args[1].(*model.FunctionCallExpression)
|
|
|
|
if isFunc && innerFunc.Name == pcl.IntrinsicConvert {
|
|
|
|
switch arg := innerFunc.Args[0].(type) {
|
|
|
|
case *model.ObjectConsExpression:
|
|
|
|
g.withinFunctionInvoke(func() {
|
|
|
|
useImplicitTypeName := g.generateOptions.implicitResourceArgsTypeName
|
|
|
|
inputTypeName := functionName + "InvokeArgs"
|
|
|
|
destTypeName := strings.ReplaceAll(fullFunctionName, functionName, inputTypeName)
|
2023-01-11 22:17:14 +00:00
|
|
|
g.genObjectConsExpressionWithTypeName(w, arg, destTypeName, useImplicitTypeName,
|
|
|
|
pcl.SortedFunctionParameters(funcExpr))
|
2022-07-21 19:04:02 +00:00
|
|
|
})
|
|
|
|
default:
|
|
|
|
g.genIntrensic(w, funcExpr.Args[0], expr.Signature.ReturnType)
|
|
|
|
}
|
|
|
|
} else {
|
2022-10-08 12:46:25 +00:00
|
|
|
if objectExpr, ok := funcExpr.Args[1].(*model.ObjectConsExpression); ok {
|
|
|
|
g.withinFunctionInvoke(func() {
|
|
|
|
useImplicitTypeName := g.generateOptions.implicitResourceArgsTypeName
|
|
|
|
inputTypeName := functionName + "InvokeArgs"
|
|
|
|
destTypeName := strings.ReplaceAll(fullFunctionName, functionName, inputTypeName)
|
2023-01-11 22:17:14 +00:00
|
|
|
g.genObjectConsExpressionWithTypeName(w, objectExpr, destTypeName, useImplicitTypeName,
|
|
|
|
pcl.SortedFunctionParameters(funcExpr))
|
2022-10-08 12:46:25 +00:00
|
|
|
})
|
|
|
|
} else {
|
|
|
|
g.Fgenf(w, "%v", funcExpr.Args[1])
|
|
|
|
}
|
2022-07-21 19:04:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
g.Fprint(w, ")")
|
|
|
|
} else {
|
|
|
|
g.Fgenf(w, "Output.Create(%.v)", expr.Args[0])
|
|
|
|
}
|
|
|
|
|
2020-05-19 08:18:38 +00:00
|
|
|
case "element":
|
2020-05-22 06:46:25 +00:00
|
|
|
g.Fgenf(w, "%.20v[%.v]", expr.Args[0], expr.Args[1])
|
2020-05-19 08:18:38 +00:00
|
|
|
case "entries":
|
2023-06-02 14:59:46 +00:00
|
|
|
g.genEntries(w, expr)
|
2020-05-19 08:18:38 +00:00
|
|
|
case "fileArchive":
|
|
|
|
g.Fgenf(w, "new FileArchive(%.v)", expr.Args[0])
|
2022-04-25 19:59:30 +00:00
|
|
|
case "remoteArchive":
|
|
|
|
g.Fgenf(w, "new RemoteArchive(%.v)", expr.Args[0])
|
|
|
|
case "assetArchive":
|
|
|
|
g.Fgen(w, "new AssetArchive(")
|
|
|
|
g.genDictionary(w, expr.Args[0].(*model.ObjectConsExpression), "AssetOrArchive")
|
|
|
|
g.Fgen(w, ")")
|
2020-05-19 08:18:38 +00:00
|
|
|
case "fileAsset":
|
|
|
|
g.Fgenf(w, "new FileAsset(%.v)", expr.Args[0])
|
2022-04-25 19:59:30 +00:00
|
|
|
case "stringAsset":
|
|
|
|
g.Fgenf(w, "new StringAsset(%.v)", expr.Args[0])
|
|
|
|
case "remoteAsset":
|
|
|
|
g.Fgenf(w, "new RemoteAsset(%.v)", expr.Args[0])
|
2021-09-10 22:09:28 +00:00
|
|
|
case "filebase64":
|
|
|
|
// Assuming the existence of the following helper method located earlier in the preamble
|
|
|
|
g.Fgenf(w, "ReadFileBase64(%v)", expr.Args[0])
|
2022-01-21 14:03:25 +00:00
|
|
|
case "filebase64sha256":
|
|
|
|
// Assuming the existence of the following helper method located earlier in the preamble
|
|
|
|
g.Fgenf(w, "ComputeFileBase64Sha256(%v)", expr.Args[0])
|
2023-03-10 11:14:28 +00:00
|
|
|
case "notImplemented":
|
|
|
|
g.Fgenf(w, "NotImplemented(%v)", expr.Args[0])
|
2023-06-11 09:05:10 +00:00
|
|
|
case "singleOrNone":
|
|
|
|
g.Fgenf(w, "Enumerable.Single(%v)", expr.Args[0])
|
2021-09-30 03:11:56 +00:00
|
|
|
case pcl.Invoke:
|
2022-07-21 19:04:02 +00:00
|
|
|
_, fullFunctionName := g.functionName(expr.Args[0])
|
|
|
|
functionParts := strings.Split(fullFunctionName, ".")
|
|
|
|
functionName := functionParts[len(functionParts)-1]
|
|
|
|
if g.insideAwait {
|
|
|
|
g.Fprintf(w, "%s.InvokeAsync(", fullFunctionName)
|
2021-11-18 22:53:17 +00:00
|
|
|
} else {
|
2022-07-21 19:04:02 +00:00
|
|
|
g.Fprintf(w, "%s.Invoke(", fullFunctionName)
|
2021-07-29 03:41:23 +00:00
|
|
|
}
|
2021-11-18 22:53:17 +00:00
|
|
|
|
2022-07-21 19:04:02 +00:00
|
|
|
innerFunc, isFunc := expr.Args[1].(*model.FunctionCallExpression)
|
|
|
|
if isFunc && innerFunc.Name == pcl.IntrinsicConvert {
|
|
|
|
// function has been "lowered" i.e. rewritten with __convert
|
|
|
|
switch arg := innerFunc.Args[0].(type) {
|
|
|
|
case *model.ObjectConsExpression:
|
|
|
|
g.withinFunctionInvoke(func() {
|
|
|
|
useImplicitTypeName := g.generateOptions.implicitResourceArgsTypeName
|
|
|
|
inputTypeName := functionName + "InvokeArgs"
|
|
|
|
if g.insideAwait {
|
|
|
|
inputTypeName = functionName + "Args"
|
|
|
|
}
|
|
|
|
|
|
|
|
destTypeName := strings.ReplaceAll(fullFunctionName, functionName, inputTypeName)
|
2023-01-11 22:17:14 +00:00
|
|
|
g.genObjectConsExpressionWithTypeName(w, arg, destTypeName, useImplicitTypeName,
|
|
|
|
pcl.SortedFunctionParameters(expr))
|
2022-07-21 19:04:02 +00:00
|
|
|
})
|
|
|
|
default:
|
|
|
|
g.genIntrensic(w, expr.Args[0], expr.Signature.ReturnType)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// function has not been rewritten
|
|
|
|
switch arg := expr.Args[1].(type) {
|
|
|
|
case *model.ObjectConsExpression:
|
|
|
|
useImplicitTypeName := true
|
|
|
|
destTypeName := "Irrelevant"
|
2023-01-11 22:17:14 +00:00
|
|
|
g.genObjectConsExpressionWithTypeName(w, arg, destTypeName, useImplicitTypeName,
|
|
|
|
pcl.SortedFunctionParameters(expr))
|
2022-07-21 19:04:02 +00:00
|
|
|
default:
|
|
|
|
g.genIntrensic(w, expr.Args[0], expr.Signature.ReturnType)
|
|
|
|
}
|
2020-05-19 08:18:38 +00:00
|
|
|
}
|
2022-07-21 19:04:02 +00:00
|
|
|
|
2021-07-29 03:41:23 +00:00
|
|
|
g.Fprint(w, ")")
|
|
|
|
case "join":
|
|
|
|
g.Fgenf(w, "string.Join(%v, %v)", expr.Args[0], expr.Args[1])
|
2020-05-19 08:18:38 +00:00
|
|
|
case "length":
|
|
|
|
g.Fgenf(w, "%.20v.Length", expr.Args[0])
|
|
|
|
case "lookup":
|
2020-05-22 06:46:25 +00:00
|
|
|
g.Fgenf(w, "%v[%v]", expr.Args[0], expr.Args[1])
|
|
|
|
if len(expr.Args) == 3 {
|
|
|
|
g.Fgenf(w, " ?? %v", expr.Args[2])
|
|
|
|
}
|
2020-05-19 08:18:38 +00:00
|
|
|
case "range":
|
|
|
|
g.genRange(w, expr, false)
|
|
|
|
case "readFile":
|
2020-05-22 06:46:25 +00:00
|
|
|
g.Fgenf(w, "File.ReadAllText(%v)", expr.Args[0])
|
2020-05-19 08:18:38 +00:00
|
|
|
case "readDir":
|
|
|
|
g.Fgenf(w, "Directory.GetFiles(%.v).Select(Path.GetFileName)", expr.Args[0])
|
2020-06-30 18:35:24 +00:00
|
|
|
case "secret":
|
|
|
|
g.Fgenf(w, "Output.CreateSecret(%v)", expr.Args[0])
|
2023-01-31 12:31:00 +00:00
|
|
|
case "unsecret":
|
|
|
|
g.Fgenf(w, "Output.Unsecret(%v)", expr.Args[0])
|
2020-05-19 08:18:38 +00:00
|
|
|
case "split":
|
|
|
|
g.Fgenf(w, "%.20v.Split(%v)", expr.Args[1], expr.Args[0])
|
2021-07-29 03:41:23 +00:00
|
|
|
case "toBase64":
|
2022-06-30 09:34:16 +00:00
|
|
|
g.Fgenf(w, "Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(%v))", expr.Args[0])
|
2022-09-16 23:12:29 +00:00
|
|
|
case "fromBase64":
|
|
|
|
g.Fgenf(w, "System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(%v))", expr.Args[0])
|
2020-05-19 08:18:38 +00:00
|
|
|
case "toJSON":
|
[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
|
|
|
if model.ContainsOutputs(expr.Args[0].Type()) {
|
|
|
|
g.Fgen(w, "Output.JsonSerialize(Output.Create(")
|
|
|
|
g.genDictionaryOrTuple(w, expr.Args[0])
|
|
|
|
g.Fgen(w, "))")
|
|
|
|
} else {
|
|
|
|
g.Fgen(w, "JsonSerializer.Serialize(")
|
|
|
|
g.genDictionaryOrTuple(w, expr.Args[0])
|
|
|
|
g.Fgen(w, ")")
|
|
|
|
}
|
2021-09-10 18:40:38 +00:00
|
|
|
case "sha1":
|
|
|
|
// Assuming the existence of the following helper method located earlier in the preamble
|
|
|
|
g.Fgenf(w, "ComputeSHA1(%v)", expr.Args[0])
|
2022-03-16 00:05:36 +00:00
|
|
|
case "stack":
|
|
|
|
g.Fgen(w, "Deployment.Instance.StackName")
|
|
|
|
case "project":
|
|
|
|
g.Fgen(w, "Deployment.Instance.ProjectName")
|
2024-08-19 03:58:19 +00:00
|
|
|
case "organization":
|
|
|
|
g.Fgen(w, "Deployment.Instance.OrganizationName")
|
2022-03-16 00:05:36 +00:00
|
|
|
case "cwd":
|
|
|
|
g.Fgenf(w, "Directory.GetCurrentDirectory()")
|
2020-05-19 08:18:38 +00:00
|
|
|
default:
|
|
|
|
g.genNYI(w, "call %v", expr.Name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-25 19:59:30 +00:00
|
|
|
func (g *generator) genDictionaryOrTuple(w io.Writer, expr model.Expression) {
|
2020-05-19 08:18:38 +00:00
|
|
|
switch expr := expr.(type) {
|
|
|
|
case *model.ObjectConsExpression:
|
2022-04-25 19:59:30 +00:00
|
|
|
g.genDictionary(w, expr, "object?")
|
2020-05-19 08:18:38 +00:00
|
|
|
case *model.TupleConsExpression:
|
[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
|
|
|
if g.isListOfDifferentTypes(expr) {
|
|
|
|
g.Fgen(w, "new object?[]\n")
|
|
|
|
} else {
|
|
|
|
g.Fgen(w, "new[]\n")
|
|
|
|
}
|
|
|
|
|
2022-07-21 19:04:02 +00:00
|
|
|
g.Fgenf(w, "%[1]s{\n", g.Indent)
|
2020-05-19 08:18:38 +00:00
|
|
|
g.Indented(func() {
|
2022-07-21 19:04:02 +00:00
|
|
|
for _, v := range expr.Expressions {
|
|
|
|
g.Fgenf(w, "%s", g.Indent)
|
|
|
|
g.genDictionaryOrTuple(w, v)
|
|
|
|
g.Fgen(w, ",\n")
|
|
|
|
}
|
2020-05-19 08:18:38 +00:00
|
|
|
})
|
2022-07-21 19:04:02 +00:00
|
|
|
g.Fgenf(w, "%s}", g.Indent)
|
2020-05-19 08:18:38 +00:00
|
|
|
default:
|
|
|
|
g.Fgenf(w, "%.v", expr)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-25 19:59:30 +00:00
|
|
|
func (g *generator) genDictionary(w io.Writer, expr *model.ObjectConsExpression, valueType string) {
|
|
|
|
g.Fgenf(w, "new Dictionary<string, %s>\n", valueType)
|
|
|
|
g.Fgenf(w, "%s{\n", g.Indent)
|
|
|
|
g.Indented(func() {
|
|
|
|
for _, item := range expr.Items {
|
2022-07-21 19:04:02 +00:00
|
|
|
g.Fgenf(w, "%s[%.v] = ", g.Indent, item.Key)
|
2022-04-25 19:59:30 +00:00
|
|
|
g.genDictionaryOrTuple(w, item.Value)
|
2022-07-21 19:04:02 +00:00
|
|
|
g.Fgen(w, ",\n")
|
2022-04-25 19:59:30 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
g.Fgenf(w, "%s}", g.Indent)
|
|
|
|
}
|
|
|
|
|
[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
|
|
|
func (g *generator) isListOfDifferentTypes(expr *model.TupleConsExpression) bool {
|
|
|
|
var prevType model.Type
|
|
|
|
for _, v := range expr.Expressions {
|
|
|
|
if prevType == nil {
|
|
|
|
prevType = v.Type()
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
_, isObjectType := prevType.(*model.ObjectType)
|
|
|
|
_, isMap := prevType.(*model.MapType)
|
|
|
|
|
|
|
|
if isObjectType || isMap {
|
|
|
|
// don't actually compare object types or maps because these are always
|
|
|
|
// mapped to Dictionary<string, object?> in C# so they will be the same type
|
|
|
|
// even if their contents are different
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
conversionFrom := prevType.ConversionFrom(v.Type())
|
|
|
|
conversionTo := v.Type().ConversionFrom(prevType)
|
|
|
|
|
|
|
|
if conversionTo != model.SafeConversion || conversionFrom != model.SafeConversion {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2020-05-19 08:18:38 +00:00
|
|
|
func (g *generator) GenIndexExpression(w io.Writer, expr *model.IndexExpression) {
|
|
|
|
g.Fgenf(w, "%.20v[%.v]", expr.Collection, expr.Key)
|
|
|
|
}
|
|
|
|
|
2020-05-22 06:46:25 +00:00
|
|
|
func (g *generator) escapeString(v string, verbatim, expressions bool) string {
|
2020-05-19 08:18:38 +00:00
|
|
|
builder := strings.Builder{}
|
|
|
|
for _, c := range v {
|
2024-08-09 14:43:51 +00:00
|
|
|
if c == '\x00' {
|
|
|
|
// escape NUL bytes
|
|
|
|
builder.WriteString("\u0000")
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2020-05-19 08:18:38 +00:00
|
|
|
if verbatim {
|
|
|
|
if c == '"' {
|
|
|
|
builder.WriteRune('"')
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if c == '"' || c == '\\' {
|
|
|
|
builder.WriteRune('\\')
|
|
|
|
}
|
|
|
|
}
|
2020-05-22 06:46:25 +00:00
|
|
|
if expressions && (c == '{' || c == '}') {
|
|
|
|
builder.WriteRune(c)
|
|
|
|
}
|
2020-05-19 08:18:38 +00:00
|
|
|
builder.WriteRune(c)
|
|
|
|
}
|
|
|
|
return builder.String()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) genStringLiteral(w io.Writer, v string) {
|
|
|
|
newlines := strings.Contains(v, "\n")
|
|
|
|
if !newlines {
|
|
|
|
// This string does not contain newlines so we'll generate a regular string literal. Quotes and backslashes
|
|
|
|
// will be escaped in conformance with
|
|
|
|
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure
|
|
|
|
g.Fgen(w, "\"")
|
2020-05-22 06:46:25 +00:00
|
|
|
g.Fgen(w, g.escapeString(v, false, false))
|
2020-05-19 08:18:38 +00:00
|
|
|
g.Fgen(w, "\"")
|
|
|
|
} else {
|
|
|
|
// This string does contain newlines, so we'll generate a verbatim string literal. Quotes will be escaped
|
|
|
|
// in conformance with
|
|
|
|
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure
|
|
|
|
g.Fgen(w, "@\"")
|
2020-05-22 06:46:25 +00:00
|
|
|
g.Fgen(w, g.escapeString(v, true, false))
|
2020-05-19 08:18:38 +00:00
|
|
|
g.Fgen(w, "\"")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) GenLiteralValueExpression(w io.Writer, expr *model.LiteralValueExpression) {
|
2021-06-24 16:17:55 +00:00
|
|
|
typ := expr.Type()
|
|
|
|
if cns, ok := typ.(*model.ConstType); ok {
|
|
|
|
typ = cns.Type
|
|
|
|
}
|
|
|
|
|
|
|
|
switch typ {
|
2020-05-19 08:18:38 +00:00
|
|
|
case model.BoolType:
|
|
|
|
g.Fgenf(w, "%v", expr.Value.True())
|
2020-08-06 20:12:27 +00:00
|
|
|
case model.NoneType:
|
|
|
|
g.Fgen(w, "null")
|
2020-05-19 08:18:38 +00:00
|
|
|
case model.NumberType:
|
|
|
|
bf := expr.Value.AsBigFloat()
|
|
|
|
if i, acc := bf.Int64(); acc == big.Exact {
|
|
|
|
g.Fgenf(w, "%d", i)
|
|
|
|
} else {
|
|
|
|
f, _ := bf.Float64()
|
|
|
|
g.Fgenf(w, "%g", f)
|
|
|
|
}
|
|
|
|
case model.StringType:
|
|
|
|
g.genStringLiteral(w, expr.Value.AsString())
|
|
|
|
default:
|
|
|
|
contract.Failf("unexpected literal type in GenLiteralValueExpression: %v (%v)", expr.Type(),
|
|
|
|
expr.SyntaxNode().Range())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) GenObjectConsExpression(w io.Writer, expr *model.ObjectConsExpression) {
|
2023-03-23 22:25:21 +00:00
|
|
|
switch argType := expr.Type().(type) {
|
|
|
|
case *model.ObjectType:
|
|
|
|
if len(argType.Annotations) > 0 {
|
|
|
|
if configMetadata, ok := argType.Annotations[0].(*ObjectTypeFromConfigMetadata); ok {
|
|
|
|
fullTypeName := fmt.Sprintf("Components.%sArgs.%s",
|
|
|
|
configMetadata.ComponentName,
|
|
|
|
configMetadata.TypeName)
|
|
|
|
g.genObjectConsExpressionWithTypeName(w, expr, fullTypeName, false, nil)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-05-19 08:18:38 +00:00
|
|
|
g.genObjectConsExpression(w, expr, expr.Type())
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) genObjectConsExpression(w io.Writer, expr *model.ObjectConsExpression, destType model.Type) {
|
|
|
|
if len(expr.Items) == 0 {
|
2022-09-16 23:12:29 +00:00
|
|
|
g.Fgenf(w, "null")
|
2020-05-19 08:18:38 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-03-24 00:06:57 +00:00
|
|
|
if schemaType, ok := g.toSchemaType(destType); ok {
|
|
|
|
if codegen.ResolvedType(schemaType) == schema.AnyType {
|
|
|
|
g.genDictionaryOrTuple(w, expr)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-18 22:53:17 +00:00
|
|
|
destTypeName := g.argumentTypeName(expr, destType)
|
2023-01-11 22:17:14 +00:00
|
|
|
g.genObjectConsExpressionWithTypeName(w, expr, destTypeName, false, nil)
|
2021-11-18 22:53:17 +00:00
|
|
|
}
|
|
|
|
|
2022-10-13 09:47:01 +00:00
|
|
|
func propertyNameOverrides(exprType model.Type) map[string]string {
|
|
|
|
overrides := make(map[string]string)
|
|
|
|
schemaType, ok := pcl.GetSchemaForType(exprType)
|
|
|
|
if !ok {
|
|
|
|
return overrides
|
|
|
|
}
|
|
|
|
|
|
|
|
switch arg := schemaType.(type) {
|
|
|
|
case *schema.ObjectType:
|
|
|
|
for _, property := range arg.Properties {
|
|
|
|
foundOverride := false
|
|
|
|
if csharp, ok := property.Language["csharp"]; ok {
|
|
|
|
if options, ok := csharp.(CSharpPropertyInfo); ok {
|
|
|
|
overrides[property.Name] = options.Name
|
|
|
|
foundOverride = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if !foundOverride {
|
|
|
|
overrides[property.Name] = property.Name
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return overrides
|
|
|
|
}
|
|
|
|
|
|
|
|
func resolvePropertyName(property string, overrides map[string]string) string {
|
|
|
|
foundOverride, ok := overrides[property]
|
|
|
|
if ok {
|
|
|
|
return propertyName(foundOverride)
|
|
|
|
}
|
|
|
|
|
|
|
|
return propertyName(property)
|
|
|
|
}
|
|
|
|
|
2023-09-28 12:43:35 +00:00
|
|
|
func unwrapIntrinsicConvert(expr model.Expression) model.Expression {
|
|
|
|
if call, ok := expr.(*model.FunctionCallExpression); ok && call.Name == pcl.IntrinsicConvert {
|
|
|
|
return call.Args[0]
|
|
|
|
}
|
|
|
|
|
|
|
|
return expr
|
|
|
|
}
|
|
|
|
|
|
|
|
func isEmptyList(expr model.Expression) bool {
|
|
|
|
expr = unwrapIntrinsicConvert(expr)
|
|
|
|
if list, ok := expr.(*model.TupleConsExpression); ok {
|
|
|
|
return len(list.Expressions) == 0
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2023-12-23 11:26:01 +00:00
|
|
|
func objectKey(item model.ObjectConsItem) string {
|
|
|
|
switch key := item.Key.(type) {
|
|
|
|
case *model.LiteralValueExpression:
|
|
|
|
return key.Value.AsString()
|
|
|
|
case *model.TemplateExpression:
|
|
|
|
// assume a template expression has one constant part that is a LiteralValueExpression
|
|
|
|
if len(key.Parts) == 1 {
|
|
|
|
if literal, ok := key.Parts[0].(*model.LiteralValueExpression); ok {
|
|
|
|
return literal.Value.AsString()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2021-11-18 22:53:17 +00:00
|
|
|
func (g *generator) genObjectConsExpressionWithTypeName(
|
2023-01-11 22:17:14 +00:00
|
|
|
w io.Writer,
|
|
|
|
expr *model.ObjectConsExpression,
|
|
|
|
destTypeName string,
|
|
|
|
implicitTypeName bool,
|
2023-03-03 16:36:39 +00:00
|
|
|
multiArguments []*schema.Property,
|
|
|
|
) {
|
2021-11-18 22:53:17 +00:00
|
|
|
if len(expr.Items) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-01-11 22:17:14 +00:00
|
|
|
if len(multiArguments) > 0 {
|
|
|
|
pcl.GenerateMultiArguments(g.Formatter, w, "null", expr, multiArguments)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-11-18 22:53:17 +00:00
|
|
|
typeName := destTypeName
|
2020-05-19 08:18:38 +00:00
|
|
|
if typeName != "" {
|
2022-07-21 19:04:02 +00:00
|
|
|
if implicitTypeName {
|
|
|
|
g.Fgenf(w, "new()")
|
|
|
|
} else {
|
|
|
|
g.Fgenf(w, "new %s", typeName)
|
|
|
|
}
|
|
|
|
|
2022-10-13 09:47:01 +00:00
|
|
|
propertyNames := propertyNameOverrides(expr.Type())
|
2020-05-19 08:18:38 +00:00
|
|
|
g.Fgenf(w, "\n%s{\n", g.Indent)
|
|
|
|
g.Indented(func() {
|
|
|
|
for _, item := range expr.Items {
|
|
|
|
g.Fgenf(w, "%s", g.Indent)
|
2023-12-23 11:26:01 +00:00
|
|
|
propertyKey := objectKey(item)
|
2022-10-13 09:47:01 +00:00
|
|
|
g.Fprint(w, resolvePropertyName(propertyKey, propertyNames))
|
2023-09-28 12:43:35 +00:00
|
|
|
if g.usingDefaultListInitializer() && isEmptyList(item.Value) {
|
|
|
|
g.Fgen(w, " = new() { },\n")
|
|
|
|
} else {
|
|
|
|
g.Fgenf(w, " = %.v,\n", item.Value)
|
|
|
|
}
|
2020-05-19 08:18:38 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
g.Fgenf(w, "%s}", g.Indent)
|
|
|
|
} else {
|
|
|
|
g.Fgenf(w, "\n%s{\n", g.Indent)
|
|
|
|
g.Indented(func() {
|
|
|
|
for _, item := range expr.Items {
|
|
|
|
g.Fgenf(w, "%s{ %.v, %.v },\n", g.Indent, item.Key, item.Value)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
g.Fgenf(w, "%s}", g.Indent)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) genRelativeTraversal(w io.Writer,
|
2023-03-03 16:36:39 +00:00
|
|
|
traversal hcl.Traversal, parts []model.Traversable, objType *schema.ObjectType,
|
|
|
|
) {
|
2020-05-19 08:18:38 +00:00
|
|
|
for i, part := range traversal {
|
|
|
|
var key cty.Value
|
|
|
|
switch part := part.(type) {
|
|
|
|
case hcl.TraverseAttr:
|
|
|
|
key = cty.StringVal(part.Name)
|
|
|
|
if objType != nil {
|
|
|
|
if p, ok := objType.Property(part.Name); ok {
|
|
|
|
if info, ok := p.Language["csharp"].(CSharpPropertyInfo); ok && info.Name != "" {
|
|
|
|
key = cty.StringVal(info.Name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
case hcl.TraverseIndex:
|
|
|
|
key = part.Key
|
|
|
|
default:
|
|
|
|
contract.Failf("unexpected traversal part of type %T (%v)", part, part.SourceRange())
|
|
|
|
}
|
|
|
|
|
|
|
|
switch key.Type() {
|
|
|
|
case cty.String:
|
2022-07-21 19:04:02 +00:00
|
|
|
if model.IsOptionalType(model.GetTraversableType(parts[i])) {
|
|
|
|
g.Fgen(w, "?")
|
|
|
|
}
|
2020-05-22 06:46:25 +00:00
|
|
|
g.Fgenf(w, ".%s", propertyName(key.AsString()))
|
2020-05-19 08:18:38 +00:00
|
|
|
case cty.Number:
|
|
|
|
idx, _ := key.AsBigFloat().Int64()
|
|
|
|
g.Fgenf(w, "[%d]", idx)
|
|
|
|
default:
|
|
|
|
contract.Failf("unexpected traversal key of type %T (%v)", key, key.AsString())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) GenRelativeTraversalExpression(w io.Writer, expr *model.RelativeTraversalExpression) {
|
|
|
|
g.Fgenf(w, "%.20v", expr.Source)
|
|
|
|
g.genRelativeTraversal(w, expr.Traversal, expr.Parts, nil)
|
|
|
|
}
|
|
|
|
|
2022-07-21 19:04:02 +00:00
|
|
|
func (g *generator) schemaTypeName(schemaType *schema.ObjectType) string {
|
|
|
|
fullyQualifiedTypeName := schemaType.Token
|
|
|
|
nameParts := strings.Split(fullyQualifiedTypeName, ":")
|
|
|
|
return Title(nameParts[len(nameParts)-1])
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) withinFunctionInvoke(run func()) {
|
|
|
|
if g.insideFunctionInvoke {
|
|
|
|
// already inside this block?
|
|
|
|
// just run the function
|
|
|
|
run()
|
|
|
|
} else {
|
|
|
|
// not inside function invoke?
|
|
|
|
// set it to true first, run, then set it back to false
|
|
|
|
g.insideFunctionInvoke = true
|
|
|
|
run()
|
|
|
|
g.insideFunctionInvoke = false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-19 08:18:38 +00:00
|
|
|
func (g *generator) GenScopeTraversalExpression(w io.Writer, expr *model.ScopeTraversalExpression) {
|
2023-03-23 22:25:21 +00:00
|
|
|
rootName := makeValidIdentifier(expr.RootName)
|
2023-03-08 13:21:34 +00:00
|
|
|
if g.isComponent {
|
|
|
|
configVars := map[string]*pcl.ConfigVariable{}
|
|
|
|
for _, configVar := range g.program.ConfigVariables() {
|
|
|
|
configVars[configVar.Name()] = configVar
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, isConfig := configVars[expr.RootName]; isConfig {
|
|
|
|
if _, configReference := expr.Parts[0].(*pcl.ConfigVariable); configReference {
|
2023-12-12 12:19:42 +00:00
|
|
|
rootName = "args." + Title(expr.RootName)
|
2023-03-08 13:21:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-19 08:18:38 +00:00
|
|
|
if _, ok := expr.Parts[0].(*model.SplatVariable); ok {
|
|
|
|
rootName = "__item"
|
|
|
|
}
|
|
|
|
|
|
|
|
g.Fgen(w, rootName)
|
|
|
|
|
2022-07-21 19:04:02 +00:00
|
|
|
invokedFunctionSchema, isFunctionInvoke := g.functionInvokes[rootName]
|
|
|
|
|
2023-01-11 22:17:14 +00:00
|
|
|
if isFunctionInvoke && !g.asyncInit && len(expr.Parts) > 1 {
|
|
|
|
lambdaArg := "invoke"
|
|
|
|
if invokedFunctionSchema.ReturnType != nil {
|
|
|
|
if objectType, ok := invokedFunctionSchema.ReturnType.(*schema.ObjectType); ok && objectType != nil {
|
|
|
|
lambdaArg = LowerCamelCase(g.schemaTypeName(objectType))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-21 19:04:02 +00:00
|
|
|
// Assume invokes are returning Output<T> instead of Task<T>
|
|
|
|
g.Fgenf(w, ".Apply(%s => %s", lambdaArg, lambdaArg)
|
2023-01-11 22:17:14 +00:00
|
|
|
|
2022-07-21 19:04:02 +00:00
|
|
|
}
|
|
|
|
|
2020-05-19 08:18:38 +00:00
|
|
|
var objType *schema.ObjectType
|
2021-09-30 03:11:56 +00:00
|
|
|
if resource, ok := expr.Parts[0].(*pcl.Resource); ok {
|
|
|
|
if schemaType, ok := pcl.GetSchemaForType(resource.InputType); ok {
|
2020-05-19 08:18:38 +00:00
|
|
|
objType, _ = schemaType.(*schema.ObjectType)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
g.genRelativeTraversal(w, expr.Traversal.SimpleSplit().Rel, expr.Parts, objType)
|
2022-07-21 19:04:02 +00:00
|
|
|
|
2023-01-11 22:17:14 +00:00
|
|
|
if isFunctionInvoke && !g.asyncInit && len(expr.Parts) > 1 {
|
2022-07-21 19:04:02 +00:00
|
|
|
g.Fgenf(w, ")")
|
|
|
|
}
|
2020-05-19 08:18:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) GenSplatExpression(w io.Writer, expr *model.SplatExpression) {
|
|
|
|
g.Fgenf(w, "%.20v.Select(__item => %.v).ToList()", expr.Source, expr.Each)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) GenTemplateExpression(w io.Writer, expr *model.TemplateExpression) {
|
|
|
|
multiLine := false
|
2020-05-22 06:46:25 +00:00
|
|
|
expressions := false
|
2020-05-19 08:18:38 +00:00
|
|
|
for _, expr := range expr.Parts {
|
2021-06-24 16:17:55 +00:00
|
|
|
if lit, ok := expr.(*model.LiteralValueExpression); ok && model.StringType.AssignableFrom(lit.Type()) {
|
2020-05-19 08:18:38 +00:00
|
|
|
if strings.Contains(lit.Value.AsString(), "\n") {
|
|
|
|
multiLine = true
|
|
|
|
}
|
|
|
|
} else {
|
2020-05-22 06:46:25 +00:00
|
|
|
expressions = true
|
2020-05-19 08:18:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if multiLine {
|
|
|
|
g.Fgen(w, "@")
|
|
|
|
}
|
2020-05-22 06:46:25 +00:00
|
|
|
if expressions {
|
2020-05-19 08:18:38 +00:00
|
|
|
g.Fgen(w, "$")
|
|
|
|
}
|
|
|
|
g.Fgen(w, "\"")
|
|
|
|
for _, expr := range expr.Parts {
|
2021-06-24 16:17:55 +00:00
|
|
|
if lit, ok := expr.(*model.LiteralValueExpression); ok && model.StringType.AssignableFrom(lit.Type()) {
|
2020-05-22 06:46:25 +00:00
|
|
|
g.Fgen(w, g.escapeString(lit.Value.AsString(), multiLine, expressions))
|
2020-05-19 08:18:38 +00:00
|
|
|
} else {
|
|
|
|
g.Fgenf(w, "{%.v}", expr)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
g.Fgen(w, "\"")
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) GenTemplateJoinExpression(w io.Writer, expr *model.TemplateJoinExpression) {
|
|
|
|
g.genNYI(w, "TemplateJoinExpression")
|
|
|
|
}
|
|
|
|
|
2022-07-21 19:04:02 +00:00
|
|
|
// Removes duplicate strings. Useful when collecting a distinct set of imports
|
|
|
|
func removeDuplicates(inputs []string) []string {
|
|
|
|
distinctInputs := make([]string, 0)
|
|
|
|
seenTexts := make(map[string]bool)
|
|
|
|
for _, input := range inputs {
|
|
|
|
if _, seen := seenTexts[input]; !seen {
|
|
|
|
seenTexts[input] = true
|
|
|
|
distinctInputs = append(distinctInputs, input)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return distinctInputs
|
|
|
|
}
|
|
|
|
|
[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
|
|
|
func (g *generator) isListOfDifferentObjectTypes(expr *model.TupleConsExpression) bool {
|
2022-07-21 19:04:02 +00:00
|
|
|
switch expr.Type().(type) {
|
|
|
|
case *model.TupleType:
|
|
|
|
tupleType := expr.Type().(*model.TupleType)
|
|
|
|
typeNames := make([]string, 0)
|
|
|
|
for _, elemType := range tupleType.ElementTypes {
|
|
|
|
if schemaType, ok := pcl.GetSchemaForType(elemType); ok {
|
|
|
|
if objectType, ok := schemaType.(*schema.ObjectType); ok {
|
|
|
|
typeName := g.schemaTypeName(objectType)
|
|
|
|
typeNames = append(typeNames, typeName)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return len(removeDuplicates(typeNames)) > 1
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2020-05-19 08:18:38 +00:00
|
|
|
func (g *generator) GenTupleConsExpression(w io.Writer, expr *model.TupleConsExpression) {
|
|
|
|
switch len(expr.Expressions) {
|
|
|
|
case 0:
|
2023-08-07 16:43:37 +00:00
|
|
|
g.Fgenf(w, "%s {}", g.listInitializer)
|
2020-05-19 08:18:38 +00:00
|
|
|
default:
|
[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
|
|
|
if !g.isListOfDifferentObjectTypes(expr) {
|
2023-08-07 16:43:37 +00:00
|
|
|
// only generate a list initializer when we don't have a list of union types
|
|
|
|
// because list of a union is mapped to InputList<object>
|
2022-07-21 19:04:02 +00:00
|
|
|
// which means new[] will not work because type-inference won't
|
2023-08-07 16:43:37 +00:00
|
|
|
// know the type of the array beforehand
|
|
|
|
g.Fgenf(w, "%s", g.listInitializer)
|
2022-07-21 19:04:02 +00:00
|
|
|
}
|
|
|
|
|
2020-05-19 08:18:38 +00:00
|
|
|
g.Fgenf(w, "\n%s{", g.Indent)
|
2022-07-21 19:04:02 +00:00
|
|
|
|
2020-05-19 08:18:38 +00:00
|
|
|
g.Indented(func() {
|
|
|
|
for _, v := range expr.Expressions {
|
|
|
|
g.Fgenf(w, "\n%s%.v,", g.Indent, v)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
g.Fgenf(w, "\n%s}", g.Indent)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *generator) GenUnaryOpExpression(w io.Writer, expr *model.UnaryOpExpression) {
|
|
|
|
opstr, precedence := "", g.GetPrecedence(expr)
|
|
|
|
switch expr.Operation {
|
|
|
|
case hclsyntax.OpLogicalNot:
|
|
|
|
opstr = "!"
|
|
|
|
case hclsyntax.OpNegate:
|
|
|
|
opstr = "-"
|
|
|
|
}
|
|
|
|
g.Fgenf(w, "%[2]v%.[1]*[3]v", precedence, opstr, expr.Operand)
|
|
|
|
}
|