GN: map strings to integers?

14 views
Skip to first unread message

Charles Nicholson

unread,
Feb 3, 2022, 3:28:29 PM2/3/22
to gn-dev
Hi GN people!

In my project I'm building support for a number of different hardware versions of our firmware.

Each hardware version has a primary name, and that name maps to a unique integer (starting at 0, ascending). The integer is used both in the code as a -D definition, but then also as a build-time argument to other vendor-provided tools.

I'd love something like a map that I could simply import from a gni file into the various BUILD files that use it, but GN doesn't appear to have this. I could have the same cascading if/else logic everywhere, but that's not great when new hardware comes along.

I could do an exec_script into python and keep the dict in a central location, but exec_script isn't a feature we're supposed to sprint towards. So, before I do that, how do other people manage this? Are there any good patterns here?

Thanks in advance,
Charles

Roland McGrath

unread,
Feb 3, 2022, 3:46:26 PM2/3/22
to Charles Nicholson, gn-dev
If you're happy to restrict the keys to strings of identifier characters ([A-Za-z0-9_]) that don't start with underscore, then you can use GN scopes for this.

```
  foo_map = {
    a = 1
    b = 2
   }
  foo_keys = [ "a", "b" ]

  foreach(key, foo_keys) {
    value = foo_map[key]
    defines += [ "${key}=${value}" ]
  }
```

There is no way to enumerate the scope, so you have to use a separate list like `foo_keys` above.

You can do fancier things by foregoing the dictionary-style lookup and just iterating over lists:

```
   foo_things = [
     { name = "a" value = 1 },
     { name = "b" value = 2 },
  ]

  foreach(thing, foo_things) {
    defines += [ "${thing.name}=${thing.value}" ]
  }
```

Aaron Wood

unread,
Feb 3, 2022, 4:10:32 PM2/3/22
to Roland McGrath, Charles Nicholson, gn-dev
When I've wanted lookup-tables or other keyed maps, I've done the latter route that Roland suggests.

(but I also didn't know that you could index a scope with a string key like that...)

--
To unsubscribe from this group and stop receiving emails from it, send an email to gn-dev+un...@chromium.org.

Charles Nicholson

unread,
Feb 3, 2022, 4:20:18 PM2/3/22
to Aaron Wood, Roland McGrath, gn-dev
Ah, thanks Roland, that's very helpful and exactly what I think will help me here. I'll explore putting such a scope variable in a .gni file, and importing it where I need it.

Best,
Charles
Reply all
Reply to author
Forward
0 new messages