hashicorp / hashicorp/hcl

Feature Request: Null Coalescing Operator

Open
#411 2 comments 4 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
5.8k
Forks
657
Avg merge
20h 36m
Merged PRs (30d)
6

Description

Many languages offer syntactic sugar for defining default values in form of a [null coalescing operator](https://en.wikipedia.org/wiki/Null_coalescing_operator). The most common one seems to be `??`. `go-cty` offers the [`coalesce()`](https://pkg.go.dev/github.com/zclconf/go-cty/cty/function/stdlib#Coalesce) function for that purpose.

The function works, but with a little sugar everything is sweeter :)

### HCL Template

```hcl
map = {
attribute1 = null ?? "default"
attribute2 = "Hello ${null ?? "world" }"
}
```

(In reality, instead of `null` we would use an expression that could actually yield a non-null result.)

### Expected behavior

`attribute1` should be assigned `default`
`attribute2` should be assigned `Hello world`

This is the same behaviour as of cty's `coalesce()` function:

```hcl
map = {
attribute1 = coalesce(null, "default")
attribute2 = "Hello ${coalesce(null, "world")}"
}
```

Obviously, "falsish" values, such as `0` or the empty string, should not be considered null. `0 ?? 1` should evaluate to `0`.

This is a feature proposal for hcl2. As `??` is a parse error at the moment, it should be possible to add the operator without breaking existing configurations.

Contributor guide

No contributing guide indexed for this repository

Research direction

No files or tests are named. Start by locating the hcl2 expression parser and its handling of operators, then compare the requested semantics with go-cty's coalesce() function. Done means ?? parses in the shown HCL expressions, returns the fallback only for null, and preserves values such as 0 and the empty string.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.