使用编译器

Solidity存储库的一个构建目标是solc,solidity命令行编译器。 使用solc --help为您提供全部选项的解释。 编译器能够生成各类输出,范围从简单的二进制文件和汇编到抽象语法树(解析树),以估计gas使用状况。 若是您只想编译单个文件,则将其做为solc --bin sourceFile.sol运行,并打印二进制文件。 在部署合同以前,在编译时使用solc --optimize --bin sourceFile.sol来激活优化器。 若是你想得到solc的一些更高级的输出变体,最好告诉它使用solc -o outputDirectory --bin --ast --asm sourceFile.sol输出全部东西来分离文件。git

命令行编译器会自动从文件系统中读取导入的文件,但也能够按照如下方式使用prefix = path来提供路径重定向:github

solc github.com/ethereum/dapp-bin/=/usr/local/lib/dapp-bin/ =/usr/local/lib/fallback file.sol

这本质上指示编译器搜索以/usr/local/lib/dapp-bin下的github.com/ethereum/dapp-bin/开头的任何内容,若是它没有在那里找到该文件,它将查看/usr/local/lib/fallback(空的前缀老是匹配)。 solc不会读取文件系统中位于重映射目标以外和显式指定的源文件所在目录以外的文件,所以import“/etc/ passwd”; 只有在添加= /做为从新映射时才有效。express

若是因为重映射而存在多个匹配,则选择具备最长公共前缀的那个匹配。json

出于安全缘由,编译器限制了它能够访问的目录。 在命令行中指定的源文件的路径(及其子目录)和经过重映射定义的路径可用于导入语句,但其余全部内容都被拒绝。 能够经过--allow-paths /sample/path,/another/sample/path开关容许其余路径(及其子目录)。安全

若是您的合约使用库,您会注意到该字节码包含__LibraryName______形式的子字符串。 您可使用solc做为连接器,这意味着它将在这些位置为您插入库地址:app

或者添加--libraries "Math:0x12345678901234567890 Heap:0xabcdef0123456"到您的命令中,为每一个库提供一个地址或将该字符串存储在一个文件中(每行一个库),并使用--libraries fileName运行solcless

若是使用选项--link调用solc,则全部输入文件被解释为以上给出的__LibraryName ____格式的非连接二进制文件(十六进制编码),并就地连接(若是从stdin读取输入,则将其写入 到标准输出)。 在这种状况下,除了--libraries以外的全部选项都被忽略(包括-o)。优化

若是使用选项--standard-json调用solc,则它将在标准输入上指望JSON输入(以下所述),并在标准输出上返回JSON输出。ui

编译器输入输出JSON描述
这些JSON格式由编译器API使用,也能够经过solc使用。 这些可能会发生变化,有些字段是可选的(如上所述),但其目的仅在于进行向后兼容的更改。this

编译器API须要JSON格式的输入,并以JSON格式的输出输出编译结果。

评论固然是不容许的,这里仅用于解释目的。
输入描述

{
  // Required: Source code language, such as "Solidity", "serpent", "lll", "assembly", etc.
  language: "Solidity",
  // Required
  sources:
  {
    // The keys here are the "global" names of the source files,
    // imports can use other files via remappings (see below).
    "myFile.sol":
    {
      // Optional: keccak256 hash of the source file
      // It is used to verify the retrieved content if imported via URLs.
      "keccak256": "0x123...",
      // Required (unless "content" is used, see below): URL(s) to the source file.
      // URL(s) should be imported in this order and the result checked against the
      // keccak256 hash (if available). If the hash doesn't match or none of the
      // URL(s) result in success, an error should be raised.
      "urls":
      [
        "bzzr://56ab...",
        "ipfs://Qma...",
        "file:///tmp/path/to/file.sol"
      ]
    },
    "mortal":
    {
      // Optional: keccak256 hash of the source file
      "keccak256": "0x234...",
      // Required (unless "urls" is used): literal contents of the source file
      "content": "contract mortal is owned { function kill() { if (msg.sender == owner) selfdestruct(owner); } }"
    }
  },
  // Optional
  settings:
  {
    // Optional: Sorted list of remappings
    remappings: [ ":g/dir" ],
    // Optional: Optimizer settings (enabled defaults to false)
    optimizer: {
      enabled: true,
      runs: 500
    },
    // Metadata settings (optional)
    metadata: {
      // Use only literal content and not URLs (false by default)
      useLiteralContent: true
    },
    // Addresses of the libraries. If not all libraries are given here, it can result in unlinked objects whose output data is different.
    libraries: {
      // The top level key is the the name of the source file where the library is used.
      // If remappings are used, this source file should match the global path after remappings were applied.
      // If this key is an empty string, that refers to a global level.
      "myFile.sol": {
        "MyLib": "0x123123..."
      }
    }
    // The following can be used to select desired outputs.
    // If this field is omitted, then the compiler loads and does type checking, but will not generate any outputs apart from errors.
    // The first level key is the file name and the second is the contract name, where empty contract name refers to the file itself,
    // while the star refers to all of the contracts.
    //
    // The available output types are as follows:
    //   abi - ABI
    //   ast - AST of all source files
    //   legacyAST - legacy AST of all source files
    //   devdoc - Developer documentation (natspec)
    //   userdoc - User documentation (natspec)
    //   metadata - Metadata
    //   ir - New assembly format before desugaring
    //   evm.assembly - New assembly format after desugaring
    //   evm.legacyAssembly - Old-style assembly format in JSON
    //   evm.bytecode.object - Bytecode object
    //   evm.bytecode.opcodes - Opcodes list
    //   evm.bytecode.sourceMap - Source mapping (useful for debugging)
    //   evm.bytecode.linkReferences - Link references (if unlinked object)
    //   evm.deployedBytecode* - Deployed bytecode (has the same options as evm.bytecode)
    //   evm.methodIdentifiers - The list of function hashes
    //   evm.gasEstimates - Function gas estimates
    //   ewasm.wast - eWASM S-expressions format (not supported atm)
    //   ewasm.wasm - eWASM binary format (not supported atm)
    //
    // Note that using a using `evm`, `evm.bytecode`, `ewasm`, etc. will select every
    // target part of that output. Additionally, `*` can be used as a wildcard to request everything.
    //
    outputSelection: {
      // Enable the metadata and bytecode outputs of every single contract.
      "*": {
        "*": [ "metadata", "evm.bytecode" ]
      },
      // Enable the abi and opcodes output of MyContract defined in file def.
      "def": {
        "MyContract": [ "abi", "evm.bytecode.opcodes" ]
      },
      // Enable the source map output of every single contract.
      "*": {
        "*": [ "evm.bytecode.sourceMap" ]
      },
      // Enable the legacy AST output of every single file.
      "*": {
        "": [ "legacyAST" ]
      }
    }
  }
}

输出描述

{
  // Optional: not present if no errors/warnings were encountered
  errors: [
    {
      // Optional: Location within the source file.
      sourceLocation: {
        file: "sourceFile.sol",
        start: 0,
        end: 100
      ],
      // Mandatory: Error type, such as "TypeError", "InternalCompilerError", "Exception", etc.
      // See below for complete list of types.
      type: "TypeError",
      // Mandatory: Component where the error originated, such as "general", "ewasm", etc.
      component: "general",
      // Mandatory ("error" or "warning")
      severity: "error",
      // Mandatory
      message: "Invalid keyword"
      // Optional: the message formatted with source location
      formattedMessage: "sourceFile.sol:100: Invalid keyword"
    }
  ],
  // This contains the file-level outputs. In can be limited/filtered by the outputSelection settings.
  sources: {
    "sourceFile.sol": {
      // Identifier (used in source maps)
      id: 1,
      // The AST object
      ast: {},
      // The legacy AST object
      legacyAST: {}
    }
  },
  // This contains the contract-level outputs. It can be limited/filtered by the outputSelection settings.
  contracts: {
    "sourceFile.sol": {
      // If the language used has no contract names, this field should equal to an empty string.
      "ContractName": {
        // The Ethereum Contract ABI. If empty, it is represented as an empty array.
        // See https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI
        abi: [],
        // See the Metadata Output documentation (serialised JSON string)
        metadata: "{...}",
        // User documentation (natspec)
        userdoc: {},
        // Developer documentation (natspec)
        devdoc: {},
        // Intermediate representation (string)
        ir: "",
        // EVM-related outputs
        evm: {
          // Assembly (string)
          assembly: "",
          // Old-style assembly (object)
          legacyAssembly: {},
          // Bytecode and related details.
          bytecode: {
            // The bytecode as a hex string.
            object: "00fe",
            // Opcodes list (string)
            opcodes: "",
            // The source mapping as a string. See the source mapping definition.
            sourceMap: "",
            // If given, this is an unlinked object.
            linkReferences: {
              "libraryFile.sol": {
                // Byte offsets into the bytecode. Linking replaces the 20 bytes located there.
                "Library1": [
                  { start: 0, length: 20 },
                  { start: 200, length: 20 }
                ]
              }
            }
          },
          // The same layout as above.
          deployedBytecode: { },
          // The list of function hashes
          methodIdentifiers: {
            "delegate(address)": "5c19a95c"
          },
          // Function gas estimates
          gasEstimates: {
            creation: {
              codeDepositCost: "420000",
              executionCost: "infinite",
              totalCost: "infinite"
            },
            external: {
              "delegate(address)": "25000"
            },
            internal: {
              "heavyLifting()": "infinite"
            }
          }
        },
        // eWASM related outputs
        ewasm: {
          // S-expressions format
          wast: "",
          // Binary format (hex string)
          wasm: ""
        }
      }
    }
  }
}

错误类型

  1. JSONError:JSON输入不符合所需的格式,例如输入不是JSON对象,不支持该语言等。
  2. IOError:IO和导入处理错误,例如在所提供的源中没法解析的URL或散列不匹配。
  3. ParserError:源代码不符合语言规则。
  4. DocstringParsingError:没法分析注释块中的NatSpec标签。
  5. SyntaxError:句法错误,例如continue在for循环以外使用。
  6. DeclarationError:无效的,没法解析的或冲突的标识符名称。例如标识符未找到
  7. TypeError:类型系统中的错误,例如无效类型转换,无效赋值等。
  8. UnimplementedFeatureError:编译器不支持该功能,但预计将在将来的版本中受支持。
  9. InternalCompilerError:在编译器中触发的内部错误 - 这应报告为问题。
  10. Exception:编译期间未知的失败 -这应该被报告为一个问题。
  11. CompilerError:编译器堆栈的使用无效 - 这应报告为问题。
  12. FatalError:致命错误未正确处理 -应将此报告为问题。
  13. Warning:警告不会中止编译,但应尽量解决。