美文网首页
Solidity编译器源码解析

Solidity编译器源码解析

作者: Scott_Song | 来源:发表于2018-09-18 18:21 被阅读207次

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);
}

未完待续

相关文章

网友评论

      本文标题:Solidity编译器源码解析

      本文链接:https://www.haomeiwen.com/subject/fkaynftx.html