feat: implement string interpolation
Add support for string interpolation with {expr} syntax:
"Hello, {name}!" becomes "Hello, " + toString(name) + "!"
Lexer changes:
- Add StringPart enum (Literal/Expr) and InterpolatedString token
- Detect {expr} in strings and capture expression text
- Support escaped braces with \{ and \}
Parser changes:
- Add desugar_interpolated_string() to convert to concatenation
- Automatically wrap expressions in toString() calls
Interpreter changes:
- Fix toString() to not add quotes around strings
Tests added:
- 4 lexer tests for interpolation tokenization
- 4 integration tests for full interpolation pipeline
Add examples/interpolation.lux demonstrating:
- Variable interpolation
- Number interpolation (auto toString)
- Expression interpolation ({a + b})
- Escaped braces
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
39
examples/interpolation.lux
Normal file
39
examples/interpolation.lux
Normal file
@@ -0,0 +1,39 @@
|
||||
// Demonstrating string interpolation in Lux
|
||||
//
|
||||
// Expected output:
|
||||
// Hello, Alice!
|
||||
// The answer is 42
|
||||
// 2 + 3 = 5
|
||||
// Nested: Hello, Bob! You are 25 years old.
|
||||
// Escaped braces: {literal} and more {text}
|
||||
|
||||
// Basic interpolation
|
||||
let name = "Alice"
|
||||
let greeting = "Hello, {name}!"
|
||||
|
||||
// Number interpolation (auto-converts with toString)
|
||||
let answer = 42
|
||||
let message = "The answer is {answer}"
|
||||
|
||||
// Expression interpolation
|
||||
let x = 2
|
||||
let y = 3
|
||||
let math = "{x} + {y} = {x + y}"
|
||||
|
||||
// Multiple interpolations
|
||||
let person = "Bob"
|
||||
let age = 25
|
||||
let intro = "Nested: Hello, {person}! You are {age} years old."
|
||||
|
||||
// Escaped braces (use \{ and \})
|
||||
let escaped = "Escaped braces: \{literal\} and more \{text\}"
|
||||
|
||||
fn printResults(): Unit with {Console} = {
|
||||
Console.print(greeting)
|
||||
Console.print(message)
|
||||
Console.print(math)
|
||||
Console.print(intro)
|
||||
Console.print(escaped)
|
||||
}
|
||||
|
||||
let output = run printResults() with {}
|
||||
Reference in New Issue
Block a user