Skip to content

Commit a075f90

Browse files
authored
Merge pull request #300 from vito/string-interpolation
Interpolate in double-quoted strings (Dang 2.5)
2 parents 11332a9 + ed2e280 commit a075f90

69 files changed

Lines changed: 37283 additions & 30502 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.agents/skills/dang-language/SKILL.md‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,12 @@ Four ideas the rest of the language hangs on:
5454
fields concurrently, so a field can't write state declared outside it.
5555
- **`#` comments, no `//`**; docstrings are real `"""..."""` strings before a
5656
declaration. Record literals use **double braces** `{{ ... }}`.
57+
- **Strings: the delimiter decides** — `"..."`/`"""..."""` process escapes and
58+
interpolate `${...}`; `'...'`/`'''...'''` are verbatim; backticks are raw
59+
with `${...}`. Quotes are for text, backticks for code. Shell-ish text that
60+
keeps `${VAR}` goes in single quotes (`'${GOBIN}:${PATH}'`, `'''sh`). Before
61+
Dang 2.5, `"..."` doesn't interpolate and `"""` is raw. See
62+
`reference/syntax.md`.
5763
- **No `for`/`while` keyword** — iterate with `xs.each { x => ... }`; repeat-until-`break`
5864
is the `loop { ... }` builtin.
5965
- **Directives** (`@deprecated`) are typed declarations, not comment pragmas.
@@ -83,7 +89,7 @@ if (v != null) { v } else { "?" } # v narrowed to T! in the then-branch
8389
- `xs.indexOf(x)` (nullable), `xs.flatMap { x => x.items }`, `s.toInt(base: 16)` — not hand-rolled index loops, `reduce([])` flattening or digit tables.
8490
- `m.values` / `m.keys` — not `m.keys.map { k => m[k] }`.
8591
- Bare `[]` / `[:]` — they infer from context (args, `??`, branches, `reduce`); no typed "empty" constants.
86-
- Templates `` `${a} (${i})` `` — not `a + " (" + toString(i) + ")"`.
92+
- Interpolation `"${a} (${i})"` — not `a + " (" + toString(i) + ")"`.
8793
- `!x` — not `x == false`.
8894
- Annotate scalar-typed bindings of literals: `` let re: Regexp! = `\d+` `` (an untyped one is `String!`).
8995
- Parenthesize an `if`/`case` used as an operand: `a + (if (c) { x } else { y })`.

‎.agents/skills/dang-language/reference/graphql.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ Mutation.createUser(input: CreateUserInput(name: "Alice", email: "..."))
9999

100100
### `dang.toml`
101101
```toml
102-
dang = "2.4"
102+
dang = "2.5"
103103

104104
[imports.Dagger]
105105
dagger = "v0.19.0"
@@ -114,7 +114,7 @@ authorization = "Bearer ${API_TOKEN}"
114114
[imports.Remote.headers]
115115
X-Custom = "value"
116116
```
117-
- `dang = "X.Y"` — the Dang version the source is written in; left out, it means the running Dang's version, and moves with each release (`dang init` pins it). Write the current syntax this skill describes. A project declaring an older version is written in that version's syntax (e.g. `for` loops, `try`/`catch`, type patterns without their `!` before 2.4): move it forward with `dang migrate` rather than mixing the two.
117+
- `dang = "X.Y"` — the Dang version the source is written in; left out, it means the running Dang's version, and moves with each release (`dang init` pins it). Write the current syntax this skill describes. A project declaring an older version is written in that version's syntax (e.g. `for` loops, `try`/`catch`, type patterns without their `!` before 2.4, `"..."` that doesn't interpolate and a raw `"""` before 2.5): move it forward with `dang migrate` rather than mixing the two.
118118
- One `[imports.<Name>]` per source; `<Name>` is the qualifier (`MyApi.User`). Must specify at least one of `dagger`, `schema`, `endpoint`, `service` — or `path` (native Dang module, below).
119119
- `schema` — path to a local `.graphqls` SDL file (relative to `dang.toml`); used for type-checking and the LSP.
120120
- `endpoint` — GraphQL HTTP URL for runtime queries; if set without `schema`, the schema is introspected (and cached) from it.

‎.agents/skills/dang-language/reference/stdlib.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,12 @@ Conversion: `toString(value)` (Dang-literal rendering of non-strings) or `value
3737
### `String!` regex methods
3838
Backtick templates auto-coerce to the `Regexp` scalar, so a pattern is usually `` `\d+` ``. Go `regexp/syntax` (RE2); named groups use `(?P<name>...)`.
3939

40-
The coercion is the literal rule (types.md): it happens where a template meets a `Regexp!` slot. A template **bound without a type** is a `String!`, so `` let re = `\d+`; s.containsMatch(re) `` is `cannot use String! as Regexp!` — annotate the binding (`` let re: Regexp! = `\d+` ``) or build it with `Regexp(...)`. `Regexp.escape(s: String!) -> String!` quotes metacharacters so arbitrary text matches literally: `Regexp(Regexp.escape(userInput))`.
40+
The coercion is the literal rule (types.md): it happens where a template meets a `Regexp!` slot. A template **bound without a type** is a `String!`, so `` let re = `\d+`; s.containsMatch(re) `` is `cannot use String! as Regexp!` — annotate the binding (`` let re: Regexp! = `\d+` ``) or build it with `Regexp(...)`. `Regexp.escape(s: String!) -> String!` quotes metacharacters so arbitrary text matches literally: `Regexp(Regexp.escape(userInput))`. Text interpolated into a backtick pattern is spliced in as regex syntax, so escape it too: `` `^a${Regexp.escape(sep)}b$` ``.
4141

4242
- `.containsMatch(pattern: Regexp!) -> Boolean!`
4343
- `.match(pattern: Regexp!) -> Match` — first match, or null
4444
- `.matchAll(pattern: Regexp!) -> [Match!]!`
45-
- `.replaceMatches(pattern: Regexp!, with: String!, count: Int = -1) -> String!` — `$0`/`$1`/`$name`/`${name}` backref expansion
45+
- `.replaceMatches(pattern: Regexp!, with: String!, count: Int = -1) -> String!` — `$0`/`$1`/`$name`/`${name}` backref expansion (a `"..."` replacement would interpolate `${name}`: write it `'${name}'`)
4646
- `.rewriteMatches(pattern: Regexp!, count: Int = -1) { match => String! } -> String!`
4747
- `.splitMatches(pattern: Regexp!, limit: Int = 0) -> [String!]!`
4848

‎.agents/skills/dang-language/reference/syntax.md‎

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ self
3737

3838
## Docstrings
3939

40-
- A **triple-quoted** `"""..."""` string placed immediately before a declaration attaches as documentation.
40+
- A **triple-quoted** `"""..."""` string placed immediately before a declaration attaches as documentation. Docstrings are always verbatim (no escapes, no interpolation, no language tag), and may start on the opening line.
4141
- Works on: modules, types, fields, functions, function parameters, directives, directive args.
4242
- This is the only docstring mechanism — there is no `///`.
4343

@@ -61,11 +61,26 @@ greet(
6161
- `true`, `false`
6262
- `null` — only assignable to nullable type positions.
6363

64-
### Strings (three flavors)
65-
- **Double-quoted** `"hello"` — single-line, escapes: `\a \b \f \n \r \t \v \" \\`, `\ooo` (octal), `\xNN`, `\uNNNN`, `\UNNNNNNNN`; `\/` yields `/`.
66-
- **Triple-quoted** `"""..."""` — multi-line, **raw** (no escape processing), dedents by minimum indent. A leading/trailing newline adjacent to the fences is stripped (`"""\nhello\n"""` == `"hello"`). Canonical docstring form.
67-
- **Backtick templates** `` `hello ${name}!` `` — single-line, `${...}` interpolation. The ONLY escape is `\${` → literal `${`; every other backslash is literal (`` `\d+` `` stays `\d+`). A lone `$` not followed by `{` is literal. Interpolated values auto-stringify like `toString` (non-strings render as Dang literals, nested strings quoted; `null` → `"null"`).
68-
- Multi-line: ```` ```...``` ```` — same minimum-indent dedent; fences grow (4+ backticks) to wrap shorter backtick blocks, and the close fence must match the open fence length. Optional language tag (` ```go ... ``` `) is parsed but does not affect the value.
64+
### Strings
65+
The delimiter decides how the contents are read; tripling it makes the string multi-line, dedented by minimum indent, with an optional language tag:
66+
67+
| | single-line | multi-line |
68+
|---|---|---|
69+
| `"` | escapes + `${...}` | `"""`: escapes + `${...}` |
70+
| `'` | verbatim | `'''`: verbatim |
71+
| `` ` `` | raw + `${...}` | ```` ``` ````: raw + `${...}` |
72+
73+
Rule of thumb: **quotes are for text, backticks are for code; double quotes interpolate, single quotes don't.**
74+
75+
- **Double-quoted** `"hello, ${name}"` — escapes: `\a \b \f \n \r \t \v \" \\ \/ \$`, `\ooo` (octal), `\xNN`, `\uNNNN`, `\UNNNNNNNN`; `\/` yields `/`. Any other backslash is a syntax error (so a regex like `\d+` can't go in `"..."`). Interpolates `${...}`; only `${` starts one, never a bare `$name`. `\$` is a literal `$`, so `\${` is a literal `${`. Interpolated values auto-stringify like `toString` (non-strings render as Dang literals, nested strings quoted; `null` → `"null"`).
76+
- **Single-quoted** `'${HOME}\bin'` — verbatim: no escapes, no interpolation. Can't hold a `'`: use `'''it's'''` (triple single quotes hold quotes, even inline) or `"it's"`. Use it for shell-ish text that must keep `${VAR}`: `.withEnvVariable("PATH", '${GOBIN}:${PATH}', expand: true)`; a shell script goes in `'''sh`.
77+
- **Backtick templates** `` `\d+ ${x}` `` — raw text with `${...}` interpolation, for code (regexes, snippets). The ONLY escape is `\${` → literal `${`; every other backslash is literal (`` `\d+` `` stays `\d+`). A lone `$` not followed by `{` is literal. `#` inside is a literal character.
78+
- Fences grow (4+ backticks) to wrap shorter backtick blocks; the close fence must match the open fence length.
79+
- **Multi-line** (`"""`, `'''`, ```` ``` ````): the newline after the opening delimiter and the one before the closing delimiter are dropped (`"""\nhello\n"""` == `"hello"`), then the text is dedented by its minimum indent. A `"""` string is dedented **before** its escapes are decoded, so `\t` at the start of a line is text, not indentation, and an escape (`\x20`) keeps trailing whitespace. A `"` or `""` before the closing `"""` must be escaped.
80+
- **Opening line**: holds at most a language tag (`"""sql`, `'''sh`, ```` ```go ````), which doesn't affect the value (editors highlight with it). Other text there is a syntax error (`text on the opening line of a multi-line string`) unless the string closes on the same line (`"""inline ${x}"""`). Careful: a lone word there IS a tag, so `"""Summary` + newline drops `Summary` from the value.
81+
- **Docstrings** are triple-quoted but always verbatim (no escapes, no interpolation, no tag), and their text may start on the opening line.
82+
- **Before Dang 2.5** (`dang = "2.4"` or older in dang.toml): `"..."` takes `${` literally and `"""` is raw (no escapes, interpolation or tag). `dang migrate` keeps every value: a `"..."` holding `${` becomes `'...'` where it can (else `\${`), a raw `"""` holding `\` or `${` becomes `'''` (else gets escapes), and text on an opening line moves to the next line.
83+
- REPL output and `toString` of collections quote strings with `${` escaped (`["\${x}"]`), so they read back as the same value.
6984

7085
### Lists
7186
- `[1, 2, 3]`, `["a", "b"]`, `[]` (empty), nested `[[1, 2], [3]]`. A trailing comma is fine, in list literals and call arguments alike (`[1, 2,]`, `f(a, b,)`).
@@ -104,7 +119,8 @@ greet(
104119
### Gotchas
105120
- **Untyped template bindings are `String!`**: `` let re = `\d+` `` is a String, not a `Regexp`; the literal-to-scalar coercion happens only where the literal meets a typed slot, so `s.containsMatch(re)` fails with `cannot use String! as Regexp!`. Annotate: `` let re: Regexp! = `\d+` `` (same for `Path!`, `URL!`, ...).
106121
- **Write `!x`, not `x == false`**, on a `Boolean!`. `!` rejects a nullable `Boolean` (narrow it, or `!(x ?? false)`); `x == false` on one is `false` for null.
107-
- **Prefer templates to `+` chains**: `` `${name} (${i})` `` over `name + " (" + toString(i) + ")"` — interpolation stringifies any value.
122+
- **Prefer interpolation to `+` chains**: `"${name} (${i})"` over `name + " (" + toString(i) + ")"` — interpolation stringifies any value.
123+
- **`${` in a `"..."` string interpolates**: shell variables, GitHub Actions expressions or `replaceMatches`' `${name}` backrefs belong in `'...'`/`'''...'''` (or escape them, `\${HOME}`). An unknown name is a compile error (`"HOME" not found; to write ${HOME} as text, single-quote the string or escape it as \${HOME}`), but a name that happens to be in scope interpolates silently.
108124

109125
### Arithmetic
110126
- `+ - * / %` on `Int`/`Float` (mixed promotes to `Float`), or on a type variable bounded `[a: Numeric]` (see types.md). Float `%` is Go's `math.Mod`: the remainder takes the dividend's sign (`-7.5 % 2 == -1.5`).

‎demos/github/dang.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
dang = "2.4"
1+
dang = "2.5"
22

33
[imports.GitHub]
44
endpoint = "https://api.github.com/graphql"

‎docs/lit/data/strings.md‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,20 @@
1414
## Construction
1515

1616
Write strings as literals (see [#literals]), join them with `+`, and append
17-
with `+=`. A backtick template interpolates `${...}`:
17+
with `+=`. A double-quoted string interpolates `${...}`; a single-quoted one
18+
keeps its text as written:
1819

1920
```dang
2021
let name = "Ada"
2122
let greeting = "hello, " + name
2223
greeting += "!"
2324
24-
[greeting, `${name} wrote the first program`]
25+
[greeting, "${name} wrote the first program", '${name} stays put']
2526
```
2627

28+
Backticks interpolate too, but take every backslash literally, so they're
29+
the form for code, like the regular expressions below.
30+
2731
## Conversion
2832

2933
`toString(value)` passes strings, enum values and custom scalar values
@@ -150,11 +154,15 @@ version.match(`beta`)
150154
```
151155

152156
`replaceMatches` fills in `$1`, `$2`, or `$name` from the match's groups.
153-
`rewriteMatches` computes each replacement with a block:
157+
`${name}` works too, but a double-quoted string would interpolate it, so
158+
write that replacement in single quotes, or as `\${name}` in a replacement
159+
that also interpolates. `rewriteMatches` computes each replacement with a
160+
block:
154161

155162
```dang
156163
[
157164
"2024-01-15".replaceMatches(`(\d+)-(\d+)-(\d+)`, "$3/$2/$1"),
165+
"2024-01-15".replaceMatches(`(?P<year>\d+)-\d+-\d+`, '${year}!'),
158166
"hello world".rewriteMatches(`\w+`) { m => m.string.toUpper },
159167
]
160168
```
@@ -165,6 +173,20 @@ version.match(`beta`)
165173
"a1b22c".splitMatches(`\d+`)
166174
```
167175

176+
A backtick pattern can interpolate, and its backslashes still need no
177+
doubling. Interpolated text is spliced in as regex syntax, though, so a `.` in
178+
it matches any character. Wrap text that should match literally in
179+
`Regexp.escape`:
180+
181+
```dang
182+
let sep = "."
183+
["a.b", "a-b"].map { s => s.containsMatch(`^a${sep}b$`) }
184+
```
185+
186+
```dang
187+
["a.b", "a-b"].map { s => s.containsMatch(`^a${Regexp.escape(sep)}b$`) }
188+
```
189+
168190
Only a literal converts to a `Regexp!` on its own (see [#enums-scalars]). A
169191
pattern held in a variable needs a cast:
170192

‎docs/lit/graphql/modules.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ mymod/
4646
a `.git` boundary).
4747

4848
```toml
49-
dang = "2.4"
49+
dang = "2.5"
5050

5151
[imports.Dagger]
5252
dagger = "v0.19.0"

‎docs/lit/index.md‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -357,15 +357,22 @@ type Circle implements Shape {
357357
}{
358358
\dang-feature{Multi-line strings}{{{
359359
## triple-quoted strings trim leading whitespace
360+
## and, like "...", interpolate ${...}
361+
let who = "there"
360362
print("""
361-
hey there
363+
hey ${who}
362364
im indented
363365
me too
364366
""")
365367
print("---")
366368

369+
## single quotes are verbatim: no escapes, no ${...}
370+
print('''sh
371+
echo "${HOME}" | tr -d '\n'
372+
''')
373+
print("---")
367374

368-
## backtick-fenced strings support interpolation
375+
## backtick fences are for code: raw text, with ${...}
369376
let daggerBin = "dagger-dev"
370377
let daggerVersion = [1, 0, 0]
371378
print(```
@@ -374,7 +381,7 @@ ${daggerVersion.join(".")}
374381
```)
375382
print("---")
376383
377-
# backtick-fences support language tags, like Markdown
384+
# all of them support language tags, like Markdown
378385
# why? because it looks nice.
379386
print(```ruby
380387
class << self

‎docs/lit/language/fields-functions.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,8 @@ clock.now
134134

135135
### Docstrings
136136

137-
A `"""..."""` literal right before a declaration documents it. This works on
137+
A `"""..."""` literal right before a declaration documents it. A docstring is
138+
always verbatim, with no escapes or interpolation. This works on
138139
modules, types, fields, functions, function parameters, directives, and
139140
directive arguments:
140141

0 commit comments

Comments
 (0)