Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What trick does Java use to avoid spaces in >>?

In the Java Generic Book, while contrasting the difference between C++ Templates and Java Generic says:

In C++, a problem arises because >> without the space denotes the right-shift operator. Java fixes the problem by a trick in the grammar.)

What is this trick?

like image 918
unj2 Avatar asked May 11 '10 05:05

unj2


People also ask

How do you ignore spaces in Java?

You can implicitly ignore them by just removing them from your input text. Therefore replace all occurrences with "" (empty text): fullName = fullName. replaceAll(" ", "");

Which method removes whitespace in Java?

In the above program, we use String's replaceAll() method to remove and replace all whitespaces in the string sentence . To learn more, visit Java String replaceAll(). We've used regular expression \\s that finds all white space characters (tabs, spaces, new line character, etc.) in the string.


2 Answers

The OpenJDK javac parser, JavacParser, massages the lexer tokens GTGTGTEQ (>>>=), GTGTEQ, GTEQ, GTGTGT (>>>) and GTGT into the token with one less '>' character when parsing type arguments.

Here is a snippet of the magic from JavacParser#typeArguments():

    switch (S.token()) {
    case GTGTGTEQ:
        S.token(GTGTEQ);
        break;
    case GTGTEQ:
        S.token(GTEQ);
        break;
    case GTEQ:
        S.token(EQ);
        break;
    case GTGTGT:
        S.token(GTGT);
        break;
    case GTGT:
        S.token(GT);
        break;
    default:
        accept(GT);
        break;
    }

One can clearly see that it is indeed a trick, and it's in the grammar :)

like image 166
clstrfsck Avatar answered Oct 16 '22 01:10

clstrfsck


This is actually being fixed in C++ in the next version. There really isn't much of a trick; if you encounter >> while in the process of parsing a generic or template where instead you expected >, then you already have enough information to generate an error message. And, if you have enough information to generate an error message, you also have enough information to interpret >> as two separate tokens: > followed by >.

like image 39
Michael Aaron Safyan Avatar answered Oct 16 '22 03:10

Michael Aaron Safyan