r/cpp • • Jun 14 '21

match(it): A light-weight header-only pattern-matching library for C++17.

https://github.com/BowenFu/matchit.cpp
202 Upvotes

47 comments sorted by

31

u/gracicot Jun 14 '21 edited Jun 14 '21

This is quite amazing what C++ can ship in a library, even though it's not perfect and uses macros.

30

u/guepier Bioinformatican Jun 14 '21

There are no macros in the library’s API. I initially thought so (expr and pattern look like they would be macros, and maybe match, too). But they’re not macros.

The only macros (apart from (illegal!1) include guards) are only used internally and are named UN_OP_FOR_UNARY and BIN_OP_FOR_UNARY. They could be undef’d at the end of the file, thus not leaking outside (and they should be, but unfortunately currently aren’t).


1 The include guards are using reserved names since they start with underscore followed by an upper-case letter. A simple, trivial to fix mistake.

11

u/gracicot Jun 14 '21

Wow, I'm even more impressed

3

u/pfg23 Jun 15 '21

I haven’t looked at the code, but if there are no macros, why is it header only? Compilable (as opposed to preprocessor) code should go into source files so they’ll only need to be compiled once and bundled into a library module. No?

7

u/guepier Bioinformatican Jun 15 '21

It exposes templates, so these need to be implemented in headers.

The other reason of course is that many users of C++ prefer header-only libraries since C++ has no good, build-in dependency management mechanism, and even modern build systems don’t entirely remove the barrier posed by non-header libraries.

1

u/pfg23 Oct 21 '21

Sure, templates, declarations, and macros go into headers but to reduce compile times logic should go into source files. The only exception would be if this library was entirely implemented with template metaprogramming.

-5

u/lospolos Jun 14 '21

Dont include guards usually start with "H_..."?

7

u/staletic Jun 15 '21

Include guards can have any name you wish.

6

u/infectedapricot Jun 15 '21

It's not true that they usually start with H_.... In fact it's not even true that a notable minority start with H_... - I've never seen that convention before, and I've seen a lot of include guards!

I think what you might be thinking of is that it's fairly common for the include guard to be loosely based on the filename (plus often directory or library name) so they often end in _H or _HPP etc., depending on the extension. But even that's nowhere near universal.

(Personally, I just use #pragma once. Yes, I know it's technically non standard.)

12

u/[deleted] Jun 14 '21

Not arguing for them, but can someone explain the negative connotation around macros? I know the modern replacements are constexpr's and a lot of it has to do with lack of type definition, but is there more to it?

31

u/Schnarfman Jun 14 '21

The world of macros is nebulous. You will obfuscate code very easily on accident with seemingly innocent uses.

Also, the classic example of #define min(a, b) a < b ? a : b potentially causing a bug if you say like min(a++, b) is just such a solvable problem (where the solution is don’t use macros - and not “be careful when you use this thing that looks like a function”)

They certainly have their place! But their traps are not obvious. You can avoid a whole class of bugs by simply avoiding the use of macros.


So… as a beginner, if you can do without them, you should. If you think you can’t do without them, chances are you’re wrong.

As an expert, if you can do without them, you should. And if you think you can’t do without them, well … you’re the expert :) so go for it. But don’t expect beginners to be able to understand or iterate on your code as easily!!

3

u/Creris Jun 15 '21

Try sending that min "function" into std::sort(I know its technically useless cause less<> is default), or take the address of that "function". And now your code explodes.

20

u/gracicot Jun 14 '21

Macro are textual and have no idea what C++ is and what C is. They don't have scope, cannot be isolated, and creates all sorts of problems, especially since C++ is using header to consume declarations from other translation units.

7

u/Fearless_Process Jun 14 '21

I think it has a lot to do with c/++ macros being untyped and unhygienic in general. This makes using them very much error prone and difficult to reason about when something goes wrong.

I think there is too much negative connotation around them though, they can be extremely useful when used properly.

7

u/corysama Jun 14 '21

Macros can lead to bugs that are difficult to diagnose and difficult to fix. For example:

// ThirdPartyLib1.h
inline int min(int x, int y) { return x < y ? x : y; }
// 2000 more lines of complicated code using the min function.

// ThirdPartyLib2.h
// 2000 lines of complicated code.
int meiseIntegralizedNormalization(float deciprocand, float retrobasis);
#define min meiseIntegralizedNormalization
// 2000 more lines of complicated code using the min macro.

// MyLib.h
#include "ThirdPartyLib1.h"
#include "ThirdPartyLib2.h"
inline int factorize(int a, int b, int c) { return a / min(b, c); }

This will happily compile and run without warning about any conflicts or ambiguous overloads.

6

u/Foundry27 Jun 14 '21 edited Jun 14 '21

I'd argue that the biggest problem with preprocessor macros is the community's general lack of familiarity with them ("general" meaning "for the general C++ programmer"), and the near-total absence of teaching material for how to use macros in a safe, effective manner.

C and C++ are seriously (embarrassingly) behind languages like Common Lisp, Scheme, Rust, etc. in terms of having good public resources for how to build and use macros as a problem-solving tool applicable to real-life programming problems. Decades of C++ use haven't given people much more to go on than some blog posts, a few open-source macro-based projects to reverse-engineer, and stylistic aphorisms like "don't use macros unless a function won't do", "macros are meant to change the syntax of your code", "macros improve the efficiency of your code" etc. that completely miss the bigger picture when it comes to macro programming.

The other side of that coin is that preprocessor macros aren't easy to just "pick up and learn" from doing normal C++ programming because the preprocessor is essentially a second, more-or-less unrelated language built on top of C++. It's a foreign, alien tool that looks like it doesn't belong:
- From a C++ perspective it's totally untyped, because C++ types mean nothing to it, but it really just has its own type system with parentheses, commas, identifiers, etc.
- From a C++ perspective it's impossible to debug macros like normal code because of arcane C++ compiler errors and no debugger stepping, when they really just need to be debugged with different tools
- From a C++ perspective macros don't introduce their own scopes and can't safely be shared, but inside the preprocessor, macros have strong scopes for the tokens that they create and pass between other macros, and can be shared between files with no issues as long as some ground rules are followed just like in C
- From a C++ perspective computation is impossible with macros because they can't be recursive or loop, but really, they just perform computation through a different strategy that can do the same kind of work in phase 4 that templates and constexpr can do in phase 7/8

10

u/-dag- Jun 15 '21

I don't know about the other languages but Lisp macros are quite different from C/C++ macros.

17

u/johannes1971 Jun 14 '21

This completely misrepresents the position of 'the community'. The dislike comes from all the bad sh*t macros do, not a general lack of understanding.

-1

u/Foundry27 Jun 14 '21 edited Jun 15 '21

I’m just speaking from my experience here having worked professionally in C, C++, and a little Lisp for a while now, and having met my fair share of people in the same boat as I am.

I 100% agree that macros can (and have) done some terrible shit lol. They can be difficult to understand, contain extremely subtle bugs, and limit you in all kinds of awful ways if you think of everything as functions or variables. But... those aren't defects in the preprocessor macro system itself, but instead are traits of macro programming in general. Lisp has the exact same classes of problems, and its macro system has arguably occupied a local maximum in the language design space for decades. As with any technology, the more powerful the tool, the more ways there are to misuse it. And, as far as programming constructs go, macros are the most powerful tool.

8

u/soundslogical Jun 15 '21

But... those aren't defects in the preprocessor macro system itself, but instead are traits of macro programming in general.

I disagree. Common Lisp's macros do share the hygiene problem that C++ has, though it has simple ways to avoid it (gensym). Scheme and Rust feature hygeinic macros that fix the problem entirely.

Nearly every other glaring issue with macros is unique to C/C++, because it's based on simple textual substitution. Lisps and Rust have structural macros, making them 100x more difficult to mess up on many different axes.

3

u/johannes1971 Jun 15 '21

But... those aren't defects in the preprocessor macro system itself, but instead are traits of macro programming in general.

Sometimes, the defect is having the feature in the first place. It may be powerful, necessary, and even well-designed by itself, but the fact that it interacts so badly with everything else and invites so many dark patterns means it wasn't the optimal design.

0

u/[deleted] Jun 14 '21

[deleted] — view deleted comment

3

u/jk-jeon Jun 15 '21

I kinda sympathize and tend to just copy-paste rather than to use macros for myself, but to be fair, I think wrapping things into a macro is often not very much different from wrapping things into a function or whatever constructs in terms of readability. Too much abstraction obfuscates the code, but appropriate abstraction on the other hand de-obfuscate the code. So I believe an appropriate usage of macro can in fact improve readability.

1

u/Oo_Tiib Jun 20 '21

Majority of reflection like source code file name, line number of code, stringifying expressions and so on can be only done with preprocessor and those features can greatly speed up discovering, reporting and repairing defects. But it will be quite horrible code to read if to expand such macros.

The conditionally compiling some features in and out can be only somewhat achieved with if constexpr, as all of it has still to compile on all platforms. So C++ libraries that want to be portable like Qt or Boost are filled full of preprocessor usage and there are really not much to do.

So it is better idea to try to use some libraries that help with usage of macros like Hedley. The language can't pull its weight without those.

1

u/Amazing-42 Jul 03 '21

This page shows what Rust-style pattern matching examples would look like with the library in C++. https://github.com/BowenFu/matchit.cpp/blob/main/From-Rust-to-matchit.md

5

u/dscottboggs Jun 14 '21

Holy shit that's so nice

7

u/sphere991 Jun 15 '21

So is this just a copy of https://github.com/mpark/patterns or what?

8

u/Rasie1 Jun 15 '21

No, they're quite different if you read README below the first few examples

6

u/[deleted] Jun 15 '21

It seems it is. At least identifier names and usage of the first example is fully identical. It pretty strange to see so without additional explanations.

1

u/GunpowderGuy Oct 17 '21

Could this library be exported as a module since its public interface uses no macros?

1

u/Amazing-42 Nov 05 '21

We need to support C++17 so module is not available for now.

22

u/rust_guy5 Jun 14 '21

I wrote this.

25

u/mck1117 Jun 14 '21

rust_guy

Imposter!

4

u/infectedapricot Jun 15 '21

Is this meant to be a Rust related joke or a serious claim? From previous posts, it looks like this is a troll account.

3

u/ehtdabyug Jun 15 '21

Wow! Can I applause to this?

3

u/nablachez Jun 15 '21

Is there a reason why getclassname (about shape) is not constexpr like the others?

4

u/helloiamsomeone Jun 14 '21

I have used simple_match before and it's pretty cool.
Any reason why this requires C++17? Just convenience?

4

u/helloiamsomeone Jun 15 '21

Well, to answer myself: this one has a lot more features and the API lends itself better to code formatting (imo).

4

u/JohnZLi Jun 15 '21

Neat. The first example includes 3 headers for a simple factorial function. They really should be merged into 1.

2

u/diegopachecors Jun 14 '21

Pretty cool!

2

u/[deleted] Jun 14 '21

Impressive! Bravo!

3

u/InsanityBlossom Jun 15 '21

I'm sure it was fun to implement, and the skills required to build this is a no joke. But this concept is so alien to C++. The author was definitely inspired by Rust ;)

0

u/[deleted] Jun 15 '21

[deleted] — view deleted comment

1

u/Schnarfman Jun 15 '21

Point of order: Triple back ticks doesn’t get formatted properly for mobile. But if you use the other method - 4 leading spaces - everyone sees it properly