看到HorkeyChen写的文章《[WebKit] JavaScriptCore解析--基础篇(三)从脚本代码到JIT编译的代码实现》,写的很好,深受启发。想补充一些Horkey没有写到的细节比如字节码是如何生成的等等,为此成文。
JSC对JavaScript的处理,其实与Webkit对CSS的处理许多地方是类似的,它这么几个部分:
(1)词法分析->出来词语(Token);
(2)语法分析->出来抽象语法树(AST:Abstract Syntax Tree);
(3)遍历抽象语法树->生成字节码(Bytecode);
(4)用解释器(LLInt:Low Level Interpreter)执行字节码;
(5)如果性能不够好就用Baseline JIT编译字节码生成机器码、然后执行此机器码;
(6)如果性能还不够好,就用DFG JIT重新编译字节码生成更好的机器码、然后执行此机器码;
(7)最后,如果还不好,就祭出重器--虚拟器(LLVM:Low Level Virtual Machine)来编译DFG的中间表示代码、生成更高优化的机器码并执行。接下来,我将会用一下系列文章描述此过程。
其中,步骤1、2是类似的,3、4、5步的思想,CSS JIT也是采用类似方法,请参考[1]。想写写JSC的文章,用菜鸟和愚公移山的方式,敲开JSC的冰山一角。
本篇主要描述词法和语法解析的细节。 一、 JavaScriptCore的词法分析器工作流程分析
W3C是这么解释词法和语法工作流程的:
词法器Tokenizer的工作过程如下,就是不断从字符串中寻找一个个的词(Token),比如找到连续的“true”字符串,就创建一个TokenTrue。词法器工作过程如下:
JavaScriptCore/interpreter/interpreter.cpp:
template
template TokenType LiteralParser::Lexer::lex(LiteralParserToken& token)
{
while (m_ptr < m_end && isJSONWhiteSpace(*m_ptr))
++m_ptr;
if (m_ptr >= m_end) {
token.type = TokEnd;
token.start = token.end = m_ptr;
return TokEnd;
}
token.type = TokError;
token.start = m_ptr;
switch (*m_ptr) {
case '[':
token.type = TokLBracket;
token.end = ++m_ptr;
return TokLBracket;
case ']':
token.type = TokRBracket;
token.end = ++m_ptr;
return TokRBracket;
case '(':
token.type = TokLParen;
token.end = ++m_ptr;
return TokLParen;
case ')':
token.type = TokRParen;
token.end = ++m_ptr;
return TokRParen;
case ',':
token.type = TokComma;
token.end = ++m_ptr;
return TokComma;
case ':':
token.type = TokColon;
token.end = ++m_ptr;
return TokColon;
case '"':
return lexString(token);
case 't':
if (m_end - m_ptr >= 4 && m_ptr[1] == 'r' && m_ptr[2] == 'u' && m_ptr[3] == 'e') {
m_ptr += 4;
token.type = TokTrue;
token.end = m_ptr;
return TokTrue;
}
break;
case '-':
case '0':
case '9':
return lexNumber(token);
}
if (m_ptr < m_end) {
if (*m_ptr == '.') {
token.type = TokDot;
token.end = ++m_ptr;
return TokDot;
}
if (*m_ptr == '=') {
token.type = TokAssign;
token.end = ++m_ptr;
return TokAssign;
}
if (*m_ptr == ';') {
token.type = TokSemi;
token.end = ++m_ptr;
return TokAssign;
}
if (isASCIIAlpha(*m_ptr) || *m_ptr == '_' || *m_ptr == '$')
return lexIdentifier(token);
if (*m_ptr == '\'') {
return lexString(token);
}
}
m_lexErrorMessage = String::format("Unrecognized token '%c'", *m_ptr).impl();
return TokError;
}
下面我们看看,语法解析具体过程:
JavaScriptCore/parser/parser.cpp:
PassRefPtr Parser::parse(JSGlobalObject* lexicalGlobalObject, Debugger* debugger, ExecState* debuggerExecState, JSObject** exception)
{
ASSERT(lexicalGlobalObject);
ASSERT(exception && !*exception);
int errLine;
UString errMsg;
if (ParsedNode::scopeIsFunction)
m_lexer->setIsReparsing();
m_sourceElements = 0;
errLine = -1;
errMsg = UString();
UString parseError = parseInner();
。。。
}
创建抽象语法树Builder,并用来解析、生成语法节点:
UString Parser::parseInner(){
UString parseError = UString();
unsigned oldFunctionCacheSize = m_functionCache ? m_functionCache->byteSize() : 0;
//抽象语法树Builder:
ASTBuilder context(const_cast(m_globalData), const_cast(m_source));
if (m_lexer->isReparsing())
m_statementDepth--;
ScopeRef scope = currentScope();
//开始解析生成语法树的一个节点:
SourceElements* sourceElements = parseSourceElements(context);
if (!sourceElements || !consume(EOFTOK))
}
举例说来,根据Token的类型,JSC认为输入的Token是一个常量声明,就会使用如下的模板函数生成语法节点(Node),然后放入ASTBuilder里面,我们先看ASTBuilder的结构:
class ASTBuilder {
......
Scope m_scope;
Vector m_binaryOperandStack;
Vector m_assignmentInfoStack;
Vector, 10> m_binaryOperatorStack;
Vector, 10> m_unaryTokenStack;
int m_evalCount;
};
template
template TreeSourceElements Parser::parseSourceElements(TreeBuilder& context)
{
const unsigned lengthOfUseStrictLiteral = 12; // "use strict".length
TreeSourceElements sourceElements = context.createSourceElements();
bool seenNonDirective = false;
const Identifier* directive = 0;
unsigned directiveLiteralLength = 0;
unsigned startOffset = m_token.m_info.startOffset;
unsigned oldLastLineNumber = m_lexer->lastLineNumber();
unsigned oldLineNumber = m_lexer->lineNumber();
bool hasSetStrict = false;
//解析语法节点--语句
while (TreeStatement statement = parseStatement(context, directive, &directiveLiteralLength)) {
if (mode == CheckForStrictMode && !seenNonDirective) {
if (directive) {
// "use strict" must be the exact literal without escape sequences or line continuation.
if (!hasSetStrict && directiveLiteralLength == lengthOfUseStrictLiteral && m_globalData->propertyNames->useStrictIdentifier == *directive) {
setStrictMode();
hasSetStrict = true;
failIfFalse(isValidStrictMode());
m_lexer->setOffset(startOffset);
next();
m_lexer->setLastLineNumber(oldLastLineNumber);
m_lexer->setLineNumber(oldLineNumber);
failIfTrue(m_error);
continue;
}
} else
seenNonDirective = true;
}
context.appendStatement(sourceElements, statement); //添加语法节点到ASTBuilder
}
if (m_error)
fail();
return sourceElements;
}
解析语句就是各种switch case,效率不高啊!
template
template TreeStatement Parser::parseStatement(TreeBuilder& context, const Identifier*& directive, unsigned* directiveLiteralLength)
{
DepthManager statementDepth(&m_statementDepth);
m_statementDepth++;
directive = 0;
int nonTrivialExpressionCount = 0;
failIfStackOverflow();
switch (m_token.m_type) {
case OPENBRACE:
return parseBlockStatement(context);
case VAR:
return parseVarDeclaration(context);
case CONSTTOKEN:
return parseConstDeclaration(context);
case FUNCTION:
failIfFalseIfStrictWithMessage(m_statementDepth == 1, "Functions cannot be declared in a nested block in strict mode");
return parseFunctionDeclaration(context);
case SEMICOLON:
next();
return context.createEmptyStatement(m_lexer->lastLineNumber());
case IF:
return parseIfStatement(context);
case DO:
return parseDoWhileStatement(context);
case WHILE:
return parseWhileStatement(context);
case FOR:
return parseForStatement(context);
case CONTINUE:
return parseContinueStatement(context);
case BREAK:
return parseBreakStatement(context);
case RETURN:
return parseReturnStatement(context);
case WITH:
return parseWithStatement(context);
case SWITCH:
return parseSwitchStatement(context);
case THROW:
return parseThrowStatement(context);
case TRY:
return parseTryStatement(context);
case DEBUGGER:
return parseDebuggerStatement(context);
case EOFTOK:
case CASE:
case CLOSEBRACE:
case DEFAULT:
// These tokens imply the end of a set of source elements
return 0;
case IDENT:
return parseExpressionOrLabelStatement(context);
case STRING:
directive = m_token.m_data.ident;
if (directiveLiteralLength)
*directiveLiteralLength = m_token.m_info.endOffset - m_token.m_info.startOffset;
nonTrivialExpressionCount = m_nonTrivialExpressionCount;
default:
TreeStatement exprStatement = parseExpressionStatement(context);
if (directive && nonTrivialExpressionCount != m_nonTrivialExpressionCount)
directive = 0;
return exprStatement;
}
}
template
template TreeConstDeclList Parser::parseConstDeclarationList(TreeBuilder& context)
{
failIfTrue(strictMode());
TreeConstDeclList constDecls = 0;
TreeConstDeclList tail = 0;
do {
next();
matchOrFail(IDENT);
//取出词(Token):
const Identifier* name = m_token.m_data.ident;
next();
//是一个=吗?
bool hasInitializer = match(EQUAL);
//
declareVariable(name);
context.addVar(name, DeclarationStacks::IsConstant | (hasInitializer ? DeclarationStacks::HasInitializer : 0));
TreeExpression initializer = 0;
if (hasInitializer) {
next(TreeBuilder::DontBuildStrings); // consume '='
initializer = parseAssignmentExpression(context);
}
新建一个“常量申明节点”放入ASTBuilder里面:
tail = context.appendConstDecl(m_lexer->lastLineNumber(), tail, name, initializer);
if (!constDecls)
constDecls = tail;
} while (match(COMMA));
return constDecls;
}
ASTBuilder.h:
ConstDeclNode* appendConstDecl(int lineNumber, ConstDeclNode* tail, const Identifier* name, ExpressionNode* initializer)
{
ConstDeclNode* result = new (m_globalData) ConstDeclNode(lineNumber, *name, initializer);
if (tail)
tail->m_next = result;
return result;
}
调用堆栈 如下:
#0 JSC::ASTBuilder::BinaryExprContext::BinaryExprContext (this=0x7fffffffbb6f) at JavaScriptCore/parser/ASTBuilder.h:85
#1 JSC::Parser >::parseBinaryExpression (this=0x7fffffffc330, context=...)JavaScriptCore/parser/Parser.cpp:1143
#2 JSC::Parser >::parseConditionalExpression (this=0x7fffffffc330, context=...) at JavaScriptCore/parser/Parser.cpp:1109
#3 JSC::Parser >::parseAssignmentExpression (this=0x7fffffffc330, context=...)
at /opt/src/opt/src/mp50/framework/webkit/WebKit_123412/Source/JavaScriptCore/parser/Parser.cpp:1051
#4 JSC::Parser >::parseVarDeclarationList (this=, context=..., declarations=@0x7fffffffbd3c: 1, lastIdent=@0x7fffffffbd30: 0xdb3060, lastInitializer=@0x7fffffffbd28: 0x0, identStart=@0x7fffffffbd24: 5, initStart=@0x7fffffffbd24: 5, initEnd=@: 5) at parser/Parser.cpp:263
#5 JSC::Parser >::parseVarDeclaration (this=0x7fffffffc330, context=...) at JavaScriptCore/parser/Parser.cpp:181
#6 JSC::Parser >::parseStatement (this=0x7fffffffc330, context=..., directive=: 0x0,directiveLiteralLength=) Parser.cpp:682
#7 JSC::Parser >::parseSourceElements<(JSC::SourceElementsMode)0, JSC::ASTBuilder> (this, context=...) at parser/Parser.cpp:145
#8 JSC::Parser >::parseInner (this=0x7fffffffc330) at Parser.cpp:93
#9 JSC::Parser >::parse (this=, lexicalGlobalObject=, debugger=0x0, debuggerExecState=, exception=) Parser.h:990
#10 JSC::parse (globalData=, lexicalGlobalObject=source,parameters, strictness=JSParseNormal,parserMode=JSParseProgramCode, debugger, execState=, exception=) Parser.h:1048
#11 JSC::ProgramExecutable::compileInternal (this=, exec=, scopeChainNode=, jitType=JSC::JITCode::BaselineJIT) at JavaScriptCore/runtime/Executable.cpp:338
#12 JSC::ProgramExecutable::compile (this=0x7ffff7fbb580, exec=0x7ffff7f9fb90, scopeChainNode=0x7ffff7f7ffc0)JavaScriptCore/runtime/Executable.h:446
#13 JSC::Interpreter::execute (this=, program=, callFrame=, scopeChain=, thisObj=0x7ffff7f9f980) at JavaScriptCore/interpreter/Interpreter.cpp:1224
#14 JSC::evaluate (exec=, scopeChain=, source=..., thisValue=..., returnedException=) JavaScriptCore/runtime/Completion.cpp:75
#15 runWithScripts (globalObject=0x7ffff7f9f980, scripts=, dump=false) at JavaScriptCore/jsc.cpp:545
#16 jscmain (argc=2, argv=0x7fffffffdc88) at JavaScriptCore/jsc.cpp:733
#17 main (argc=2, argv=0x7fffffffdc88) atavaScriptCore/jsc.cpp:510
接下来,就会调用BytecodeGenerator::generate生成字节码,具体分下节分析。我们先看看下面来自JavaScript的一个个语法树节点生成字节码的过程:
JavaScriptCore/bytecompiler/BytecodeGenerator.cpp:
RegisterID* BooleanNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
if (dst == generator.ignoredResult())
return 0;
return generator.emitLoad(dst, m_value);
}
以下是我准备写的文章题目:
一、 JavaScriptCore的词法分析器工作流程分析;
二、 JavaScriptCore的语法分析器工作流程分析;
三、 JavaScriptCore的字节码生成流程分析;
四、 LLInt解释器工作流程分析;
五、 Baseline JIT编译器的工作流程分析;
六、 DFG JIT编译器的工作流程分析;
七、LLVM虚拟机的工作流程分析;
八、JavaScriptCore的未来展望;
文笔粗糙,不善表达,希望能越写越好。
原创,转载请注明:http://blog.csdn.net/lichwei1983/article/details/44658533
第一时间获得博客更新提醒,以及更多技术信息分享,欢迎关注个人微信公众平台:程序员互动联盟(coder_online),扫一扫下方二维码或搜索微信号coder_online即可关注,我们可以在线交流。
引用:
1 https://www.webkit.org/blog/3271/webkit-css-selector-jit-compiler/
2 http://blog.csdn.net/horkychen/article/details/8928578