Solidity編譯器源碼解析

MAC下開發環境

安裝最新版Xcode,安裝后檢查make,clang, cmake等工具是否已經安裝到系統中。

安裝porosity.
porosity是deassembly工具,可以將生成的字節碼轉成匯編碼,這樣可以檢測字節碼正確性。
安裝方法可參看: https://github.com/comaeio/porosity

常用命令
solc 將sol文件編譯成字節碼,然后通過porosity反匯編驗證結果。

//生成字節碼
solc *.sol --asm
//根據字節碼反匯編得到匯編碼
porosity --code 60606040526000600160006101000a81548160ff021916908302179055506101bb8061002b6000396000f360606040526000357c010000000000000 --disassm

源碼結構:

solc: 程序入口main.cpp ,solc命令參數解析,根據參數調用相應方法。

libsolidity:編譯器的核心。

libsolidity/parsing:詞法分析,把程序按字符串順序依次把所有token解析出來,生成AST

libsolidity/ast:AST類包,包括定義各種node類型,node附加信息類,對node的訪問,解析,類型等。對節點訪問使用了vistor設計模式,因為需要在不同階段訪問不同類型的節點,階段和節點類型都是動態綁定。

libsolidity/analysis:語義分析,靜態分析,類型檢查

libsolidity/codegen:根據AST節點生成指令集

libevmasm:根據匯編指令生成字節碼

libdevcore:工具

docs :有幾個有用的文檔比如grammer.rst, assembly.rst


代碼解析

solc:

main.cpp: 調用CommandLineInterface的幾個函數解析參數和sol文件
setDefaultOrCLocale();
   dev::solidity::CommandLineInterface cli;
   //命令參數解析
   if (!cli.parseArguments(argc, argv))
       return 1;
   //對sol文件進行解析,生成字節碼
   if (!cli.processInput())
       return 1;
   bool success = false;
   try
   {
       success = cli.actOnInput();
   }
   catch (boost::exception const& _exception)
   {
       cerr << "Exception during output generation: " << boost::diagnostic_information(_exception) << endl;
       success = false;
   }

   return success ? 0 : 1;
CommandLineInterface.h/cpp:

提供解析命令參數以及編譯sol文件的方法。
使用boost::program_options解析參數
調用CompilerStack的對象編譯sol文件

    /// Parse command line arguments and return false if we should not continue
    bool parseArguments(int _argc, char** _argv);
    /// Parse the files and create source code objects
    bool processInput();
    /// Perform actions on the input depending on provided compiler arguments
    /// @returns true on success.
    bool actOnInput();

    /// Compiler arguments variable map
    boost::program_options::variables_map m_args;
    /// Solidity compiler stack
    std::unique_ptr<dev::solidity::CompilerStack> m_compiler;

libsolidity:

libsolidity/interface:

CompilerStack.h/cpp

solc編譯器, 將sol源碼編譯生成bytecode字節碼
主要函數:parse,analyze,compile,分別執行了編譯過程中的詞法分析,語法分析,語義分析,代碼生成。

    /// Parses all source units that were added
    /// @returns false on error.
    bool parse();

    /// Performs the analysis steps (imports, scopesetting, syntaxCheck, referenceResolving,
    ///  typechecking, staticAnalysis) on previously parsed sources.
    /// @returns false on error.
    bool analyze();

    /// Compiles the source units that were previously added and parsed.
    /// @returns false on error.
    bool compile();

parse()調用Parser類對象的parse方法,返回生成的ast。

Source& source = m_sources[path];
source.scanner->reset();
source.ast = Parser(m_errorReporter).parse(source.scanner);

analyze() 調用libsolidity/analysis下的類對象遍歷ast做語法分析,變量名分析,類型檢查等。

//語法分析
SyntaxChecker syntaxChecker(m_errorReporter);
for (Source const* source: m_sourceOrder)
    if (!syntaxChecker.checkSyntax(*source->ast))
        noErrors = false;
//解析contract名,方法名
DocStringAnalyser docStringAnalyser(m_errorReporter);
for (Source const* source: m_sourceOrder)
    if (!docStringAnalyser.analyseDocStrings(*source->ast))
        noErrors = false;
//解析變量名和變量類型
NameAndTypeResolver resolver(m_globalContext->declarations(), m_scopes, m_errorReporter);
for (Source const* source: m_sourceOrder)
    if (!resolver.registerDeclarations(*source->ast))
        return false;

compile()
調用libsolidity/codegen 下的Compiler對象生成EVM-assembly 。

compileContract(*contract, compiledContracts);

comiileContract

// Run optimiser and compile the contract.
compiler->compileContract(_contract, _compiledContracts, cborEncodedMetadata);

libsolidity/parsing

Token.h/cpp
定義了Solidity的token集合,包括關鍵字,操作符。如果要添加新的關鍵字,首先要在這里把新關鍵字加到token的enum里。

UnderMaros.h 防止已定義的Token跟一些操作系統環境沖突。

Scanner.h/cpp
將sol文件視為一個長字符串,從頭掃到尾,識別和區分各個token,變量名,literal。parser會用scanner 對象去取token。

DocStringParser.h/cpp
解析sol文件的docstring,將每個tag(@)的tag名和內容,保存在m_docTags

/// Mapping tag name -> content.
std::multimap<std::string, DocTag> m_docTags;

Parser.h/cpp
解析每個token,根據token的不同類型調用不同的方法進行解析,并創建不同類型的ASTNode,舉例說明:

ASTPointer<IfStatement> Parser::parseIfStatement(ASTPointer<ASTString> const& _docString)
{
    RecursionGuard recursionGuard(*this);
    ASTNodeFactory nodeFactory(*this);
    expectToken(Token::If);
    expectToken(Token::LParen);
    ASTPointer<Expression> condition = parseExpression();
    expectToken(Token::RParen);
    ASTPointer<Statement> trueBody = parseStatement();
    ASTPointer<Statement> falseBody;
    if (m_scanner->currentToken() == Token::Else)
    {
        m_scanner->next();
        falseBody = parseStatement();
        nodeFactory.setEndPositionFromNode(falseBody);
    }
    else
        nodeFactory.setEndPositionFromNode(trueBody);
    return nodeFactory.createNode<IfStatement>(_docString, condition, trueBody, falseBody);
}

未完待續

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 標題: Rakudo and NQP Internals子標題: The guts tormented imple...
    焉知非魚閱讀 1,428評論 1 3
  • 引言 維基百科:編譯語言(英語:Compiled language)是一種以編譯器來實現的編程語言。它不像解釋型語...
    Flame_Dream閱讀 8,597評論 5 52
  • 前言 2000年,伊利諾伊大學厄巴納-香檳分校(University of Illinois at Urbana-...
    星光社的戴銘閱讀 15,942評論 8 180
  • 如果有來世,我愿意當一棵樹,深深的站立大地上,高大而挺立,為我愛的人,遮風擋雨。 如果有來世,我愿意當一只小鳥,自...
    易足樂閱讀 225評論 0 0
  • 1、下午的讀書會進行的很順利,對自己的表現也很滿意 2、和旺兒的磨合更好了,上午帶他出去玩兒,中午趕在讀書會前到家...
    星空夢旅人Beverly閱讀 84評論 0 0