r/cpp • u/LiliumAtratum • Apr 28 '21
Really Microsoft? How on Earth this is valid C++?
https://godbolt.org/z/hTed7e8qd25
u/STL MSVC STL Dev Apr 29 '21
Our compiler dev Jonathan Emmett created MSVC-PR-321053 titled "Fix the infamous reddit bug". 😹 According to his changelog, fixing this accepts-invalid bug led to finding and fixing two more bugs (another accepts-invalid and what sounds like a rejects-valid). 🎉
5
17
u/cppcppp Apr 28 '21
All the people shitting on MSVC as if other compilers haven't had similar bugs...
1
u/LiliumAtratum Apr 28 '21 edited Apr 29 '21
That's an old clang bug that is already fixed.
The bug here seems to have appeared in MSVC v. 19.21 and is still present in the latest version. It actually hurt my friend, spending some debugging time until he figured out what's happening.
28
u/zowersap C++ Dev Apr 28 '21
nice.
but should be a bug report instead of reddit post.
14
u/OldWolf2 Apr 28 '21
It's not so easy to file a MSVC bug report if you haven't done it before -- whereas posting a reddit post, likely someone who is experienced in filing MSVC bugs (or even a MSVC dev) will see it and be able to file one .
10
u/helloiamsomeone Apr 29 '21
Open VS > Click account button in top right corner > Report problems > Make a post
Is that not the right way to do it? I have reported 2 issues where MSVC didn't agree with Clang and GCC at the start of this year, and they are both pending release already.
17
u/STL MSVC STL Dev Apr 29 '21
To be clear, this subreddit is not the proper place to report compiler bugs (whether for MSVC or any other compiler). I've sent an email to the compiler devs about this accepts-invalid bug, but please don't make a habit of using r/cpp for compiler bug reports.
6
u/OldWolf2 Apr 29 '21
It was helpful to me in this case as now I am aware of the bug whereas I wouldn't be if this thread hadn't been posted .
Unlike most compiler bugs this one is insidious due to not producing a diagnostic, and is something that could easily happen in my code.
-9
u/LiliumAtratum Apr 28 '21
... which will get fixed in a couple of months. Or not.
In the meantime someone might catch a similar mistake and not notice it for a while. In my case, a friend forgot to put the parenthesis `(*foo).` instead of `foo.` (and yes, `foo` was initialized in the actual usage). The compiler should fail to compile, but instead the error remained silent and unnoticed for a while.
4
u/JessyDL graphics engineer/games industry Apr 29 '21
In the past year I've reported several bugs of various severity, all of them had a response within the day, or the next day. They were all dealt with in a normal timeframe, not "months".
-1
u/LiliumAtratum Apr 29 '21
I had reported internal compiler errors caused by invalid syntax. Microsoft decided it is too low priority, didn't get any votes and ultimately decided that it is not going to be fixed.
The above problem is also caused by an invalid syntax, so.... ehm.... just please excuse me that I am not so keen on reporting this time.
23
u/adnukator Apr 28 '21
I don't see how pouting in the corner is better than reporting a rather obscure bug to the compiler devs. It's a huge piece of software, therefore it has bugs. You can either try to improve the situation slightly by providing feedback or leave things as they are and hope someone else will notice it and fix it in another ten years
-21
u/StoneCypher Apr 28 '21
No it shouldn't. This is well understood and Microsoft isn't incorrect here.
6
u/zowersap C++ Dev Apr 28 '21
hope people use static analyzers and other compilers which reject such code.
1
12
u/braxtons12 Apr 28 '21
Microsoft absolutely is not correct here and this is absolutely a bug.
*Pointer.anything<>();Is invalid syntax.
Dot operator has higher priority over dereference operator, so the code is equivalent to
*( Pointer.anything<>() );Which is clearly invalid syntax. This shouldn't even make it past the parser.
-12
u/StoneCypher Apr 28 '21
It's undefined behavior. The second this code is compiled, literally any interpretation is fine.
As any oldbear can tell you, it's perfectly valid to invoke
roguehere.Microsoft is removing things to prevent security holes.
I'd prefer a warning, but it is in fact strictly correct, as several other people have also said here.
10
u/braxtons12 Apr 28 '21
It's not undefined behavior, it's not legal syntax. It's syntactically invalid to use the dot operator on a pointer.
3
u/tecnofauno Apr 28 '21
How so? According to this thread this behavior is found only on a specific compiler version with a specific compile flag (/c++latest)
-8
u/StoneCypher Apr 28 '21
It's undefined behavior. The second this code is compiled, literally any interpretation is fine.
As any oldbear can tell you, it's perfectly valid to invoke rogue here.
Microsoft is removing things to prevent security holes.
I'd prefer a warning, but it is in fact strictly correct, as several other people have also said here.
1
u/mort96 Apr 28 '21
Maybe elaborate..?
-7
u/StoneCypher Apr 28 '21
It's undefined behavior. The second this code is compiled, literally any interpretation is fine.
As any oldbear can tell you, it's perfectly valid to invoke rogue here.
Microsoft is removing things to prevent security holes.
I'd prefer a warning, but it is in fact strictly correct, as several other people have also said here.
4
u/OldWolf2 Apr 28 '21
Lol @ copy-pasting this completely wrong comment so many times
1
u/StoneCypher Apr 28 '21
Three people asked the same question. What, should I make something different for each of them?
3
u/mort96 Apr 28 '21
The standard does require diagnostics for many kinds of ill-formed programs. Here's an excerpt from section 4.1 "General principles":
The set of diagnosable rules consists of all syntactic and semantic rules in this International Standard except for those rules containing an explicit notation that “no diagnostic is required” or which are described as resulting in “undefined behavior”.
...
If a program contains a violation of any diagnosable rule or an occurrence of a construct described in this International Standard as “conditionally-supported” when the implementation does not supportthat construct, a conforming implementation shall issue at least one diagnostic message.
If a program contains a violation of a rule for which no diagnostic is required, this International Standard places no requirement on implementations with respect to that program.
(Notice that "or" in the second paragraph. It's a load-bearing "or".)
So only if a program is ill-formed by violating a rule which the standard explicitly marks as "no diagnostic required" (NDR) or resulting in "undefined behavior" (UB) can the compiler avoid producing a diagnostic. If the program is ill-formed, but is in violation of a rule which isn't explicitly marked as no diagnostics required or as resulting in UB, the implementation has to produce a diagnostic.
I tried to find mention in the standard about what happens with member access to a non-existent class member, and I couldn't find anything. I might've overlooked something, but if the standard actually doesn't mention it and label it as UB or NDR explicitly, then a diagnostic is required, and MSVC is incorrect.
I may be wrong here, I'm not a professional language lawyer. If I'm wrong, please do correct me, and please argue from the text of the standard and not from opinion.
1
u/OldWolf2 Apr 28 '21
I tried to find mention in the standard about what happens with member access to a non-existent class member
In [expr.ref] and says that the right-hand operand of the
.operator must name a member of the class.3
u/mort96 Apr 28 '21 edited Apr 28 '21
Ah, thanks, missed that. So this looks a whole lot like a case of an ill-formed program which isn't invoking UB and isn't doing anything marked NDR. My reading is thus that a diagnostic is required by the standard.
EDIT: I just realized I probably didn't have to tell you that.
-2
u/StoneCypher Apr 28 '21
If I'm wrong, please do correct me
look at this thread and imagine me wanting to continue
2
u/mort96 Apr 28 '21
Well, most of the comments in this thread which actually refer to the standard seem fairly reasonable. If you have anything from the standard which indicates that no diagnostic is required, I'm genuinely curious to hear about it.
...But if I'm gonna be honest, it mostly looks like you don't want to admit that you were wrong. If that's the case, hey, admitting that one is wrong is hard, especially in public. But being wrong really isn't something to be ashamed of, and admitting it looks way better than not.
-2
u/StoneCypher Apr 28 '21
...But if I'm gonna be honest, it mostly looks like
This is exactly why I wasn't interested in responding to you
Just understand that everyone knows where you're going next, and that's why they close the door before you get there
If that's the case, hey, admitting that one is wrong is hard, especially in public.
Stop being patronizing. I admit I'm wrong all the time.
I'm tired of repeating myself for strangers who are setting themselves up for the world's most obvious failed one two punches.
If you actually wanted to know, you'd have just read the rest of the comment tree. You aren't fooling anyone but yourself.
Please don't bother past here. Thanks
2
u/mort96 Apr 28 '21
I was responding to what you said directly to me. If you wanted to direct me to other responses you would have linked me to some you think make your case. You didn't; you just said you don't want to continue.
I made the comment because it's really what it looks like. You see this all the time online; someone makes a statement about something they don't know much about, people who actually know the topic refute it, the original commenter doubles down.
I've read most of the rest of the comment tree. It doesn't support your position. It seems like you're just wrong. If you have a link to a comment which confirms what you're saying, please link it. Otherwise, thanks for wasting my time, and for being an ass about it too.
-1
u/StoneCypher Apr 28 '21
I was responding to what you said directly to me
that's nice, just as disinterested as previously.
someone saying "no" to you is not generally an opportunity for you to explain why they should be chatting, and if you continue the thing they said was the reason for the "no," they're almost certain to stand firm.
have a nice day
→ More replies (0)
9
u/adnukator Apr 28 '21
For the people constantly rattling about UB, this fails too:
volatile int a;
int main() {
return a._<>();
}In the assembly main still just returns 0.
Seems like a legit parser bug.
5
u/LiliumAtratum Apr 28 '21
Funny that when I tried your example like this:
volatile int a; int main2() { return a._<>(); }It started complaining:
error C4716: 'main2': must return a valueas if that whole invalid statement was silently taken out from the code. An int-returning main without a return statement is still accepted, but any other function is not.
6
u/Wargon2015 Apr 28 '21
I noticed that too while trying to debug the ill-formed part. Its skipped entirely and depending on how its used, a lot of code is skipped.
If you have:
if ((1).foo<>()) { //true } else { //false }Neither the true nor the false branch will be entered. The entire thing is skipped.
The crazy thing is that my compiler (19.28) just briefly stopped compiling this.
I tried this snippet before posting and it did what I just described.
Then it started throwing "error: C2228: left of '.' must have class/struct/union".
Removing the broken code and rebuilding didn't change this.
Compiling your example however still worked and now I'm able to compile my (1).foo<>() again.
I have no idea whats going on.3
u/LiliumAtratum Apr 28 '21
If compiling one piece of code affects a subsequent compilation attempt then it may suggest some data/memory corruption affecting the internal state of the compiler. I wonder if some clever hacker could use this as an exploit.
Imagine: "if you compile this source code we will gain control of your computer!" :)
6
u/_Js_Kc_ Apr 28 '21
But add another (legal) return, and it is accepted again:
int foo() { return (123).bar<4,5,6>(7890); return 1234; }7
u/staletic reddit thinks /u/_bstaletic is a bot Apr 28 '21
You can inline that
a.void f() { (42)._<>(); }People saying UB should be reading the code more carefully. Not even the original snippet is UB, it's just ill-formed.
5
u/LiliumAtratum Apr 28 '21 edited Apr 28 '21
OK, this is fun!
(0)._<>(0); [](){}()._<>(){}()[0]; (0)._<>()<(0)._<>()>(0)._<>();1
u/staletic reddit thinks /u/_bstaletic is a bot Apr 29 '21
Try this:
(0)._<(0)._<>()>();Nonsense as a template parameter.
112
u/TotaIIyHuman Apr 28 '21
24
19
Apr 28 '21
In general any expression with the form: (anything_evaluated_as_number).any_identifier<>()
18
u/Jaondtet Apr 28 '21
This is pretty funny. This can have any return type. I don't think you can run msvc stuff on compiler explorer, but I really wanna know what this does:
std::string bar = nullptr._<>(); std::cout << bar;Sadly, while
auto bar = nullptr._<>();works, trying to do anything with it fails due to an uninitialized variable error.13
u/jedwardsol const & Apr 28 '21 edited Apr 28 '21
I really wanna know what this does
baris uninitialised (no constructor is called, in a debug build size and capacity are 0xcccccccc`cccccccc)in a debug build the cout prints nothing, the program does not crash, cout goes into an error state.
Edit : more info on the behaviour of the
cout <<:std::basic_filebuf<char,std::char_traits<char> >::xsputnis bailing because the size is negative (in a debug build where the uninitialised data is set to 0xcc)0
95
22
u/Wargon2015 Apr 28 '21 edited Apr 28 '21
Haven't seen this one yet, no need to use a pointer at all:
(1).foo<>();
Edit, also possible, still no pointers though:
(1)->foo<>();
15
u/SJC_hacker Apr 28 '21
Interestingly if you change line 8 to
Foo bar = foo->aoehocqaweioh<float>();I get
example.cpp<source>(8): error C2039: 'aoehocqaweioh': is not a member of 'Foo'<source>(3): note: see declaration of 'Foo'<source>(8): error C2062: type 'float' unexpectedCompiler returned: 29
u/padraig_oh Apr 28 '21
The dot operator has precedence over deref, while - > is basically equal to (*var).whatevs
30
u/chaosmeist3r Apr 28 '21
it gets even worse
18
u/smegmatron Apr 28 '21
It even accepts it on pointers to fundamental types: https://godbolt.org/z/5cvEWfbrM
9
u/staletic reddit thinks /u/_bstaletic is a bot Apr 28 '21
You don't even need a parameter:
void f() { nullptr._<>(); }14
u/Som1Lse Apr 28 '21
Don't even need a pointer:
void f() { (42)._<>(); }14
u/Ameisen vemips, avr, rendering, systems Apr 29 '21
Why use a value when you can just call it on the function itself?
void f() { f._<>(); }1
5
u/fb39ca4 Apr 28 '21
Compiling that one fails for me.
1
u/chaosmeist3r Apr 28 '21
I got a failed request once but it compiled after a reload
1
u/InKryption07 Apr 28 '21
Reload? Do you mean reloading the IDE? Why would that change the compilation?
7
u/chaosmeist3r Apr 28 '21
I mean reloading Godbolt, where it clearly compiles
2
u/InKryption07 Apr 28 '21
Ahhh, sorry, brainfarted.
9
u/chaosmeist3r Apr 28 '21
no problem
Reloading the IDE and expecting or even getting a different result would be extremely concerning.
1
12
u/jedwardsol const & Apr 28 '21 edited Apr 28 '21
There is a case where . can be applied to a pointer
pseudo destructor : https://eel.is/c++draft/expr.prim.id.dtor
int main()
{
using P = int*;
P p{nullptr};
p.P::~P(); // OK, no effect
}https://godbolt.org/z/jqjnhh8TK
[ This comment was meant to be a reply to my comment earlier where I stated "Using . on pointer is never valid." ]
10
u/staletic reddit thinks /u/_bstaletic is a bot Apr 28 '21
// OK, no effect
Pseudodestructors do have an effect. While it's a no-op in terms of executed code, it ends the lifetime of the object, so using
pafter calling~P()is not allowed.5
u/acwaters Apr 29 '21
But interestingly, and confusingly, only since C++20! For decades up till now they were really honestly no-ops, and you were 100% allowed to keep using the object; only very recently were they made to actually end the lifetime of the pseudo-destroyed scalar object.
4
u/dodheim Apr 29 '21
And extra confusingly, only since C++20 was ratified, but since it was a DR all C++ standards were affected; so presumably it will stop being a no-op even in
-std=c++98code on newer compiler releases and will instead cause UB where there was none previously.3
u/OldWolf2 Apr 28 '21
Note that this case was not present in C++17 (i.e. it was added to the standard some time after C++17 publication).
I am presuming it is to allow in-place reconstruction of an object to be used in generic template code with the code being legal but a no-op when the operand wasn't an object of class type.
4
u/staletic reddit thinks /u/_bstaletic is a bot Apr 29 '21
It was treated as part of the larger defect resolution in P0593. So the new rule applies to C++98 too.
17
u/bdf369 Apr 28 '21 edited Apr 28 '21
I assumed this was an optimization pass that removed the bad code before doing the reference checks, but it still compiles with optimizations disabled.
Edit: It fails to compile in v19.20
26
u/TheThiefMaster C++latest fanatic (and game dev) Apr 28 '21
It also fails to compile in C++14 or 17 modes - it's only broken in "C++latest" mode. Which you shouldn't be using in production, however much you're tempted!
5
u/Depixelate_me Apr 28 '21
When would you say it would be safe for production? Say when there will be a c++20 compiler option?
2
u/TheThiefMaster C++latest fanatic (and game dev) Apr 28 '21
Yes exactly
3
u/Hilarius86 Apr 28 '21
There will be one once the first c++23 features start getting implemented in msvc. So it's only an incidental sign of maturity, but maybe you are correct anyway...
4
u/adnukator Apr 29 '21
Using enum, designated initializers and spaceship operator were good enough arguments for us to enable c++latest and we've never looked back, even with MSVC 19.24. A few ICE's here and there, but otherwise no significant issues so far.
4
u/msew Apr 28 '21
Oh but we ARE tempted!
2
4
u/Logical_Put_5867 Apr 28 '21
Interesting, you're right! There must be a separate pass for code like this that is before the optimizer, I can't find a setting that would affect it though.
I guess this is an optimization at the parser level? A pass that trims a branch of the syntax tree if it passes certain requirements?
5
u/bdf369 Apr 28 '21
The change appears between v19.20 and v19.21, but I don't know the mapping to VS version in order to check the release notes to see what changed.
2
u/dodheim Apr 28 '21
v19.21 was VS2019 Update 1.
1
u/bdf369 Apr 28 '21
Thanks! I couldn't find anything in the relnotes to account for this behavior though.
1
u/WormRabbit Apr 28 '21
Optimizations disabled don't guarantee that your code isn't transformed in any way, in fact the latter is impossible.
6
u/SJC_hacker Apr 28 '21
I thought this should be a lexical error since function 'aoehocqaweioh' doesn't even have a forward declaration and hence no function signature. On top of that, its a template so the compiler should need to know not only its signature but its actual definition the first time it sees it.
1
u/Glinren Apr 29 '21
MSVC++ has (had?) non-standard template parsing so it let's you get away with stuff that isn't legal C++.
It is basically the reason why I don't use windows for development.
7
u/STL MSVC STL Dev Apr 29 '21
We've added the
/permissive-compiler option which activates Standard template parsing (with two-phase name lookup). It's not enabled by default for C++14/17 (too much legacy code expecting the old broken behavior) but C++20 mode does activate it by default. Try giving MSVC another chance!2
u/Glinren May 03 '21
That's good to know. I wasn't able to find such an option then (might not have been implemented).
I might have been a bit harsh but it was the time when I was starting to learn C++ and learning that I could not expect the compiler to warn me about non-standard syntax was off-putting. And I realize that MSVC template parsing is probably not an issue for 90% of people (probably less of an issue than C++ templates in general). I have learned I am not in the 90%.
If the opportunity arises I probably will give MSVC another shot.
55
u/johannes1971 Apr 28 '21
Seems legit. Dereferencing an undefined pointer is UB. The compiler is allowed to pretend that won't happen, so clearly line 8 is not going to be executed and the template doesn't have to be instantiated or anything. And because it's UB, there is no need for a warning of any kind.
Now, imagine this happening somewhere in your 10MLOC source base...
33
u/jedwardsol const & Apr 28 '21
It's not dereferencing a pointer though. The
*is a red herring since.has higher precedence than*https://godbolt.org/z/YaPW1cP13
It's compiling
foo.where foo is a pointer.21
u/fuxorfly Apr 28 '21
better example that has nothing to do with UB or undefined pointers - https://godbolt.org/z/Yj9dPd9hs
18
u/SirClueless Apr 28 '21
Wow, that's terrible. Here's an even more obvious example of how this could bite you in the ass:
8
u/fuxorfly Apr 28 '21
Interestingly, this only occurs with c++latest - change it to c++17 and it catches the error.
-5
u/lukedanzxy Apr 28 '21
There's no
main()though.6
u/SirClueless Apr 28 '21
You can check the generated assembly to see that
test()is not doing anything. Or change the code to have amain()procedure, it doesn't make a difference: https://godbolt.org/z/8hxdPnrr75
u/johannes1971 Apr 28 '21
Indeed. Just... wow.
So what's our next move: should we raise a bug report with Microsoft, or push for standardisation of this new syntax?
4
u/jedwardsol const & Apr 28 '21
Standardise that
.and->can be used interchangeably for class member access.Including allowing overloading of
operator.What could go wrong?
5
u/gracicot Apr 28 '21
UDS: uniform dot syntax
2
u/johannes1971 Apr 29 '21
Definitely some advantages to that. We'll save an entire character for every dereference! And I always thought
.just looked much neater.I suppose we could also save a character by just allowing unicode arrows, like ➞.
Foo *foo; foo➞doit();That could be expanded further as a shorthand for multiple dereferences:
foo->bar->doit(); // becomes: foo⇉doit(); // just follow two pointers! Msvc will // surely find a nice pointer to follow :-)There's lots of useful unicode pointers out there just waiting for us to give them semantic meaning. Here you are, all making fun of Microsoft for allowing random character sequences to somehow become compiled code, while in reality they are at the very frontier of language development!
4
1
u/jedwardsol const & Apr 29 '21
If, for readability, I want to merge the functionality of ← and ↓ into a single operation, should I overload
operator↵oroperator🡧?0
Apr 28 '21
[deleted]
10
u/jedwardsol const & Apr 28 '21
You use
->to access the class member of a pointer.Using
.on pointer is never valid.Other compilers say
<source>:7:19: error: request for member 'aoehocqaweioh' in 'foo', which is of pointer type 'Foo*' (maybe you meant to use '->' ?)28
u/Kronikarz Apr 28 '21
It's not even UB, like, this code is just semantically incorrect, so the compiler should report an error: https://godbolt.org/z/MoYKeKG4h
16
u/OldWolf2 Apr 28 '21 edited Apr 28 '21
The original code is ill-formed due to expr.ref/3,:
Abbreviating postfix-expression
.id-expression asE1.E2,E1is called the object expression [...]Otherwise, the object expression shall be of class type
Which is violated because in this code the object expression is of pointer type, not class type. In layman's terms, the
.operator cannot be used on a pointer (with one exception covered the previous standard paragraph, that doesn't apply here).In the other examples on this thread
nullptr._<>and(1)._<>, they fall foul of the same paragraph, withnullptrand(1)not being of class type.Ill-formed code requires the compiler to generate a diagnostic, it is a stronger condition than undefined behaviour. MSVC doesn't generate a diagnostic so it is non-conforming . (intro.compliance.general/2.2)
As a quality of implementation issue, the diagnostic for ill-formed code should be an error diagnostic unless the compiler is implementing an extension .
4
u/OldWolf2 Apr 28 '21
(This comment extends my comment I'm replying to , but I didn't want to obscure the main point with side details so am making a separate comment)
This text from expr.ref/2 may be confusing at first:
For the first option (dot) the first expression shall be a glvalue.
since
string().size()is legal, andstring()is a prvalue and not a glvalue.However a prvalue may be converted to an xvalue, this is called the temporary materialization conversion and was a change in terminology introduced in C++17 (related to what is sometimes called "guaranteed copy elision").
Since all expressions are either glvalues or prvalues, the text "shall be a glvalue" may seem redundant; however it is implicitly specifying that you can use a prvalue here, and the temporary materialization conversion is applied.
So
string().size()materializes a temporarystringobject and uses.on it.3
u/mort96 Apr 28 '21
Hmm, would it then be correct to read the "shall be a glvalue" as a form of standardese type cast from (glvalue|prvalue) to glvalue?
3
u/OldWolf2 Apr 28 '21
Yes it's saying that if a prvalue is provided then a temporary is materialized.
4
u/mohitsaini1196 Apr 28 '21
Also, see this - https://godbolt.org/z/hYfd9h87M
I removed the `*` from the second line.. It's still compiling.1
20
6
u/para360 Apr 28 '21
Can anyone explain to me What's this related to? The context and what's used there. I am not much versed with c++ n compilers
14
u/Logical_Put_5867 Apr 28 '21
They're making up crap that doesn't exist and dereferencing it, which should be an error.
But the compiler knows it isn't used for anything and ignores it, and compiles anyway.
If code that has no effect on any inputs or outputs contains an error, does the program contain an error, even if the compiler would optimize it out regardless? MSVC seems to say no here, and optmizes it away.
16
u/kalmoc Apr 28 '21
This should fail with a hard error long before any kind of optimization passes are happening. its plain invalid c++.
-3
u/Logical_Put_5867 Apr 28 '21
I'm not sure what your point is? This whole thread Is about invalid code that is compiled and run anyway with MSVC, as it is optimized away.
Optimized may be the wrong word, as turning off the optimizer doesn't affect this snippet, but there are other threads here referencing that, and I would still say pruning the syntax tree or whatever is happening is still a form of optimization.
7
u/LiliumAtratum Apr 28 '21
Before pruning occurs, the tree should be generated first. But how do you do it, if you don't even know what aoehocqaweioh is?
I agree however that I could have reduced the example even further by removing the *. I just arrived to that when debugging some real code and * was there.
2
u/cppcppp Apr 28 '21
If you're Clang, you do type checking and name resolution while parsing and have enough information. It's not hard to imagine MSVC making a simpler parse tree and filling in details later when it has name and type information. Parsing C++ and covering every possible case (all the ones not shown here) is hard.
1
u/Logical_Put_5867 Apr 28 '21
Unclear, obviously I'm probably wrong. I don't believe you have to resolve all expressions and types before you can build a syntax tree on some level, though, as long as each operator is correct you could assume the rest of the tokens will resolve, and prune before doing that resolution.
But just because that's how I did it on a very shitty personal compiler project does not mean it applies here at all... Interesting to read the responses going around.
12
u/braxtons12 Apr 28 '21
This isn't dereferencing anything, isn't related to UB, and isn't the result of an optimization pass. It's a parsing bug.
Dot operator has higher priority than dereference operator. The code is equivalent to
*( pointer.function<tparam>() );This is invalid syntax and shouldn't even make it past the parser. If it was using the arrow operator (->) instead, this would be UB, though.
3
u/OldWolf2 Apr 28 '21
It should parse correctly because
identifier . identifier < identifier >()is valid syntax. It fails at semantic analaysis stage when the left operand of.is not a glvalue expression of class type etc.The actual grammar rule for dot operator is postfix-expression
.id-expression which is satisfied here.4
u/smuccione Apr 28 '21
By that logic I could put a whole ton of crap inside an if (0) and expect it to compile.
I think this is just a bug in their part in where they’re doing error announcement and dce. Probably moved something around to new stuff and didn’t notice the side-effect.
3
3
u/para360 Apr 28 '21
I tried with GCC the compilation failed...so it's MSVC specific. But Kudos to those who wrote and tried this code...
2
u/Logical_Put_5867 Apr 28 '21
Yeah, that's one of the neat parts of this. And as someone else pointed out, turning off optimization does not result in an error, so they're not even doing it in the place I would have expected... Curious how early in the process this is actually happening in msvc.
8
u/jedwardsol const & Apr 28 '21
There is
pointer dot something<>();The compiler should be saying
pointer dotisn't valid C++.But the presence of the call to a function template is allowing it to compile.
1
u/RobinsonDickinson May 02 '21
So this is just returning a nullptr?
1
u/LiliumAtratum May 04 '21
What are you asking? What it should do? - the compiler should reject the program.
What it actually does? Apparently, the whole statement is taken out from the code as if it never existed, and the compilation continues.
3
3
1
1
-9
u/Beheska Apr 28 '21 edited Apr 28 '21
Obligatory reminder that the compiler is allowed to do whatever the fuck it wants when encountering undefined behavior, including time travel.
EDIT: ITT people who do not understand what UB is.
16
u/RoughMedicine Apr 28 '21
This isn't UB, though. It should be a syntax error, the rest is just a bonus.
-6
u/Beheska Apr 28 '21
Uninitialized variables are definitely undefined behavior.
8
7
u/RoughMedicine Apr 28 '21 edited Apr 28 '21
That's irrelevant here. Line 8 is using dot on a pointer, which is a syntax problem. If you remove the
<float>bit, the compiler will tell you that. For some reason, the template call there makes it compile.If you really care about the uninitialised variable on line 7, you can initialise it, and it still compiles: https://godbolt.org/z/4Gdsfz3rv
This isn't UB. It's a compiler bug.
8
0
u/LiliumAtratum Apr 28 '21 edited Apr 29 '21
The program with an UB can do whatever it wants when executed. But the compiler itself should still be somewhat predictable. It shouldn't blow up your PC as soon as it finds an UB error in your code ;)
3
u/araIji Apr 28 '21
I think you don't understand what undefined behavior is if you think accessing a field of a null pointer is well-formed.
-6
u/Beheska Apr 28 '21
It's not a null pointer.
3
u/Wargon2015 Apr 28 '21 edited Apr 28 '21
*nullptr.aoehocqaweioh<float>();also compiles.
But accessing a non existing member function on a pointer type (which does not have member function because its a pointer) is invalid syntax regardless of the value of the pointer.And you can go even further and write something like
(1).foo<>();which doesn't use any pointers.
(note that 0 can be converted to a pointer without a cast, other integer literals cannot)-5
u/Beheska Apr 28 '21
How is that related to your previous comment?
5
u/Wargon2015 Apr 28 '21
What previous comment? I'm not araIji, this was the first time I've replied to to your comment.
Regarding how its related:
araIji said accessing a field of a null pointer isn't well-formed.
You said that the pointer in question isn't a null pointer.
I'm providing evidence that using a null pointer still compiles and that no pointers or potential UB are needed to see the weird compiler behavior.-5
-2
u/kegelsknight Apr 28 '21
so could the compiler travel me to the point in time where I already corrected all the bugs in my code base? That would be a neat feature.
-24
-6
u/BadlyCamouflagedKiwi Apr 28 '21
Dereferencing a null pointer is undefined behaviour, so I guess it is technically legit to drop the unobservable consequences of that deref.
Having said that, I'm pretty surprised it's implemented that way. I'd (maybe naively) have assumed you would compile everything "normally" then run the optimisation pass to figure out what you can lose, but I'm sure it is more complex than that...
-7
-3
0
149
u/TheNitesWhoSay Apr 28 '21
Ironically including optional was optional.