r/programming • u/jonjonbee • Jun 05 '18
Code golfing challenge leads to discovery of string concatenation bug in JDK 9+ compiler
https://stackoverflow.com/questions/50683786/why-does-arrayin-i-give-different-results-in-java-8-and-java-10179
u/-ghostinthemachine- Jun 05 '18 edited Jun 05 '18
This feels a little derpy for such an important language. Not some obscure edge case, but any left hand expression that mutates? Are there really no tests for these?? Makes me scared for the future of Java.
138
u/CptCap Jun 05 '18 edited Jun 05 '18
any expression that mutates
This only works with strings. Strings require special handling as they are the only objects with operators.
49
u/XkF21WNJ Jun 05 '18
Having one type that behaves differently from all others just sounds like a bug waiting to happen.
56
u/mirhagk Jun 05 '18 edited Jun 05 '18
And it also sounds like something that should have it's own explicit test cases. For such a huge language it's absolutely unacceptable that there was no test that caught this.
It's one of the very first things the spec says about
+=and while making a language every rule in the spec should have tests for it.6
u/Likely_not_Eric Jun 05 '18
I wonder if it'll even have test coverage now. It's not like Oracle to invest in software when they could use that money to threaten someone with litigation.
6
u/duhace Jun 05 '18
the bug report already has them adding specific test coverage to catch a regression like this in the future.
10
Jun 05 '18
Strings behave differently in every other language anyways. I avoid operators aside from concatenation and wouldn't use an operator in a left hand expression in this manner. This is a really strange case.
10
u/XkF21WNJ Jun 05 '18
I don't know many languages where strings are fundamentally different from other classes (apart from being a primitive class), usually they still fit somewhere in the usual categories.
2
u/isaacarsenal Jun 05 '18
I doubt that. Take C# for example, does they behave differently compared to other classes?
8
u/DrFloyd5 Jun 05 '18
var X=“blue”; var Y=X; X+=“your mind.”; // Y still equals blue;Compare
var c=new List<string>(); var d=c; c.Add(“a string”); // d also contains “a string”Strings are objects but are immutable. But the language definition allows for automatically updating the reference to a new string.
4
u/isaacarsenal Jun 05 '18 edited Jun 05 '18
Well, isn't this true for all immutable objects in C#?
X+="your mind"expands toX = X + "your mind"which creates a new string object and assigns it to X. Same thing for operator+can be implemented for any other custom immutable class.The point is, does C# treat string as a special class in a way that same functionality cannot be achieved for a custom class like
MyString?4
u/kurav Jun 05 '18
Yes, strings are very much special on language level in C# as well. Obviously, they have a unique literal expression syntax (
"hello world"), but also the string concatenation operator (+) is not implemented as operator overload of theSystem.Stringclass, but as a semantically specific expression. Contrast this with e.g.System.DateTimeclass, which defines addition of its type as an operator overload.Also, the lowercase
stringidentifier is a keyword lexically reserved as an alias of theSystem.Stringclass.→ More replies (3)17
u/fishy_snack Jun 05 '18
Also the linked issue logged is marked P3. Maybe I don’t understand their priority levels but that seems low for fairly mainstream bad code gen regression.
3
Jun 05 '18
Because there's a switch to revert to the old behavior?
12
u/fishy_snack Jun 05 '18
I missed that, but bad codegen is insidious since you may not notice the bug for a while then it’s expensive to root cause as the compiler is the last thing you suspect.
1
u/jack104 Jun 06 '18
Yea man. Java has made it business as usual to do not automated testing and provide absolutely fuck all in the way of useful documentation beyond the most nominal applications. God damnit people if you are going to spend the time to build something people rely upon to accomplish a task then spend the extra 5 minutes to help me use it as it is capable of being. To quote the OG flight director of the NASA Apollo program "I dont care what anything is designed to do, I care about what it can do!"
→ More replies (3)0
u/yatea34 Jun 05 '18
Are there really no tests for these?? Makes me scared
If it concerns you, you're welcome to add such tests to their test suite.
That's kinda the whole point to open source software.
13
Jun 05 '18
People actually use common programming languages for code golf? Even as verbose as Java?
30
u/TidB Jun 05 '18
Sure. Sometimes they'll use intentionally verbose languages (for example Brainfuck or ArnoldC) just for fun, for the challenge or because they're comfortable with a particular language.
14
u/msiekkinen Jun 05 '18
Rankings against same language should be only relevant thing
9
u/nakilon Jun 05 '18
Sadly it's not how it really works. In that stupid stackexchange site about codegolf almost every thread is "won" by a golfscript -- a DSL made specifically for golf. That's absolutely stupid and it's only one of a hundred of stupid things about that site and its community, so I could not stay there for long.
11
u/Pazer2 Jun 05 '18
Hey guys! Check out my groundbreaking new scripting language for code golfing! It just happens to interpret a blank input file as "output executable code for the solution to this particular problem".
7
u/adrianmonk Jun 05 '18
This trick is also used in data compression contests by people who want to be irritating.
7
u/nakilon Jun 05 '18
There was a cool contest two years ago. You had to make a classifier that would tell if the word is from the dictionary (exact "English words" dictionary was given) of 4 megabytes. The whole solution (code + data) had to fit into 48 kilobytes. https://habr.com/company/hola/blog/282624/
IIRC guys who won with amazing accuracy (mine was only 71%) were using Bloom filter.3
u/zenflux Jun 06 '18
I usually see those kind contests score the sum of output size and decoder executable size. Or maybe I'm only seeing these contests after someone decided to be cheeky with storing the file in it's path and they made the rule.
2
u/bitofabyte Jun 06 '18
I think that they (stack exchange golf people) have a rule that you can only use a language (maybe language version) that was published before the problem, specifically to prevent this.
4
u/msiekkinen Jun 05 '18
Yeah I know, that's why I said "should". Sometimes I try to problems just for fun but I never submit b/c even with my language of choice there's always something "better".
3
u/nakilon Jun 05 '18
Golfing in esoteric languange is not that useful than golfing in language you really work with.
3
Jun 05 '18
I agree with that. Unfortunately if you wanna be competitive you gotta do something funky with some funky language
45
u/Aceeri Jun 05 '18
Does the precedence and ordering of post/pre increment/decrement annoy anyone else? I feel that
array[i] += 1;
i += 1;Just rolls off easier and doesn't require you to think as much while reading.
181
u/FarkCookies Jun 05 '18
Keep in mind that the original code was written for the code golf, which requires the shortest program possible.
14
u/SilasX Jun 05 '18
Also keep in mind that some people have accepted that kind of increment as idiomatic.
7
u/FarkCookies Jun 05 '18
Well too bad, keeping side effects out of mixed expressions should be idiomatic.
5
u/SilasX Jun 05 '18
Agreed -- my point was just that this wasn't merely the kind of thing you'd see limited to absurd code golfing.
24
Jun 05 '18
In original example(
array[i++%size] += i + " ";) - yes. As it hasiin several places and one of them is changing it value, which is a Big-No-No for C and I-don't-Care-What-Standard-Says for java(or c#). In this example - not really. Code likeout[i++] = ID_BLOB; out[i++] = (size >> 8) & 0xFF;is pretty common for filling buffers(e.g. network/file packets), so
array[i++] += 1doesn't look too troublesome.15
Jun 05 '18
Don't dwell on increment here. The same shit happens with any other expression with a side effect, including a mere method call.
5
u/Cunicularius Jun 05 '18
Not if you're used to C.
13
u/XkF21WNJ Jun 05 '18 edited Jun 05 '18
Although in this case I'm fairly sure the behaviour of something like
array[i++] = iis undefined in C.6
u/zid Jun 05 '18
Yea, in C there is no sequence point between the i++ and the i, so i's value isn't determined for either the index or the rvalue.
3
u/adrianmonk Jun 05 '18
in this case
That isn't this case. The grandparent of your comment reads "plus equal one", not "plus equal letter i".
1
u/XkF21WNJ Jun 05 '18
I was referring to this post not the GP which talked about pre/post-increments in general.
1
2
u/SilasX Jun 05 '18
Yeah I’m always mystified how we accepted inline increments. Much harder to check at a glance.
2
u/Treyzania Jun 05 '18
Keyboards for the PDPs that C was developed on were really annoying to type on, so we have a lot of odd abbreviations. Also why so many UNIX commands are nice and short.
1
u/jephthai Jun 06 '18
It saves a line of code. Imagine that you're using a terminal that can only show 24 rows -- saving a line here and there makes the difference between being able to see a whole function at one time and not. I'm still affected by the classic terminal sizes, and put more of a priority on vertical space than most moderns.
1
u/adrianmonk Jun 05 '18
doesn't require you to think as much
It's mostly about what you're used to seeing. Auto-increment doesn't require any extra thinking for me because it's an idiom I've seen thousands of times.
0
u/BloodRainOnTheSnow Jun 07 '18
Nope. But people who use += 1/ -= 1 instead of ++/-- sure do annoy me. ++/-- even break down into INC/DEC in assembly. Any serious programming shouldn't have any mental blocks to increment or decrement.
0
Jun 05 '18
[deleted]
25
u/StillNoNumb Jun 05 '18
That's not his point. His point is that
array[i++] = 5;is weirder to read thanarray[i] = 5; i++;.5
u/rebootyourbrainstem Jun 05 '18 edited Jun 05 '18
This is a very common idiom in C. It's very succinct and expressive, which is pretty hard to come by in that language.
Basically
array[i++] = expression;says "I do this to element number i and now I'm done with it, move on to the next one".In other languages there may be better ways to express this (iterators, generator expressions, list push/pop methods) and even in C it's often cleaner to do the increment as part of a for loop, but this pattern definitely has its uses.
An example:
void filter_negative(int *numbers, size_t *count) { size_t i, j; for (i = 0, j = 0; i < *count; i++) if (numbers[i] >= 0) numbers[j++] = numbers[i]; *count = j; }3
u/nathreed Jun 05 '18
I very much agree...I like to have each statement have effect on one “thing” as much as possible (of course barring function calls). Having to read and remember that it’s doing two things (array access and incrementing i) is much more annoying for me and leads to worse understanding. I have no idea why my CS professor insisted on using it in his slides, but then again he used really crappy code style anyway.
→ More replies (6)1
u/tjsr Jun 05 '18
Not trying to be disagreeable, but I don't agree. However this may just come down to having decades of experience looking at those kinds of statements. While I certainly believe lambda expressions lead to some of the most unreadable code I've seen since I started a learning software development, simple statements that do two (sometimes more) clear things instead of just one while the same context all exists on the small elite is pretty straightforward to an experienced developer.
3
u/Emerentius_the_Rusty Jun 05 '18
Why did you rename
itoindexwhen your point is abouti++vsi += 1?1
u/yur_mom Jun 05 '18
I the example you gave the i++ is on its own line due to semicolon so it would not matter if you use pre or post inc, which is where a lot of confusion comes.
4
6
u/noeatnosleep Jun 05 '18
Hi. I'm from /r/all.
What's code golfing?
24
u/smilliam_work Jun 05 '18
It's a form of programming where the goal is to write a valid program performing a specific task using the fewest possible characters. The "golfing" is in reference to how players are seeking to minimize their "score" (file size).
6
4
Jun 05 '18 edited Jun 06 '18
This is what happens when optimisations are done on a high level AST, instead of a relevant IR level.
EDIT: I was looking at the older JDK output which produced a StringBuilder for this code as a half-assed optimisation attempt. In JDK9 a single intrinsic call is emited, though I'd still classify this as an optimisation and blame for this issue is on a fact that javac does not use multiple IRs before reducing to bytecode.
40
u/ygra Jun 05 '18
String concatenation has been weird in Java for ages, since it used to be compiled into a new StringBuilder and some method calls on that. That's already a rather complex series of statements for a single +.
2
Jun 05 '18
Sure, but this sort of optimisations is ok (see the idiom detection in LLVM for example). It's just the implementation that is amateurish here.
12
u/vytah Jun 05 '18
Except the bug is in javac and javac doesn't optimize anything (except for constant folding).
→ More replies (31)17
u/reddister Jun 05 '18 edited Jun 05 '18
This is not about optimization. (Even if it uses Stringbuilder now)
String += is syntactic sugar. This has nothing to do with optimization.
5
Jun 05 '18
Recognising a StringBuilder pattern vs. a single concatenation is an optimisation. Or at least it should be.
The right way to implement such a thing - translate string addition to concatenation first, recognise the builder pattern in optimisation passes later.
The amateurish way of doing it is to treat it as a syntax sugar.
11
u/F54280 Jun 05 '18
The amateurish way of doing it is to treat it as a syntax sugar.
“Syntactic sugar causes cancer of the semicolon.” -- Alan Perlis
3
u/Deaod Jun 05 '18
The amateurish way of doing it is to treat it as a syntax sugar.
Even if you do treat it as syntax sugar, at least make sure your replacement is idempotent.
2
4
u/mirhagk Jun 05 '18
It has nothing to do with recognizing a StringBuilder pattern or not, and nothing to do with optimizations.
It's an incorrect translation from
+=to relevant IR. They turnedX += Y;intoX = X + Y;which is incorrect.The compiled code doesn't even use StringBuilder. If you look at the generated Java what it does is:
translate string addition to concatenation first,
ie exactly what you said it should do.
→ More replies (16)2
u/Uncaffeinated Jun 05 '18
There is no such thing as string concatenation at the bytecode level. You have to compile it to some sequence of method calls anyway (or invokedynamic now) and StringBuilder is as good a choice as any.
1
Jun 05 '18
Wrong. For a loop or a sequence of concatenations you must only instantiate one StringBuilder. A correct and efficient implementation must use loop analysis to avoid overhead.
2
u/Uncaffeinated Jun 05 '18
Javac doesn't do optimizations like that. It leaves things like that to the JVM.
AFAIK, the only optimizations javac does are precomputing the value of constant expressions and inlining static final fields.
Anyway, that's irrelevant to my original point. I was responding to the claim that javac could just compile it to "string concatenation" instead of StringBuilder sequences, which is false.
→ More replies (5)
2
1
u/Ineeditunesalot Jun 05 '18
There should be an ELI5 bot and someone can post the basics of every post that makes it to r/all cause I never have any idea what any of this stuff means 🤔 still curious though
12
Jun 05 '18
A "compiler" is a software program that converts text in a "programming language" (which is easy for humans to understand) to binary instructions in a "machine language" (which is what computers understand)
Java is an extremely widely-used programming language
Someone discovered a bug in one version of the standard Java compiler, causing it to produce machine language programs whose behavior is not correct.
As for why it made it to the front page, I don't know, since compilers, like all software, have bugs all the time.
21
Jun 05 '18
Because it's a surprisingly simple bug in an extremely widely used programming language, we're all surprised it wasn't caught in testing.
1
1
u/CarthOSassy Jun 05 '18
Java should honestly get rid of string operators.
→ More replies (1)20
u/mirhagk Jun 05 '18
Java needs more operators, not less. The problem is that strings have to be treated specially, which makes this a corner case instead of an edge case. The lack of proper operators makes Java unintuitive.
(a == b).Equals((a.Equals(b))requires knowing not just the types and values ofaandbbut also how they were declared (constants or variables). And additional optimizations that fold more constants could possibly change the result of that expression. Oh and if they areIntegerthen if they are less than 128 then they may be equal because of optimizations, but of course that'd depend on JVM version.That doesn't make for an intuitive and easy to use language.
7
u/renrutal Jun 05 '18
== should have been a shortcut to all value equalities, be they primitives or composite types/objects(as a shortcut to .equals()). Then you could have a === for reference comparisons.
And then you have the whole gaping hole lack of operators for BigInteger/BigDecimal math.
4
u/mirhagk Jun 05 '18
Yeah
==should just be syntactic sugar for.Equals. And honestly a dedicated operator for reference equality isn't necessary. Reference equality isn't really used all that much.2
u/possessed_flea Jun 05 '18
Difference being that .equals is a function call which at the very least creates a new stack frame, performs a jump, and dumps some registers onto the stack ( and pulls them out back on its way out ) meanwhile == simply performs a comparison.
Reference for equality is by far the most common use case ( maybe not in your code, but I mean in general )
Adding that syntactic sugar would have some pretty serious performance impact and it makes sense that they made that choice in 1996, and that choice still applies today. If you don't care about performance then use JavaScript
3
u/mirhagk Jun 05 '18
If Java had no optimizations at all then yes you'd be right. But the optimizations are fairly trivial to perform and would give the same performance characteristics.
If something can be compared by value then you almost always want to do that (reference equality is an anti pattern on strings and Integers). For other types reference equality is fine. You usually know on a type level. So types with value equality define equals as such. Types with reference equality leave the default (which is by reference).
If the optimization of inlining it is 100% critical then it can be a compile time decision. C# defines == as .equals but it does it based on compile time types (ie no inheritance) and therefore will always receive that optimization.
1
u/possessed_flea Jun 05 '18
So you are suggesting code become visually ambiguous?
In Java Since 1.5 Integer would unbox for the comparison anyway .
If we are looking for syntactic sugar for Java then my vote would be to bring in Delphi style properties which would save hugely on code bloat.
→ More replies (4)1
u/ItzWarty Jun 06 '18
As a gross case:
public class MyClass { public static void main(String args[]) { double x = 0.0 / 0.0; // NaN System.out.println(x == x); System.out.println(new Double(x).equals(new Double(x))); } }Outputs:
false trueThis is because IEEE-754 specifies NaN compared with NaN evaluates to false whereas Java and C# define otherwise for their Equals().
3
u/adrianmonk Jun 05 '18
Then you could have a === for reference comparisons.
As a matter of language ergonomics, I strongly prefer if two easily-confused operators do not differ by only one character, especially if it is the number of repetitions of that character.
1
u/IllustriousTackle Jun 05 '18
I believe is a defect of the language. It is quite evident in its design the heavy influence of C because the references feel more like pointers than proper references: The operators = and == act on the reference, not in the value. The worst defect are null references, Java references feel like pointers cosplaying as references.
930
u/lubutu Jun 05 '18
Summary:
array[i++] += "a"is compiled asarray[i++] = array[i++] + "a", which incrementsitwice.