Let’s first talk about what word segmentation is. Word segmentation is to decompose a string of characters into code blocks that are meaningful to the programming language. These code blocks are called tokens. For example, the code var a = 2
will be decomposed into the following lexical units. Specifically: var,a,=,2.
Note: Word segmentation is actually to split the entire code above into segments.
Parsing is to convert the stream of lexical units into a tree composed of elements nested level by level, which represents the grammatical structure of the program. This tree is called: abstract syntax tree. In view of the overly long standard words here, we will not consider them. I will directly display them in a more intuitive form. The details are as follows:
Analysis: The abstract syntax tree will have a top-level node of var, followed by a child node with the variable a and a node with the assignment operator =. There is another child node of 2 under the assignment symbol. Specifically, it corresponds to the code var a = 2
.
The process of converting an abstract syntax tree into executable code is called code generation. This process is closely related to language and target platform. Simply put, there is a way to convert the abstract syntax tree of var a = 2
into machine instructions. Used to create a variable called a and store a value in a.
mainly rely on the engine to execute JavaScript code. When the engine executes var a = 2, it will determine whether variable a has been declared by looking for it. The search process is assisted by scopes. During the query process, the engine will perform LHS (left query) for variable a and right query for the value. To put it simply, when the variable appears on the left side of the assignment operation, an LHS query is performed, and when it appears on the right side, an RHS query is performed. To be more precise, the LHS query tries to find the container of the variable itself, while the RHS query tries to get its source value.
Note: In the function, there will be both LHS and RHS queries. Because in the process of passing parameters, the code will perform implicit assignment.
When the variable has not been declared, the behavior of LHS query and RHS query is different.
function foo(a){ console.log(a+b); b=a;}foo(2)
Note: The first right query on b cannot find the variable, which means that it is an undeclared variable because it cannot be found in any relevant scope. If RHS cannot find the required variables in the nested scope, the engine will throw an exception.
function foo(a){ var b=a; return a+b; } var c=foo(2)
problem: find all LHS queries and RHS
Answer: LHS(c=…,a=2,b=…) and RHS(foo(2…,=a,a…,…b))