Skip to content

String interpolation (eg fmt) raises undeclared identifier but identifier is in scope #9544

Closed
@joshgoebel

Description

@joshgoebel

I have a macro generating code:

  result.add quote do:
    proc find*(t: type[`model`], id: string | int) : `model` =
      echo tableName # no error here
      ...
      var query = sql(&"select * from {tableName} where {pk}  = ?") # Error: undeclared identifier: 'tableName'

    proc insert*(p: var `model`) : int64 =
      echo "TABLENAME ",&"{tableName}" # no error here
      var query = sql(&"insert into {tableName} {full_insert} values {full_values}") # no error here

tableName is a const at the top-level that has been generated elsewhere.

What happens

What happens is the interpolation in find fails with Error: undeclared identifier: 'tableName'. The interpolation in insert works just fine.

What I expect to happen

What I expect to happen is that the value of tableName is inserted into the string for find (just as it is successfully is for insert.

Possible Solution

If you first assign the constant to anther local variable (jumping thru all the ident quoting hoops) and then try to interpolate it it will work.

IE:

  var tn = ident"tn"
  var idtableName = ident"tableName"
  result.add quote do:
    proc find*(t: type[`model`], id: string | int) : `model` =
      var `tn` = `idtableName`
      var query = sql(&&"select * from {tn} where {pk}  = ?") # Error: undeclared identifier: 'tableName'

This makes working with interpolation in macros crazy cumbersome though. I'm hoping I'm mising something.

Additional Information

I found and tried -d:debugFmtDsl but it didn't reveal anything I thought would be useful.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions