使用编译器¶

Using the Commandline Compiler¶

Note

This section doesn’t apply to solcjs.

One of the build targets of the Solidity repository is solc, the solidity commandline compiler.Using solc —help provides you with an explanation of all options. The compiler can produce various outputs, ranging from simple binaries and assembly over an abstract syntax tree (parse tree) to estimations of gas usage.If you only want to compile a single file, you run it as solc —bin sourceFile.sol and it will print the binary. Before you deploy your contract, activate the optimizer while compiling using solc —optimize —bin sourceFile.sol. If you want to get some of the more advanced output variants of solc, it is probably better to tell it to output everything to separate files using solc -o outputDirectory —bin —ast —asm sourceFile.sol.

The commandline compiler will automatically read imported files from the filesystem, butit is also possible to provide path redirects using prefix=path in the following way:

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

This essentially instructs the compiler to search for anything starting withgithub.com/ethereum/dapp-bin/ under /usr/local/lib/dapp-bin and if it does notfind the file there, it will look at /usr/local/lib/fallback (the empty prefixalways matches). solc will not read files from the filesystem that lie outside ofthe remapping targets and outside of the directories where explicitly specified sourcefiles reside, so things like import "/etc/passwd"; only work if you add =/ as a remapping.

If there are multiple matches due to remappings, the one with the longest common prefix is selected.

For security reasons the compiler has restrictions what directories it can access. Paths (and their subdirectories) of source files specified on the commandline and paths defined by remappings are allowed for import statements, but everything else is rejected. Additional paths (and their subdirectories) can be allowed via the —allow-paths /sample/path,/another/sample/path switch.

If your contracts use libraries, you will notice that the bytecode contains substrings of the form LibraryName__. You can use solc as a linker meaning that it will insert the library addresses for you at those points:

Either add —libraries "Math:0x12345678901234567890 Heap:0xabcdef0123456" to your command to provide an address for each library or store the string in a file (one library per line) and run solc using —libraries fileName.

If solc is called with the option —link, all input files are interpreted to be unlinked binaries (hex-encoded) in the LibraryName__-format given above and are linked in-place (if the input is read from stdin, it is written to stdout). All options except —libraries are ignored (including -o) in this case.

If solc is called with the option —standard-json, it will expect a JSON input (as explained below) on the standard input, and return a JSON output on the standard output.

Compiler Input and Output JSON Description¶

These JSON formats are used by the compiler API as well as are available through solc. These are subject to change,some fields are optional (as noted), but it is aimed at to only make backwards compatible changes.

The compiler API expects a JSON formatted input and outputs the compilation result in a JSON formatted output.

Comments are of course not permitted and used here only for explanatory purposes.

Input Description¶

  1. {
  2. // Required: Source code language, such as "Solidity", "serpent", "lll", "assembly", etc.
  3. language: "Solidity",
  4. // Required
  5. sources:
  6. {
  7. // The keys here are the "global" names of the source files,
  8. // imports can use other files via remappings (see below).
  9. "myFile.sol":
  10. {
  11. // Optional: keccak256 hash of the source file
  12. // It is used to verify the retrieved content if imported via URLs.
  13. "keccak256": "0x123...",
  14. // Required (unless "content" is used, see below): URL(s) to the source file.
  15. // URL(s) should be imported in this order and the result checked against the
  16. // keccak256 hash (if available). If the hash doesn't match or none of the
  17. // URL(s) result in success, an error should be raised.
  18. "urls":
  19. [
  20. "bzzr://56ab...",
  21. "ipfs://Qma...",
  22. "file:///tmp/path/to/file.sol"
  23. ]
  24. },
  25. "mortal":
  26. {
  27. // Optional: keccak256 hash of the source file
  28. "keccak256": "0x234...",
  29. // Required (unless "urls" is used): literal contents of the source file
  30. "content": "contract mortal is owned { function kill() { if (msg.sender == owner) selfdestruct(owner); } }"
  31. }
  32. },
  33. // Optional
  34. settings:
  35. {
  36. // Optional: Sorted list of remappings
  37. remappings: [ ":g/dir" ],
  38. // Optional: Optimizer settings (enabled defaults to false)
  39. optimizer: {
  40. enabled: true,
  41. runs: 500
  42. },
  43. evmVersion: "byzantium", // Version of the EVM to compile for. Affects type checking and code generation. Can be homestead, tangerineWhistle, spuriousDragon, byzantium or constantinople
  44. // Metadata settings (optional)
  45. metadata: {
  46. // Use only literal content and not URLs (false by default)
  47. useLiteralContent: true
  48. },
  49. // Addresses of the libraries. If not all libraries are given here, it can result in unlinked objects whose output data is different.
  50. libraries: {
  51. // The top level key is the the name of the source file where the library is used.
  52. // If remappings are used, this source file should match the global path after remappings were applied.
  53. // If this key is an empty string, that refers to a global level.
  54. "myFile.sol": {
  55. "MyLib": "0x123123..."
  56. }
  57. }
  58. // The following can be used to select desired outputs.
  59. // If this field is omitted, then the compiler loads and does type checking, but will not generate any outputs apart from errors.
  60. // The first level key is the file name and the second is the contract name, where empty contract name refers to the file itself,
  61. // while the star refers to all of the contracts.
  62. //
  63. // The available output types are as follows:
  64. // abi - ABI
  65. // ast - AST of all source files
  66. // legacyAST - legacy AST of all source files
  67. // devdoc - Developer documentation (natspec)
  68. // userdoc - User documentation (natspec)
  69. // metadata - Metadata
  70. // ir - New assembly format before desugaring
  71. // evm.assembly - New assembly format after desugaring
  72. // evm.legacyAssembly - Old-style assembly format in JSON
  73. // evm.bytecode.object - Bytecode object
  74. // evm.bytecode.opcodes - Opcodes list
  75. // evm.bytecode.sourceMap - Source mapping (useful for debugging)
  76. // evm.bytecode.linkReferences - Link references (if unlinked object)
  77. // evm.deployedBytecode* - Deployed bytecode (has the same options as evm.bytecode)
  78. // evm.methodIdentifiers - The list of function hashes
  79. // evm.gasEstimates - Function gas estimates
  80. // ewasm.wast - eWASM S-expressions format (not supported atm)
  81. // ewasm.wasm - eWASM binary format (not supported atm)
  82. //
  83. // Note that using a using `evm`, `evm.bytecode`, `ewasm`, etc. will select every
  84. // target part of that output. Additionally, `*` can be used as a wildcard to request everything.
  85. //
  86. outputSelection: {
  87. // Enable the metadata and bytecode outputs of every single contract.
  88. "*": {
  89. "*": [ "metadata", "evm.bytecode" ]
  90. },
  91. // Enable the abi and opcodes output of MyContract defined in file def.
  92. "def": {
  93. "MyContract": [ "abi", "evm.bytecode.opcodes" ]
  94. },
  95. // Enable the source map output of every single contract.
  96. "*": {
  97. "*": [ "evm.bytecode.sourceMap" ]
  98. },
  99. // Enable the legacy AST output of every single file.
  100. "*": {
  101. "": [ "legacyAST" ]
  102. }
  103. }
  104. }
  105. }

Output Description¶

  1. {
  2. // Optional: not present if no errors/warnings were encountered
  3. errors: [
  4. {
  5. // Optional: Location within the source file.
  6. sourceLocation: {
  7. file: "sourceFile.sol",
  8. start: 0,
  9. end: 100
  10. ],
  11. // Mandatory: Error type, such as "TypeError", "InternalCompilerError", "Exception", etc.
  12. // See below for complete list of types.
  13. type: "TypeError",
  14. // Mandatory: Component where the error originated, such as "general", "ewasm", etc.
  15. component: "general",
  16. // Mandatory ("error" or "warning")
  17. severity: "error",
  18. // Mandatory
  19. message: "Invalid keyword"
  20. // Optional: the message formatted with source location
  21. formattedMessage: "sourceFile.sol:100: Invalid keyword"
  22. }
  23. ],
  24. // This contains the file-level outputs. In can be limited/filtered by the outputSelection settings.
  25. sources: {
  26. "sourceFile.sol": {
  27. // Identifier (used in source maps)
  28. id: 1,
  29. // The AST object
  30. ast: {},
  31. // The legacy AST object
  32. legacyAST: {}
  33. }
  34. },
  35. // This contains the contract-level outputs. It can be limited/filtered by the outputSelection settings.
  36. contracts: {
  37. "sourceFile.sol": {
  38. // If the language used has no contract names, this field should equal to an empty string.
  39. "ContractName": {
  40. // The Ethereum Contract ABI. If empty, it is represented as an empty array.
  41. // See https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI
  42. abi: [],
  43. // See the Metadata Output documentation (serialised JSON string)
  44. metadata: "{...}",
  45. // User documentation (natspec)
  46. userdoc: {},
  47. // Developer documentation (natspec)
  48. devdoc: {},
  49. // Intermediate representation (string)
  50. ir: "",
  51. // EVM-related outputs
  52. evm: {
  53. // Assembly (string)
  54. assembly: "",
  55. // Old-style assembly (object)
  56. legacyAssembly: {},
  57. // Bytecode and related details.
  58. bytecode: {
  59. // The bytecode as a hex string.
  60. object: "00fe",
  61. // Opcodes list (string)
  62. opcodes: "",
  63. // The source mapping as a string. See the source mapping definition.
  64. sourceMap: "",
  65. // If given, this is an unlinked object.
  66. linkReferences: {
  67. "libraryFile.sol": {
  68. // Byte offsets into the bytecode. Linking replaces the 20 bytes located there.
  69. "Library1": [
  70. { start: 0, length: 20 },
  71. { start: 200, length: 20 }
  72. ]
  73. }
  74. }
  75. },
  76. // The same layout as above.
  77. deployedBytecode: { },
  78. // The list of function hashes
  79. methodIdentifiers: {
  80. "delegate(address)": "5c19a95c"
  81. },
  82. // Function gas estimates
  83. gasEstimates: {
  84. creation: {
  85. codeDepositCost: "420000",
  86. executionCost: "infinite",
  87. totalCost: "infinite"
  88. },
  89. external: {
  90. "delegate(address)": "25000"
  91. },
  92. internal: {
  93. "heavyLifting()": "infinite"
  94. }
  95. }
  96. },
  97. // eWASM related outputs
  98. ewasm: {
  99. // S-expressions format
  100. wast: "",
  101. // Binary format (hex string)
  102. wasm: ""
  103. }
  104. }
  105. }
  106. }
  107. }

Error types¶

  • JSONError: JSON input doesn’t conform to the required format, e.g. input is not a JSON object, the language is not supported, etc.
  • IOError: IO and import processing errors, such as unresolvable URL or hash mismatch in supplied sources.
  • ParserError: Source code doesn’t conform to the language rules.
  • DocstringParsingError: The NatSpec tags in the comment block cannot be parsed.
  • SyntaxError: Syntactical error, such as continue is used outside of a for loop.
  • DeclarationError: Invalid, unresolvable or clashing identifier names. e.g. Identifier not found
  • TypeError: Error within the type system, such as invalid type conversions, invalid assignments, etc.
  • UnimplementedFeatureError: Feature is not supported by the compiler, but is expected to be supported in future versions.
  • InternalCompilerError: Internal bug triggered in the compiler - this should be reported as an issue.
  • Exception: Unknown failure during compilation - this should be reported as an issue.
  • CompilerError: Invalid use of the compiler stack - this should be reported as an issue.
  • FatalError: Fatal error not processed correctly - this should be reported as an issue.
  • Warning: A warning, which didn’t stop the compilation, but should be addressed if possible.

原文: http://solidity.apachecn.org/cn/doc/v0.4.21/using-the-compiler.html