Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce 'f' sigils for string interpolation #9512

Open
wants to merge 7 commits into
base: master
Choose a base branch
from

Conversation

williamthome
Copy link
Contributor

@williamthome williamthome commented Feb 28, 2025

This PR introduces ~f sigils for ergonomic string interpolation, enabling cleaner binary/iolist generation while reducing boilerplate and errors.

Key Features

  • ~f: Returns a flattened binary (ideal for in-memory processing).
  • fs: Returns an iolist (ideal for I/O operations).

Note

Currently, Erlang has those sigils: s, S, b, and B. Following up on all of them, I've also implemented:

  • fb, fB, bf or Bf: is the same as f.
  • fS, sf or Sf: is the same as fs.

Syntax

  • Erlang expressions are enclosed in {} within the string.
  • Nesting interpolated strings is allowed.
  • Escape { with a backslash \ to treat it as a literal.

Minimal Example

~f"text {ErlangExpr}"  % Binary
~fs"text {ErlangExpr}" % IOList

Why This Is a Good Thing

Developer Experience

  • Eliminates manual <<...>>/++ juggling.
  • Mirrors interpolation in modern languages (Python/Ruby/Elixir).

Flexibility

  • Choose between binaries (~f) or iolists (~fs) based on use case.

Backward-Compatible

  • No breaking changes; opt-in adoption.

Examples

  1. HTML Templating (~f for Binaries)

    render(User) ->  
        ~f"""  
        <div>  
          <h1>{User#user.name}</h1>  
          <p>ID: {User#user.id}</p>  
        </div>  
        """.  
    % Returns: <<"<div>\n  <h1>Alice</h1>\n  <p>ID: 123</p>\n</div>">>  
  2. Logging (~fs for IOList Efficiency)

    log_error(Req, Error) ->  
        logger:error(~fs"Request {Req#request.id} failed: {Error}").  
    % Returns: [<<"Request ">>, <<"req_123">>, <<" failed: ">>, <<"timeout">>]  

Edge Cases

  • Escaping: Use \{ for literal {.

    ~f"Escaped: \{NotInterpolated}" % <<"Escaped: {NotInterpolated}">>
  • Nesting: Combine ~f and ~fs freely.

Discussion

No major drawbacks come to mind with this approach, but feedback is welcome.
It would be fantastic to include this feature in OTP-28!
Please see the Erlang Forums thread for more details and discussion.

Related Links

Copy link
Contributor

github-actions bot commented Feb 28, 2025

CT Test Results

    2 files     97 suites   1h 8m 39s ⏱️
2 196 tests 2 149 ✅ 47 💤 0 ❌
2 563 runs  2 514 ✅ 49 💤 0 ❌

Results for commit e1fabd7.

♻️ This comment has been updated with latest results.

To speed up review, make sure that you have read Contributing to Erlang/OTP and that all checks pass.

See the TESTING and DEVELOPMENT HowTo guides for details about how to run test locally.

Artifacts

// Erlang/OTP Github Action Bot

@williamthome williamthome force-pushed the feat/f-sigil branch 6 times, most recently from c625f3c to 1eb9678 Compare March 1, 2025 16:26
This commit introduces a strict way of generating payloads using the `f`
sigils. It constructs a binary and only accepts binaries as dynamic
values. For example:

```erlang
1> User = #{name => ~"Bob", age => 27}.
2> ~f"""
   Name: {maps:get(name, User)}
   Age: {integer_to_binary(maps:get(age, User))}
   """.
<<"Name: Bob\nAgen: 27">>
```
This commit adds more flexibility to the `f` sigil by introducing more
sigil prefixes that output strings. For example:

```erlang
1> User = #{name => ~"Bob", age => 27}.
2> ~fs"""
   Name: {maps:get(name, User)}
   Age: {integer_to_binary(maps:get(age, User))}
   """.
["Name: ",<<"Bob">>,"\nAge: ",<<"27">>]
```

The `f` sigil will not raise an exception for string modifiers if the
dynamic value is not a string or a binary. For example:

```erlang
1> User = #{name => 'Bob', age => 27}.
2> ~fs"""
   Name: {maps:get(name, User)}
   Age: {maps:get(age, User)}
   """.
["Name: ",'Bob',"\nAge: ",27]
```
This commit changes texts to be UTF-8 binaries instead of lists. For example:

```erlang
1> User = #{name => ~"Bob", age => 27}.
2> ~fs"""
   Name: {maps:get(name, User)}
   Age: {integer_to_binary(maps:get(age, User))}
   """.
[<<"Name: ">>,<<"Bob">>,<<"\nAge: ">>,<<"27">>]
```
@williamthome williamthome changed the title Introduce 'f' sigil for string interpolation Introduce 'f' sigils for string interpolation Mar 2, 2025
It's not easy to determine the exact column of the forms. This commit
changes to only store the line as the location to avoid confusion and
misleadings.

This commit also removes the unneeded text in the strings anno.
@jhogberg jhogberg added the team:LG Assigned to OTP language group label Mar 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
team:LG Assigned to OTP language group
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants