[SERVER-63281] Add support for case ranges via macro Created: 03/Feb/22  Updated: 06/Dec/22  Resolved: 14/Feb/22

Status: Closed
Project: Core Server
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: New Feature Priority: Major - P3
Reporter: Ian Boros Assignee: Backlog - Service Architecture
Resolution: Won't Fix Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Assigned Teams:
Service Arch
Participants:

 Description   

As a GCC extension, you can write 'case ranges' in switch statements, e.g.

 

switch (x) {
case 1 ... 5:
   // etc
} 

It would be nice if we had a macro which allows us to use this extension. When the compiler supports the extension, it can use the syntax above, and when the compiler does not support it, it could expand to a series of 'case' labels.

 

switch (x) {
MONGO_CASE_RANGE(kSomethingMin, kSomethingMax):
   // etc
} 

 



 Comments   
Comment by Billy Donahue [ 14/Feb/22 ]

Codegen for if/else should be as good as switch/case.
The macro idea may be unimplementable.

Comment by Billy Donahue [ 14/Feb/22 ]

I don't think we can provide this.

As far as I can tell, there isn't a macro that can expand into a range iteration between 2 symbolic constants like that. I don't think there's even a macro to expand between numeric literals, without going to rather extreme preprocessor _VA_ARGS_ dispatching techniques that we shouldn't be getting into for this.

The optimizer should be able to generate efficient dispatch among simple disjoint integral ranges if they're written as if/else statements among constexpr alternatives.
So an

if (x <= kSomethingMin && x < kSomethingMax) {
    etc
} else ...

should be competitive with a switch under optimization.

This seems to check out. Example: https://gcc.godbolt.org/z/KqPhqnz5G

Generated at Thu Feb 08 05:57:22 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.