Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't javac accept `x = x+++++y`?

From the perspective of Compiler Theory, why would the javac compiler not accept a statement of the form x = x+++++y but accept x = x+++ ++y ?

like image 877
Force444 Avatar asked May 10 '13 08:05

Force444


People also ask

What is C in javac command?

The javac command reads source files that contain module, package and type declarations written in the Java programming language, and compiles them into class files that run on the Java Virtual Machine. The javac command can also process annotations in Java source files and classes.

What is Xlint?

-Xlint. Enable all recommended warnings. In this release, enabling all available warnings is recommended. -Xlint:all. Enable all recommended warnings.

Where is javac located?

The javac.exe file is located in the bin folder of the JDK.

What compiler is used for Java?

In fact, the Java compiler is often called the JVM compiler (for Java Virtual Machine). Consequently, you can write a Java program (on any platform) and use the JVM compiler (called javac) to generate a bytecode file (bytecode files use the extension . class).


1 Answers

Because ++ is a valid token for the java lexer, the statement x+++ ++y will be parsed into tokens as :

(x)(++)(+)( )(++)(y)

Whereas x+++++y will be tokenized into the invalid:

(x)(++)(++)(+)(y)

The above is invalid java because the ++ operator can only be applied to things that are numeric variables, which the result of (x++) is not. This type of tokenizing is a great example of the concept known as maximal munch.

From the JLS section 3.2

The longest possible translation is used at each step, even if the result does not ultimately make a correct program while another lexical translation would.

Thus, the input characters a--b are tokenized (§3.5) as a, --, b, which is not part of any grammatically correct program, even though the tokenization a, -, -, b could be part of a grammatically correct program.

like image 147
cyon Avatar answered Oct 16 '22 02:10

cyon