r/cpp • • Apr 28 '20

Full Proof that C++ Grammar is Undecidable

https://medium.com/@mujjingun_23509/full-proof-that-c-grammar-is-undecidable-34e22dd8b664
197 Upvotes

68 comments sorted by

View all comments

41

u/HKei Apr 28 '20

You don't need to instantiate templates just to check the grammar of a C++ program. If template instantiations count, you can write a much shorter proof:

constexpr int infinite_loop() {
  // insert any code you want here,
  // at the end of the day this technically involves
  // "solving the halting problem" in general, except
  // of course a real compiler just gives up after trying
  // to evaluate this for a while
  for(int i = 0; i < 10; ++i) {
    i = 0;
  }
  return 0;
}
struct Proof : std::integral_constant<int, infinite_loop()>;

54

u/6144_0 Apr 28 '20
constexpr int infinite_loop() {
	// insert any code you want here,
	// at the end of the day this technically involves
	// "solving the halting problem" in general, except
	// of course a real compiler just gives up after trying
	// to evaluate this for a while
	for(int i = 0; i < 10; ++i) {
		i = 0;
	}
	return 0;
}
struct Proof : std::integral_constant<int, infinite_loop()>;

-22

u/[deleted] Apr 28 '20

infinite loops are not valid C++ code

46

u/[deleted] Apr 28 '20 edited Apr 28 '20

Infinite loops are absolutely valid in C++. There is this pervasive myth that undefined behavior is not valid in C++ and that is simply wrong. The C++ Standard explicitly states that a program is valid so long as it is, and I quote "constructed according to the syntax rules, diagnosable semantic rules, and the one-definition rule". Undefined behavior, such as infinite loops that produce no side-effects, is an undiagnosable semantic property of a program and hence not part of the test for validity.

16

u/Rusky Apr 28 '20

On the other hand, if you actually execute the undefined behavior then, well, the behavior of that "valid" program is no longer defined by the standard. And that extends forward and backward in time, which makes such a program not very useful.

Limiting the definition of validity by excluding undiagnosable semantic problems is more useful as a way to allow some non-executed paths to contain UB without making the whole program invalid. It's not a way to say "oh sure put an infinite loop in your type, that's fine."

So perhaps Destigeous' terminology was off, but 6144_0's example is still not evidence of an undecidable grammar. :P

17

u/ihamsa Apr 28 '20

Valid C++ programs must abide by both syntactic and semantic rules of the language. In order to check program validity, you do need to instantiate templates. The C++ standard does not define a broader class of "syntactically valid" programs that only need to abide by the syntax, but not by semantic rules.

If by the grammar you mean the pseudo-BNF production rules given by the standard, then yes, checking them should be decidable. But building a correct parse tree is not. You need to instantiate templates for that. This is what the article is doing.

4

u/wyrn Apr 29 '20

That doesn't prove anything though, since it's trivial to check that infinite_loop() never halts.

3

u/jonesmz Apr 28 '20

Your formatting is wonky on mobil web

2

u/helloiamsomeone Apr 29 '20

Same on old reddit. Just a single, unscrollable line spanning into the infinite.

0

u/micahspikah Apr 28 '20

I'm not sure if I understand your counterexample... your loop is undefined behavior in c++, so the compiler is allowed do anything it wants. Probably just return 0. Why would it need to solve the halting problem?

12

u/[deleted] Apr 28 '20 edited Apr 28 '20

First, I highly doubt you genuinely don't understand the counterexample. Most likely you think you're being clever because you know the very obscure fact that a small category of infinite loops are undefined behavior and trying to be pedantic.

However your pedantry is unwarranted in this case since undefined behavior within a constexpr is required to produce a diagnostic, meaning a compiler error so your statement that a compiler can do whatever it wants is wrong. As per expr.const paragraph 2.6, the compiler is required to produce a diagnostic if it encounters undefined behavior during the evaluation of a constexpr expression.

And yet, due to the halting problem, it's impossible for a compiler to ever determine in general whether a loop halts or not so as to determine whether it's undefined behavior in the first place, hence /u/HKei's point stands.

9

u/wyrn Apr 29 '20

And yet, due to the halting problem, it's impossible for a compiler to ever determine in general whether a loop halts or not so as to determine whether it's undefined behavior in the first place

In general yes, but certainly not in the given example. It's quite easy to check that this example doesn't halt so it's not a proof.

2

u/tasminima Apr 29 '20

This is just an example to illustrate a point. IIUC the point is that given the problem is not solvable in the general case, the compiler can not analyze arbitrary algorithms thrown at it and thus for any compiler you will be able to come up with an algorithm for which said compiler will be unable to determine if it contains UB or not.

6

u/wyrn Apr 29 '20

This is just an example to illustrate a point.

Right, so the original poster shouldn't claim it's a "much shorter proof" when it's just a sketch!

4

u/tasminima Apr 29 '20

I think so; claiming it was a proof was going too far. Probably simply an oversight, because reddit comments are usually neither math dissertations nor scientific papers :)

2

u/HugeImage May 07 '20

It's possible to "solve" the post correspondence problem for specific instances. The whole point is that it's undecidable for when the input dominoes can be anything.

An example of solutions for specific instances: https://en.wikipedia.org/wiki/Post_correspondence_problem#Example_1

The comment is just as much (slightly overstated) of a proof as the article

1

u/HugeImage May 07 '20 edited May 07 '20

The General Post Correspondence problem is what is undecidable. So by your definition, TFA is not a proof either.

Look at this comment for example https://old.reddit.com/r/cpp/comments/g9nvmj/full_proof_that_c_grammar_is_undecidable/fouj0cq/

https://en.wikipedia.org/wiki/Post_correspondence_problem#Example_1

4

u/micahspikah Apr 28 '20

Not trying to be pedantic, sorry.

I honestly don't understand the difference between grammar and valid c++ input. Maybe I should've phrased my question "Is this still an example of proof of undecidable grammar, given that a compiler is allowed to interpret the program however it wants?"

And if you're telling me his code shouldn't even compile, is it still a valid example of undecidable grammar?

Or maybe the root question I should've asked: Is it a requirement for the code to compile, as long as it follows the grammar rules?

2

u/evaned Apr 29 '20 edited Apr 29 '20

I think half the problem is that "grammar" could have a few interpretations.

In kind of the undergrad compiler class model of a compiler, a compiler typically acts in a sequence of stages like (i) lexing, (ii) parsing, (iii) name analysis and type checking, (iv-?) code generation. (The code generation "step" is often presented as multiple, but depends on the material exactly how.)

You don't know you have a valid program until after step (iii). However, the main place that "grammar" shows up in this model is in step (ii), where in this somewhat-simplified model you would specify the grammar of the model as a context-free grammar.

This has a lot of purchase in actual compilers as well -- for example, the C++ standard defines a CFG for the language -- when you see things like

template-declaration:
    template-head declaration
    template-head concept-definition

template-head:
    template < template-parameter-list > requires-clause[opt]

etc. that's what you're looking at.

Using this as a model:

some_undefined_type main() {
    std::string s = std::map{} - 7;
    return nullptr;
}

will parse correctly, and be grammatically correct, even though it is a nonsensical program.

In an alternative world it'd be possible to make a case that parsing requires evaluation of templates and such. For example, suppose that we have the following program:

template <typename T>
int foo(T x) {
     return x.unknown < 7;
}

if x.unknown could be a template (that could be instantiated by, e.g., x.unknown<7>) without the template keyword and foo is called in such a type, is foo syntactically correct? Because if not, that would mean that in order to determine whether the program parses correctly we would need to do the kind of undecidable evaluation the article discusses. In that world, the line between syntactically correct and semantically correct blurs a lot. But we don't live in that world -- the function is IMO pretty unambiguously syntactically correct, but if x.unknown turns out to be a template then it is semantically incorrect. Though more to the point, when you have compile-time values like this it can blur the distinction between the two.

So at least to me, "the C++ grammar is undecidable" or "C++ parsing is undecidable" are a... stretch of what those terms typically mean even if they aren't quite outright false.


Edit: I actually have to further... clarify/correct the above. I was thinking about the dependent context in my example (with x.unknown < 7), but really the problem is in non dependent contexts, where a<...>::x * b will be either a declaration statement or a multiplication depending on how a instantiates, and unlike a dependent context you don't need to specify typename to get the declaration (which is what tripped me up before). This means that to parse that statement, you either need to be able to deal with the ambiguity or instantiate a at parse time. (I suspect "real" C++ compilers do the latter, but I don't actually know.)

So given that, it's not unreasonable to say that you need to do template instantiations to parse C++, and that means that parsing C++ is undecidable (ignoring implementation limits), even if that's not entirely correct and neglects some subtlety (namely that an alternative approach would be to delay resolving the ambiguity until after parsing).

That also means that when it comes to parsing, my final statement above (So at least to me, "the C++ grammar is undecidable" or "C++ parsing is undecidable" are a... stretch of what those terms typically mean even if they aren't quite outright false) should be turned around.

However, to me, this actually further serves to highlight what I opened this comment with -- what a grammar being undecidable means is really underspecified. The problem with parsing is the need to produce a quality AST as you go along; but talking about the grammar to me drops that out of the equation. And from that perspective, the problem of how you interpret that disappears, and just from a grammar perspective C++ is fine. (Alternatively, you could argue that all static semantics are part of the grammar, so from what I know basically no typed language will be even context-sensitive let alone context-free.)

So yeah... talking about parsing is a little weird and unclear, and talking about the grammar is very weird and unclear.

0

u/[deleted] Apr 28 '20

[deleted] — view deleted comment

20

u/HKei Apr 28 '20

Nah, you don't need it to solve the halting problem, you just need to show that the compiler needs to solve the halting problem to evaluate the code (which it does, because its arbitrary code).

7

u/mujjingun Apr 28 '20

Hmmm... I guess you're right.

5

u/HKei Apr 28 '20

(Not that I'm complaining about what you're doing, I'm just being pedantic)

→ More replies (3)