As we all know, computers can only recognize binary languages, and it is not possible to directly identify high-level languages such as Java C C + +. Converting a high-level language to a computer can be another binary language, and this process is called compiling.
There was an interview, the interviewer asked a "Java compiler principle is what", at that time to be ignorant, only know is to convert the Java file into a class file, and then executed by the JVM, the specific process is not known. Today read Xilingpo authored "in-depth analysis of Java Web Technology Insider" a book, which is about the javac of the compilation principle, read it again, feel a little foggy, not very clear, and then have to look at a few times, more online search information in-depth study.
Today, we summarize the overall process of Javac compilation, and then carefully analyze the details of each process.
The compiler compiles the source code into the target machine, the two-level code that the computer can recognize, or the set of instructions that the CPU executes. and the Javac compiler and C C + + assembly language is not the same place, is Javac is the Java this high-level language compiled into a Java Virtual machine (JVM) can recognize a language, and then by the JVM to the JVM language to the current machine can recognize the machine language, This is the most fundamental reason that Java can cross the platform. Javac's task is to compile Java code into Java bytecode, which is often said to convert. java files into. class files.
Javac the basic process of compiling:
1. Lexical analysis
Read the source code, a byte-by-byte read, find out which of the keywords we have defined (such as the If else for keyword in Java, identify what if is a legitimate keyword, which is not), which is the lexical analyzer process of lexical analysis, The result is to find the normalized token stream from the source code.
2. Grammatical analysis
Parsing the token stream through the syntax parser, this step checks to see if these keyword combinations are again compliant with the Java language specification (e.g. after if it is not followed by a Boolean judgment expression), the result of lexical analysis is to form an abstract syntax tree that conforms to the Java language specification.
3. Semantic Analysis
Semantic analysis through the semantic parser. Speech analysis is mainly to convert some difficult and complex grammar into a simpler syntax, resulting in the simplest syntax (such as converting foreach to A For loop, annotations, etc.), and finally forming an annotated abstract syntax tree, which is closer to the grammar rules of the target language.
4. Generate byte code
The annotated abstract syntax tree is converted into bytecode code that conforms to the JVM specification through the bytecode producer.
There are 4 main modules of Javac, namely lexical analyzer, parser, semantic parser, code generator.
Javac compilation principle (i)