Write in front: The HiBlock blockchain community has set up a translation team to translate technical documentation and information on blockchain. This is part 8 of the Solidity document translation “Using the Compiler” for public proofreading. You can add baobaotalk_com to the Solidity document translation. Verify that you type in ‘Solidity’ and send us your views and suggestions, or leave a comment in the ‘comments’ area at the bottom of the article. Valid ideas will be adopted and incorporated into the next version and a small gift will be sent to you as a token of appreciation.

1

Use the command line compiler

Solc is one of the building targets of the Solidity source library, which is the command-line compiler for Solidity. You can use the solc –help command to see an explanation of all its options. The compiler can generate a variety of output, ranging from simple binaries, assembler files, to abstract syntax trees (parse trees) for estimating “gas” usage. If you only want to compile a file, you can run solc –bin sourcefile.sol to generate the binary. If you want more advanced output from solc, you can save all the output into a separate folder with the solc -o outputDirectory –bin –ast –asm sourcefile.sol command.

Before you deploy your contract, activate the optimizer while compiling using solc –optimize –bin sourceFile.sol. By default, the optimizer will optimize the contract for 200 runs. If you want to optimize for initial contract deployment and get the smallest output, set it to –runs=1. If you expect many transactions and don’t care for higher deployment cost and output size, set –runs to a high number.

The command line compiler automatically reads and imports files from the file system, but it also supports path redirection with the prefix=path option. Such as:

This essentially tells the compiler to search the /usr/local/lib/dapp-bin directory for all files starting with github.com/ethereum/dapp-bin/. If the compiler can’t find such a file, It then reads all files in the /usr/local/lib/fallback directory (empty prefix means always match). Solc does not read files from file systems that are outside the redirection target and outside the explicitly specified source file directory, so import “/etc/passwd”; The compiler will only try to load /etc/passwd from the root directory after you add the =/ option.

If there are multiple matches under the redirect path, the match with the longest public prefix is selected.

For security reasons, the compiler restricts the directories it can access. The path to the source file (and its subdirectories) specified on the command line and the path defined by redirection are available for import statements, others are rejected. Additional path (and its subdirectories) can pass – allow – paths/sample/path, / another/sample/path configured.

If your contract uses libraries, you’ll notice that the compiled hexadecimal bytecode contains a string of the form LibraryName__. When you use Solc as a linker, it will give you the address to insert into the library in the following cases: Either on the command line to add – libraries “x12345678901234567890 Heap Math: 0:0 xabcdef0123456” to provide the address for each library, or to save the string to a file (each row of a library), And use the –libraries fileName parameter.

If the –link option is used when calling the solc command, all input files are parsed into unlinked binary data (hexadecimal encoding) in the __LibraryName____ format mentioned above, and linked in place. (If the input is read from STdin, the generated data is written to stdout). In this case, options other than –libraries (including -o) are ignored.

If the –standard-json option is used when calling the solc command, it parses the input on standard input in JSON format and returns jSON-formatted output on standard output.

2

The compiler inputs and outputs JSON descriptions

The JSON formats shown below are used by the compiler API and, of course, are available on SolC. Some fields are optional (see comments), and they may change, but all changes should be backward compatible.

The compiler API requires jSON-formatted input and outputs the compiled results in JSON format.

Comments are not allowed and are used here for explanatory purposes only.

Input instructions

{// Required: source code languages such as "Solidity", "serpent", "LLL", "Assembly", etc:"Solidity", // Required sources: {// The keys here are "global" names of the source files, which can be connected to other remappings (see below)."myFile.sol": {// Optional: The kaccAK256 hash of the source file, which can be used to validate content loaded through the URL."keccak256": "0x123...", // Required (unless stated"content"Field) : URL pointing to the source file. // Urls (s) are loaded sequentially, and the result is checked against the keccAK256 hash (if there is one) // If the hash values do not match, or if no URL returns success, an exception is thrown."urls":
     [
       "bzzr://56ab..."."ipfs://Qma..."."file:///tmp/path/to/file.sol"]},"mortal": {// Optional: The keccAK256 hash of the file"keccak256": "0x234...", // Required (unless stated"urls"Field) : the literal content of the source file"content": "contract mortal is owned { function kill() { if (msg.sender == owner) selfdestruct(owner); }}"}}, // Optional Settings: {// Optional: an order list of redirection parameters remappings: [":g/dir"], // Optional: Optimizer configuration: {// Default is disabled enabled:true, // Optimize based on how many times you want to run the code. // A smaller value can optimize the initial deployment cost more, and a larger value can optimize high frequency usage. Runs: 200}, // Specifies the version of EVM to compile. This affects code generation and type checking. Available versions are: Homestead, tangerineWhistle, spuriousDragon, Byzantium, Constantinople evmVersion:"byzantium", // Optional: metadata configuration metadata: {// use literal content only, not URLs (defaultfalse) useLiteralContent:true}, // Library address. The outermost key is the name of the source file that uses these libraries. // If a redirect is used, the source files should match the global path after the redirect. // If the name of the source file is empty, all libraries are global references"myFile.sol": {
       "MyLib": "0x123123..."}} // The following can be used to select the desired output. // If this field is ignored, the compiler loads and does a type check, but produces no output other than an error. // The first level of key is the file name, the second level is the contract name, if the contract name is empty, the file itself. // If the wildcard character * is used, it represents all contracts. The output types available at // // are as follows: // abi-abi // AST - Legacy AST for all source files // legacyAST - Legacy AST for 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 - JSON old style assembly format // EVm.bytecode. object - bytecode object // EVM.bytecode. opcodes-opcode list // EVM.bytecode. sourceMap - source code mapping (for debugging) // Evm entry. The bytecode. LinkReferences - link references (if it is not a link object) / / evm entry deployedBytecode * - deployment of bytecode (and evm entry. The bytecode with the same options) / / MethodIdentifiers - List of function hashes // evm.gasEstimates - Gas estimates of functions // ewasm. wast-ewasm s-Expressions format (ATM not supported) // Ewasm. Wasm - ewASM binary format (ATM not supported) // // Note that if you use 'evm', 'evm.bytecode', 'ewASM' and so on, all of their children will be selected as output. In addition, '*' can be used as a wildcard to request everything. // outputSelection: {// Generates metadata and bytecode output for each contract."*": {
       "*": [ "metadata"."evm.bytecode"}, // enable abi and Opcodes output for "MyContract" contracts defined in the "def" file."def": {
       "MyContract": [ "abi"."evm.bytecode.opcodes"}, // generate source map output for each contract"*": {
       "*": [ "evm.bytecode.sourceMap"}, // Each file generates legacy AST output"*": {
       "": [ "legacyAST"]}}}}Copy the code

The output shows that

{// Optional: Errors not presented if no errors/warnings are encountered: [{// Optional: location in source filesourceLocation: {
       file: "sourceFile.sol", start: 0, end: 100], // Enforce: error types, such as "TypeError", "InternalCompilerError", "Exception", etc. // Check the complete list of error types at the end of this articletype: "TypeError", // Force: error component, such as "general", "ewasm", etc. Component:"general"// Mandatory: Error severity (" error "or" warning ") severity:"error", // enforce message:"Invalid keyword"// Optional: formattedMessage with error source position:"sourceFile.sol:100: Invalid keyword"}], // this contains file-level output. You can set limits/filters through outputSelection. sources: {"sourceFile.sol": {// identifier (used for source mapping) ID: 1, // AST object AST: {}, // Legacy AST object legacyAST: {}}}, // This contains contract-level output. You can set limits/filters through outputSelection. contracts: {"sourceFile.sol"This field should be left blank if the language used does not have a contract name."ContractName": {// The application binary Interface (ABI) for ethereum contracts. If empty, it represents an empty array. / / please refer to the https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI abi: [], / / please refer to the metadata output (serialized JSON string) metadata:"{... }", // User documentation (natspec) userDoc: {}, // Developer documentation (natspec) devdoc: {},"", // EVM related output EVM: {// assembly (string) assembly:"", // Old style legacyAssembly: {}, // bytecode: {// Hexadecimal string bytecode: {"00fe", // Opcodes list (string)"", // Source mapped string. See the definition of source mapssourceMap: ""// This is an unlinked object."libraryFile.sol": {// byte offset in bytecode; Replaces 20 bytes from the specified location when linking"Library1"[{start: 0, length: 20}, {start: 200, length: 20}]}}}, // Same layout as above {}, // Function hash list methodIdentifiers: {"delegate(address)": "5c19a95c"}, // function gasEstimates: {creation: {codeDepositCost:"420000",
             executionCost: "infinite",
             totalCost: "infinite"
           },
           external: {
             "delegate(address)": "25000"
           },
           internal: {
             "heavyLifting()": "infinite"}}}, // eWASM related output eWASM: {// s-expressions wast:"", // Binary format (hexadecimal string)""
       }
     }
   }
 }
}
Copy the code

Wrong type

JSONError: The JSON input does not conform to the required format. For example, the input is not a JSON object, and the language is not supported.

IOError: IO and import processing errors, for example, containing unparsed urls or hash mismatches in the supplied source.

ParserError: Source code does not conform to language rules.

DocstringParsingError: The NatSpec tag in the comment block cannot be parsed.

SyntaxError: Syntax errors such as continue used outside the for loop.

DeclarationError: Invalid, unresolvable, or conflicting Identifier names such as Identifier not found.

TypeError: Errors in the type system, such as invalid type conversions, invalid assignments, etc.

UnimplementedFeatureError: the compiler does not support the current function, but is expected to support in future versions.

InternalCompilerError: An internal error fired in the compiler — this should be reported as an issue.

Exception: Unknown failure at compile time — this should be reported as an issue.

CompilerError: Invalid use of compiler stack – this should be reported as an issue.

FatalError: Fatal errors are not handled correctly — this should be reported as an issue.

Warning: Warning that compilation will not be stopped, but should be processed if possible.

Read on: Smart Contracts -Solidity Official Document (1)

Install the Solidity compiler -Solidity Official Documentation (2)

Learn about Solidity with examples -Solidity official Document (3)

In-depth understanding of Solidity source files and contract structure – Solidity Chinese Document (4)

Safety Considerations – Solidity Chinese Document (5)

Meta Data for Contracts – Solidity Chinese Document (6)

Applying the Binary Interface (ABI) Instructions – Solidity Chinese Document (7)

Click “Read original” to view the full Chinese document

Note: This is part 8 of the Solidity translation, “Using the Compiler”. For public proofreading, you can add baobaotalk_com, verify your solidity, and send us your views and suggestions. You can also leave a comment in the comments area at the end of this article, or visit our Github via the original link. Valid suggestions will be accepted and improved in time, and a small gift will be sent to you to show our gratitude.

This article is from the HiBlock Blockchain community translation group, thanks to all the translators for their hard work. Click “Read original” to view the full Chinese document.

** Online courses recommended **

Online course: 8-hour Block Chain Smart Contract Development Practice

Training lecturer: Jiang Yong, author of “Vernacular Blockchain”

Course original price: 999 yuan, current price 399 yuan

More benefits:

  • If you invite your friends to sign up, you will get 50% rebate

  • @ Students who sign up for the course and complete the exam within the specified time can share the 10000 yuan bonus

Click “Read original” to view the full Chinese document