[WebKit内核] JavaScript引擎深度解析--基础篇(一)字节码生成及语法树的构建详情分析
2015-03-26 23:26 2285人阅读 评论(1) 收藏 举报
分类:
Webkit(34) JavascriptCore/JIT(3)
版权声明:本文为博主原创文章,未经博主允许不得转载。
看到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。词法器工作过程如下:
[cpp] view plain copy
- JavaScriptCore/interpreter/interpreter.cpp:
- template <typename CharType>
- template <ParserMode mode> TokenType LiteralParser<CharType>::Lexer::lex(LiteralParserToken<CharType>& 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<mode, ‘"‘>(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<mode, ‘\‘‘>(token);
- }
- }
- m_lexErrorMessage = String::format("Unrecognized token ‘%c‘", *m_ptr).impl();
- return TokError;
- }
经过此过程,一个完整的JSC世界的Token就生成了。然后,再进行语法分析,生成抽象语法树.下图就是JavaScriptCore世界语法节点的静态类关系:
下面我们看看,语法解析具体过程:
JavaScriptCore/parser/parser.cpp:
[cpp] view plain copy
- PassRefPtr<ParsedNode> Parser<LexerType>::parse(JSGlobalObject* lexicalGlobalObject, Debugger* debugger, ExecState* debuggerExecState, JSObject** exception)</span>
[cpp] view plain copy
- {
- 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,并用来解析、生成语法节点:
[cpp] view plain copy
- UString Parser<LexerType>::parseInner(){
- UString parseError = UString();
- unsigned oldFunctionCacheSize = m_functionCache ? m_functionCache->byteSize() : 0;
- //抽象语法树Builder:
- ASTBuilder context(const_cast<JSGlobalData*>(m_globalData), const_cast<SourceCode*>(m_source));
- if (m_lexer->isReparsing())
- m_statementDepth--;
- ScopeRef scope = currentScope();
- //开始解析生成语法树的一个节点:
- SourceElements* sourceElements = parseSourceElements<CheckForStrictMode>(context);
- if (!sourceElements || !consume(EOFTOK))
- }
举例说来,根据Token的类型,JSC认为输入的Token是一个常量声明,就会使用如下的模板函数生成语法节点(Node),然后放入ASTBuilder里面,我们先看ASTBuilder的结构:
[cpp] view plain copy
- class ASTBuilder {
- ......
- Scope m_scope;
- Vector<BinaryOperand, 10> m_binaryOperandStack;
- Vector<AssignmentInfo, 10> m_assignmentInfoStack;
- Vector<pair<int, int>, 10> m_binaryOperatorStack;
- Vector<pair<int, int>, 10> m_unaryTokenStack;
- int m_evalCount;
- };
再看主要语法解析过程(Parser/parser.cpp):
[cpp] view plain copy
- template <typename LexerType>
- template <SourceElementsMode mode, class TreeBuilder> TreeSourceElements Parser<LexerType>::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,效率不高啊!
[cpp] view plain copy
- template <typename LexerType>
- template <class TreeBuilder> TreeStatement Parser<LexerType>::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;
- }
- }
举其中一个例子:
JavaScriptCore/parser/parser.cpp:
[cpp] view plain copy
- template <typename LexerType>
- template <class TreeBuilder> TreeConstDeclList Parser<LexerType>::parseConstDeclarationList(TreeBuilder& context)
- {
- failIfTrue(strictMode());
- TreeConstDeclList constDecls = 0;
- TreeConstDeclList tail = 0;
- do {
- next();
- matchOrFail(IDENT);
[cpp] view plain copy
- //取出词(Token):
- const Identifier* name = m_token.m_data.ident;
- next();
[cpp] view plain copy
- //是一个=吗?
- bool hasInitializer = match(EQUAL);
[cpp] view plain copy
- //
- declareVariable(name);
- context.addVar(name, DeclarationStacks::IsConstant | (hasInitializer ? DeclarationStacks::HasInitializer : 0));
- TreeExpression initializer = 0;
- if (hasInitializer) {
- next(TreeBuilder::DontBuildStrings); // consume ‘=‘
- initializer = parseAssignmentExpression(context);
- }
[cpp] view plain copy
- <span style="white-space:pre"> </span>新建一个“常量申明节点”放入ASTBuilder里面:
- tail = context.appendConstDecl(m_lexer->lastLineNumber(), tail, name, initializer);
- if (!constDecls)
- constDecls = tail;
- } while (match(COMMA));
- return constDecls;
- }
ASTBuilder.h:
[cpp] view plain copy
- 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;
- }
调用堆栈 如下:
[cpp] view plain copy
- #0 JSC::ASTBuilder::BinaryExprContext::BinaryExprContext (this=0x7fffffffbb6f) at JavaScriptCore/parser/ASTBuilder.h:85
- #1 JSC::Parser<JSC::Lexer<unsigned char> >::parseBinaryExpression<JSC::ASTBuilder> (this=0x7fffffffc330, context=...)JavaScriptCore/parser/Parser.cpp:1143
- #2 JSC::Parser<JSC::Lexer<unsigned char> >::parseConditionalExpression<JSC::ASTBuilder> (this=0x7fffffffc330, context=...) at JavaScriptCore/parser/Parser.cpp:1109
- #3 JSC::Parser<JSC::Lexer<unsigned char> >::parseAssignmentExpression<JSC::ASTBuilder> (this=0x7fffffffc330, context=...)
- at /opt/src/opt/src/mp50/framework/webkit/WebKit_123412/Source/JavaScriptCore/parser/Parser.cpp:1051
- #4 JSC::Parser<JSC::Lexer<unsigned char> >::parseVarDeclarationList<JSC::ASTBuilder> (this=, context=..., [email protected]: 1, [email protected]: 0xdb3060, [email protected]: 0x0, [email protected]: 5, [email protected]: 5, [email protected]: 5) at parser/Parser.cpp:263
- #5 JSC::Parser<JSC::Lexer<unsigned char> >::parseVarDeclaration<JSC::ASTBuilder> (this=0x7fffffffc330, context=...) at JavaScriptCore/parser/Parser.cpp:181
- #6 JSC::Parser<JSC::Lexer<unsigned char> >::parseStatement<JSC::ASTBuilder> (this=0x7fffffffc330, context=..., directive=: 0x0,directiveLiteralLength=) Parser.cpp:682
- #7 JSC::Parser<JSC::Lexer<unsigned char> >::parseSourceElements<(JSC::SourceElementsMode)0, JSC::ASTBuilder> (this, context=...) at parser/Parser.cpp:145
- #8 JSC::Parser<JSC::Lexer<unsigned char> >::parseInner (this=0x7fffffffc330) at Parser.cpp:93
- #9 JSC::Parser<JSC::Lexer<unsigned char> >::parse<JSC::ProgramNode> (this=, lexicalGlobalObject=, debugger=0x0, debuggerExecState=, exception=) Parser.h:990
- #10 JSC::parse<JSC::ProgramNode> (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)
[cpp] view plain copy
- {
- 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